code
stringlengths
2
1.05M
/*! UIkit 3.6.22 | https://www.getuikit.com | (c) 2014 - 2021 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitupload', ['uikit-util'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitUpload = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Component = { props: { allow: String, clsDragover: String, concurrent: Number, maxSize: Number, method: String, mime: String, msgInvalidMime: String, msgInvalidName: String, msgInvalidSize: String, multiple: Boolean, name: String, params: Object, type: String, url: String }, data: { allow: false, clsDragover: 'uk-dragover', concurrent: 1, maxSize: 0, method: 'POST', mime: false, msgInvalidMime: 'Invalid File Type: %s', msgInvalidName: 'Invalid File Name: %s', msgInvalidSize: 'Invalid File Size: %s Kilobytes Max', multiple: false, name: 'files[]', params: {}, type: '', url: '', abort: uikitUtil.noop, beforeAll: uikitUtil.noop, beforeSend: uikitUtil.noop, complete: uikitUtil.noop, completeAll: uikitUtil.noop, error: uikitUtil.noop, fail: uikitUtil.noop, load: uikitUtil.noop, loadEnd: uikitUtil.noop, loadStart: uikitUtil.noop, progress: uikitUtil.noop }, events: { change: function(e) { if (!uikitUtil.matches(e.target, 'input[type="file"]')) { return; } e.preventDefault(); if (e.target.files) { this.upload(e.target.files); } e.target.value = ''; }, drop: function(e) { stop(e); var transfer = e.dataTransfer; if (!transfer || !transfer.files) { return; } uikitUtil.removeClass(this.$el, this.clsDragover); this.upload(transfer.files); }, dragenter: function(e) { stop(e); }, dragover: function(e) { stop(e); uikitUtil.addClass(this.$el, this.clsDragover); }, dragleave: function(e) { stop(e); uikitUtil.removeClass(this.$el, this.clsDragover); } }, methods: { upload: function(files) { var this$1 = this; if (!files.length) { return; } uikitUtil.trigger(this.$el, 'upload', [files]); for (var i = 0; i < files.length; i++) { if (this.maxSize && this.maxSize * 1000 < files[i].size) { this.fail(this.msgInvalidSize.replace('%s', this.maxSize)); return; } if (this.allow && !match(this.allow, files[i].name)) { this.fail(this.msgInvalidName.replace('%s', this.allow)); return; } if (this.mime && !match(this.mime, files[i].type)) { this.fail(this.msgInvalidMime.replace('%s', this.mime)); return; } } if (!this.multiple) { files = [files[0]]; } this.beforeAll(this, files); var chunks = chunk(files, this.concurrent); var upload = function (files) { var data = new FormData(); files.forEach(function (file) { return data.append(this$1.name, file); }); for (var key in this$1.params) { data.append(key, this$1.params[key]); } uikitUtil.ajax(this$1.url, { data: data, method: this$1.method, responseType: this$1.type, beforeSend: function (env) { var xhr = env.xhr; xhr.upload && uikitUtil.on(xhr.upload, 'progress', this$1.progress); ['loadStart', 'load', 'loadEnd', 'abort'].forEach(function (type) { return uikitUtil.on(xhr, type.toLowerCase(), this$1[type]); } ); return this$1.beforeSend(env); } }).then( function (xhr) { this$1.complete(xhr); if (chunks.length) { upload(chunks.shift()); } else { this$1.completeAll(xhr); } }, function (e) { return this$1.error(e); } ); }; upload(chunks.shift()); } } }; function match(pattern, path) { return path.match(new RegExp(("^" + (pattern.replace(/\//g, '\\/').replace(/\*\*/g, '(\\/[^\\/]+)*').replace(/\*/g, '[^\\/]+').replace(/((?!\\))\?/g, '$1.')) + "$"), 'i')); } function chunk(files, size) { var chunks = []; for (var i = 0; i < files.length; i += size) { var chunk = []; for (var j = 0; j < size; j++) { chunk.push(files[i + j]); } chunks.push(chunk); } return chunks; } function stop(e) { e.preventDefault(); e.stopPropagation(); } if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('upload', Component); } return Component; })));
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import ButtonBase from '../ButtonBase'; import capitalize from '../utils/capitalize'; import useThemeProps from '../styles/useThemeProps'; import experimentalStyled from '../styles/experimentalStyled'; import unsupportedProp from '../utils/unsupportedProp'; import tabClasses, { getTabUtilityClass } from './tabClasses'; import { jsxs as _jsxs } from "react/jsx-runtime"; var useUtilityClasses = function useUtilityClasses(styleProps) { var classes = styleProps.classes, textColor = styleProps.textColor, fullWidth = styleProps.fullWidth, wrapped = styleProps.wrapped, icon = styleProps.icon, label = styleProps.label, selected = styleProps.selected, disabled = styleProps.disabled; var slots = { root: ['root', icon && label && 'labelIcon', "textColor".concat(capitalize(textColor)), fullWidth && 'fullWidth', wrapped && 'wrapped', selected && 'selected', disabled && 'disabled'], wrapper: ['wrapper'] }; return composeClasses(slots, getTabUtilityClass, classes); }; var TabRoot = experimentalStyled(ButtonBase, { name: 'MuiTab', slot: 'Root', overridesResolver: function overridesResolver(props, styles) { var styleProps = props.styleProps; return _extends({}, styles.root, styleProps.label && styleProps.icon && styles.labelIcon, styles["textColor".concat(capitalize(styleProps.textColor))], styleProps.fullWidth && styles.fullWidth, styleProps.wrapped && styles.wrapped); } })(function (_ref) { var _ref3, _ref4, _ref5; var theme = _ref.theme, styleProps = _ref.styleProps; return _extends({}, theme.typography.button, { maxWidth: 360, minWidth: 90, position: 'relative', minHeight: 48, flexShrink: 0, padding: '12px 16px', overflow: 'hidden', whiteSpace: 'normal', textAlign: 'center' }, styleProps.icon && styleProps.label && _defineProperty({ minHeight: 72, paddingTop: 9, paddingBottom: 9 }, "& .".concat(tabClasses.wrapper, " > *:first-child"), { marginBottom: 6 }), styleProps.textColor === 'inherit' && (_ref3 = { color: 'inherit', opacity: 0.6 }, _defineProperty(_ref3, "&.".concat(tabClasses.selected), { opacity: 1 }), _defineProperty(_ref3, "&.".concat(tabClasses.disabled), { opacity: theme.palette.action.disabledOpacity }), _ref3), styleProps.textColor === 'primary' && (_ref4 = { color: theme.palette.text.secondary }, _defineProperty(_ref4, "&.".concat(tabClasses.selected), { color: theme.palette.primary.main }), _defineProperty(_ref4, "&.".concat(tabClasses.disabled), { color: theme.palette.text.disabled }), _ref4), styleProps.textColor === 'secondary' && (_ref5 = { color: theme.palette.text.secondary }, _defineProperty(_ref5, "&.".concat(tabClasses.selected), { color: theme.palette.secondary.main }), _defineProperty(_ref5, "&.".concat(tabClasses.disabled), { color: theme.palette.text.disabled }), _ref5), styleProps.fullWidth && { flexShrink: 1, flexGrow: 1, flexBasis: 0, maxWidth: 'none' }, styleProps.wrapped && { fontSize: theme.typography.pxToRem(12), lineHeight: 1.5 }); }); var TabWrapper = experimentalStyled('span', { name: 'MuiTab', slot: 'Wrapper', overridesResolver: function overridesResolver(props, styles) { return styles.wrapper; } })({ /* Styles applied to the `icon` and `label`'s wrapper element. */ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '100%', flexDirection: 'column', lineHeight: 1.25 }); var Tab = /*#__PURE__*/React.forwardRef(function Tab(inProps, ref) { var props = useThemeProps({ props: inProps, name: 'MuiTab' }); var className = props.className, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$disableFocusRi = props.disableFocusRipple, disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi, fullWidth = props.fullWidth, icon = props.icon, indicator = props.indicator, label = props.label, onChange = props.onChange, onClick = props.onClick, onFocus = props.onFocus, selected = props.selected, selectionFollowsFocus = props.selectionFollowsFocus, _props$textColor = props.textColor, textColor = _props$textColor === void 0 ? 'inherit' : _props$textColor, value = props.value, _props$wrapped = props.wrapped, wrapped = _props$wrapped === void 0 ? false : _props$wrapped, other = _objectWithoutProperties(props, ["className", "disabled", "disableFocusRipple", "fullWidth", "icon", "indicator", "label", "onChange", "onClick", "onFocus", "selected", "selectionFollowsFocus", "textColor", "value", "wrapped"]); var styleProps = _extends({}, props, { disabled: disabled, disableFocusRipple: disableFocusRipple, selected: selected, icon: !!icon, label: !!label, fullWidth: fullWidth, textColor: textColor, wrapped: wrapped }); var classes = useUtilityClasses(styleProps); var handleClick = function handleClick(event) { if (!selected && onChange) { onChange(event, value); } if (onClick) { onClick(event); } }; var handleFocus = function handleFocus(event) { if (selectionFollowsFocus && !selected && onChange) { onChange(event, value); } if (onFocus) { onFocus(event); } }; return /*#__PURE__*/_jsxs(TabRoot, _extends({ focusRipple: !disableFocusRipple, className: clsx(classes.root, className), ref: ref, role: "tab", "aria-selected": selected, disabled: disabled, onClick: handleClick, onFocus: handleFocus, styleProps: styleProps, tabIndex: selected ? 0 : -1 }, other, { children: [/*#__PURE__*/_jsxs(TabWrapper, { className: classes.wrapper, styleProps: styleProps, children: [icon, label] }), indicator] })); }); process.env.NODE_ENV !== "production" ? Tab.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * This prop isn't supported. * Use the `component` prop if you need to change the children structure. */ children: unsupportedProp, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * If `true`, the component is disabled. * @default false */ disabled: PropTypes.bool, /** * If `true`, the keyboard focus ripple is disabled. * @default false */ disableFocusRipple: PropTypes.bool, /** * If `true`, the ripple effect is disabled. * * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure * to highlight the element by applying separate styles with the `.Mui-focusedVisible` class. * @default false */ disableRipple: PropTypes.bool, /** * The icon to display. */ icon: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), /** * The label element. */ label: PropTypes.node, /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ onClick: PropTypes.func, /** * @ignore */ onFocus: PropTypes.func, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * You can provide your own value. Otherwise, we fallback to the child position index. */ value: PropTypes.any, /** * Tab labels appear in a single row. * They can use a second line if needed. * @default false */ wrapped: PropTypes.bool } : void 0; export default Tab;
/** * @license Highcharts JS v9.2.1 (2021-08-19) * @module highcharts/modules/pattern-fill * @requires highcharts * * Module for adding patterns and images as point fills. * * (c) 2010-2021 Highsoft AS * Author: Torstein Hønsi, Øystein Moseng * * License: www.highcharts.com/license */ 'use strict'; import '../../Extensions/PatternFill.js';
/** * @license Highcharts JS v9.2.0 (2021-08-18) * @module highcharts/modules/variwide * @requires highcharts * * Highcharts variwide module * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import '../../Series/Variwide/VariwideSeries.js';
/*! * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license * * billboard.js, JavaScript chart library * https://naver.github.io/billboard.js/ * * @version 2.2.4 * @requires billboard.js * @summary billboard.js plugin */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("d3-selection")); else if(typeof define === 'function' && define.amd) define("bb", ["d3-selection"], factory); else if(typeof exports === 'object') exports["bb"] = factory(require("d3-selection")); else root["bb"] = root["bb"] || {}, root["bb"]["plugin"] = root["bb"]["plugin"] || {}, root["bb"]["plugin"]["bubblecompare"] = factory(root["d3"]); })(this, function(__WEBPACK_EXTERNAL_MODULE__1__) { return /******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ /* 0 */, /* 1 */ /***/ (function(module) { module.exports = __WEBPACK_EXTERNAL_MODULE__1__; /***/ }) /******/ ]); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(__webpack_module_cache__[moduleId]) { /******/ return __webpack_module_cache__[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ !function() { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = function(exports, definition) { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ !function() { /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /******/ }(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. !function() { // EXPORTS __webpack_require__.d(__webpack_exports__, { "default": function() { return /* binding */ BubbleCompare; } }); ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } // EXTERNAL MODULE: external {"commonjs":"d3-selection","commonjs2":"d3-selection","amd":"d3-selection","root":"d3"} var external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_ = __webpack_require__(1); ;// CONCATENATED MODULE: ./src/Plugin/Plugin.ts /** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ /** * Base class to generate billboard.js plugin * @class Plugin */ /** * Version info string for plugin * @name version * @static * @memberof Plugin * @type {string} * @example * bb.plugin.stanford.version; // ex) 1.9.0 */ var Plugin = /*#__PURE__*/function () { /** * Constructor * @param {Any} options config option object * @private */ function Plugin(options) { options === void 0 && (options = {}), this.$$ = void 0, this.options = void 0, this.options = options; } /** * Lifecycle hook for 'beforeInit' phase. * @private */ var _proto = Plugin.prototype; return _proto.$beforeInit = function $beforeInit() {} /** * Lifecycle hook for 'init' phase. * @private */ , _proto.$init = function $init() {} /** * Lifecycle hook for 'afterInit' phase. * @private */ , _proto.$afterInit = function $afterInit() {} /** * Lifecycle hook for 'redraw' phase. * @private */ , _proto.$redraw = function $redraw() {} /** * Lifecycle hook for 'willDestroy' phase. * @private */ , _proto.$willDestroy = function $willDestroy() { var _this = this; Object.keys(this).forEach(function (key) { _this[key] = null, delete _this[key]; }); }, Plugin; }(); Plugin.version = "2.2.3"; ;// CONCATENATED MODULE: ./src/Plugin/bubblecompare/index.ts /** * Bubble compare diagram plugin.<br> * Compare data 3-dimensional ways: x-axis, y-axis & bubble-size. * - **NOTE:** * - Plugins aren't built-in. Need to be loaded or imported to be used. * - Non required modules from billboard.js core, need to be installed separately. * - **Required modules:** * - [d3-selection](https://github.com/d3/d3-selection) * @class plugin-bubblecompare * @requires d3-selection * @param {object} options bubble compare plugin options * @augments Plugin * @returns {BubbleCompare} * @example * // Plugin must be loaded before the use. * <script src="$YOUR_PATH/plugin/billboardjs-plugin-bubblecompare.js"></script> * * var chart = bb.generate({ * data: { * columns: [ ... ], * type: "bubble" * } * ... * plugins: [ * new bb.plugin.bubblecompare({ * minR: 11, * maxR: 74, * expandScale: 1.1 * }), * ] * }); * @example * import {bb} from "billboard.js"; * import BubbleCompare from "billboard.js/dist/billboardjs-plugin-bubblecompare.esm"; * * bb.generate({ * plugins: [ * new BubbleCompare({ ... }) * ] * }) */ var BubbleCompare = /*#__PURE__*/function (_Plugin) { function BubbleCompare(options) { var _this; return _this = _Plugin.call(this, options) || this, _this.$$ = void 0, _assertThisInitialized(_this) || _assertThisInitialized(_this); } _inheritsLoose(BubbleCompare, _Plugin); var _proto = BubbleCompare.prototype; return _proto.$init = function $init() { var $$ = this.$$; $$.findClosest = this.findClosest.bind(this), $$.getBubbleR = this.getBubbleR.bind(this), $$.pointExpandedR = this.pointExpandedR.bind(this); }, _proto.pointExpandedR = function pointExpandedR(d) { var baseR = this.getBubbleR(d), _this$options$expandS = this.options.expandScale, expandScale = _this$options$expandS === void 0 ? 1 : _this$options$expandS; return BubbleCompare.raiseFocusedBubbleLayer(d), this.changeCursorPoint(), baseR * expandScale; }, BubbleCompare.raiseFocusedBubbleLayer = function raiseFocusedBubbleLayer(d) { d.raise && (0,external_commonjs_d3_selection_commonjs2_d3_selection_amd_d3_selection_root_d3_.select)(d.node().parentNode.parentNode).raise(); }, _proto.changeCursorPoint = function changeCursorPoint() { this.$$.$el.svg.select(".bb-event-rect").style("cursor", "pointer"); }, _proto.findClosest = function findClosest(values, pos) { var _this2 = this, $$ = this.$$; return values.filter(function (v) { return v && !$$.isBarType(v.id); }).reduce(function (acc, cur) { var d = $$.dist(cur, pos); return d < _this2.getBubbleR(cur) ? cur : acc; }, 0); }, _proto.getBubbleR = function getBubbleR(d) { var _this3 = this, _this$options = this.options, minR = _this$options.minR, maxR = _this$options.maxR, curVal = this.getZData(d); if (!curVal) return minR; var _this$$$$data$targets = this.$$.data.targets.reduce(function (_ref, cur) { var accMin = _ref[0], accMax = _ref[1], val = _this3.getZData(cur.values[0]); return [Math.min(accMin, val), Math.max(accMax, val)]; }, [1e4, 0]), min = _this$$$$data$targets[0], max = _this$$$$data$targets[1], size = min > 0 && max === min ? 0 : curVal / max; return Math.abs(size) * (maxR - minR) + minR; }, _proto.getZData = function getZData(d) { return this.$$.isBubbleZType(d) ? this.$$.getBubbleZData(d.value, "z") : d.value; }, BubbleCompare; }(Plugin); BubbleCompare.version = "0.0.1"; }(); __webpack_exports__ = __webpack_exports__.default; /******/ return __webpack_exports__; /******/ })() ; });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); require('./reducer-d2994695.js'); require('redux'); require('immer'); require('./Debug-a6563590.js'); require('flatted'); require('./ai-9c3a6356.js'); require('./initialize-8bfbe4ed.js'); var client = require('./client-fb78b9dd.js'); exports.Client = client.Client;
/*! * DevExtreme (dx.aspnet.mvc.js) * Version: 21.1.0 (build 20322-0316) * Build date: Tue Nov 17 2020 * * Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ ! function(factory) { if ("function" === typeof define && define.amd) { define(function(require, exports, module) { module.exports = factory(require("jquery"), require("./core/templates/template_engine_registry").setTemplateEngine, require("./core/templates/template_base").renderedCallbacks, require("./core/guid"), require("./ui/validation_engine"), require("./core/utils/iterator"), require("./core/utils/dom").extractTemplateMarkup, require("./core/utils/string").encodeHtml, require("./core/utils/ajax"), require("./core/utils/console")) }) } else { DevExpress.aspnet = factory(window.jQuery, DevExpress.setTemplateEngine, DevExpress.templateRendered, DevExpress.data.Guid, DevExpress.validationEngine, DevExpress.utils.iterator, DevExpress.utils.dom.extractTemplateMarkup, DevExpress.utils.string.encodeHtml, DevExpress.utils.ajax, DevExpress.utils.console) } }(function($, setTemplateEngine, templateRendered, Guid, validationEngine, iteratorUtils, extractTemplateMarkup, encodeHtml, ajax, console) { var templateCompiler = createTemplateCompiler(); var pendingCreateComponentRoutines = []; var enableAlternativeTemplateTags = true; var warnBug17028 = false; function createTemplateCompiler() { var OPEN_TAG = "<%", CLOSE_TAG = "%>", ENCODE_QUALIFIER = "-", INTERPOLATE_QUALIFIER = "="; var EXTENDED_OPEN_TAG = /[<[]%/g, EXTENDED_CLOSE_TAG = /%[>\]]/g; function acceptText(bag, text) { if (text) { bag.push("_.push(", JSON.stringify(text), ");") } } function acceptCode(bag, code) { var encode = code.charAt(0) === ENCODE_QUALIFIER, value = code.substr(1), interpolate = code.charAt(0) === INTERPOLATE_QUALIFIER; if (encode || interpolate) { bag.push("_.push("); bag.push(encode ? "arguments[1](" + value + ")" : value); bag.push(");") } else { bag.push(code + "\n") } } return function(text) { var bag = ["var _ = [];", "with(obj||{}) {"], chunks = text.split(enableAlternativeTemplateTags ? EXTENDED_OPEN_TAG : OPEN_TAG); if (warnBug17028 && chunks.length > 1) { if (text.indexOf(OPEN_TAG) > -1) { console.logger.warn("Please use an alternative template syntax: https://community.devexpress.com/blogs/aspnet/archive/2020/01/29/asp-net-core-new-syntax-to-fix-razor-issue.aspx"); warnBug17028 = false } } acceptText(bag, chunks.shift()); for (var i = 0; i < chunks.length; i++) { var tmp = chunks[i].split(enableAlternativeTemplateTags ? EXTENDED_CLOSE_TAG : CLOSE_TAG); if (2 !== tmp.length) { throw "Template syntax error" } acceptCode(bag, tmp[0]); acceptText(bag, tmp[1]) } bag.push("}", "return _.join('')"); return new Function("obj", bag.join("")) } } function createTemplateEngine() { return { compile: function(element) { return templateCompiler(extractTemplateMarkup(element)) }, render: function(template, data) { var html = template(data, encodeHtml); var dxMvcExtensionsObj = window.MVCx; if (dxMvcExtensionsObj && !dxMvcExtensionsObj.isDXScriptInitializedOnLoad) { html = html.replace(/(<script[^>]+)id="dxss_.+?"/g, "$1") } return html } } } function getValidationSummary(validationGroup) { var result; $(".dx-validationsummary").each(function(_, element) { var summary = $(element).data("dxValidationSummary"); if (summary && summary.option("validationGroup") === validationGroup) { result = summary; return false } }); return result } function createValidationSummaryItemsFromValidators(validators, editorNames) { var items = []; iteratorUtils.each(validators, function(_, validator) { var widget = validator.$element().data("dx-validation-target"); if (widget && $.inArray(widget.option("name"), editorNames) > -1) { items.push({ text: widget.option("validationError.message"), validator: validator }) } }); return items } function createComponent(name, options, id, validatorOptions) { var selector = "#" + String(id).replace(/[^\w-]/g, "\\$&"); pendingCreateComponentRoutines.push(function() { var $element = $(selector); if ($element.length) { var $component = $(selector)[name](options); if ($.isPlainObject(validatorOptions)) { $component.dxValidator(validatorOptions) } return true } return false }) } templateRendered.add(function() { var snapshot = pendingCreateComponentRoutines.slice(); var leftover = []; pendingCreateComponentRoutines = []; snapshot.forEach(function(func) { if (!func()) { leftover.push(func) } }); pendingCreateComponentRoutines = pendingCreateComponentRoutines.concat(leftover) }); return { createComponent: createComponent, renderComponent: function(name, options, id, validatorOptions) { id = id || "dx-" + new Guid; createComponent(name, options, id, validatorOptions); return '<div id="' + id + '"></div>' }, getEditorValue: function(inputName) { var $widget = $("input[name='" + inputName + "']").closest(".dx-widget"); if ($widget.length) { var dxComponents = $widget.data("dxComponents"), widget = $widget.data(dxComponents[0]); if (widget) { return widget.option("value") } } }, setTemplateEngine: function() { if (setTemplateEngine) { setTemplateEngine(createTemplateEngine()) } }, enableAlternativeTemplateTags: function(value) { enableAlternativeTemplateTags = value }, warnBug17028: function() { warnBug17028 = true }, createValidationSummaryItems: function(validationGroup, editorNames) { var groupConfig, items, summary = getValidationSummary(validationGroup); if (summary) { groupConfig = validationEngine.getGroupConfig(validationGroup); if (groupConfig) { items = createValidationSummaryItemsFromValidators(groupConfig.validators, editorNames); items.length && summary.option("items", items) } } }, sendValidationRequest: function(propertyName, propertyValue, url, method) { var d = $.Deferred(); var data = {}; data[propertyName] = propertyValue; ajax.sendRequest({ url: url, dataType: "json", method: method || "GET", data: data }).then(function(response) { if ("string" === typeof response) { d.resolve({ isValid: false, message: response }) } else { d.resolve(response) } }, function(xhr) { d.reject({ isValid: false, message: xhr.responseText }) }); return d.promise() } } });
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import * as React from 'react'; import ButtonBase from '../ButtonBase'; import ArrowDownwardIcon from '../internal/svg-icons/ArrowDownward'; import styled from '../styles/styled'; import useThemeProps from '../styles/useThemeProps'; import capitalize from '../utils/capitalize'; import tableSortLabelClasses, { getTableSortLabelUtilityClass } from './tableSortLabelClasses'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; var useUtilityClasses = function useUtilityClasses(ownerState) { var classes = ownerState.classes, direction = ownerState.direction, active = ownerState.active; var slots = { root: ['root', active && 'active'], icon: ['icon', "iconDirection".concat(capitalize(direction))] }; return composeClasses(slots, getTableSortLabelUtilityClass, classes); }; var TableSortLabelRoot = styled(ButtonBase, { name: 'MuiTableSortLabel', slot: 'Root', overridesResolver: function overridesResolver(props, styles) { var ownerState = props.ownerState; return [styles.root, ownerState.active && styles.active]; } })(function (_ref) { var theme = _ref.theme; return _defineProperty({ cursor: 'pointer', display: 'inline-flex', justifyContent: 'flex-start', flexDirection: 'inherit', alignItems: 'center', '&:focus': { color: theme.palette.text.secondary }, '&:hover': _defineProperty({ color: theme.palette.text.secondary }, "& .".concat(tableSortLabelClasses.icon), { opacity: 0.5 }) }, "&.".concat(tableSortLabelClasses.active), _defineProperty({ color: theme.palette.text.primary }, "& .".concat(tableSortLabelClasses.icon), { opacity: 1, color: theme.palette.text.secondary })); }); var TableSortLabelIcon = styled('span', { name: 'MuiTableSortLabel', slot: 'Icon', overridesResolver: function overridesResolver(props, styles) { var ownerState = props.ownerState; return [styles.icon, styles["iconDirection".concat(capitalize(ownerState.direction))]]; } })(function (_ref3) { var theme = _ref3.theme, ownerState = _ref3.ownerState; return _extends({ fontSize: 18, marginRight: 4, marginLeft: 4, opacity: 0, transition: theme.transitions.create(['opacity', 'transform'], { duration: theme.transitions.duration.shorter }), userSelect: 'none' }, ownerState.direction === 'desc' && { transform: 'rotate(0deg)' }, ownerState.direction === 'asc' && { transform: 'rotate(180deg)' }); }); /** * A button based label for placing inside `TableCell` for column sorting. */ var TableSortLabel = /*#__PURE__*/React.forwardRef(function TableSortLabel(inProps, ref) { var props = useThemeProps({ props: inProps, name: 'MuiTableSortLabel' }); var _props$active = props.active, active = _props$active === void 0 ? false : _props$active, children = props.children, className = props.className, _props$direction = props.direction, direction = _props$direction === void 0 ? 'asc' : _props$direction, _props$hideSortIcon = props.hideSortIcon, hideSortIcon = _props$hideSortIcon === void 0 ? false : _props$hideSortIcon, _props$IconComponent = props.IconComponent, IconComponent = _props$IconComponent === void 0 ? ArrowDownwardIcon : _props$IconComponent, other = _objectWithoutProperties(props, ["active", "children", "className", "direction", "hideSortIcon", "IconComponent"]); var ownerState = _extends({}, props, { active: active, direction: direction, hideSortIcon: hideSortIcon, IconComponent: IconComponent }); var classes = useUtilityClasses(ownerState); return /*#__PURE__*/_jsxs(TableSortLabelRoot, _extends({ className: clsx(classes.root, className), component: "span", disableRipple: true, ownerState: ownerState, ref: ref }, other, { children: [children, hideSortIcon && !active ? null : /*#__PURE__*/_jsx(TableSortLabelIcon, { as: IconComponent, className: clsx(classes.icon), ownerState: ownerState })] })); }); process.env.NODE_ENV !== "production" ? TableSortLabel.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, the label will have the active styling (should be true for the sorted column). * @default false */ active: PropTypes.bool, /** * Label contents, the arrow will be appended automatically. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The current sort direction. * @default 'asc' */ direction: PropTypes.oneOf(['asc', 'desc']), /** * Hide sort icon when active is false. * @default false */ hideSortIcon: PropTypes.bool, /** * Sort icon to use. * @default ArrowDownwardIcon */ IconComponent: PropTypes.elementType, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object } : void 0; export default TableSortLabel;
// simple echo action var bole = require('bole'), stream = require('stream'), util = require('util') ; var EchoRule = module.exports = function EchoRule() { stream.Writable.call(this, { objectMode: true }); this.logger = bole('echo'); }; util.inherits(EchoRule, stream.Writable); EchoRule.prototype._write = function _write(event, encoding, callback) { this.logger.info('event', event); callback(); };
import acid from '../namespace/index'; import { assign } from '../internal/object'; import { hasValue } from '../internal/is'; import { toPath } from '../utility/toPath'; import { whileArray } from '../array/each'; /** * Returns property on an object. * * @function get * @category utility * @type {Function} * @param {string} propertyString - String used to retrieve properties. * @param {Object} objectChain - Object which has a property retrieved from it. * @returns {Object} - Returns property from the given object. * * @example * get('post.like[2]', { * post: { * like: ['a','b','c'] * } * }); * // => 'c' */ export const get = (propertyString, objectChain = acid) => { let link = objectChain; whileArray(toPath(propertyString), (item) => { link = link[item]; return hasValue(link); }); return link; }; assign(acid, { get });
var app = require('express')(), wizard = require('hmpo-form-wizard'), steps = require('./steps'), fields = require('./fields'); app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' })); app.use(wizard(steps, fields, { templatePath: 'priority_service_170202/photoguide-myself' })); module.exports = app;
pc.extend(pc, function () { /** * @name pc.ComponentSystem * @class Component Systems contain the logic and functionality to update all Components of a particular type * @param {pc.Application} app The running Application */ var ComponentSystem = function (app) { this.app = app; this.dataStore = {}; this.schema = []; pc.events.attach(this); }; // Class methods pc.extend(ComponentSystem, { initialize: function (root) { ComponentSystem.fire('initialize', root); }, postInitialize: function (root) { ComponentSystem.fire('postInitialize', root); }, /** * Update all ComponentSystems */ update: function (dt, inTools) { if (inTools) { ComponentSystem.fire('toolsUpdate', dt); } else { ComponentSystem.fire('update', dt); } }, /** * Update all ComponentSystems */ fixedUpdate: function (dt, inTools) { ComponentSystem.fire('fixedUpdate', dt); }, /** * Update all ComponentSystems */ postUpdate: function (dt, inTools) { ComponentSystem.fire('postUpdate', dt); } }); // Instance methods ComponentSystem.prototype = { /** * @private * @field * @type Array * @name pc.ComponentSystem#store * @description The store where all {@link pc.ComponentData} objects are kept */ get store() { return this.dataStore; }, /** * @private * @function * @name pc.ComponentSystem#addComponent * @description Create new {@link pc.Component} and {@link pc.ComponentData} instances and attach them to the entity * @param {pc.Entity} entity The Entity to attach this component to * @param {Object} data The source data with which to create the component * @returns {pc.Component} Returns a Component of type defined by the component system * @example * var entity = new pc.Entity(app); * app.systems.model.addComponent(entity, { type: 'box' }); * // entity.model is now set to a pc.ModelComponent */ addComponent: function (entity, data) { var component = new this.ComponentType(this, entity); var componentData = new this.DataType(); data = data || {}; this.dataStore[entity._guid] = { entity: entity, data: componentData }; entity[this.id] = component; entity.c[this.id] = component; this.initializeComponentData(component, data, []); this.fire('add', entity, component); return component; }, /** * @private * @function * @name pc.ComponentSystem#removeComponent * @description Remove the {@link pc.Component} from the entity and delete the associated {@link pc.ComponentData} * @param {pc.Entity} entity The entity to remove the component from * @example * app.systems.model.removeComponent(entity); * // entity.model === undefined */ removeComponent: function (entity) { var record = this.dataStore[entity._guid]; var component = entity.c[this.id]; this.fire('beforeremove', entity, component); delete this.dataStore[entity._guid]; delete entity[this.id]; delete entity.c[this.id]; this.fire('remove', entity, record.data); }, /** * @private * @function * @name pc.ComponentSystem#cloneComponent * @description Create a clone of component. This creates a copy all ComponentData variables. * @param {pc.Entity} entity The entity to clone the component from * @param {pc.Entity} clone The entity to clone the component into */ cloneComponent: function (entity, clone) { // default clone is just to add a new component with existing data var src = this.dataStore[entity._guid]; return this.addComponent(clone, src.data); }, /** * @private * @function * @name pc.ComponentSystem#initializeComponentData * @description Called during {@link pc.ComponentSystem#addComponent} to initialize the {@link pc.ComponentData} in the store * This can be overridden by derived Component Systems and either called by the derived System or replaced entirely */ initializeComponentData: function (component, data, properties) { data = data || {}; // initialize properties.forEach(function(value) { if (data[value] !== undefined) { component[value] = data[value]; } else { component[value] = component.data[value]; } }, this); // after component is initialized call onEnable if (component.enabled && component.entity.enabled) { component.onEnable(); } } }; // Add event support pc.events.attach(ComponentSystem); ComponentSystem.destroy = function () { ComponentSystem.off('initialize'); ComponentSystem.off('postInitialize'); ComponentSystem.off('toolsUpdate'); ComponentSystem.off('update'); ComponentSystem.off('fixedUpdate'); ComponentSystem.off('postUpdate'); }; return { ComponentSystem: ComponentSystem }; }());
{ Vue.prototype._init = function(options) { var vm = this; vm._uid = uid++; var startTag, endTag; if (process.env.NODE_ENV !== "production" && config.performance && mark) { startTag = "vue-perf-init:" + vm._uid; endTag = "vue-perf-end:" + vm._uid; mark(startTag); } vm._isVue = true; if (options && options._isComponent) { initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } if (process.env.NODE_ENV !== "production") { initProxy(vm); } else { vm._renderProxy = vm; } vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, "beforeCreate"); initInjections(vm); initState(vm); initProvide(vm); callHook(vm, "created"); if (process.env.NODE_ENV !== "production" && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(vm._name + " init", startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; }
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var abstract_1 = require("./abstract"); var ReferenceType = (function (_super) { __extends(ReferenceType, _super); function ReferenceType(name, symbolID, reflection) { _super.call(this); this.name = name; this.symbolID = symbolID; this.reflection = reflection; } ReferenceType.prototype.clone = function () { var clone = new ReferenceType(this.name, this.symbolID, this.reflection); clone.isArray = this.isArray; clone.typeArguments = this.typeArguments; return clone; }; ReferenceType.prototype.equals = function (type) { return type instanceof ReferenceType && type.isArray == this.isArray && (type.symbolID == this.symbolID || type.reflection == this.reflection); }; ReferenceType.prototype.toObject = function () { var result = _super.prototype.toObject.call(this); result.type = 'reference'; result.name = this.name; if (this.reflection) { result.id = this.reflection.id; } if (this.typeArguments) { result.typeArguments = this.typeArguments.map(function (t) { return t.toObject(); }); } return result; }; ReferenceType.prototype.toString = function () { if (this.reflection) { return this.reflection.name + (this.isArray ? '[]' : ''); } else { return this.name + (this.isArray ? '[]' : ''); } }; ReferenceType.SYMBOL_ID_RESOLVED = -1; ReferenceType.SYMBOL_ID_RESOLVE_BY_NAME = -2; return ReferenceType; }(abstract_1.Type)); exports.ReferenceType = ReferenceType;
module.exports={A:{A:{"2":"K C G E B A WB"},B:{"2":"D u Y I M H"},C:{"2":"0 1 2 3 5 6 7 UB z F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v g SB RB"},D:{"1":"0 1 2 3 5 6 7 h i j k l m n o p q r s t y v g GB BB DB VB EB","2":"F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L"},E:{"2":"F J K C G E B A FB AB HB IB JB KB LB MB"},F:{"1":"b c d e f L h i j k l m n o p q r s t","2":"8 9 E A D I M H N O P Q R S T U V W X w Z a NB OB PB QB TB x"},G:{"2":"4 G A AB CB XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"2":"4 z F v gB hB iB jB kB lB"},J:{"2":"C B"},K:{"1":"L","2":"8 9 B A D x"},L:{"1":"BB"},M:{"2":"g"},N:{"2":"B A"},O:{"2":"mB"},P:{"1":"F J"},Q:{"1":"nB"},R:{"1":"oB"}},B:5,C:"Web App Manifest"};
import React from 'react'; import {Icon, Popup} from "semantic-ui-react"; export class IconButton extends React.Component{ render() { const icon = ( <Icon circular inverted disabled={this.props.disabled} name={this.props.name} link={!this.props.disabled} color={this.props.color} onClick={this.props.onClick} /> ); return ( <Popup trigger={icon} content={this.props.tooltip} size="tiny" inverted /> ); } }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 6c-3.87 0-7 3.13-7 7s3.13 7 7 7 7-3.13 7-7-3.13-7-7-7zm0 1c.46 0 .9.06 1.33.15l-2.72 4.7-2.32-3.56C9.31 7.49 10.6 7 12 7zm-6 6c0-1.54.59-2.95 1.55-4.01L10.81 14H6.09c-.05-.33-.09-.66-.09-1zm.35 2h5.33l-2.03 3.5.11.06c-1.59-.64-2.84-1.94-3.41-3.56zM12 19c-.48 0-.94-.06-1.39-.17l2.85-4.92 2.11 3.9c-1 .74-2.23 1.19-3.57 1.19zm6-6c0 1.6-.63 3.06-1.66 4.13L13.57 12h4.34c.05.33.09.66.09 1zm-5.74-2 2.05-3.54c1.56.65 2.77 1.94 3.34 3.54h-5.39z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M7.55 8.99C6.59 10.05 6 11.46 6 13c0 .34.04.67.09 1h4.72L7.55 8.99zm6.76-1.53L12.26 11h5.39c-.57-1.6-1.78-2.89-3.34-3.54zm-.98-.31C12.9 7.06 12.46 7 12 7c-1.4 0-2.69.49-3.71 1.29l2.32 3.56 2.72-4.7zM11.68 15H6.35c.57 1.62 1.82 2.92 3.41 3.56l-.11-.06 2.03-3.5zm7.35-7.61 1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zM9 1h6v2H9zm7.34 16.13C17.37 16.06 18 14.6 18 13c0-.34-.04-.67-.09-1h-4.34l2.77 5.13zm-5.73 1.7c.45.11.91.17 1.39.17 1.34 0 2.57-.45 3.57-1.19l-2.11-3.9-2.85 4.92z" }, "1")], 'ShutterSpeedTwoTone'); exports.default = _default;
var searchData= [ ['kinematics',['Kinematics',['../classrobotis__manipulator_1_1_kinematics.html#a3d08da271bc5cce3cafa2d331277cc5d',1,'robotis_manipulator::Kinematics']]] ];
const ipcRenderer = require('electron').ipcRenderer; const CallbacksRegistry = require('electron').CallbacksRegistry; const v8Util = process.atomBinding('v8_util'); const callbacksRegistry = new CallbacksRegistry; var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; // Check for circular reference. var isCircular = function(field, visited) { if (typeof field === 'object') { if (indexOf.call(visited, field) >= 0) { return true; } visited.push(field); } return false; }; // Convert the arguments object into an array of meta data. var wrapArgs = function(args, visited) { var valueToMeta; if (visited == null) { visited = []; } valueToMeta = function(value) { var field, prop, ret; if (Array.isArray(value)) { return { type: 'array', value: wrapArgs(value, visited) }; } else if (Buffer.isBuffer(value)) { return { type: 'buffer', value: Array.prototype.slice.call(value, 0) }; } else if (value instanceof Date) { return { type: 'date', value: value.getTime() }; } else if ((value != null ? value.constructor.name : void 0) === 'Promise') { return { type: 'promise', then: valueToMeta(value.then.bind(value)) }; } else if ((value != null) && typeof value === 'object' && v8Util.getHiddenValue(value, 'atomId')) { return { type: 'remote-object', id: v8Util.getHiddenValue(value, 'atomId') }; } else if ((value != null) && typeof value === 'object') { ret = { type: 'object', name: value.constructor.name, members: [] }; for (prop in value) { field = value[prop]; ret.members.push({ name: prop, value: valueToMeta(isCircular(field, visited) ? null : field) }); } return ret; } else if (typeof value === 'function' && v8Util.getHiddenValue(value, 'returnValue')) { return { type: 'function-with-return-value', value: valueToMeta(value()) }; } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: v8Util.getHiddenValue(value, 'location') }; } else { return { type: 'value', value: value }; } }; return Array.prototype.slice.call(args).map(valueToMeta); }; // Convert meta data from browser into real value. var metaToValue = function(meta) { var RemoteFunction, el, i, j, len, len1, member, ref1, ref2, results, ret; switch (meta.type) { case 'value': return meta.value; case 'array': ref1 = meta.members; results = []; for (i = 0, len = ref1.length; i < len; i++) { el = ref1[i]; results.push(metaToValue(el)); } return results; case 'buffer': return new Buffer(meta.value); case 'promise': return Promise.resolve({ then: metaToValue(meta.then) }); case 'error': return metaToPlainObject(meta); case 'date': return new Date(meta.value); case 'exception': throw new Error(meta.message + "\n" + meta.stack); break; default: if (meta.type === 'function') { // A shadow class to represent the remote function object. ret = RemoteFunction = (function() { function RemoteFunction() { var obj; if (this.constructor === RemoteFunction) { // Constructor call. obj = ipcRenderer.sendSync('ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)); /* Returning object in constructor will replace constructed object with the returned object. http://stackoverflow.com/questions/1978049/what-values-can-a-constructor-return-to-avoid-returning-this */ return metaToValue(obj); } else { // Function call. obj = ipcRenderer.sendSync('ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)); return metaToValue(obj); } } return RemoteFunction; })(); } else { ret = v8Util.createObjectWithName(meta.name); } // Polulate delegate members. ref2 = meta.members; for (j = 0, len1 = ref2.length; j < len1; j++) { member = ref2[j]; if (member.type === 'function') { ret[member.name] = createRemoteMemberFunction(meta.id, member.name); } else { Object.defineProperty(ret, member.name, createRemoteMemberProperty(meta.id, member.name)); } } // Track delegate object's life time, and tell the browser to clean up // when the object is GCed. v8Util.setDestructor(ret, function() { return ipcRenderer.send('ATOM_BROWSER_DEREFERENCE', meta.id); }); // Remember object's id. v8Util.setHiddenValue(ret, 'atomId', meta.id); return ret; } }; // Construct a plain object from the meta. var metaToPlainObject = function(meta) { var i, len, name, obj, ref1, ref2, value; obj = (function() { switch (meta.type) { case 'error': return new Error; default: return {}; } })(); ref1 = meta.members; for (i = 0, len = ref1.length; i < len; i++) { ref2 = ref1[i], name = ref2.name, value = ref2.value; obj[name] = value; } return obj; }; // Create a RemoteMemberFunction instance. // This function's content should not be inlined into metaToValue, otherwise V8 // may consider it circular reference. var createRemoteMemberFunction = function(metaId, name) { var RemoteMemberFunction; return RemoteMemberFunction = (function() { function RemoteMemberFunction() { var ret; if (this.constructor === RemoteMemberFunction) { // Constructor call. ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CONSTRUCTOR', metaId, name, wrapArgs(arguments)); return metaToValue(ret); } else { // Call member function. ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CALL', metaId, name, wrapArgs(arguments)); return metaToValue(ret); } } return RemoteMemberFunction; })(); }; // Create configuration for defineProperty. // This function's content should not be inlined into metaToValue, otherwise V8 // may consider it circular reference. var createRemoteMemberProperty = function(metaId, name) { return { enumerable: true, configurable: false, set: function(value) { // Set member data. ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_SET', metaId, name, value); return value; }, get: function() { // Get member data. return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, name)); } }; }; // Browser calls a callback in renderer. ipcRenderer.on('ATOM_RENDERER_CALLBACK', function(event, id, args) { return callbacksRegistry.apply(id, metaToValue(args)); }); // A callback in browser is released. ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function(event, id) { return callbacksRegistry.remove(id); }); // List all built-in modules in browser process. const browserModules = require('../../../browser/api/lib/exports/electron'); // And add a helper receiver for each one. var fn = function(name) { return Object.defineProperty(exports, name, { get: function() { return exports.getBuiltin(name); } }); }; for (var name in browserModules) { fn(name); } // Get remote module. // (Just like node's require, the modules are cached permanently, note that this // is safe leak since the object is not expected to get freed in browser) var moduleCache = {}; exports.require = function(module) { var meta; if (moduleCache[module] != null) { return moduleCache[module]; } meta = ipcRenderer.sendSync('ATOM_BROWSER_REQUIRE', module); return moduleCache[module] = metaToValue(meta); }; // Optimize require('electron'). moduleCache.electron = exports; // Alias to remote.require('electron').xxx. var builtinCache = {}; exports.getBuiltin = function(module) { var meta; if (builtinCache[module] != null) { return builtinCache[module]; } meta = ipcRenderer.sendSync('ATOM_BROWSER_GET_BUILTIN', module); return builtinCache[module] = metaToValue(meta); }; // Get current BrowserWindow object. var windowCache = null; exports.getCurrentWindow = function() { var meta; if (windowCache != null) { return windowCache; } meta = ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WINDOW'); return windowCache = metaToValue(meta); }; // Get current WebContents object. var webContentsCache = null; exports.getCurrentWebContents = function() { var meta; if (webContentsCache != null) { return webContentsCache; } meta = ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WEB_CONTENTS'); return webContentsCache = metaToValue(meta); }; // Get a global object in browser. exports.getGlobal = function(name) { var meta; meta = ipcRenderer.sendSync('ATOM_BROWSER_GLOBAL', name); return metaToValue(meta); }; // Get the process object in browser. var processCache = null; exports.__defineGetter__('process', function() { if (processCache == null) { processCache = exports.getGlobal('process'); } return processCache; }); // Create a funtion that will return the specifed value when called in browser. exports.createFunctionWithReturnValue = function(returnValue) { var func; func = function() { return returnValue; }; v8Util.setHiddenValue(func, 'returnValue', true); return func; }; // Get the guest WebContents from guestInstanceId. exports.getGuestWebContents = function(guestInstanceId) { var meta; meta = ipcRenderer.sendSync('ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId); return metaToValue(meta); };
/* * @require ../../server/author.js */ /************ vue ************/ var imgAlipay = __inline('../public/yhklogo.png'); var imgArrowRight = __inline('../public/arrow.png'); var imgCard = __inline('../public/zfblogo.png'); var imgEmpty = __inline('../public/konglogo.png'); var imgLogo = __inline('../public/jbylogo_58px.png'); var imgWechat = __inline('../public/wxlogo.png'); var yhtml5Data = { appId: 000001, imgLogo: imgLogo, imgEmpty: imgEmpty, imgArrowRight: imgArrowRight, name: '测试商品', money: '$55.00', channels: [ { img: imgAlipay, name: '支付宝', text: '推荐支付宝用户' }, { img: imgWechat, name: '微信', text: '推荐微信用户' }, { img: imgCard, name: '信用卡', text: '推荐使用信用卡' } ], copyright: '该服务由聚宝云计费提供', tel: '如果支付问题请拨打 0571-86800282' } var yhtml5VM = new Vue({ el: '#yhtml5', data: yhtml5Data, methods: { openChannel: function (index) { console.log(index) console.log(yhtml5Data.channels[index].name) }, isList: function isList() { if (yhtml5Data.channels === '') { yhtml5Data.isList = false } else { yhtml5Data.isList = true } return isList }, } }); yhtml5VM.isList()
/** * define content script namespace * @type {Object} */ window.Inspect3js = window.Inspect3js || {} ////////////////////////////////////////////////////////////////////////////////// // Comments ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // Comments ////////////////////////////////////////////////////////////////////////////////// /** * Change a property in a object - called from devtool panel * * @param {String} id - object uid * @param {String} data - property name e.g. "position.x" */ Inspect3js.ChangeProperty = function( object3dUUID, data ) { // console.log('ChangeProperty', data.property, 'to', data.value) var object3d = Inspect3js._objectsCache[ object3dUUID ]; var curObject = object3d; var fields = data.property.split( '.' ); for( var fieldIndex = 0; fieldIndex < fields.length; fieldIndex++ ) { var fieldName = fields[fieldIndex] var matchArray = fieldName.match(/(.*)\[(\d+)\]/) if( matchArray !== null ){ var indexInArray = matchArray === null ? -1 : parseInt(matchArray[2], 10) fieldName = matchArray[1] }else{ var indexInArray = -1 } if( fieldIndex === fields.length - 1 ) { if( indexInArray === -1 ) curObject[ fieldName ] = data.value; else curObject[ fieldName ][indexInArray] = data.value; } else { if( indexInArray === -1 ) curObject = curObject[ fieldName ]; else curObject = curObject[ fieldName ][indexInArray]; } } } /** * Call a function on a object3d * * @param {String} object3dUUID - object uid * @param {Function} fct - the function to call * @param {Array} data - the parameters to send to function */ Inspect3js.ChangeObject3dFunction = function( object3dUUID, fct, args ) { // console.log('ChangeObject3dFunction', fct.toString(), args) var object3d = Inspect3js._objectsCache[ object3dUUID ]; console.assert(object3d instanceof THREE.Object3D) var newArgs = args.slice(0) newArgs.unshift(object3d); fct.apply(null, newArgs) }
var request = require('../../'); var setup = require('../support/setup'); var base = setup.uri; var fs = require('fs'); describe('pipe on redirect', function () { var destPath = 'test/node/fixtures/pipe.txt'; after(function removeTmpfile(done) { fs.unlink(destPath, done); }); it('should follow Location', function (done) { var stream = fs.createWriteStream(destPath); var redirects = []; var req = request .get(base) .on('redirect', function (res) { redirects.push(res.headers.location); }) stream.on('finish', function () { redirects.should.eql(['/movies', '/movies/all', '/movies/all/0']); fs.readFileSync(destPath, 'utf8').should.eql('first movie page'); done(); }); req.pipe(stream); }); });
function basetext(widget_id, url, skin, parameters) { // Will be using "self" throughout for the various flavors of "this" // so for consistency ... self = this; // Initialization self.widget_id = widget_id; // Store on brightness or fallback to a default // Parameters may come in useful later on self.parameters = parameters; self.OnChange = OnChange; var callbacks = [ {"observable": "TextValue", "action": "change", "callback": self.OnChange}, ]; // Define callbacks for entities - this model allows a widget to monitor multiple entities if needed // Initial will be called when the dashboard loads and state has been gathered for the entity // Update will be called every time an update occurs for that entity self.OnStateAvailable = OnStateAvailable; self.OnStateUpdate = OnStateUpdate; if ("entity" in parameters) { var monitored_entities = [ {"entity": parameters.entity, "initial": self.OnStateAvailable, "update": self.OnStateUpdate} ] } else { var monitored_entities = [] } // Finally, call the parent constructor to get things moving WidgetBase.call(self, widget_id, url, skin, parameters, monitored_entities, callbacks); // Function Definitions // The StateAvailable function will be called when // self.state[<entity>] has valid information for the requested entity // state is the initial state // Methods function OnChange(self, state) { if (self.state != self.ViewModel.TextValue()) { self.state = self.ViewModel.TextValue() args = self.parameters.post_service args["value"] = self.state self.call_service(self, args) } } function OnStateAvailable(self, state) { set_value(self, state) } function OnStateUpdate(self, state) { set_value(self, state) } function set_value(self, state) { value = self.map_state(self, state.state) self.set_field(self, "TextValue", value) } }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15l1-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15l1-2H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3l-1 2h4.06c-.04.33-.06.66-.06 1s.02.67.06 1H3l-1 2h4.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z" }), 'EuroSharp'); exports.default = _default;
module.exports = { demoTest: function (client) { client.url('http://localhost') .assert.elementPresent('#weblogin') .end(); }, afterEach: function(client, done) { } };
require([ 'gitbook' ], function(gitbook) { gitbook.events.on('start', function(e, config) { $('.fancybox').fancybox($.extend({ 'loop': false, 'afterLoad' : function() { this.title = (this.index + 1) + '/' + this.group.length + (this.title ? ' - ' + this.title : ''); } },config.fancybox)); }); });
"use strict"; var p = require('./modules/utils.js').prettyPrint; var Tcp = require('./modules/classes.js').Tcp; var server, socket, client; function Server(host, port) { Tcp.call(this); p("server", this); this.bind(host, port); this.listen(128, this.onConnection); } Server.prototype.__proto__ = Tcp.prototype; Server.prototype.onConnection = function onConnection(err) { assert(this === server); if (err) { throw err; } p("server.onconnection"); socket = new ClientHandler(this); p("server.accept", socket); this.accept(socket); p("socket.readStart"); socket.readStart(socket.onRead); }; function ClientHandler(server) { Tcp.call(this); p("socket", this); this.server = server; } ClientHandler.prototype.__proto__ = Tcp.prototype; ClientHandler.prototype.onRead = function onRead(err, data) { assert(this === socket); if (err) { throw err; } p("socket.onread", data); if (data) { p("socket.write", data); this.write(data); } else { p("socket.shutdown"); this.shutdown(); p("socket.readStop"); this.readStop(); p("socket.close"); this.close(); p("server.close"); this.server.close(); } }; function Client(host, port) { Tcp.call(this); p("client", this); p("client.connect"); this.connect(host, port, this.onConnect); } Client.prototype.__proto__ = Tcp.prototype; Client.prototype.onConnect = function onConnect(err) { assert(this === client); if (err) { throw err; } this.readStart(this.onRead); var buffer = Duktape.Buffer(3); buffer[0] = 0x10; buffer[1] = 0x00; buffer[2] = 0x50; p("client.write", buffer); this.write(buffer); p("client.write", "A \0 B"); this.write("A \0 B", this.onWrite); }; Client.prototype.onRead = function onRead(err, data) { assert(this === client); if (err) { throw err; } p("client.onread", data); if (data) { p("client.shutdown"); this.shutdown(); } else { p("client.close"); this.close(); } }; Client.prototype.onWrite = function onWrite(err) { assert(this === client); if (err) { throw err; } p("client.onwrite"); }; server = new Server("127.0.0.1", 1337); client = new Client("127.0.0.1", 1337); function assert(cond, message) { if (!cond) { throw new Error(message || "Assertion Failure"); } }
var searchData= [ ['id',['id',['../structrobotis__manipulator_1_1_joint_constant.html#ac4e09e4e2886029c58d6f727e9b1e274',1,'robotis_manipulator::JointConstant']]], ['inertia',['inertia',['../structrobotis__manipulator_1_1_relative.html#ad761bd6e74a48a22dedb93feed45f5db',1,'robotis_manipulator::Relative']]], ['inertia_5ftensor',['inertia_tensor',['../structrobotis__manipulator_1_1_inertia.html#a61b16b0ad0ac7366fe046b946c04c97e',1,'robotis_manipulator::Inertia']]] ];
lychee.define('fertilizer.event.flow.html.Build').includes([ 'fertilizer.event.Flow' ]).exports((lychee, global, attachments) => { const _Flow = lychee.import('fertilizer.event.Flow'); const _INDEX = { application: attachments['index.html'], library: attachments['index.js'] }; const _META = { application: attachments['index.appcache'], library: attachments['package.json'] }; /* * HELPERS */ const _build_index = function(variant, stuff) { stuff = stuff instanceof Stuff ? stuff : null; if (stuff !== null) { let code = stuff.buffer.toString('utf8'); if (code.includes('${blob}') === false) { code = _INDEX[variant].buffer.toString('utf8'); } let env = this.__environment; if (env !== null) { let lines = code.split('\n'); let blob = JSON.stringify(env.serialize(), null, '\t'); let blob_line = lines.find(line => line.includes('${blob}')) || null; if (blob_line !== null) { let indent = blob_line.substr(0, blob_line.indexOf(blob_line.trim())); if (indent !== '') { blob = blob.split('\n').map((line, l) => { return l === 0 ? line : indent + line; }).join('\n'); } } let profile = JSON.stringify(this.__profile, null, '\t'); let profile_line = lines.find(line => line.includes('{$profile}')) || null; if (profile_line !== null) { let indent = profile_line.substr(0, profile_line.indexOf(profile_line.trim())); if (indent !== '') { profile = profile.split('\n').map((line, l) => { return l === 0 ? line : indent + line; }).join('\n'); } } stuff.buffer = Buffer.from(code.replaceObject({ id: env.id, blob: blob, profile: profile }), 'utf8'); } } }; const _build_meta = function(variant, asset) { if (variant === 'application') { // XXX: Nothing to do } else if (variant === 'library') { let buffer = asset.buffer; if (buffer instanceof Object) { let env = this.__environment; if (env !== null) { asset.buffer = JSON.parse(JSON.stringify(buffer).replaceObject({ id: env.id })); } } } }; const _create_index = function(variant) { let template = null; if (variant === 'application') { template = lychee.serialize(_INDEX.application); } else if (variant === 'library') { template = lychee.serialize(_INDEX.library); } if (template !== null) { let asset = lychee.deserialize(template); if (asset !== null) { let base = asset.url.split('/').pop(); let name = base.split('.').slice(1).join('.'); asset.url = './' + name; } return asset; } return null; }; const _create_meta = function(variant) { let template = null; if (variant === 'application') { template = lychee.serialize(_META.application); } else if (variant === 'library') { template = lychee.serialize(_META.library); } if (template !== null) { let asset = lychee.deserialize(template); if (asset !== null) { let base = asset.url.split('/').pop(); let name = base.split('.').slice(1).join('.'); asset.url = './' + name; } return asset; } return null; }; /* * IMPLEMENTATION */ const Composite = function(data) { let states = Object.assign({}, data); _Flow.call(this, states); states = null; /* * INITIALIZATION */ this.unbind('build-assets'); this.bind('build-assets', function(oncomplete) { let action = this.action; let project = this.project; if (action !== null && project !== null) { console.log('fertilizer: ' + action + '/BUILD-ASSETS "' + project + '"'); let env = this.__environment; if (env !== null) { let base_index = '*'; let base_meta = '*'; let variant = env.variant; if (variant === 'application') { base_index = 'index.html'; base_meta = 'index.appcache'; } else if (variant === 'library') { base_index = 'index.js'; base_meta = 'package.json'; } let meta = this.assets.find(asset => asset.url.endsWith('/' + base_meta)) || null; if (meta === null || meta.buffer === null) { meta = _create_meta.call(this, variant); _build_meta.call(this, variant, meta); this.assets.push(meta); } else { _build_meta.call(this, variant, meta); } let index = this.assets.find(asset => asset.url.endsWith('/' + base_index)) || null; if (index === null || index.buffer === null) { index = _create_index.call(this, variant); _build_index.call(this, variant, index); this.assets.push(index); } else { _build_index.call(this, variant, index); } oncomplete(true); } else { oncomplete(false); } } else { oncomplete(true); } }, this); /* * FLOW */ // this.then('configure-project'); this.then('read-package'); this.then('read-assets'); this.then('read-assets-crux'); this.then('build-environment'); this.then('build-assets'); this.then('write-assets'); this.then('build-project'); // this.then('package-runtime'); // this.then('package-project'); // this.then('publish-project'); }; Composite.prototype = { // deserialize: function(blob) {}, serialize: function() { let data = _Flow.prototype.serialize.call(this); data['constructor'] = 'fertilizer.event.flow.html.Build'; return data; } }; return Composite; });
/* global $ */ $(() => { "use strict"; var $qanda = $(".js-q-and-a"); var url = "http://localhost:8000/5614e8bded37eded3f16a9e6"; fetch(url).then((response) => { response.json().then((resp) => { if (!resp._embedded || !resp._embedded["hack:questions"] || !resp._embedded["hack:questions"].length) { throw new Error("Unable to find questions!"); } let questions = resp._embedded["hack:questions"]; $qanda.html(""); questions.forEach((q) => { if (!q._embedded || !q._embedded["hack:answers"] || !q._embedded["hack:answers"].length) { return; // skip, no answers yet for this question } let answers = q._embedded["hack:answers"].reduce((i, answer) => { return `${i} <li class="question--answer">${answer.answer}</li>`; }, ""); $qanda.append(` <div class="question"> <h4 class="question--title">${q.question}</h4> <div class="question--info"> <span>on ${q.createdAt}</span> | <span>Upvotes: ${q.positive}</span> </div> <ul>${answers}</ul> </div> `); }); }); }); });
YUI.add('yui2-logger', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0pr1 */ /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * The LogMsg class defines a single log message. * * @class LogMsg * @constructor * @param oConfigs {Object} Object literal of configuration params. */ YAHOO.widget.LogMsg = function(oConfigs) { // Parse configs /** * Log message. * * @property msg * @type String */ this.msg = /** * Log timestamp. * * @property time * @type Date */ this.time = /** * Log category. * * @property category * @type String */ this.category = /** * Log source. The first word passed in as the source argument. * * @property source * @type String */ this.source = /** * Log source detail. The remainder of the string passed in as the source argument, not * including the first word (if any). * * @property sourceDetail * @type String */ this.sourceDetail = null; if (oConfigs && (oConfigs.constructor == Object)) { for(var param in oConfigs) { if (oConfigs.hasOwnProperty(param)) { this[param] = oConfigs[param]; } } } }; /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * The LogWriter class provides a mechanism to log messages through * YAHOO.widget.Logger from a named source. * * @class LogWriter * @constructor * @param sSource {String} Source of LogWriter instance. */ YAHOO.widget.LogWriter = function(sSource) { if(!sSource) { YAHOO.log("Could not instantiate LogWriter due to invalid source.", "error", "LogWriter"); return; } this._source = sSource; }; ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the LogWriter instance. * * @method toString * @return {String} Unique name of the LogWriter instance. */ YAHOO.widget.LogWriter.prototype.toString = function() { return "LogWriter " + this._sSource; }; /** * Logs a message attached to the source of the LogWriter. * Note: the LogReader adds the message and category to the DOM as HTML. * * @method log * @param sMsg {HTML} The log message. * @param sCategory {HTML} Category name. */ YAHOO.widget.LogWriter.prototype.log = function(sMsg, sCategory) { YAHOO.widget.Logger.log(sMsg, sCategory, this._source); }; /** * Public accessor to get the source name. * * @method getSource * @return {String} The LogWriter source. */ YAHOO.widget.LogWriter.prototype.getSource = function() { return this._source; }; /** * Public accessor to set the source name. * * @method setSource * @param sSource {String} Source of LogWriter instance. */ YAHOO.widget.LogWriter.prototype.setSource = function(sSource) { if(!sSource) { YAHOO.log("Could not set source due to invalid source.", "error", this.toString()); return; } else { this._source = sSource; } }; ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Source of the LogWriter instance. * * @property _source * @type String * @private */ YAHOO.widget.LogWriter.prototype._source = null; /** * The Logger widget provides a simple way to read or write log messages in * JavaScript code. Integration with the YUI Library's debug builds allow * implementers to access under-the-hood events, errors, and debugging messages. * Output may be read through a LogReader console and/or output to a browser * console. * * @module logger * @requires yahoo, event, dom * @optional dragdrop * @namespace YAHOO.widget * @title Logger Widget */ /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ // Define once if(!YAHOO.widget.Logger) { /** * The singleton Logger class provides core log management functionality. Saves * logs written through the global YAHOO.log function or written by a LogWriter * instance. Provides access to logs for reading by a LogReader instance or * native browser console such as the Firebug extension to Firefox or Safari's * JavaScript console through integration with the console.log() method. * * @class Logger * @static */ YAHOO.widget.Logger = { // Initialize properties loggerEnabled: true, _browserConsoleEnabled: false, categories: ["info","warn","error","time","window"], sources: ["global"], _stack: [], // holds all log msgs maxStackEntries: 2500, _startTime: new Date().getTime(), // static start timestamp _lastTime: null, // timestamp of last logged message _windowErrorsHandled: false, _origOnWindowError: null }; ///////////////////////////////////////////////////////////////////////////// // // Public properties // ///////////////////////////////////////////////////////////////////////////// /** * True if Logger is enabled, false otherwise. * * @property loggerEnabled * @type Boolean * @static * @default true */ /** * Array of categories. * * @property categories * @type String[] * @static * @default ["info","warn","error","time","window"] */ /** * Array of sources. * * @property sources * @type String[] * @static * @default ["global"] */ /** * Upper limit on size of internal stack. * * @property maxStackEntries * @type Number * @static * @default 2500 */ ///////////////////////////////////////////////////////////////////////////// // // Private properties // ///////////////////////////////////////////////////////////////////////////// /** * Internal property to track whether output to browser console is enabled. * * @property _browserConsoleEnabled * @type Boolean * @static * @default false * @private */ /** * Array to hold all log messages. * * @property _stack * @type Array * @static * @private */ /** * Static timestamp of Logger initialization. * * @property _startTime * @type Date * @static * @private */ /** * Timestamp of last logged message. * * @property _lastTime * @type Date * @static * @private */ ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Saves a log message to the stack and fires newLogEvent. If the log message is * assigned to an unknown category, creates a new category. If the log message is * from an unknown source, creates a new source. If browser console is enabled, * outputs the log message to browser console. * Note: the LogReader adds the message, category, and source to the DOM * as HTML. * * @method log * @param sMsg {HTML} The log message. * @param sCategory {HTML} Category of log message, or null. * @param sSource {HTML} Source of LogWriter, or null if global. */ YAHOO.widget.Logger.log = function(sMsg, sCategory, sSource) { if(this.loggerEnabled) { if(!sCategory) { sCategory = "info"; // default category } else { sCategory = sCategory.toLocaleLowerCase(); if(this._isNewCategory(sCategory)) { this._createNewCategory(sCategory); } } var sClass = "global"; // default source var sDetail = null; if(sSource) { var spaceIndex = sSource.indexOf(" "); if(spaceIndex > 0) { // Substring until first space sClass = sSource.substring(0,spaceIndex); // The rest of the source sDetail = sSource.substring(spaceIndex,sSource.length); } else { sClass = sSource; } if(this._isNewSource(sClass)) { this._createNewSource(sClass); } } var timestamp = new Date(); var logEntry = new YAHOO.widget.LogMsg({ msg: sMsg, time: timestamp, category: sCategory, source: sClass, sourceDetail: sDetail }); var stack = this._stack; var maxStackEntries = this.maxStackEntries; if(maxStackEntries && !isNaN(maxStackEntries) && (stack.length >= maxStackEntries)) { stack.shift(); } stack.push(logEntry); this.newLogEvent.fire(logEntry); if(this._browserConsoleEnabled) { this._printToBrowserConsole(logEntry); } return true; } else { return false; } }; /** * Resets internal stack and startTime, enables Logger, and fires logResetEvent. * * @method reset */ YAHOO.widget.Logger.reset = function() { this._stack = []; this._startTime = new Date().getTime(); this.loggerEnabled = true; this.log("Logger reset"); this.logResetEvent.fire(); }; /** * Public accessor to internal stack of log message objects. * * @method getStack * @return {Object[]} Array of log message objects. */ YAHOO.widget.Logger.getStack = function() { return this._stack; }; /** * Public accessor to internal start time. * * @method getStartTime * @return {Date} Internal date of when Logger singleton was initialized. */ YAHOO.widget.Logger.getStartTime = function() { return this._startTime; }; /** * Disables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method disableBrowserConsole */ YAHOO.widget.Logger.disableBrowserConsole = function() { YAHOO.log("Logger output to the function console.log() has been disabled."); this._browserConsoleEnabled = false; }; /** * Enables output to the browser's global console.log() function, which is used * by the Firebug extension to Firefox as well as Safari. * * @method enableBrowserConsole */ YAHOO.widget.Logger.enableBrowserConsole = function() { this._browserConsoleEnabled = true; YAHOO.log("Logger output to the function console.log() has been enabled."); }; /** * Surpresses native JavaScript errors and outputs to console. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method handleWindowErrors */ YAHOO.widget.Logger.handleWindowErrors = function() { if(!YAHOO.widget.Logger._windowErrorsHandled) { // Save any previously defined handler to call if(window.error) { YAHOO.widget.Logger._origOnWindowError = window.onerror; } window.onerror = YAHOO.widget.Logger._onWindowError; YAHOO.widget.Logger._windowErrorsHandled = true; YAHOO.log("Logger handling of window.onerror has been enabled."); } else { YAHOO.log("Logger handling of window.onerror had already been enabled."); } }; /** * Unsurpresses native JavaScript errors. By default, * Logger does not handle JavaScript window error events. * NB: Not all browsers support the window.onerror event. * * @method unhandleWindowErrors */ YAHOO.widget.Logger.unhandleWindowErrors = function() { if(YAHOO.widget.Logger._windowErrorsHandled) { // Revert to any previously defined handler to call if(YAHOO.widget.Logger._origOnWindowError) { window.onerror = YAHOO.widget.Logger._origOnWindowError; YAHOO.widget.Logger._origOnWindowError = null; } else { window.onerror = null; } YAHOO.widget.Logger._windowErrorsHandled = false; YAHOO.log("Logger handling of window.onerror has been disabled."); } else { YAHOO.log("Logger handling of window.onerror had already been disabled."); } }; ///////////////////////////////////////////////////////////////////////////// // // Public events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when a new category has been created. * * @event categoryCreateEvent * @param sCategory {String} Category name. */ YAHOO.widget.Logger.categoryCreateEvent = new YAHOO.util.CustomEvent("categoryCreate", this, true); /** * Fired when a new source has been named. * * @event sourceCreateEvent * @param sSource {String} Source name. */ YAHOO.widget.Logger.sourceCreateEvent = new YAHOO.util.CustomEvent("sourceCreate", this, true); /** * Fired when a new log message has been created. * * @event newLogEvent * @param sMsg {String} Log message. */ YAHOO.widget.Logger.newLogEvent = new YAHOO.util.CustomEvent("newLog", this, true); /** * Fired when the Logger has been reset has been created. * * @event logResetEvent */ YAHOO.widget.Logger.logResetEvent = new YAHOO.util.CustomEvent("logReset", this, true); ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Creates a new category of log messages and fires categoryCreateEvent. * * @method _createNewCategory * @param sCategory {String} Category name. * @private */ YAHOO.widget.Logger._createNewCategory = function(sCategory) { this.categories.push(sCategory); this.categoryCreateEvent.fire(sCategory); }; /** * Checks to see if a category has already been created. * * @method _isNewCategory * @param sCategory {String} Category name. * @return {Boolean} Returns true if category is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewCategory = function(sCategory) { for(var i=0; i < this.categories.length; i++) { if(sCategory == this.categories[i]) { return false; } } return true; }; /** * Creates a new source of log messages and fires sourceCreateEvent. * * @method _createNewSource * @param sSource {String} Source name. * @private */ YAHOO.widget.Logger._createNewSource = function(sSource) { this.sources.push(sSource); this.sourceCreateEvent.fire(sSource); }; /** * Checks to see if a source already exists. * * @method _isNewSource * @param sSource {String} Source name. * @return {Boolean} Returns true if source is unknown, else returns false. * @private */ YAHOO.widget.Logger._isNewSource = function(sSource) { if(sSource) { for(var i=0; i < this.sources.length; i++) { if(sSource == this.sources[i]) { return false; } } return true; } }; /** * Outputs a log message to global console.log() function. * * @method _printToBrowserConsole * @param oEntry {Object} Log entry object. * @private */ YAHOO.widget.Logger._printToBrowserConsole = function(oEntry) { if ((window.console && console.log) || (window.opera && opera.postError)) { var category = oEntry.category; var label = oEntry.category.substring(0,4).toUpperCase(); var time = oEntry.time; var localTime; if (time.toLocaleTimeString) { localTime = time.toLocaleTimeString(); } else { localTime = time.toString(); } var msecs = time.getTime(); var elapsedTime = (YAHOO.widget.Logger._lastTime) ? (msecs - YAHOO.widget.Logger._lastTime) : 0; YAHOO.widget.Logger._lastTime = msecs; var output = localTime + " (" + elapsedTime + "ms): " + oEntry.source + ": "; if (window.console) { console.log(output, oEntry.msg); } else { opera.postError(output + oEntry.msg); } } }; ///////////////////////////////////////////////////////////////////////////// // // Private event handlers // ///////////////////////////////////////////////////////////////////////////// /** * Handles logging of messages due to window error events. * * @method _onWindowError * @param sMsg {String} The error message. * @param sUrl {String} URL of the error. * @param sLine {String} Line number of the error. * @private */ YAHOO.widget.Logger._onWindowError = function(sMsg,sUrl,sLine) { // Logger is not in scope of this event handler try { YAHOO.widget.Logger.log(sMsg+' ('+sUrl+', line '+sLine+')', "window"); if(YAHOO.widget.Logger._origOnWindowError) { YAHOO.widget.Logger._origOnWindowError(); } } catch(e) { return false; } }; ///////////////////////////////////////////////////////////////////////////// // // First log // ///////////////////////////////////////////////////////////////////////////// YAHOO.widget.Logger.log("Logger initialized"); } /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ (function () { var Logger = YAHOO.widget.Logger, u = YAHOO.util, Dom = u.Dom, Event = u.Event, d = document; function make(el,props) { el = d.createElement(el); if (props) { for (var p in props) { if (props.hasOwnProperty(p)) { el[p] = props[p]; } } } return el; } /** * The LogReader class provides UI to read messages logged to YAHOO.widget.Logger. * * @class LogReader * @constructor * @param elContainer {HTMLElement} (optional) DOM element reference of an existing DIV. * @param elContainer {String} (optional) String ID of an existing DIV. * @param oConfigs {Object} (optional) Object literal of configuration params. */ function LogReader(elContainer, oConfigs) { this._sName = LogReader._index; LogReader._index++; this._init.apply(this,arguments); /** * Render the LogReader immediately upon instantiation. If set to false, * you must call myLogReader.render() to generate the UI. * * @property autoRender * @type {Boolean} * @default true */ if (this.autoRender !== false) { this.render(); } } ///////////////////////////////////////////////////////////////////////////// // // Static member variables // ///////////////////////////////////////////////////////////////////////////// YAHOO.lang.augmentObject(LogReader, { /** * Internal class member to index multiple LogReader instances. * * @property _memberName * @static * @type Number * @default 0 * @private */ _index : 0, /** * Node template for the log entries * @property ENTRY_TEMPLATE * @static * @type {HTMLElement} * @default <code>pre</code> element with class yui-log-entry */ ENTRY_TEMPLATE : (function () { return make('pre',{ className: 'yui-log-entry' }); })(), /** * Template used for innerHTML of verbose entry output. * @property VERBOSE_TEMPLATE * @static * @default "&lt;p>&lt;span class='{category}'>{label}&lt;/span>{totalTime}ms (+{elapsedTime}) {localTime}:&lt;/p>&lt;p>{sourceAndDetail}&lt;/p>&lt;p>{message}&lt;/p>" */ VERBOSE_TEMPLATE : "<p><span class='{category}'>{label}</span> {totalTime}ms (+{elapsedTime}) {localTime}:</p><p>{sourceAndDetail}</p><p>{message}</p>", /** * Template used for innerHTML of compact entry output. * @property BASIC_TEMPLATE * @static * @default "&lt;p>&lt;span class='{category}'>{label}&lt;/span>{totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}&lt;/p>" */ BASIC_TEMPLATE : "<p><span class='{category}'>{label}</span> {totalTime}ms (+{elapsedTime}) {localTime}: {sourceAndDetail}: {message}</p>" }); ///////////////////////////////////////////////////////////////////////////// // // Public member variables // ///////////////////////////////////////////////////////////////////////////// LogReader.prototype = { /** * Whether or not LogReader is enabled to output log messages. * * @property logReaderEnabled * @type Boolean * @default true */ logReaderEnabled : true, /** * Public member to access CSS width of the LogReader container. * * @property width * @type String */ width : null, /** * Public member to access CSS height of the LogReader container. * * @property height * @type String */ height : null, /** * Public member to access CSS top position of the LogReader container. * * @property top * @type String */ top : null, /** * Public member to access CSS left position of the LogReader container. * * @property left * @type String */ left : null, /** * Public member to access CSS right position of the LogReader container. * * @property right * @type String */ right : null, /** * Public member to access CSS bottom position of the LogReader container. * * @property bottom * @type String */ bottom : null, /** * Public member to access CSS font size of the LogReader container. * * @property fontSize * @type String */ fontSize : null, /** * Whether or not the footer UI is enabled for the LogReader. * * @property footerEnabled * @type Boolean * @default true */ footerEnabled : true, /** * Whether or not output is verbose (more readable). Setting to true will make * output more compact (less readable). * * @property verboseOutput * @type Boolean * @default true */ verboseOutput : true, /** * Custom output format for log messages. Defaults to null, which falls * back to verboseOutput param deciding between LogReader.VERBOSE_TEMPLATE * and LogReader.BASIC_TEMPLATE. Use bracketed place holders to mark where * message info should go. Available place holder names include: * <ul> * <li>category</li> * <li>label</li> * <li>sourceAndDetail</li> * <li>message</li> * <li>localTime</li> * <li>elapsedTime</li> * <li>totalTime</li> * </ul> * * @property entryFormat * @type String * @default null */ entryFormat : null, /** * Whether or not newest message is printed on top. * * @property newestOnTop * @type Boolean */ newestOnTop : true, /** * Output timeout buffer in milliseconds. * * @property outputBuffer * @type Number * @default 100 */ outputBuffer : 100, /** * Maximum number of messages a LogReader console will display. * * @property thresholdMax * @type Number * @default 500 */ thresholdMax : 500, /** * When a LogReader console reaches its thresholdMax, it will clear out messages * and print out the latest thresholdMin number of messages. * * @property thresholdMin * @type Number * @default 100 */ thresholdMin : 100, /** * True when LogReader is in a collapsed state, false otherwise. * * @property isCollapsed * @type Boolean * @default false */ isCollapsed : false, /** * True when LogReader is in a paused state, false otherwise. * * @property isPaused * @type Boolean * @default false */ isPaused : false, /** * Enables draggable LogReader if DragDrop Utility is present. * * @property draggable * @type Boolean * @default true */ draggable : true, ///////////////////////////////////////////////////////////////////////////// // // Public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the LogReader instance. * * @method toString * @return {String} Unique name of the LogReader instance. */ toString : function() { return "LogReader instance" + this._sName; }, /** * Pauses output of log messages. While paused, log messages are not lost, but * get saved to a buffer and then output upon resume of LogReader. * * @method pause */ pause : function() { this.isPaused = true; this._timeout = null; this.logReaderEnabled = false; if (this._btnPause) { this._btnPause.value = "Resume"; } }, /** * Resumes output of log messages, including outputting any log messages that * have been saved to buffer while paused. * * @method resume */ resume : function() { this.isPaused = false; this.logReaderEnabled = true; this._printBuffer(); if (this._btnPause) { this._btnPause.value = "Pause"; } }, /** * Adds the UI to the DOM, attaches event listeners, and bootstraps initial * UI state. * * @method render */ render : function () { if (this.rendered) { return; } this._initContainerEl(); this._initHeaderEl(); this._initConsoleEl(); this._initFooterEl(); this._initCategories(); this._initSources(); this._initDragDrop(); // Subscribe to Logger custom events Logger.newLogEvent.subscribe(this._onNewLog, this); Logger.logResetEvent.subscribe(this._onReset, this); Logger.categoryCreateEvent.subscribe(this._onCategoryCreate, this); Logger.sourceCreateEvent.subscribe(this._onSourceCreate, this); this.rendered = true; this._filterLogs(); }, /** * Removes the UI from the DOM entirely and detaches all event listeners. * Implementers should note that Logger will still accumulate messages. * * @method destroy */ destroy : function () { Event.purgeElement(this._elContainer,true); this._elContainer.innerHTML = ''; this._elContainer.parentNode.removeChild(this._elContainer); this.rendered = false; }, /** * Hides UI of LogReader. Logging functionality is not disrupted. * * @method hide */ hide : function() { this._elContainer.style.display = "none"; }, /** * Shows UI of LogReader. Logging functionality is not disrupted. * * @method show */ show : function() { this._elContainer.style.display = "block"; }, /** * Collapses UI of LogReader. Logging functionality is not disrupted. * * @method collapse */ collapse : function() { this._elConsole.style.display = "none"; if(this._elFt) { this._elFt.style.display = "none"; } this._btnCollapse.value = "Expand"; this.isCollapsed = true; }, /** * Expands UI of LogReader. Logging functionality is not disrupted. * * @method expand */ expand : function() { this._elConsole.style.display = "block"; if(this._elFt) { this._elFt.style.display = "block"; } this._btnCollapse.value = "Collapse"; this.isCollapsed = false; }, /** * Returns related checkbox element for given filter (i.e., category or source). * * @method getCheckbox * @param {String} Category or source name. * @return {Array} Array of all filter checkboxes. */ getCheckbox : function(filter) { return this._filterCheckboxes[filter]; }, /** * Returns array of enabled categories. * * @method getCategories * @return {String[]} Array of enabled categories. */ getCategories : function() { return this._categoryFilters; }, /** * Shows log messages associated with given category. * * @method showCategory * @param {String} Category name. */ showCategory : function(sCategory) { var filtersArray = this._categoryFilters; // Don't do anything if category is already enabled // Use Array.indexOf if available... if(filtersArray.indexOf) { if(filtersArray.indexOf(sCategory) > -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i<filtersArray.length; i++) { if(filtersArray[i] === sCategory){ return; } } } this._categoryFilters.push(sCategory); this._filterLogs(); var elCheckbox = this.getCheckbox(sCategory); if(elCheckbox) { elCheckbox.checked = true; } }, /** * Hides log messages associated with given category. * * @method hideCategory * @param {String} Category name. */ hideCategory : function(sCategory) { var filtersArray = this._categoryFilters; for(var i=0; i<filtersArray.length; i++) { if(sCategory == filtersArray[i]) { filtersArray.splice(i, 1); break; } } this._filterLogs(); var elCheckbox = this.getCheckbox(sCategory); if(elCheckbox) { elCheckbox.checked = false; } }, /** * Returns array of enabled sources. * * @method getSources * @return {Array} Array of enabled sources. */ getSources : function() { return this._sourceFilters; }, /** * Shows log messages associated with given source. * * @method showSource * @param {String} Source name. */ showSource : function(sSource) { var filtersArray = this._sourceFilters; // Don't do anything if category is already enabled // Use Array.indexOf if available... if(filtersArray.indexOf) { if(filtersArray.indexOf(sSource) > -1) { return; } } // ...or do it the old-fashioned way else { for(var i=0; i<filtersArray.length; i++) { if(sSource == filtersArray[i]){ return; } } } filtersArray.push(sSource); this._filterLogs(); var elCheckbox = this.getCheckbox(sSource); if(elCheckbox) { elCheckbox.checked = true; } }, /** * Hides log messages associated with given source. * * @method hideSource * @param {String} Source name. */ hideSource : function(sSource) { var filtersArray = this._sourceFilters; for(var i=0; i<filtersArray.length; i++) { if(sSource == filtersArray[i]) { filtersArray.splice(i, 1); break; } } this._filterLogs(); var elCheckbox = this.getCheckbox(sSource); if(elCheckbox) { elCheckbox.checked = false; } }, /** * Does not delete any log messages, but clears all printed log messages from * the console. Log messages will be printed out again if user re-filters. The * static method YAHOO.widget.Logger.reset() should be called in order to * actually delete log messages. * * @method clearConsole */ clearConsole : function() { // Clear the buffer of any pending messages this._timeout = null; this._buffer = []; this._consoleMsgCount = 0; var elConsole = this._elConsole; elConsole.innerHTML = ''; }, /** * Updates title to given string. * * @method setTitle * @param sTitle {String} New title. */ setTitle : function(sTitle) { this._title.innerHTML = this.html2Text(sTitle); }, /** * Gets timestamp of the last log. * * @method getLastTime * @return {Date} Timestamp of the last log. */ getLastTime : function() { return this._lastTime; }, formatMsg : function (entry) { var entryFormat = this.entryFormat || (this.verboseOutput ? LogReader.VERBOSE_TEMPLATE : LogReader.BASIC_TEMPLATE), info = { category : entry.category, // Label for color-coded display label : entry.category.substring(0,4).toUpperCase(), sourceAndDetail : entry.sourceDetail ? entry.source + " " + entry.sourceDetail : entry.source, // Escape HTML entities in the log message itself for output // to console message : this.html2Text(entry.msg || entry.message || '') }; // Add time info if (entry.time && entry.time.getTime) { info.localTime = entry.time.toLocaleTimeString ? entry.time.toLocaleTimeString() : entry.time.toString(); // Calculate the elapsed time to be from the last item that // passed through the filter, not the absolute previous item // in the stack info.elapsedTime = entry.time.getTime() - this.getLastTime(); info.totalTime = entry.time.getTime() - Logger.getStartTime(); } var msg = LogReader.ENTRY_TEMPLATE.cloneNode(true); if (this.verboseOutput) { msg.className += ' yui-log-verbose'; } // Bug 2061169: Workaround for YAHOO.lang.substitute() msg.innerHTML = entryFormat.replace(/\{(\w+)\}/g, function (x, placeholder) { return (placeholder in info) ? info[placeholder] : ''; }); return msg; }, /** * Converts input chars "<", ">", and "&" to HTML entities. * * @method html2Text * @param sHtml {String} String to convert. * @private */ html2Text : function(sHtml) { if(sHtml) { sHtml += ""; return sHtml.replace(/&/g, "&#38;"). replace(/</g, "&#60;"). replace(/>/g, "&#62;"); } return ""; }, ///////////////////////////////////////////////////////////////////////////// // // Private member variables // ///////////////////////////////////////////////////////////////////////////// /** * Name of LogReader instance. * * @property _sName * @type String * @private */ _sName : null, //TODO: remove /** * A class member shared by all LogReaders if a container needs to be * created during instantiation. Will be null if a container element never needs to * be created on the fly, such as when the implementer passes in their own element. * * @property _elDefaultContainer * @type HTMLElement * @private */ //YAHOO.widget.LogReader._elDefaultContainer = null; /** * Buffer of log message objects for batch output. * * @property _buffer * @type Object[] * @private */ _buffer : null, /** * Number of log messages output to console. * * @property _consoleMsgCount * @type Number * @default 0 * @private */ _consoleMsgCount : 0, /** * Date of last output log message. * * @property _lastTime * @type Date * @private */ _lastTime : null, /** * Batched output timeout ID. * * @property _timeout * @type Number * @private */ _timeout : null, /** * Hash of filters and their related checkbox elements. * * @property _filterCheckboxes * @type Object * @private */ _filterCheckboxes : null, /** * Array of filters for log message categories. * * @property _categoryFilters * @type String[] * @private */ _categoryFilters : null, /** * Array of filters for log message sources. * * @property _sourceFilters * @type String[] * @private */ _sourceFilters : null, /** * LogReader container element. * * @property _elContainer * @type HTMLElement * @private */ _elContainer : null, /** * LogReader header element. * * @property _elHd * @type HTMLElement * @private */ _elHd : null, /** * LogReader collapse element. * * @property _elCollapse * @type HTMLElement * @private */ _elCollapse : null, /** * LogReader collapse button element. * * @property _btnCollapse * @type HTMLElement * @private */ _btnCollapse : null, /** * LogReader title header element. * * @property _title * @type HTMLElement * @private */ _title : null, /** * LogReader console element. * * @property _elConsole * @type HTMLElement * @private */ _elConsole : null, /** * LogReader footer element. * * @property _elFt * @type HTMLElement * @private */ _elFt : null, /** * LogReader buttons container element. * * @property _elBtns * @type HTMLElement * @private */ _elBtns : null, /** * Container element for LogReader category filter checkboxes. * * @property _elCategoryFilters * @type HTMLElement * @private */ _elCategoryFilters : null, /** * Container element for LogReader source filter checkboxes. * * @property _elSourceFilters * @type HTMLElement * @private */ _elSourceFilters : null, /** * LogReader pause button element. * * @property _btnPause * @type HTMLElement * @private */ _btnPause : null, /** * Clear button element. * * @property _btnClear * @type HTMLElement * @private */ _btnClear : null, ///////////////////////////////////////////////////////////////////////////// // // Private methods // ///////////////////////////////////////////////////////////////////////////// /** * Initializes the instance's message buffer, start time, etc * * @method _init * @param container {String|HTMLElement} (optional) the render target * @param config {Object} (optional) instance configuration * @protected */ _init : function (container, config) { // Internal vars this._buffer = []; // output buffer this._filterCheckboxes = {}; // pointers to checkboxes this._lastTime = Logger.getStartTime(); // timestamp of last log message to console // Parse config vars here if (config && (config.constructor == Object)) { for(var param in config) { if (config.hasOwnProperty(param)) { this[param] = config[param]; } } } this._elContainer = Dom.get(container); YAHOO.log("LogReader initialized", null, this.toString()); }, /** * Initializes the primary container element. * * @method _initContainerEl * @private */ _initContainerEl : function() { // Default the container if unset or not a div if(!this._elContainer || !/div$/i.test(this._elContainer.tagName)) { this._elContainer = d.body.insertBefore(make("div"),d.body.firstChild); // Only position absolutely if an in-DOM element is not supplied Dom.addClass(this._elContainer,"yui-log-container"); } Dom.addClass(this._elContainer,"yui-log"); // If implementer has provided container values, trust and set those var style = this._elContainer.style, styleProps = ['width','right','top','fontSize'], prop,i; for (i = styleProps.length - 1; i >= 0; --i) { prop = styleProps[i]; if (this[prop]){ style[prop] = this[prop]; } } if(this.left) { style.left = this.left; style.right = "auto"; } if(this.bottom) { style.bottom = this.bottom; style.top = "auto"; } // Opera needs a little prodding to reflow sometimes if (YAHOO.env.ua.opera) { d.body.style += ''; } }, /** * Initializes the header element. * * @method _initHeaderEl * @private */ _initHeaderEl : function() { // Destroy header if present if(this._elHd) { // Unhook DOM events Event.purgeElement(this._elHd, true); // Remove DOM elements this._elHd.innerHTML = ""; } // Create header // TODO: refactor this into an innerHTML this._elHd = make("div",{ className: "yui-log-hd" }); Dom.generateId(this._elHd, 'yui-log-hd' + this._sName); this._elCollapse = make("div",{ className: 'yui-log-btns' }); this._btnCollapse = make("input",{ type: 'button', className: 'yui-log-button', value: 'Collapse' }); Event.on(this._btnCollapse,'click',this._onClickCollapseBtn,this); this._title = make("h4",{ innerHTML : "Logger Console" }); this._elCollapse.appendChild(this._btnCollapse); this._elHd.appendChild(this._elCollapse); this._elHd.appendChild(this._title); this._elContainer.appendChild(this._elHd); }, /** * Initializes the console element. * * @method _initConsoleEl * @private */ _initConsoleEl : function() { // Destroy console if(this._elConsole) { // Unhook DOM events Event.purgeElement(this._elConsole, true); // Remove DOM elements this._elConsole.innerHTML = ""; } // Ceate console this._elConsole = make("div", { className: "yui-log-bd" }); // If implementer has provided console, trust and set those if(this.height) { this._elConsole.style.height = this.height; } this._elContainer.appendChild(this._elConsole); }, /** * Initializes the footer element. * * @method _initFooterEl * @private */ _initFooterEl : function() { // Don't create footer elements if footer is disabled if(this.footerEnabled) { // Destroy console if(this._elFt) { // Unhook DOM events Event.purgeElement(this._elFt, true); // Remove DOM elements this._elFt.innerHTML = ""; } // TODO: use innerHTML this._elFt = make("div",{ className: "yui-log-ft" }); this._elBtns = make("div", { className: "yui-log-btns" }); this._btnPause = make("input", { type: "button", className: "yui-log-button", value: "Pause" }); Event.on(this._btnPause,'click',this._onClickPauseBtn,this); this._btnClear = make("input", { type: "button", className: "yui-log-button", value: "Clear" }); Event.on(this._btnClear,'click',this._onClickClearBtn,this); this._elCategoryFilters = make("div", { className: "yui-log-categoryfilters" }); this._elSourceFilters = make("div", { className: "yui-log-sourcefilters" }); this._elBtns.appendChild(this._btnPause); this._elBtns.appendChild(this._btnClear); this._elFt.appendChild(this._elBtns); this._elFt.appendChild(this._elCategoryFilters); this._elFt.appendChild(this._elSourceFilters); this._elContainer.appendChild(this._elFt); } }, /** * Initializes Drag and Drop on the header element. * * @method _initDragDrop * @private */ _initDragDrop : function() { // If Drag and Drop utility is available... // ...and draggable is true... // ...then make the header draggable if(u.DD && this.draggable && this._elHd) { var ylog_dd = new u.DD(this._elContainer); ylog_dd.setHandleElId(this._elHd.id); //TODO: use class name this._elHd.style.cursor = "move"; } }, /** * Initializes category filters. * * @method _initCategories * @private */ _initCategories : function() { // Initialize category filters this._categoryFilters = []; var aInitialCategories = Logger.categories; for(var j=0; j < aInitialCategories.length; j++) { var sCategory = aInitialCategories[j]; // Add category to the internal array of filters this._categoryFilters.push(sCategory); // Add checkbox element if UI is enabled if(this._elCategoryFilters) { this._createCategoryCheckbox(sCategory); } } }, /** * Initializes source filters. * * @method _initSources * @private */ _initSources : function() { // Initialize source filters this._sourceFilters = []; var aInitialSources = Logger.sources; for(var j=0; j < aInitialSources.length; j++) { var sSource = aInitialSources[j]; // Add source to the internal array of filters this._sourceFilters.push(sSource); // Add checkbox element if UI is enabled if(this._elSourceFilters) { this._createSourceCheckbox(sSource); } } }, /** * Creates the UI for a category filter in the LogReader footer element. * * @method _createCategoryCheckbox * @param sCategory {String} Category name. * @private */ _createCategoryCheckbox : function(sCategory) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sCategory + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sCategory, type: "checkbox", category: sCategory }), label = make("label", { htmlFor: checkid, className: sCategory, innerHTML: sCategory }); // Subscribe to the click event Event.on(check,'click',this._onCheckCategory,this); this._filterCheckboxes[sCategory] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elCategoryFilters.appendChild(filter); check.checked = true; } }, /** * Creates a checkbox in the LogReader footer element to filter by source. * * @method _createSourceCheckbox * @param sSource {String} Source name. * @private */ _createSourceCheckbox : function(sSource) { if(this._elFt) { var filter = make("span",{ className: "yui-log-filtergrp" }), checkid = Dom.generateId(null, "yui-log-filter-" + sSource + this._sName), check = make("input", { id: checkid, className: "yui-log-filter-" + sSource, type: "checkbox", source: sSource }), label = make("label", { htmlFor: checkid, className: sSource, innerHTML: sSource }); // Subscribe to the click event Event.on(check,'click',this._onCheckSource,this); this._filterCheckboxes[sSource] = check; // Append el at the end so IE 5.5 can set "type" attribute // and THEN set checked property filter.appendChild(check); filter.appendChild(label); this._elSourceFilters.appendChild(filter); check.checked = true; } }, /** * Reprints all log messages in the stack through filters. * * @method _filterLogs * @private */ _filterLogs : function() { // Reprint stack with new filters if (this._elConsole !== null) { this.clearConsole(); this._printToConsole(Logger.getStack()); } }, /** * Sends buffer of log messages to output and clears buffer. * * @method _printBuffer * @private */ _printBuffer : function() { this._timeout = null; if(this._elConsole !== null) { var thresholdMax = this.thresholdMax; thresholdMax = (thresholdMax && !isNaN(thresholdMax)) ? thresholdMax : 500; if(this._consoleMsgCount < thresholdMax) { var entries = []; for (var i=0; i<this._buffer.length; i++) { entries[i] = this._buffer[i]; } this._buffer = []; this._printToConsole(entries); } else { this._filterLogs(); } if(!this.newestOnTop) { this._elConsole.scrollTop = this._elConsole.scrollHeight; } } }, /** * Cycles through an array of log messages, and outputs each one to the console * if its category has not been filtered out. * * @method _printToConsole * @param aEntries {Object[]} Array of LogMsg objects to output to console. * @private */ _printToConsole : function(aEntries) { // Manage the number of messages displayed in the console var entriesLen = aEntries.length, df = d.createDocumentFragment(), msgHTML = [], thresholdMin = this.thresholdMin, sourceFiltersLen = this._sourceFilters.length, categoryFiltersLen = this._categoryFilters.length, entriesStartIndex, i, j, msg, before; if(isNaN(thresholdMin) || (thresholdMin > this.thresholdMax)) { thresholdMin = 0; } entriesStartIndex = (entriesLen > thresholdMin) ? (entriesLen - thresholdMin) : 0; // Iterate through all log entries for(i=entriesStartIndex; i<entriesLen; i++) { // Print only the ones that filter through var okToPrint = false, okToFilterCats = false, entry = aEntries[i], source = entry.source, category = entry.category; for(j=0; j<sourceFiltersLen; j++) { if(source == this._sourceFilters[j]) { okToFilterCats = true; break; } } if(okToFilterCats) { for(j=0; j<categoryFiltersLen; j++) { if(category == this._categoryFilters[j]) { okToPrint = true; break; } } } if(okToPrint) { // Start from 0ms elapsed time if (this._consoleMsgCount === 0) { this._lastTime = entry.time.getTime(); } msg = this.formatMsg(entry); if (typeof msg === 'string') { msgHTML[msgHTML.length] = msg; } else { df.insertBefore(msg, this.newestOnTop ? df.firstChild || null : null); } this._consoleMsgCount++; this._lastTime = entry.time.getTime(); } } if (msgHTML.length) { msgHTML.splice(0,0,this._elConsole.innerHTML); this._elConsole.innerHTML = this.newestOnTop ? msgHTML.reverse().join('') : msgHTML.join(''); } else if (df.firstChild) { this._elConsole.insertBefore(df, this.newestOnTop ? this._elConsole.firstChild || null : null); } }, ///////////////////////////////////////////////////////////////////////////// // // Private event handlers // ///////////////////////////////////////////////////////////////////////////// /** * Handles Logger's categoryCreateEvent. * * @method _onCategoryCreate * @param sType {String} The event. * @param aArgs {Object[]} Data passed from event firer. * @param oSelf {Object} The LogReader instance. * @private */ _onCategoryCreate : function(sType, aArgs, oSelf) { var category = aArgs[0]; // Add category to the internal array of filters oSelf._categoryFilters.push(category); if(oSelf._elFt) { oSelf._createCategoryCheckbox(category); } }, /** * Handles Logger's sourceCreateEvent. * * @method _onSourceCreate * @param sType {String} The event. * @param aArgs {Object[]} Data passed from event firer. * @param oSelf {Object} The LogReader instance. * @private */ _onSourceCreate : function(sType, aArgs, oSelf) { var source = aArgs[0]; // Add source to the internal array of filters oSelf._sourceFilters.push(source); if(oSelf._elFt) { oSelf._createSourceCheckbox(source); } }, /** * Handles check events on the category filter checkboxes. * * @method _onCheckCategory * @param v {HTMLEvent} The click event. * @param oSelf {Object} The LogReader instance. * @private */ _onCheckCategory : function(v, oSelf) { var category = this.category; if(!this.checked) { oSelf.hideCategory(category); } else { oSelf.showCategory(category); } }, /** * Handles check events on the category filter checkboxes. * * @method _onCheckSource * @param v {HTMLEvent} The click event. * @param oSelf {Object} The LogReader instance. * @private */ _onCheckSource : function(v, oSelf) { var source = this.source; if(!this.checked) { oSelf.hideSource(source); } else { oSelf.showSource(source); } }, /** * Handles click events on the collapse button. * * @method _onClickCollapseBtn * @param v {HTMLEvent} The click event. * @param oSelf {Object} The LogReader instance * @private */ _onClickCollapseBtn : function(v, oSelf) { if(!oSelf.isCollapsed) { oSelf.collapse(); } else { oSelf.expand(); } }, /** * Handles click events on the pause button. * * @method _onClickPauseBtn * @param v {HTMLEvent} The click event. * @param oSelf {Object} The LogReader instance. * @private */ _onClickPauseBtn : function(v, oSelf) { if(!oSelf.isPaused) { oSelf.pause(); } else { oSelf.resume(); } }, /** * Handles click events on the clear button. * * @method _onClickClearBtn * @param v {HTMLEvent} The click event. * @param oSelf {Object} The LogReader instance. * @private */ _onClickClearBtn : function(v, oSelf) { oSelf.clearConsole(); }, /** * Handles Logger's newLogEvent. * * @method _onNewLog * @param sType {String} The event. * @param aArgs {Object[]} Data passed from event firer. * @param oSelf {Object} The LogReader instance. * @private */ _onNewLog : function(sType, aArgs, oSelf) { var logEntry = aArgs[0]; oSelf._buffer.push(logEntry); if (oSelf.logReaderEnabled === true && oSelf._timeout === null) { oSelf._timeout = setTimeout(function(){oSelf._printBuffer();}, oSelf.outputBuffer); } }, /** * Handles Logger's resetEvent. * * @method _onReset * @param sType {String} The event. * @param aArgs {Object[]} Data passed from event firer. * @param oSelf {Object} The LogReader instance. * @private */ _onReset : function(sType, aArgs, oSelf) { oSelf._filterLogs(); } }; YAHOO.widget.LogReader = LogReader; })(); YAHOO.register("logger", YAHOO.widget.Logger, {version: "2.9.0pr1", build: "2725"}); }, '2.9.0pr1.2725' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event", "yui2-skin-sam-logger"], "optional": ["yui2-dragdrop"]});
import always from 'ramda/src/always'; import moment from 'moment'; const NOW = 'now'; const defaultMessage = '<%= propertyName %> must greater than <%= ruleParams[1] %>.'; // Use object (it will be passed as reference at index.js) to represent the message, // because we want to change it dynamically based on the offset parameter // based on the offset parameters. const message = {}; const validate = (val, ruleObj) => { if (!val) { return true; } let dateTime; const dateTimeInputFormat = ruleObj.params[0]; const dateTimeInput = moment(val, dateTimeInputFormat); let offset = Number(ruleObj.params[2]); const unit = ruleObj.params[3] || 'seconds'; if (ruleObj.params[1].toLowerCase() === NOW) { dateTime = moment(); } else { dateTime = moment(ruleObj.params[1], dateTimeInputFormat); } // Always start with a defaultMessage message.toString = always(defaultMessage); if (offset) { if (offset < 0) { offset = Math.abs(offset); message.toString = always( '<%= propertyName %> must greater than <%= ruleParams[1] %> minus <%= Math.abs(ruleParams[2]) %> <%= ruleParams[3] %>.' ); dateTime = dateTime.subtract(offset, unit); } else { message.toString = always('<%= propertyName %> must greater than <%= ruleParams[1] %> plus <%= ruleParams[2] %> <%= ruleParams[3] %>.'); dateTime = dateTime.add(offset, unit); } } return dateTimeInput.isAfter(dateTime, unit); }; export default {validate, message};
version https://git-lfs.github.com/spec/v1 oid sha256:19a2379369398913bbc402789e778c0c45d45104bacd7d2bc64f95033f1061a2 size 17119
var assert = require('assert'), request = require('request'), swintProcOps = require('../lib'); global.swintVar.printLevel = 5; describe('Basic feature', function() { before(function(done) { var procOps = swintProcOps({ server: { enabled: true }, keyBind: { enabled: true } }); procOps.start(function() { process.on('message', function(msg) { if(msg.type === 'control') { switch(msg.data) { case 'healthCheck': setTimeout(function() { process.emit('controlEnd', null, ['Process info']); }, 100); break; case 'softReset': case 'hardReset': setTimeout(function() { process.emit('controlEnd'); }, 100); break; } } }); done(); }); }); it('should be able to respond healthCheck request and emit event', function(done) { request.get({ url: 'https://localhost:33233/healthCheck?pass=SwintIsForTwins', strictSSL: false }, function(err, resp, body) { assert.deepEqual(JSON.parse(body), { success: true, error: '', data: { processes: ['Process info'] } }); done(); }); process.once('message', function(msg) { assert.deepEqual(msg, { type: 'control', data: 'healthCheck' }); }); }); it('should be able to respond softReset request and emit event', function(done) { request.get({ url: 'https://localhost:33233/softReset?pass=SwintIsForTwins', strictSSL: false }, function(err, resp, body) { assert.deepEqual(JSON.parse(body), { success: true, error: '', data: { message: "Soft reset has successfully done" } }); done(); }); process.once('message', function(msg) { assert.deepEqual(msg, { type: 'control', data: 'softReset' }); }); }); it('should be able to respond hardReset request and emit event', function(done) { request.get({ url: 'https://localhost:33233/hardReset?pass=SwintIsForTwins', strictSSL: false }, function(err, resp, body) { assert.deepEqual(JSON.parse(body), { success: true, error: '', data: { message: "Hard reset has successfully done" } }); done(); }); process.once('message', function(msg) { assert.deepEqual(msg, { type: 'control', data: 'hardReset' }); }); }); it('should be able to respond healthCheck key and emit event', function(done) { setTimeout(function() { process.stdin.emit('keypress', null, { name: 'm' }); }, 10); process.once('message', function(msg) { assert.deepEqual(msg, { type: 'control', data: 'healthCheck' }); done(); }); }); it('should be able to respond softReset key and emit event', function(done) { setTimeout(function() { process.stdin.emit('keypress', null, { name: 's' }); }, 10); process.once('message', function(msg) { assert.deepEqual(msg, { type: 'control', data: 'softReset' }); done(); }); }); it('should be able to respond hardReset key and emit event', function(done) { setTimeout(function() { process.stdin.emit('keypress', null, { name: 'r' }); }, 10); process.once('message', function(msg) { assert.deepEqual(msg, { type: 'control', data: 'hardReset' }); done(); }); }); });
var http = require('http'), request = require('request'), helpers = require('./helpers'); /** * MailChimp API wrapper for the API version 1.1. This object should not be * instantiated directly but by using the version wrapper {@link MailChimpAPI}. * * @param apiKey The API key to access the MailChimp API with * @param options Configuration options * @return Instance of {@link MailChimpAPI_v1_1} */ function MailChimpAPI_v1_1 (apiKey, options) { if (!options) var options = {}; this.version = '1.1'; this.apiKey = apiKey; this.secure = options.secure || false; this.packageInfo = options.packageInfo; this.datacenter = apiKey.split('-'); this.datacenter = this.datacenter[1]; this.httpHost = this.datacenter+'.api.mailchimp.com'; this.httpUri = (this.secure) ? 'https://'+this.httpHost+':443' : 'http://'+this.httpHost+':80'; this.userAgent = options.userAgent+' ' || ''; } module.exports = MailChimpAPI_v1_1; /** * Sends a given request as a JSON object to the MailChimp API and finally * calls the given callback function with the resulting JSON object. This * method should not be called directly but will be used internally by all API * methods defined. * * @param method MailChimp API method to call * @param availableParams Parameters available for the specified API method * @param givenParams Parameters to call the MailChimp API with * @param callback Callback function to call on success */ MailChimpAPI_v1_1.prototype.execute = function (method, availableParams, givenParams, callback) { var finalParams = { apikey : this.apiKey }; var currentParam; for (var i = 0; i < availableParams.length; i++) { currentParam = availableParams[i]; if (typeof givenParams[currentParam] !== 'undefined') finalParams[currentParam] = givenParams[currentParam]; } request({ uri : this.httpUri+'/'+this.version+'/?output=json&method='+method, method: 'POST', headers : { 'User-Agent' : this.userAgent+'node-mailchimp/'+this.packageInfo['version'] }, body : encodeURIComponent(JSON.stringify(finalParams)) }, function (error, response, body) { helpers.handleMailChimpResponse(error, response, body, callback); }); } /*****************************************************************************/ /************************* Campaign Related Methods **************************/ /*****************************************************************************/ /** * Get the content (both html and text) for a campaign either as it would * appear in the campaign archive or as the raw, original content. * * @see http://www.mailchimp.com/api/1.1/campaigncontent.func.php */ MailChimpAPI_v1_1.prototype.campaignContent = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignContent', [ 'cid', 'for_archive', ], params, callback); } /** * Create a new draft campaign to send. * * @see http://www.mailchimp.com/api/1.1/campaigncreate.func.php */ MailChimpAPI_v1_1.prototype.campaignCreate = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignCreate', [ 'type', 'options', 'content', 'segment_opts', 'type_opts', ], params, callback); } /** * Delete a campaign. * * @see http://www.mailchimp.com/api/1.1/campaigndelete.func.php */ MailChimpAPI_v1_1.prototype.campaignDelete = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignDelete', [ 'cid', ], params, callback); } /** * Attach Ecommerce Order Information to a Campaign. * * @see http://www.mailchimp.com/api/1.1/campaignecommaddorder.func.php */ MailChimpAPI_v1_1.prototype.campaignEcommAddOrder = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignEcommAddOrder', [ 'order', ], params, callback); } /** * List all the folders for a user account. * * @see http://www.mailchimp.com/api/1.1/campaignfolders.func.php */ MailChimpAPI_v1_1.prototype.campaignFolders = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignFolders', [ ], params, callback); } /** * Pause an AutoResponder or RSS campaign from sending. * * @see http://www.mailchimp.com/api/1.1/campaignpause.func.php */ MailChimpAPI_v1_1.prototype.campaignPause = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignPause', [ 'cid', ], params, callback); } /** * Replicate a campaign. * * @see http://www.mailchimp.com/api/1.1/campaignreplicate.func.php */ MailChimpAPI_v1_1.prototype.campaignReplicate = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignReplicate', [ 'cid', ], params, callback); } /** * Resume sending an AutoResponder or RSS campaign. * * @see http://www.mailchimp.com/api/1.1/campaignresume.func.php */ MailChimpAPI_v1_1.prototype.campaignResume = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignResume', [ 'cid', ], params, callback); } /** * Schedule a campaign to be sent in the future. * * @see http://www.mailchimp.com/api/1.1/campaignschedule.func.php */ MailChimpAPI_v1_1.prototype.campaignSchedule = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignSchedule', [ 'cid', 'schedule_time', 'schedule_time_b', ], params, callback); } /** * Allows one to test their segmentation rules before creating a campaign using * them. * * @see http://www.mailchimp.com/api/1.1/campaignsegmenttest.func.php */ MailChimpAPI_v1_1.prototype.campaignSegmentTest = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignSegmentTest', [ 'list_id', 'options', ], params, callback); } /** * Send a given campaign immediately. * * @see http://www.mailchimp.com/api/1.1/campaignsendnow.func.php */ MailChimpAPI_v1_1.prototype.campaignSendNow = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignSendNow', [ 'cid', ], params, callback); } /** * Send a test of this campaign to the provided email address. * * @see http://www.mailchimp.com/api/1.1/campaignsendtest.func.php */ MailChimpAPI_v1_1.prototype.campaignSendTest = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignSendTest', [ 'cid', 'test_emails', 'send_type', ], params, callback); } /** * Retrieve all templates defined for your user account. * * @see http://www.mailchimp.com/api/1.1/campaigntemplates.func.php */ MailChimpAPI_v1_1.prototype.campaignTemplates = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignTemplates', [ ], params, callback); } /** * Unschedule a campaign that is scheduled to be sent in the future. * * @see http://www.mailchimp.com/api/1.1/campaignunschedule.func.php */ MailChimpAPI_v1_1.prototype.campaignUnschedule = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignUnschedule', [ 'cid', ], params, callback); } /** * Update just about any setting for a campaign that has not been sent. * * @see http://www.mailchimp.com/api/1.1/campaignupdate.func.php */ MailChimpAPI_v1_1.prototype.campaignUpdate = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignUpdate', [ 'cid', 'name', 'value', ], params, callback); } /** * Get the list of campaigns and their details matching the specified filters. * * @see http://www.mailchimp.com/api/1.1/campaigns.func.php */ MailChimpAPI_v1_1.prototype.campaigns = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaigns', [ 'filter_id', 'filter_folder', 'filter_fromname', 'filter_fromemail', 'filter_title', 'filter_subject', 'filter_sendtimestart', 'filter_sendtimeend', 'filter_exact', 'start', 'limit', ], params, callback); } /*****************************************************************************/ /************************** Campaign Stats Methods ***************************/ /*****************************************************************************/ /** * Get all email addresses that complained about a given campaign. * * @see http://www.mailchimp.com/api/1.1/campaignabusereports.func.php */ MailChimpAPI_v1_1.prototype.campaignAbuseReports = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignAbuseReports', [ 'cid', 'start', 'limit', ], params, callback); } /** * Get an array of the urls being tracked, and their click counts for a given * campaign. * * @see http://www.mailchimp.com/api/1.1/campaignclickstats.func.php */ MailChimpAPI_v1_1.prototype.campaignClickStats = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignClickStats', [ 'cid', ], params, callback); } /** * Get all email addresses with Hard Bounces for a given campaign. * * @see http://www.mailchimp.com/api/1.1/campaignhardbounces.func.php */ MailChimpAPI_v1_1.prototype.campaignHardBounces = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignHardBounces', [ 'cid', 'start', 'limit', ], params, callback); } /** * Get all email addresses with Soft Bounces for a given campaign. * * @see http://www.mailchimp.com/api/1.1/campaignsoftbounces.func.php */ MailChimpAPI_v1_1.prototype.campaignSoftBounces = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignSoftBounces', [ 'cid', 'start', 'limit', ], params, callback); } /** * Given a list and a campaign, get all the relevant campaign statistics * (opens, bounces, clicks, etc.). * * @see http://www.mailchimp.com/api/1.1/campaignstats.func.php */ MailChimpAPI_v1_1.prototype.campaignStats = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignStats', [ 'cid', ], params, callback); } /** * Get all unsubscribed email addresses for a given campaign. * * @see http://www.mailchimp.com/api/1.1/campaignunsubscribes.func.php */ MailChimpAPI_v1_1.prototype.campaignUnsubscribes = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignUnsubscribes', [ 'cid', 'start', 'limit', ], params, callback); } /*****************************************************************************/ /*************************** Campaign AIM Methods ***************************/ /*****************************************************************************/ /** * Return the list of email addresses that clicked on a given url, and how many * times they clicked. * * @see http://www.mailchimp.com/api/1.1/campaignclickdetailaim.func.php */ MailChimpAPI_v1_1.prototype.campaignClickDetailAIM = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignClickDetailAIM', [ 'cid', 'url', 'start', 'limit', ], params, callback); } /** * Given a campaign and email address, return the entire click and open history * with timestamps, ordered by time. * * @see http://www.mailchimp.com/api/1.1/campaignemailstatsaim.func.php */ MailChimpAPI_v1_1.prototype.campaignEmailStatsAIM = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignEmailStatsAIM', [ 'cid', 'email_address', ], params, callback); } /** * Given a campaign and correct paging limits, return the entire click and open * history with timestamps, ordered by time, for every user a campaign was * delivered to. * * @see http://www.mailchimp.com/api/1.1/campaignemailstatsaimall.func.php */ MailChimpAPI_v1_1.prototype.campaignEmailStatsAIMAll = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignEmailStatsAIMAll', [ 'cid', 'start', 'limit', ], params, callback); } /** * Retrieve the list of email addresses that did not open a given campaign. * * @see http://www.mailchimp.com/api/1.1/campaignnotopenedaim.func.php */ MailChimpAPI_v1_1.prototype.campaignNotOpenedAIM = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignNotOpenedAIM', [ 'cid', 'start', 'limit', ], params, callback); } /** * Retrieve the list of email addresses that opened a given campaign with how * many times they opened - note: this AIM function is free and does not * actually require the AIM module to be installed. * * @see http://www.mailchimp.com/api/1.1/campaignopenedaim.func.php */ MailChimpAPI_v1_1.prototype.campaignOpenedAIM = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('campaignOpenedAIM', [ 'cid', 'start', 'limit', ], params, callback); } /*****************************************************************************/ /****************************** Helper Methods *******************************/ /*****************************************************************************/ /** * Create a new folder to file campaigns in. * * @see http://www.mailchimp.com/api/1.1/createfolder.func.php */ MailChimpAPI_v1_1.prototype.createFolder = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('createFolder', [ 'name', ], params, callback); } /** * Have HTML content auto-converted to a text-only format. * * @see http://www.mailchimp.com/api/1.1/generatetext.func.php */ MailChimpAPI_v1_1.prototype.generateText = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('generateText', [ 'type', 'content', ], params, callback); } /** * Retrieve your User Unique Id and your Affiliate link to display/use for * Monkey Rewards. * * @see http://www.mailchimp.com/api/1.1/getaffiliateinfo.func.php */ MailChimpAPI_v1_1.prototype.getAffiliateInfo = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('getAffiliateInfo', [ ], params, callback); } /** * Send your HTML content to have the CSS inlined and optionally remove the * original styles. * * @see http://www.mailchimp.com/api/1.1/inlinecss.func.php */ MailChimpAPI_v1_1.prototype.inlineCss = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('inlineCss', [ 'html', 'strip_css', ], params, callback); } /** * "Ping" the MailChimp API - a simple method you can call that will return a * constant value as long as everything is good. * * @see http://www.mailchimp.com/api/1.1/ping.func.php */ MailChimpAPI_v1_1.prototype.ping = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('ping', [ ], params, callback); } /*****************************************************************************/ /*************************** List Related Methods ****************************/ /*****************************************************************************/ /** * Subscribe a batch of email addresses to a list at once. * * @see http://www.mailchimp.com/api/1.1/listbatchsubscribe.func.php */ MailChimpAPI_v1_1.prototype.listBatchSubscribe = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listBatchSubscribe', [ 'id', 'batch', 'double_optin', 'update_existing', 'replace_interests', ], params, callback); } /** * Unsubscribe a batch of email addresses to a list. * * @see http://www.mailchimp.com/api/1.1/listbatchunsubscribe.func.php */ MailChimpAPI_v1_1.prototype.listBatchUnsubscribe = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listBatchUnsubscribe', [ 'id', 'emails', 'delete_member', 'send_goodbye', 'send_notify', ], params, callback); } /** * Add a single Interest Group - if interest groups for the List are not yet * enabled, adding the first group will automatically turn them on. * * @see http://www.mailchimp.com/api/1.1/listinterestgroupadd.func.php */ MailChimpAPI_v1_1.prototype.listInterestGroupAdd = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listInterestGroupAdd', [ 'id', 'group_name', 'grouping_id', 'optional', ], params, callback); } /** * Delete a single Interest Group - if the last group for a list is deleted, * this will also turn groups for the list off. * * @see http://www.mailchimp.com/api/1.1/listinterestgroupdel.func.php */ MailChimpAPI_v1_1.prototype.listInterestGroupDel = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listInterestGroupDel', [ 'id', 'group_name', 'grouping_id', 'optional', ], params, callback); } /** * Get the list of interest groupings for a given list, including the label, * form information, and included groups for each. * * @see http://www.mailchimp.com/api/1.1/listinterestgroupings.func.php */ MailChimpAPI_v1_1.prototype.listInterestGroupings = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listInterestGroupings', [ 'id', ], params, callback); } /** * Get the list of interest groups for a given list, including the label and * form information. * * @see http://www.mailchimp.com/api/1.1/listinterestgroups.func.php */ MailChimpAPI_v1_1.prototype.listInterestGroups = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listInterestGroups', [ 'id', ], params, callback); } /** * Get all the information for particular members of a list. * * @see http://www.mailchimp.com/api/1.1/listmemberinfo.func.php */ MailChimpAPI_v1_1.prototype.listMemberInfo = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listMemberInfo', [ 'id', 'email_address', ], params, callback); } /** * Get all of the list members for a list that are of a particular status. * * @see http://www.mailchimp.com/api/1.1/listmembers.func.php */ MailChimpAPI_v1_1.prototype.listMembers = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listMembers', [ 'id', 'status', 'start', 'limit', ], params, callback); } /** * Add a new merge tag to a given list. * * @see http://www.mailchimp.com/api/1.1/listmergevaradd.func.php */ MailChimpAPI_v1_1.prototype.listMergeVarAdd = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listMergeVarAdd', [ 'id', 'tag', 'name', 'req', ], params, callback); } /** * Delete a merge tag from a given list and all its members. * * @see http://www.mailchimp.com/api/1.1/listmergevardel.func.php */ MailChimpAPI_v1_1.prototype.listMergeVarDel = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listMergeVarDel', [ 'id', 'tag', ], params, callback); } /** * Get the list of merge tags for a given list, including their name, tag, and * required setting. * * @see http://www.mailchimp.com/api/1.1/listmergevars.func.php */ MailChimpAPI_v1_1.prototype.listMergeVars = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listMergeVars', [ 'id', ], params, callback); } /** * Subscribe the provided email to a list. * * @see http://www.mailchimp.com/api/1.1/listsubscribe.func.php */ MailChimpAPI_v1_1.prototype.listSubscribe = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listSubscribe', [ 'id', 'email_address', 'merge_vars', 'email_type', 'double_optin', ], params, callback); } /** * Unsubscribe the given email address from the list. * * @see http://www.mailchimp.com/api/1.1/listunsubscribe.func.php */ MailChimpAPI_v1_1.prototype.listUnsubscribe = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listUnsubscribe', [ 'id', 'email_address', 'delete_member', 'send_goodbye', 'send_notify', ], params, callback); } /** * Edit the email address, merge fields, and interest groups for a list member. * * @see http://www.mailchimp.com/api/1.1/listupdatemember.func.php */ MailChimpAPI_v1_1.prototype.listUpdateMember = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('listUpdateMember', [ 'id', 'email_address', 'merge_vars', 'email_type', 'replace_interests', ], params, callback); } /** * Retrieve all of the lists defined for your user account. * * @see http://www.mailchimp.com/api/1.1/lists.func.php */ MailChimpAPI_v1_1.prototype.lists = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('lists', [ ], params, callback); } /*****************************************************************************/ /************************* Security Related Methods **************************/ /*****************************************************************************/ /** * Add an API Key to your account. * * @see http://www.mailchimp.com/api/1.1/apikeyadd.func.php */ MailChimpAPI_v1_1.prototype.apikeyAdd = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('apikeyAdd', [ 'username', 'password', ], params, callback); } /** * Expire a Specific API Key. * * @see http://www.mailchimp.com/api/1.1/apikeyexpire.func.php */ MailChimpAPI_v1_1.prototype.apikeyExpire = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('apikeyExpire', [ 'username', 'password', ], params, callback); } /** * Retrieve a list of all MailChimp API Keys for this User. * * @see http://www.mailchimp.com/api/1.1/apikeys.func.php */ MailChimpAPI_v1_1.prototype.apikeys = function (params, callback) { if (typeof params == 'function') callback = params, params = {}; this.execute('apikeys', [ 'username', 'password', 'expired', ], params, callback); }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _colorLogger = require('color-logger'); var _colorLogger2 = _interopRequireDefault(_colorLogger); var _AbstractDocJs = require('./AbstractDoc.js'); var _AbstractDocJs2 = _interopRequireDefault(_AbstractDocJs); /** * Doc Class for Assignment AST node. */ var AssignmentDoc = (function (_AbstractDoc) { _inherits(AssignmentDoc, _AbstractDoc); function AssignmentDoc() { _classCallCheck(this, AssignmentDoc); _get(Object.getPrototypeOf(AssignmentDoc.prototype), 'constructor', this).apply(this, arguments); } _createClass(AssignmentDoc, [{ key: '@_kind', /** * specify ``variable`` to kind. */ value: function _kind() { _get(Object.getPrototypeOf(AssignmentDoc.prototype), '@_kind', this).call(this); if (this._value.kind) return; this._value.kind = 'variable'; } /** * take out self name from self node. */ }, { key: '@_name', value: function _name() { _get(Object.getPrototypeOf(AssignmentDoc.prototype), '@_name', this).call(this); if (this._value.name) return; var name = this._flattenMemberExpression(this._node.left).replace(/^this\./, ''); this._value.name = name; } /** * take out self memberof from file path. */ }, { key: '@_memberof', value: function _memberof() { _get(Object.getPrototypeOf(AssignmentDoc.prototype), '@_memberof', this).call(this); if (this._value.memberof) return; this._value.memberof = this._pathResolver.filePath; } }]); return AssignmentDoc; })(_AbstractDocJs2['default']); exports['default'] = AssignmentDoc; module.exports = exports['default'];
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var Perimeter = require('./Perimeter'); var Point = require('../point/Point'); /** * Position is a value between 0 and 1 where 0 = the top-left of the rectangle and 0.5 = the bottom right. * * @function Phaser.Geom.Rectangle.GetPoint * @since 3.0.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * * @param {Phaser.Geom.Rectangle} rectangle - [description] * @param {number} position - [description] * @param {(Phaser.Geom.Point|object)} [out] - [description] * * @return {Phaser.Geom.Point} [description] */ var GetPoint = function (rectangle, position, out) { if (out === undefined) { out = new Point(); } if (position <= 0 || position >= 1) { out.x = rectangle.x; out.y = rectangle.y; return out; } var p = Perimeter(rectangle) * position; if (position > 0.5) { p -= (rectangle.width + rectangle.height); if (p <= rectangle.width) { // Face 3 out.x = rectangle.right - p; out.y = rectangle.bottom; } else { // Face 4 out.x = rectangle.x; out.y = rectangle.bottom - (p - rectangle.width); } } else if (p <= rectangle.width) { // Face 1 out.x = rectangle.x + p; out.y = rectangle.y; } else { // Face 2 out.x = rectangle.right; out.y = rectangle.y + (p - rectangle.width); } return out; }; module.exports = GetPoint;
/** * Utility functions for activity monitor presentation * @module built.app.activity.activity */ define(function(require, exports, module) { var vent = require('built/app/vent').vent; var events = require('./events'); var count = 0; /** * called to trigger activity monitor to be presented * should be called every time you want to display indicator * @function * @memberOf built.app.activity.activity */ function presentNetworkActivityIndicator(){ count++; vent.trigger(events.PRESENT); } /** * called to trigger dismissal of the activity monitor * @function * @memberOf built.app.activity.activity */ function dismissNetworkActivityIndicator(){ count--; if(count <= 0){ count = 0; vent.trigger(events.DISMISS); } } exports.presentNetworkActivityIndicator = presentNetworkActivityIndicator; exports.dismissNetworkActivityIndicator = dismissNetworkActivityIndicator; });
// https://github.com/DevExpress/DevExtreme.AspNet.Data // Copyright (c) Developer Express Inc. // jshint strict: true, browser: true, jquery: true, undef: true, unused: true, eqeqeq: true /* global DevExpress, define */ (function(factory) { "use strict"; if(typeof define === "function" && define.amd) { define(function(require, exports, module) { module.exports = factory( require("jquery"), require("devextreme/data/custom_store"), require("devextreme/data/utils") ); }); } else { DevExpress.data.AspNet = factory( jQuery, DevExpress.data.CustomStore, DevExpress.data.utils ); } })(function($, CustomStore, dataUtils) { "use strict"; function createStore(options) { var store = new CustomStore(createStoreConfig(options)); store._useDefaultSearch = true; return store; } function createStoreConfig(options) { var keyExpr = options.key, loadUrl = options.loadUrl, loadParams = options.loadParams, updateUrl = options.updateUrl, insertUrl = options.insertUrl, deleteUrl = options.deleteUrl, onBeforeSend = options.onBeforeSend; function send(operation, requiresKey, ajaxSettings, customSuccessHandler) { var d = $.Deferred(); if(requiresKey && !keyExpr) { d.reject(new Error("Primary key is not specified (operation: '" + operation + "', url: '" + ajaxSettings.url + "')")); } else { if(operation === "load") ajaxSettings.cache = false; if(onBeforeSend) onBeforeSend(operation, ajaxSettings); $.ajax(ajaxSettings) .done(function(res) { if(customSuccessHandler) customSuccessHandler(d, res); else d.resolve(res); }) .fail(function(xhr, textStatus) { var message = getErrorMessageFromXhr(xhr); if(message) d.reject(message); else d.reject(xhr, textStatus); }); } return d.promise(); } function filterByKey(keyValue) { if(!$.isArray(keyExpr)) return [keyExpr, keyValue]; return $.map(keyExpr, function(i) { return [[i, keyValue[i]]]; }); } function loadOptionsToActionParams(options, isCountQuery) { var result = {}; if(isCountQuery) result.isCountQuery = isCountQuery; if(options) { $.each(["skip", "take", "requireTotalCount", "requireGroupCount"], function() { if(this in options) result[this] = options[this]; }); var normalizeSorting = dataUtils.normalizeSortingInfo, group = options.group, filter = options.filter; if(options.sort) result.sort = JSON.stringify(normalizeSorting(options.sort)); if(group) { if(!isAdvancedGrouping(group)) group = normalizeSorting(group); result.group = JSON.stringify(group); } if($.isArray(filter)) { filter = $.extend(true, [], filter); stringifyDatesInFilter(filter); result.filter = JSON.stringify(filter); } if(options.totalSummary) result.totalSummary = JSON.stringify(options.totalSummary); if(options.groupSummary) result.groupSummary = JSON.stringify(options.groupSummary); } $.extend(result, loadParams); return result; } return { key: keyExpr, load: function(loadOptions) { return send( "load", false, { url: loadUrl, data: loadOptionsToActionParams(loadOptions) }, function(d, res) { if("data" in res) d.resolve(res.data, { totalCount: res.totalCount, summary: res.summary, groupCount: res.groupCount }); else d.resolve(res); } ); }, totalCount: function(loadOptions) { return send("load", false, { url: loadUrl, data: loadOptionsToActionParams(loadOptions, true) }); }, byKey: function(key) { return send( "load", true, { url: loadUrl, data: loadOptionsToActionParams({ filter: filterByKey(key) }) }, function(d, res) { d.resolve(res[0]); } ); }, update: updateUrl && function(key, values) { return send("update", true, { url: updateUrl, type: options.updateMethod || "PUT", data: { key: serializeKey(key), values: JSON.stringify(values) } }); }, insert: insertUrl && function(values) { return send("insert", true, { url: insertUrl, type: options.insertMethod || "POST", data: { values: JSON.stringify(values) } }); }, remove: deleteUrl && function(key) { return send("delete", true, { url: deleteUrl, type: options.deleteMethod || "DELETE", data: { key: serializeKey(key) } }); } }; } function serializeKey(key) { if(typeof key === "object") return JSON.stringify(key); return key; } function serializeDate(date) { function zpad(text, len) { text = String(text); while(text.length < len) text = "0" + text; return text; } var builder = [1 + date.getMonth(), "/", date.getDate(), "/", date.getFullYear()], h = date.getHours(), m = date.getMinutes(), s = date.getSeconds(), f = date.getMilliseconds(); if(h + m + s + f > 0) builder.push(" ", zpad(h, 2), ":", zpad(m, 2), ":", zpad(s, 2), ".", zpad(f, 3)); return builder.join(""); } function stringifyDatesInFilter(crit) { $.each(crit, function(k, v) { switch($.type(v)) { case "array": stringifyDatesInFilter(v); break; case "date": crit[k] = serializeDate(v); break; } }); } function isAdvancedGrouping(expr) { if(!$.isArray(expr)) return false; for(var i = 0; i < expr.length; i++) { if("groupInterval" in expr[i] || "isExpanded" in expr[i]) return true; } return false; } function getErrorMessageFromXhr(xhr) { var mime = xhr.getResponseHeader("Content-Type"), responseText = xhr.responseText; if(!mime) return null; if(mime.indexOf("text/plain") === 0) return responseText; if(mime.indexOf("application/json") === 0) { var jsonObj = safeParseJSON(responseText); if(typeof jsonObj === "string") return jsonObj; if($.isPlainObject(jsonObj)) { for(var key in jsonObj) { if(typeof jsonObj[key] === "string") return jsonObj[key]; } } return responseText; } return null; } function safeParseJSON(json) { try { return JSON.parse(json); } catch(x) { return null; } } return { createStore: createStore }; });
/* jquery.nexMenu.js http://www.extgrid.com/menu author:nobo qq:505931977 QQ交流群:13197510 email:zere.nobo@gmail.com or QQ邮箱 */ ;(function($){ "use strict"; var menu = Nex.widget('menu'); //Nex.menuzIndex = 99997; $.nexMenu = $.extMenu = menu; menu.extend({ version : '1.0', getDefaults : function(opt){ var _opt = { prefix : 'nexmenu-', renderTo : document.body, width : 0, height : 0, maxWidth : 0, minWidth : 120, minHeight : 0, maxHeight : 0, isIE : !!window.ActiveXObject, url : '',//无效 不支持支持远程创建 返回数据格式 json cache : true, dataType : 'json', queryParams : {}, method : 'get', parames : {}, data : [], splitChr : ['-',',',';','|'], cls : '', delay : 0,//延迟毫秒数 ms _t_delay : 0, IEVer : Nex.IEVer, border : false, borderCls : 'nex-menu-border', showShadow : true, hideToRemove : true, showMenuVLine : false,//显示节点线条 showMenuIcon : true,//显示节点图标 showMenuMore : true,//如果列表过多 显示上下 btn _speedTime : 10, _speedNum : 5, _data : {}, _childrens : {}, _levelData : {},//level=>[] _firstNodes : {},// 0:node1,1:node2 k=>v k表示第几级 _lastNodes : {},// 0:node1,1:node2 k=>v k表示第几级 clickToHide : true, expandOnEvent : 0,//0 mousover 1 click simpleData : false, root : '0',//simpleData下可不用设置且只在初始化时有效,初始化后会用showRowId代替 showRootId : '0',//请设置对应的顶层ID 非simpleData下可不用设置 iconField : 'icon',//图标字段 样式 iconClsField : 'iconCls',//图标字段 样式 idField : 'id', textField : 'text', openField : 'open', levelField : '_level', parentField : 'pid', sortField : 'order', childField : 'items', disabledField : 'disabled', groupNode : false,//开启后会对叶子和节点进行分类 showConf : {xAlign:'right',yAlign:'bottom',zAlign:'x'}, events : { onStart : $.noop, onCreate : $.noop, onSizeChange : $.noop, onClick : $.noop, onDblClick : $.noop, onFocus : $.noop, onBlur : $.noop, onKeyDown : $.noop, onKeyUp : $.noop, onKeyPress : $.noop, onMouseOver : $.noop, onMouseOut : $.noop, onPaste : $.noop, onMouseDown : $.noop, onMouseUp : $.noop, onDestroy : $.noop } }; var _opt = this.extSet(_opt); return $.extend({},_opt,opt); } }); $.nexMenu.fn.extend({ _init : function(opt) { var self = this; self._mapTree(opt.data); //self.show(); }, _sysEvents : function(){ var self = this; var opt = self.configs; self.bind("onMouseOver.over",self.onMouseOver,self); self.bind("onMouseOut.over",self.onMouseOut,self); self.bind("onClick.click",self._clickItem,self); self.bind(opt.expandOnEvent == 0 ? "onMouseOver.over" : "onClick.over",self._displayMenu,self); return self; }, _clickItem : function(li,tid,node,e){ var self = this, opt=this.configs; if( node[opt.disabledField] ) { return; } if( $.isFunction( node['callBack'] ) ) node['callBack'].apply(self,[li,tid,node,e]); if( self.isLeaf( tid ) && opt.clickToHide ) { self.hideAllMenu(opt.root,1); } }, onMouseOver : function(li,tid,node,e){ var self = this, opt=this.configs; if( node[opt.disabledField] ) { return; } $(li).addClass("nex-menu-item-over"); }, onMouseOut : function(li,tid,node,e){ var self = this, opt=this.configs, undef; if( node[opt.disabledField] ) { return; } $(li).removeClass("nex-menu-item-over"); }, _displayMenu : function(div,tid,node,e){ var self = this, opt=this.configs, undef; self.hideAllMenu(tid); if( node[opt.disabledField] ) { return; } var menu = self.createMenu(tid); self._showAt( menu,div,opt.showConf ); }, _getNode : function(tid,pro){ var self = this, opt=this.configs, undef; //var node = opt._data[ opt._tfix+tid ]; var node = opt._data[ tid ]; if( node === undef ) { return false; } return pro===undef ? node : node[pro]; }, _getParentID : function(tid){ var self = this, opt=this.configs, undef; var pid = self._getNode(tid,opt.parentField); return pid === opt.root ? opt.root : pid; }, _parseSimpleData : function(data,pid){ var self = this, opt=this.configs; var undef; var _ids = {}; for( var i=0;i<data.length;i++ ) { var node = data[i]; if( self.inArray( node,opt.splitChr ) !== -1 ) { node = { splitLine : true }; } if( node[opt.parentField] === undef ) { node[opt.parentField] = pid === undef ? opt.root : pid; node[opt.levelField] = pid === undef ? 0 : self._getNode(pid,opt.levelField)+1; } else { node[opt.levelField] = self._getNode(node[opt.parentField],opt.levelField)+1; } if( !(opt.idField in node) ) { node[opt.idField] = 'menu_'+self.unique(); } else{ if(node[opt.idField].toString().length<=0) { node[opt.idField] = 'menu_'+self.unique(); } } opt._data[ node[opt.idField] ] = node; var _pid = node[opt.parentField]; opt._childrens[ _pid ] = opt._childrens[ _pid ] === undef ? [] : opt._childrens[ _pid ]; var childs = opt._childrens[ _pid ]; childs.push(node); //levelData var _lv = node[opt.levelField]; opt._levelData[ _lv ] = opt._levelData[ _lv ] === undef ? [] : opt._levelData[ _lv ]; var levels = opt._levelData[ _lv ]; levels.push(node); _ids[_pid] = true; } for( var nid in _ids ) { //self.groupNodes( nid ); self.updateLastNodes( nid ); } }, //解析数据 _mapTree : function(data,pid){ var self = this, opt=this.configs; var undef; if( opt.simpleData ) { self._parseSimpleData(data,pid); return self; } for( var i=0;i<data.length;i++ ) { var node = data[i]; if( self.inArray( node,opt.splitChr ) !== -1 ) { node = { splitLine : true }; } node[opt.levelField] = pid === undef ? 0 : self._getNode(pid,opt.levelField)+1; node[opt.parentField] = pid === undef ? opt.root : pid; if( !(opt.idField in node) ) { node[opt.idField] = 'menu_'+self.unique(); } opt._data[ node[opt.idField] ] = node; var _pid = node[opt.parentField]; opt._childrens[ _pid ] = opt._childrens[ _pid ] === undef ? [] : opt._childrens[ _pid ]; var childs = opt._childrens[ _pid ]; childs.push(node); //levelData var _lv = node[opt.levelField]; opt._levelData[ _lv ] = opt._levelData[ _lv ] === undef ? [] : opt._levelData[ _lv ]; var levels = opt._levelData[ _lv ]; levels.push(node); if( ( opt.childField in node ) && node[opt.childField].length ) { self._mapTree(node[opt.childField],node[opt.idField]); } if( (i+1) === data.length ) { //self.groupNodes( _pid ); self.updateLastNodes( _pid ); } } return self; }, /* * 对当前级的数据进行节点和叶子分类 */ groupNodes : function(pid){ var self = this, opt=this.configs, undef; var pid = pid === undef ? opt.root : pid; var _d = opt._childrens[ pid ]; if( !opt.groupNode ) return _d; var nodes=[],leafs=[]; var len = _d.length; for( var i=0;i<len;i++ ) { if(self.isLeaf( _d[i] )) { leafs.push( _d[i] ); } else { nodes.push( _d[i] ); } } opt._childrens[ pid ] = nodes.concat(leafs); return opt._childrens[pid]; }, /* *更新 第一个节点和最后一个节点的索引 */ updateLastNodes : function(pid){ var self = this, opt=this.configs, undef; var pid = pid === undef ? opt.root : pid; var chlids = opt._childrens[pid]; if( chlids.length ) { opt._firstNodes[pid] = chlids[0]; opt._lastNodes[pid] = chlids[chlids.length-1]; } }, addChildren : function(tid,data){ var self = this, opt=this.configs, undef; var d = !$.isArray( data ) ? [data] : data; self._mapTree(d,tid); // self.refreshMenu(tid); }, isSplitLine : function( node ){ var self = this ,opt=this.configs ,undef; if( node.splitLine ) return true; return false; }, isLeaf : function(node){ var self = this ,opt=this.configs ,undef; if( node === opt.root ) return false; var tnode = $.isPlainObject(node) ? node : self._getNode(node); if( tnode === false && !self._isRoot(node) ) return true; if( self._isRoot(node) ) return false; if( tnode.leaf === undef ) { var tid = tnode[opt.idField]; var childrens = self.getChildrens(tid); if( childrens.length ) { return false; } if( (opt.childField in tnode) && tnode[opt.childField].length ) { return false; } return true; } else { return !!tnode.leaf; } }, getAllChildrens : function(pid) { var self = this ,opt=this.configs ,undef; var childs = []; var pid = self._undef(pid,opt.root); var getChilds = function(pid){ var _childs = self.getChildrens(pid); if( _childs.length ) { childs = childs.concat(_childs); for( var i=0;i<_childs.length;i++ ) { getChilds(_childs[i][opt.idField]); } } } getChilds(pid); return childs; }, /* *获取子级 */ getChildrens : function(pid){ var self = this ,opt=this.configs ,undef; var pid = pid === undef ? opt.root : pid; return opt._childrens[pid] === undef ? [] : opt._childrens[pid]; }, _getParentsList : function(tid){ var self = this ,opt=this.configs ,root=opt.root ,pids = []; var node = $.isPlainObject(tid) ? tid : self._getNode(tid); if( node===false ) return []; var id = node[opt.idField]; var pid = self._getParentID(id); while( 1 ) { if( !(pid in opt._data) ) break; pids.push( pid ); pid = self._getParentID(pid); if( pid === opt.root ) break; } return pids.reverse(); }, _isFirstNode : function(tid){ var self = this ,opt=this.configs; var _pid = self._getParentID(tid); return opt._firstNodes[_pid][opt.idField] === tid ? true : false; }, _isLastNode : function(tid){ var self = this ,opt=this.configs; var _pid = self._getParentID(tid); return opt._lastNodes[_pid][opt.idField] === tid ? true : false; }, getMenuItem : function(tnode){ var self = this ,opt=this.configs ,spacers = []; var node = $.isPlainObject(tnode) ? tnode : self._getNode(tnode); if( node===false ) return ''; if( self.isSplitLine( node ) ) { return '<div class="nex-menu-item-separator"><div class="nex-menu-line-h"></div></div>'; } var tid = node[opt.idField]; var menuID = [opt.id,'_',node[opt.idField]].join(""); var _pid = self._getParentID(tid); var liCls=''; if( opt._firstNodes[_pid][opt.idField] === tid ) { liCls = 'nex-menu-first'; if( opt._firstNodes[opt.root][opt.idField] === tid ) { liCls+=' nex-menu-first-all'; } } if( opt._lastNodes[_pid][opt.idField] === tid ) { liCls = 'nex-menu-last'; } if( node[opt.disabledField] ) { liCls += ' nex-menu-item-disabled'; } var isLeaf = self.isLeaf(tid); self.fireEvent('onBeforeCreateItem',[ tid,liCls ]); var _s = []; var _bg = ''; if( tnode[opt.iconField] ) { _bg = "background-image:url("+tnode[opt.iconField]+")"; } _s.push(['<div id="',menuID,'_item" menuid="',tid,'" class="nex-menu-item ',liCls,'">'].join("")); if( opt.showMenuIcon ) { _s.push(['<span class="nex-menu-icon ',tnode[opt.iconClsField],'" style="',_bg,'"></span>'].join('')); } _s.push(['<span class="nex-menu-title">',node[opt.textField],'</span>'].join('')); if( !isLeaf ) { _s.push(['<span class="nex-menu-arrow">&nbsp;</span>'].join('')); } _s.push('</div>'); self.fireEvent('onCreateItem',[ tid,_s ]); return _s.join(''); }, _isRoot : function(tid){ var self = this ,opt=this.configs; return (tid === opt.root) ? true : false; }, _bindUpBtnEvent : function( up,menu ){ var self = this ,opt=this.configs; var menu = menu || down.parent(); var wraper = $('>.nex-menu-items-wraper',menu); var down = $('>.nex-menu-down',menu); up.bind({ mouseenter : function(){ var i = parseInt(wraper.css( 'margin-top' )); var tid = $(this).attr('menuid'); self.hideAllMenu2( tid ); down.show(); if( opt._t_down ) { clearInterval( opt._t_down ); } opt._t_down = setInterval(function(){ i = i+opt._speedNum; i = Math.min(i,0); wraper.css({ 'margin-top' : i }); if( i>=0 ) { up.hide(); clearInterval( opt._t_down ); } },opt._speedTime); }, mouseleave : function(){ clearInterval( opt._t_down ); } }); }, _bindDownBtnEvent : function( down,menu ){ var self = this ,opt=this.configs; var menu = menu || down.parent(); var up = $('>.nex-menu-up',menu); var wraper = $('>.nex-menu-items-wraper',menu); var h1 = $(menu).height(), h2 = wraper.outerHeight(); var diff = h2 - h1; down.bind({ mouseenter : function(){ var i = -parseInt(wraper.css( 'margin-top' )); var tid = $(this).attr('menuid'); self.hideAllMenu2( tid ); up.show(); if( opt._t_down ) { clearInterval( opt._t_down ); } opt._t_down = setInterval(function(){ i = i+opt._speedNum; i = Math.min(i,diff); wraper.css({ 'margin-top' : -i }); if( i>=diff ) { down.hide(); clearInterval( opt._t_down ); } },opt._speedTime); }, mouseleave : function(){ clearInterval( opt._t_down ); } }); }, _checkMenuHeight : function( tid,menu ){ var self = this ,opt=this.configs; if( !menu ) return false; var h1 = $(menu).height(), h2 = $('>.nex-menu-items-wraper',menu).outerHeight(); if( h2 <= h1 ) return false; var up = $('<div class="nex-menu-up" menuid="'+tid+'"></div>'), down = $('<div class="nex-menu-down" menuid="'+tid+'"></div>'); menu.append( up ); menu.append( down ); up.hide(); self._bindUpBtnEvent(up,menu); self._bindDownBtnEvent(down,menu); self.fireEvent('onMenuScrollBtnCreate',[tid,up,down,opt]); }, /* *事件绑定 注:并没有阻止事件冒泡 */ _bindMenuEvent : function(lis){ var self = this ,opt=this.configs; var menus = opt._data; var callBack = function(type,e){ var tid = $(this).attr('menuid'); var node = self._getNode(tid); var r = true; if( (type in node) && $.isFunction(node[type]) ) { r = node[type].apply(self,[this,tid,menus[tid],e]); } if( r!==false ) { r = self.fireEvent(type,[ this,tid,menus[tid],e ]); } if( r === false ) { e.stopPropagation(); e.preventDefault(); } }; var events = { 'click' : function(e) { callBack.call(this,'onClick',e); }, 'dblclick' : function(e) { callBack.call(this,'onDblClick',e); }, 'keydown' : function(e) { callBack.call(this,'onKeyDown',e); }, 'keyup' : function(e) { callBack.call(this,'onKeyUp',e); }, 'keypress' : function(e){ callBack.call(this,'onKeyPress',e); }, 'mouseenter' : function(e){ callBack.call(this,'onMouseOver',e); }, 'mouseleave' : function(e){ callBack.call(this,'onMouseOut',e); }, 'mousedown' : function(e) { callBack.call(this,'onMouseDown',e); }, 'mouseup' : function(e) { callBack.call(this,'onMouseUp',e); }, 'contextmenu' : function(e){ callBack.call(this,'onContextMenu',e); } }; lis.bind(events); self.fireEvent('onBindMenuEvents',[ lis,events,opt ]); }, bindMenuEvent : function(menu){ var returnfalse = function(){return false;}; $(menu).bind({ 'mousedown' : returnfalse, 'mouseover' : returnfalse, contextmenu : returnfalse, click : returnfalse }); this._bindMenuEvent($(">.nex-menu-item",menu)); }, /* *创建Tree但不显示 */ _bulidMenu : function(tid){ var self = this ,opt=this.configs; var tid = self._undef(tid,opt.root); if( self.isLeaf( tid ) ) { return false; } var node = self._getNode(tid); var menuID = [opt.id,'_',tid].join(""); var menu = $("#"+menuID); var r = self.fireEvent('onBeforeBulidMenu',[ menu,tid,opt ]); if( r === false ) return false; var createMenu = function(){ var childrens = self._undef(opt._childrens[ tid ],[]);; var menuCls = ['nex-menu']; if( opt.border ) { menuCls.push( opt.borderCls ); } menuCls.push( opt.cls ); Nex.zIndex = Nex.zIndex + 2; var menu = ['<div id="',menuID,'" style="z-index:',Nex.zIndex,'" class="',menuCls.join(' '),'">']; menu.push('<div class="nex-menu-items-wraper" id="'+opt.id+'_items_wraper">') menu.push(opt.showMenuVLine ? '<div class="nex-menu-line-v"></div>' : ''); for( var i=0;i<childrens.length;i++ ) { menu.push( self.getMenuItem(childrens[i]) ); } menu.push('</div></div>'); menu = $(menu.join("")); var render = $(opt.renderTo); render.append(menu); opt.height = menu._outerHeight(); opt.width = node.width ? node.width : menu._outerWidth(); var maxWidth = opt.maxWidth,maxHeight = opt.maxHeight; var mh = render.is('body') ? $(window) : render; if(!opt.maxWidth) { maxWidth = mh.width(); } if(!opt.maxHeight) { maxHeight = mh.height(); } if( opt.minWidth>0 ) { opt.width = Math.max(opt.width,opt.minWidth); } if( opt.minHeight>0 ) { opt.height = Math.max(opt.height,opt.minHeight); } if( maxWidth>0 ) { opt.width = Math.min(opt.width,maxWidth); } if( maxHeight>0 ) { opt.height = Math.min(opt.height,maxHeight); } var cutH = self._getCutHeight(), cutW = self._getCutWidth(); opt.height -= cutH; opt.width -= cutW; menu._outerHeight(opt.height); menu._outerWidth(opt.width); return menu; }; if( !menu.length ) { menu = createMenu(); menu.bind('selectstart.menu',function(){return false;}); self.fireEvent('onBulidMenu',[ menu,tid,opt ]); self.bindMenuEvent($('>.nex-menu-items-wraper',menu)); if( opt.showMenuMore ) { self._checkMenuHeight( tid,menu ); } } return menu; }, _createMenu : function(tid){ var self = this ,opt=this.configs ,undef ,pids = []; if( tid === undef ) return false; var node = self._getNode(tid); if( node === false && !self._isRoot(tid) ) return false ; var tree = self._bulidMenu(tid); if( tree === false ) return false; if( node ) { node[opt.openField] = true; } //$("#"+opt.id+'_'+tid+'_wraper').addClass("nex-tree-open"); self.fireEvent('onCreateMenu',[tid,opt]); return tree; }, showMenu : function(tid,m){//m == true 默认显示 m==false 不显示 var self = this ,opt=this.configs ,undef; var tid = self._undef(tid,opt.root); var m = m === undef ? true : m; if( self.isLeaf(tid) ) { return false; } var r = self.fireEvent('onBeforeShowMenu',[tid,opt]);//CreateMenu if( r === false ) return false; var menu = self._createMenu(tid); if( m ) { menu.show(); } if( menu ) { $("#"+opt.id+"_"+tid+"_item").addClass("nex-menu-item-active"); } self.fireEvent('onShowMenu',[tid,opt]); return menu; }, createMenu : function(tid){ return this.showMenu(tid,0); }, hideMenu : function(menuid){ var self = this, opt=this.configs, undef; if( menuid === undef ) return true; var treeID = [opt.id,'_',menuid].join(""); var r = self.fireEvent('onBeforeHideMenu',[menuid,opt]); if( r === false ) return false; if( opt.hideToRemove ) { $("#"+treeID).remove(); } else { $("#"+treeID).hide(); } $("#"+treeID+'_shadow').remove(); $("#"+opt.id+"_"+menuid+"_item").removeClass("nex-menu-item-active"); self.fireEvent('onHideMenu',[menuid,opt]); return true; }, hideAllMenu2 : function(pid,m){ var self = this, opt=this.configs; var pid = self._undef(pid,opt.root); var allChilds = self.getAllChildrens(pid); for( var i=0;i<allChilds.length;i++ ) { var tid = allChilds[i][opt.idField]; var isLeaf = self.isLeaf(tid); if( !isLeaf ) { self.hideMenu(tid); } } }, /* * 隐藏当前同级item列表下所有的contextmenu */ hideAllMenu : function(pid,m){ var self = this, opt=this.configs; var pid = self._undef(pid,opt.root); pid = self._isRoot( pid ) ? pid : self._getParentID(pid); var allChilds = self.getAllChildrens(pid); if( m ) { self.hideMenu(pid); } for( var i=0;i<allChilds.length;i++ ) { var tid = allChilds[i][opt.idField]; var isLeaf = self.isLeaf(tid); if( !isLeaf ) { self.hideMenu(tid); } } }, hideRoot : function(){ this.hideAllMenu(undefined,1); }, hideLeveMenu : function(level){ var self = this, opt=this.configs, undef; if( level === undef ) return true; var menus = opt._levelData[ level ]; for( var i=0;i<menus.length;i++ ) { self.hideMenu( menus[i][opt.idField] ); } return true; }, /* *IE9以下版本不支持shadow 属性 所以用其他方法实现 */ _setShadow : function(source){ var self = this, opt=this.configs, undef; /*if( !opt.IEVer || opt.IEVer>=9 ) { return true; }*/ var shadowid = $(source).attr('id') + '_shadow'; $("#"+shadowid).remove(); var shadow = $('<div class="nex-menu-shadow" id="'+shadowid+'"><iframe class="nex-menu-shadow-iframe" frameborder="0"></iframe></div>'); shadow.appendTo(opt.renderTo); shadow.width( $(source)._outerWidth() ); shadow.height( $(source)._outerHeight() ); shadow.css( $(source).offset() ); shadow.css( "zIndex",$(source).css('z-index') - 1 ); return true; }, _showAt : function(source,target,conf,animate){ var self = this, opt=this.configs, undef; var confs = {}; var animate = animate === undef ? true : animate; $.extend( confs,opt.showConf,conf,{el:target} ); if( !source ) { return ; } if( animate && opt.delay>0 ) { if( opt._t_delay ) { clearTimeout( opt._t_delay ); opt._t_delay = 0; } opt._t_delay = setTimeout(function(){ $(source).showAt(confs); if( opt.showShadow ) { self._setShadow( source ); } },opt.delay); } else { $(source).showAt(confs); if( opt.showShadow ) { self._setShadow( source ); } } }, //显示根节点的时候 调用 showAt : function(source,target,conf){ this._showAt(source,target,conf,false); } }); })(jQuery);
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import NavigationMenu from 'material-ui/svg-icons/navigation/menu'; import MenuPopComponent from './MenuPopComponent'; import { toggleMenuAction } from './action'; class NavigationBar extends Component { static propTypes = { appbar: PropTypes.shape({ open: PropTypes.bool.isRequired, }), toggleMenu: PropTypes.func.isRequired, }; handleMenuIconTapped(event) { event.preventDefault(); if (!this.menuAnchor) { this.menuAnchor = event.currentTarget; } this.props.toggleMenu(); } handleClose() { this.props.toggleMenu(); } renderMenuButton() { return (<IconButton onTouchTap={this.handleMenuIconTapped.bind(this)} > <NavigationMenu /> </IconButton>); } render() { return (<div> <AppBar ref={bar => this.node = { bar }} title="Carbon" iconElementLeft={this.renderMenuButton()} /> <MenuPopComponent anchorEl={this.menuAnchor} open={this.props.appbar.open} handleClose={this.handleClose.bind(this)} /> </div>); } } const mapStateToProps = (state) => { const { appbar } = state; return { appbar }; }; const mapDispatchToProps = (dispatch) => { const toggleMenu = (el) => dispatch(toggleMenuAction(el)); return { toggleMenu }; }; export default connect( mapStateToProps, mapDispatchToProps, )(NavigationBar);
// Testing the main file describe(".removeClass()", function() { //var work = false; beforeEach(function(){ base.addClass('bla blu blo'); hasClass('bla blu blo'); }); afterEach(function(){ base.removeClass('bla blu blo'); hasClass('bla blu blo', true); }); it("should be defined", function() { isFn(work ? base.removeClass : false); }); it("can be called empty", function() { base.removeClass(); base.removeClass(""); base.removeClass([]); base.removeClass("",""); base.removeClass(" "); if (!work) throw "Force failure"; }); it("removes a single class", function() { if (work) base.removeClass('bla'); hasClass('bla', true); }); it("can be concatenated", function() { if (work) base.removeClass('bla').removeClass('blu'); hasClass('bla blu', true); }); describe("single argument", function(){ base.addClass('bla blu blo'); listOfClasses.forEach(function(part){ it("accepts " + part.it, function(){ if (work) base.removeClass(part.from); hasClass('bla blu blo', true); }); }); }); describe("single function argument uses the return value", function(){ base.addClass('bla blu blo'); listOfClasses.forEach(function(part){ it("accepts as a return value " + part.it, function(){ if (work) base.removeClass(function() { return part.from; }); hasClass('bla blu blo', true); }); }); }); describe("multiple functions uses the return value", function(){ function add(arg){ return function(){ return arg; }; } listOfClasses.forEach(function(part){ it("accepts as a return value " + part.it, function(){ if (work) base.removeClass(add(part.from), add("bli")); hasClass('bla blu blo bli', true); }); }); }); describe("several arguments", function(){ listOfClasses.filter(function(part){ return Array.isArray(part.from); }).forEach(function(part){ it("used .apply() with " + part.it, function(){ if (work) base.removeClass.apply(base, part.from); hasClass('bla blu blo', true); }); }); }); });
/* * Controllers for the NIPAP AngularJS app */ var nipapAppControllers = angular.module('nipapApp.controllers', []); /* * VRFListController - used to list VRFs on the /vrf/list-page */ nipapAppControllers.controller('VRFListController', function ($scope, $http) { // Fetch VRFs from backend $http.get('/xhr/list_vrf') .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.vrfs = data; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); /* * Display remove confirmation dialog */ $scope.vrfConfirmRemove = function (evt, vrf) { evt.preventDefault(); var dialog = showDialogYesNo('Really remove VRF?', 'Are you sure you want to remove the VRF "' + vrf.rt + '"?', function () { var data = { 'id': vrf.id }; $http.get('/xhr/remove_vrf', { 'params': data }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { var index = $scope.vrfs.indexOf(vrf); $scope.vrfs.splice(index, 1); // Update VRF filter - the removed VRF might be in the // VRF filter list $http.get('/xhr/get_current_vrfs') .success(receiveCurrentVRFs); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); dialog.dialog('close'); }); } }); /* * PoolListController - used to list pools on the /pool/list-page */ nipapAppControllers.controller('PoolListController', function ($scope, $http) { // Fetch Pools from backend $http.get('/xhr/list_pool') .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.pools = data; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); /* * Display remove confirmation dialog */ $scope.poolConfirmRemove = function (evt, pool) { evt.preventDefault(); var dialog = showDialogYesNo('Really remove pool?', 'Are you sure you want to remove the pool "' + pool.name + '"?', function () { var data = { 'id': pool.id }; $http.get('/xhr/remove_pool', { 'params': data }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { var index = $scope.pools.indexOf(pool); $scope.pools.splice(index, 1); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); dialog.dialog('close'); }); } }); /* * PrefixListController - Display prefix list */ nipapAppControllers.controller('PrefixListController', function ($scope, $modal) { /* * Display a popup notice informing the user of how prefixes are added from * a pool. */ $scope.showAddPrefixFromPoolNotice = function () { var modalInstance = $modal.open({ templateUrl: 'add_prefix_from_pool_notice.html', windowClass: 'nipap_modal' }); } /* * Display a popup notice informing the user of how prefixes are added from * a prefix. */ $scope.showAddPrefixFromPrefixNotice = function () { var modalInstance = $modal.open({ templateUrl: 'add_prefix_from_prefix_notice.html', windowClass: 'nipap_modal' }); } }); /* * PrefixAddController - Used to add prefixes to NIPAP */ nipapAppControllers.controller('PrefixAddController', function ($scope, $routeParams, $http, prefixHelpers) { // prefix method is add - used to customize prefix form template $scope.method = 'add'; // Expose prefixHelpers.enableNodeInput to templates $scope.enableNodeInput = prefixHelpers.enableNodeInput; // open up the datepicker $scope.dpOpen = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.dpOpened = !$scope.dpOpened; }; $scope.prefix_alloc_method = null; // Set to true if allocation method was provided in URL $scope.prefix_alloc_method_provided = false; $scope.from_pool = null; // Set to true if the pool to allocate from was provided in the URL $scope.from_pool_provided = false; $scope.from_prefix = null; // Set to true if the prefix to allocate from was provided in the URL $scope.from_prefix_provided = false; // Set to true if pool has a default prefix length for current address family $scope.pool_has_default_preflen = false; // Keep track on whether the user wants to use the pool's default prefix // length or not $scope.pool_use_default_preflen = true; $scope.pool_default_preflen = null; // Keep track of whether the user has chosen to enable the prefix type // input fields, when allocating prefix from a pool (ie. to not use the // pool's default prefix type) $scope.display_type_input_pool = false; $scope.prefix_family = 4; $scope.prefix_length = null; $scope.prefix = { prefix: null, vrf: null, pool: null, status: 'assigned', description: null, comment: null, node: null, tags: [], type: null, country: null, order_id: null, customer_id: null, vlan: null, monitor: false, alarm_priority: null, avps: [] }; // List of prefixes added to NIPAP $scope.added_prefixes = []; /* * Handle route parameters (extracted from the URL) */ // Is allocation method set? if ($routeParams.hasOwnProperty('allocation_method')) { $scope.prefix_alloc_method = $routeParams.allocation_method; $scope.prefix_alloc_method_provided = true; } // Did we get any allocation parameters (pool ID or prefix ID)? if ($routeParams.hasOwnProperty('allocation_method_parameter')) { var allocation_parameter = parseInt($routeParams.allocation_method_parameter); if ($scope.prefix_alloc_method == 'from-pool') { // Allocation method parameter is pool ID - fetch pool $scope.from_pool_provided = true; $http.get('/xhr/list_pool', { 'params': { 'id': allocation_parameter } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.from_pool = data[0]; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } else if ($scope.prefix_alloc_method == 'from-prefix') { // Allocation method parameter is prefix ID - fetch prefix $scope.from_prefix_provided = true; $http.get('/xhr/list_prefix', { 'params': { 'id': allocation_parameter } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.from_prefix = data[0]; $scope.prefix_family = data[0].family; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } } /* * Watch for change to 'from_pool' and 'prefix_family' variables */ $scope.$watchCollection('[ from_pool, prefix_family ]', function(newValue, oldValue){ if ($scope.from_pool !== null) { // We're allocating from a pool - reset from_prefix $scope.from_prefix = null; if ($scope.from_pool.default_type !== null) { $scope.prefix.type = $scope.from_pool.default_type; $scope.display_type_input_pool = false; } else { $scope.display_type_input_pool = true; } // Extract default prefix length for selected address family var def_preflen; if ($scope.prefix_family == "4") { def_preflen = "ipv4_default_prefix_length"; } else { def_preflen = "ipv6_default_prefix_length"; } if ($scope.from_pool[def_preflen] !== null) { $scope.pool_has_default_preflen = true; $scope.pool_default_preflen = $scope.from_pool[def_preflen]; $scope.prefix_length = $scope.from_pool[def_preflen]; } else { $scope.pool_has_default_preflen = false; $scope.pool_default_preflen = null; $scope.pool_use_default_preflen = false; $scope.prefix_length = null; } if ($scope.from_pool.vrf_id !== null) { // fetch VRF data for pool's implied VRF $http.get('/xhr/smart_search_vrf', { 'params': { 'vrf_id': $scope.from_pool.vrf_id, 'query_string': '' }}) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.prefix.vrf = data.result[0]; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } else { // Pool is missing implied VRF - means the pool is empty! $scope.prefix.vrf = null; } } }); /* * Watch for changes to the 'from_prefix' variable */ $scope.$watch('from_prefix', function() { if ($scope.from_prefix !== null) { // We're allocating from a prefix - reset from_pool $scope.from_pool = null; // Fetch prefix's VRF $http.get('/xhr/smart_search_vrf', { 'params': { 'vrf_id': $scope.from_prefix.vrf_id, 'query_string': '' }}) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.prefix.vrf = data.result[0]; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); // If we're allocating from an assignment, set prefix type to host // and prefix length to max prefix length for the selected address family. if ($scope.from_prefix.type == 'assignment') { $scope.prefix.type = 'host'; if ($scope.from_prefix.family == 4) { $scope.prefix_length = 32; } else { $scope.prefix_length = 128; } } } }); // add another empty "extra attribute" (AVP) input row $scope.addAvp = function() { $scope.prefix.avps.push({ 'attribute': '', 'value': '' }); } // remove AVP row $scope.removeAvp = function(avp) { var index = $scope.prefix.avps.indexOf(avp); $scope.prefix.avps.splice( index, 1 ); } /* * Submit prefix form - add prefix to NIPAP */ $scope.submitForm = function () { /* * Create object specifying prefix attributes and how it should be * added. For simplicity, we start with a copy of the prefix object * from the scope and add/remove attributes according to what's * required by the different allocation methods. */ var query_data = angular.copy($scope.prefix); query_data.vrf = null; query_data.pool = null; // Tags, VRF and pool are needed no matter allocation method query_data.tags = JSON.stringify($scope.prefix.tags.map(function (elem) { return elem.text; })); if ($scope.prefix.vrf != null) { query_data.vrf = $scope.prefix.vrf.id; } if ($scope.prefix.pool != null) { query_data.pool = $scope.prefix.pool.id; } // Mangle avps query_data.avps = {}; $scope.prefix.avps.forEach(function(avp) { query_data.avps[avp.attribute] = avp.value; }); query_data.avps = JSON.stringify(query_data.avps); if ($scope.prefix_alloc_method == 'from-pool') { // Allocation from pool requires prefix length, family and pool to // allocate from. Prefix not needed. delete query_data.prefix; query_data.family = $scope.prefix_family; if ($scope.pool_use_default_preflen) { query_data.prefix_length = $scope.pool_default_preflen; } else { query_data.prefix_length = $scope.prefix_length; } query_data.from_pool = $scope.from_pool.id; } else if ($scope.prefix_alloc_method == 'from-prefix') { // Allocation from prefix requires prefix length and prefix to // allocate from. Prefix not needed. delete query_data.prefix; query_data.prefix_length = $scope.prefix_length; query_data['from_prefix[]'] = $scope.from_prefix.prefix; } // Send query! $http.get('/xhr/add_prefix', { 'params': query_data }) .success(function (data){ if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.added_prefixes.push(data); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } }); /* * PrefixEditController - used to edit prefixes */ nipapAppControllers.controller('PrefixEditController', function ($scope, $routeParams, $http, $filter, prefixHelpers) { // Prefix method is edit - used to customize prefix form template $scope.method = 'edit'; // Expose prefixHelpers.enableNodeInput to templates $scope.enableNodeInput = prefixHelpers.enableNodeInput; // The tags-attributes needs to be initialized due to bug, // see https://github.com/mbenford/ngTagsInput/issues/204 $scope.prefix = { 'tags': [], 'inherited_tags': [] }; $scope.edited_prefixes = []; // open up the datepicker $scope.dpOpen = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.dpOpened = !$scope.dpOpened; }; // add another empty "extra attribute" (AVP) input row $scope.addAvp = function() { $scope.prefix.avps.push({ 'attribute': '', 'value': '' }); } // remove AVP row $scope.removeAvp = function(avp) { var index = $scope.prefix.avps.indexOf(avp); $scope.prefix.avps.splice( index, 1 ); } // Fetch prefix to edit from backend $http.get('/xhr/list_prefix', { 'params': { 'id': $routeParams.prefix_id } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { pref = data[0]; pref.vrf = null; pref.pool = null; // Tags needs to be mangled for use with tags-input // TODO: When all interaction with prefix add & edit functions // are moved to AngularJS, change XHR functions to use the same // format as tags-input pref.tags = Object.keys(pref.tags).map(function (elem) { return { 'text': elem }; } ); pref.inherited_tags = Object.keys(pref.inherited_tags).map(function (elem) { return { 'text': elem }; } ); pref.avps = Object.keys(pref.avps).sort().map(function (key) { return { 'attribute': key, 'value': pref.avps[key] }; } ); $scope.prefix = pref; // Fetch prefix's VRF $http.get('/xhr/smart_search_vrf', { 'params': { 'vrf_id': $scope.prefix.vrf_id, 'query_string': '' }}) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.prefix.vrf = data.result[0]; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); // Fetch prefix's pool, if any if ($scope.prefix.pool_id !== null) { $http.get('/xhr/list_pool', { 'params': { 'id': $scope.prefix.pool_id, } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.prefix.pool = data[0]; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } // Display statistics // TODO: Do in AngularJS-way, probably easiest to encapsulate // in a directive var data_prefix_addresses = [ { value: $scope.prefix.used_addresses, color: '#d74228', highlight: '#e74228', label: 'Used' }, { value: $scope.prefix.free_addresses, color: '#368400', highlight: '#36a200', label: 'Free' } ]; var options = { animationSteps : 20, animationEasing: "easeOutQuart" }; var chart_prefix_addresses = new Chart($("#canvas_prefix_addresses")[0].getContext("2d")).Doughnut(data_prefix_addresses, options); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); /* * Form submitted */ $scope.submitForm = function () { // If prefix is owned by other system, ask user to verify the changes if ($scope.prefix.authoritative_source != 'nipap') { // TODO: Replace with AngularJS-style widget showDialogYesNo( 'Confirm prefix edit', 'The prefix ' + $scope.prefix.prefix + ' is managed by ' + '\'' + $scope.prefix.authoritative_source + '\'.<br><br>' + 'Are you sure you want to edit it?', function() { $scope.savePrefix(); $(this).dialog("close"); } ); } else { $scope.savePrefix(); } } /* * Save changes made to prefix */ $scope.savePrefix = function() { // Create new object with prefix data var prefix_data = angular.copy($scope.prefix); delete prefix_data.vrf; // Mangle tags prefix_data.tags = JSON.stringify($scope.prefix.tags.map(function (elem) { return elem.text; })); // Mangle avps prefix_data.avps = {}; $scope.prefix.avps.forEach(function(avp) { prefix_data.avps[avp.attribute] = avp.value; }); prefix_data.avps = JSON.stringify(prefix_data.avps); // handle null or 'infinity' as.. infinity if ($scope.prefix.expires == null) { // empty string signifies infinity prefix_data.expires = ''; } else { // mangle prefix into ISO8601 format prefix_data.expires = $filter('date')($scope.prefix.expires, 'yyyy-MM-dd HH:mm:ss'); } // Set pool, if any if ($scope.prefix.pool !== null) { prefix_data.pool = $scope.prefix.pool.id; } // Send query! $http.get('/xhr/edit_prefix/' + $scope.prefix.id, { 'params': prefix_data }) .success(function (data){ if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.edited_prefixes.push(data); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } }); /* * VRFAddController - used to add VRFs */ nipapAppControllers.controller('VRFAddController', function ($scope, $http) { $scope.method = 'add'; $scope.added_vrfs = []; $scope.vrf = { 'rt': null, 'name': null, 'description': null, 'tags': [], 'avps': [] }; // add another empty "extra attribute" (AVP) input row $scope.addAvp = function() { $scope.vrf.avps.push({ 'attribute': '', 'value': '' }); } // remove AVP row $scope.removeAvp = function(avp){ var index = $scope.vrf.avps.indexOf(avp); $scope.vrf.avps.splice( index, 1 ); }; /* * Submit VRF form - add VRF to NIPAP */ $scope.submitForm = function () { /* * Create object specifying VRF attributes. Start with a copy of the * VRF object from the scope. */ var query_data = angular.copy($scope.vrf); // Rewrite tags list to match what's expected by the XHR functions query_data.tags = JSON.stringify($scope.vrf.tags.map(function (elem) { return elem.text; })); query_data.avps = {}; $scope.vrf.avps.forEach(function(avp) { query_data.avps[avp.attribute] = avp.value; }); query_data.avps = JSON.stringify(query_data.avps); // Send query! $http.get('/xhr/add_vrf', { 'params': query_data }) .success(function (data){ if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.added_vrfs.push(data); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } }); /* * VRFEditController - used to edit VRFs */ nipapAppControllers.controller('VRFEditController', function ($scope, $routeParams, $http) { $scope.method = 'edit'; $scope.edited_vrfs = []; $scope.vrf = { 'tags': [] }; // add another empty "extra attribute" (AVP) input row $scope.addAvp = function() { $scope.vrf.avps.push({ 'attribute': '', 'value': '' }); } // remove AVP row $scope.removeAvp = function(avp){ var index = $scope.vrf.avps.indexOf(avp); $scope.vrf.avps.splice( index, 1 ); }; // Fetch VRF to edit from backend $http.get('/xhr/smart_search_vrf', { 'params': { 'vrf_id': $routeParams.vrf_id, 'query_string': '' } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { vrf = data.result[0]; // Tags needs to be mangled for use with tags-input // TODO: When all interaction with prefix add & edit functions // are moved to AngularJS, change XHR functions to use the same // format as tags-input vrf.tags = Object.keys(vrf.tags).map(function (elem) { return { 'text': elem }; } ); vrf.avps = Object.keys(vrf.avps).sort().map(function (key) { return { 'attribute': key, 'value': vrf.avps[key] }; } ); $scope.vrf = vrf; // Display statistics // TODO: Do in AngularJS-way, probably easiest to encapsulate // in a directive var data_charts = [ { color: '#d74228', highlight: '#e74228', label: 'Used' }, { color: '#368400', highlight: '#36a200', label: 'Free' } ]; var data_vrf_addresses_v4 = angular.copy(data_charts); data_vrf_addresses_v4[0]['value'] = vrf.used_addresses_v4; data_vrf_addresses_v4[1]['value'] = vrf.free_addresses_v4; var data_vrf_addresses_v6 = angular.copy(data_charts); data_vrf_addresses_v6[0]['value'] = vrf.used_addresses_v6; data_vrf_addresses_v6[1]['value'] = vrf.free_addresses_v6; var options = { animationSteps : 20, animationEasing: "easeOutQuart" }; if (vrf.num_prefixes_v4 > 0) { var chart_vrf_addresses_v4 = new Chart($("#canvas_vrf_addresses_v4")[0].getContext("2d")).Doughnut(data_vrf_addresses_v4, options); } if (vrf.num_prefixes_v6 > 0) { var chart_vrf_addresses_v6 = new Chart($("#canvas_vrf_addresses_v6")[0].getContext("2d")).Doughnut(data_vrf_addresses_v6, options); } } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); /* * Submit VRF form - edit VRF */ $scope.submitForm = function () { /* * Create object specifying VRF attributes. Start with a copy of the * VRF object from the scope. */ var query_data = angular.copy($scope.vrf); // Rewrite tags list to match what's expected by the XHR functions query_data.tags = JSON.stringify($scope.vrf.tags.map(function (elem) { return elem.text; })); query_data.avps = {}; $scope.vrf.avps.forEach(function(avp) { query_data.avps[avp.attribute] = avp.value; }); query_data.avps = JSON.stringify(query_data.avps); // Send query! $http.get('/xhr/edit_vrf/' + $scope.vrf.id, { 'params': query_data }) .success(function (data){ if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.edited_vrfs.push(data); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } }); /* * PoolAddController - used to add pools */ nipapAppControllers.controller('PoolAddController', function ($scope, $http) { $scope.method = 'add'; $scope.added_pools = []; $scope.pool = { 'name': null, 'description': null, 'tags': [], 'default_type': null, 'ipv4_default_prefix_length': null, 'ipv6_default_prefix_length': null, 'avps': [] }; // add another empty "extra attribute" (AVP) input row $scope.addAvp = function() { $scope.pool.avps.push({ 'attribute': '', 'value': '' }); } // remove AVP row $scope.removeAvp = function(avp) { var index = $scope.pool.avps.indexOf(avp); $scope.pool.avps.splice( index, 1 ); } /* * Submit pool form - add pool */ $scope.submitForm = function() { /* * Create object specifying pool attributes. Start with a copy of the * pool object from the scope. */ var query_data = angular.copy($scope.pool); // Rewrite tags list to match what's expected by the XHR functions query_data.tags = JSON.stringify($scope.pool.tags.map(function (elem) { return elem.text; })); // Mangle avps query_data.avps = {}; $scope.pool.avps.forEach(function(avp) { query_data.avps[avp.attribute] = avp.value; }); query_data.avps = JSON.stringify(query_data.avps); // Send query! $http.get('/xhr/add_pool', { 'params': query_data }) .success(function (data){ if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.added_pools.push(data); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } }); /* * PoolEditController - used to edit pools */ nipapAppControllers.controller('PoolEditController', function ($scope, $routeParams, $http, $modal) { $scope.method = 'edit'; $scope.edited_pools = []; $scope.pool = { 'tags': [] }; $scope.pool_prefixes = []; // add another empty "extra attribute" (AVP) input row $scope.addAvp = function() { $scope.pool.avps.push({ 'attribute': '', 'value': '' }); } // remove AVP row $scope.removeAvp = function(avp) { var index = $scope.pool.avps.indexOf(avp); $scope.pool.avps.splice( index, 1 ); } // Fetch VRF to edit from backend $http.get('/xhr/list_pool', { 'params': { 'id': $routeParams.pool_id, } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { pool = data[0]; // Tags needs to be mangled for use with tags-input // TODO: When all interaction with prefix add & edit functions // are moved to AngularJS, change XHR functions to use the same // format as tags-input pool.tags = Object.keys(pool.tags).map(function (elem) { return { 'text': elem }; } ); pool.avps = Object.keys(pool.avps).sort().map(function (key) { return { 'attribute': key, 'value': pool.avps[key] }; } ); // Fetch pool's VRF if (pool.vrf_id !== null) { $http.get('/xhr/smart_search_vrf', { 'params': { 'vrf_id': $scope.pool.vrf_id, 'query_string': '' }}) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.pool.vrf = data.result[0]; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } else { pool.vrf = null; } $scope.pool = pool; // Fetch pool's prefixes $http.get('/xhr/list_prefix', { 'params': { 'pool': pool.id }}) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.pool_prefixes = data; } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); // Display statistics // TODO: Do in AngularJS-way, probably easiest to encapsulate // in a directive var data_charts = [ { color: '#d74228', highlight: '#e74228', label: 'Used' }, { color: '#368400', highlight: '#36a200', label: 'Free' } ]; var options = { animationSteps : 20, animationEasing: "easeOutQuart" }; if (pool.member_prefixes_v4 > 0 && pool.ipv4_default_prefix_length !== null > 0) { var data_pool_prefixes_v4 = angular.copy(data_charts); data_pool_prefixes_v4[0]['value'] = pool.used_prefixes_v4; data_pool_prefixes_v4[1]['value'] = pool.free_prefixes_v4; var chart_pool_prefixes_v4 = new Chart($("#canvas_pool_prefixes_v4")[0] .getContext("2d")) .Doughnut(data_pool_prefixes_v4, options); } if (pool.member_prefixes_v6 > 0 && pool.ipv6_default_prefix_length !== null) { var data_pool_prefixes_v6 = angular.copy(data_charts); data_pool_prefixes_v6[0]['value'] = pool.used_prefixes_v6; data_pool_prefixes_v6[1]['value'] = pool.free_prefixes_v6; var chart_pool_prefixes_v6 = new Chart($("#canvas_pool_prefixes_v6")[0] .getContext("2d")) .Doughnut(data_pool_prefixes_v6, options); } if (pool.member_prefixes_v4 > 0) { var data_pool_addresses_v4 = angular.copy(data_charts); data_pool_addresses_v4[0]['value'] = pool.used_addresses_v4; data_pool_addresses_v4[1]['value'] = pool.free_addresses_v4; var chart_pool_addresses_v4 = new Chart($("#canvas_pool_addresses_v4")[0] .getContext("2d")) .Doughnut(data_pool_addresses_v4, options); } if (pool.member_prefixes_v6 > 0) { var data_pool_addresses_v6 = angular.copy(data_charts); data_pool_addresses_v6[0]['value'] = pool.used_addresses_v6; data_pool_addresses_v6[1]['value'] = pool.free_addresses_v6; var chart_pool_addresses_v6 = new Chart($("#canvas_pool_addresses_v6")[0] .getContext("2d")) .Doughnut(data_pool_addresses_v6, options); } } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); /* * Submit pool form - edit pool */ $scope.submitForm = function () { /* * Create object specifying pool attributes. Start with a copy of the * pool object from the scope. */ var query_data = angular.copy($scope.pool); // Rewrite tags list to match what's expected by the XHR functions query_data.tags = JSON.stringify($scope.pool.tags.map(function (elem) { return elem.text; })); // Mangle avps query_data.avps = {}; $scope.pool.avps.forEach(function(avp) { query_data.avps[avp.attribute] = avp.value; }); query_data.avps = JSON.stringify(query_data.avps); // Send query! $http.get('/xhr/edit_pool/' + $scope.pool.id, { 'params': query_data }) .success(function (data){ if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { $scope.edited_pools.push(data); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); } /* * Confirm remove of prefix from pool */ $scope.prefixConfirmRemove = function (evt, prefix) { var dialog = showDialogYesNo('Remove ' + prefix.display_prefix + '?', 'Are you sure you want to remove ' + prefix.display_prefix + ' from pool? You cannot undo this action.', function () { $http.get('/xhr/edit_prefix/' + prefix.id, { 'params': { 'pool': '' } }) .success(function (data) { if (data.hasOwnProperty('error')) { showDialogNotice('Error', data.message); } else { var index = $scope.pool_prefixes.indexOf(prefix); $scope.pool_prefixes.splice(index, 1); } }) .error(function (data, stat) { var msg = data || "Unknown failure"; showDialogNotice('Error', stat + ': ' + msg); }); dialog.dialog('close'); } ); } /* * Display a popup notice informing the user of how pools are expanded * nowadays. */ $scope.showExpandPoolNotice = function () { var modalInstance = $modal.open({ templateUrl: 'expand_pool_notice.html', windowClass: 'nipap_modal' }); } });
module.exports = require("./lib/experimental-worker");
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// // jscs:disable validateIndentation define( [ "dojo/Evented", "dojo", "dojo/_base/declare", "dojo/_base/lang", "dojo/on", "dojo/keys", 'dojo/dom-construct', 'dojo/dom-style', "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dojo/text!./AttachmentUploader.html", 'dojo/i18n!esri/nls/jsapi' ], function ( Evented, dojo, declare, lang, on, keys, domConstruct, domStyle, _WidgetBase, _TemplatedMixin, widgetTemplate, esriBundle ) { return declare([_WidgetBase, Evented, _TemplatedMixin], { declaredClass: "jimu-widget-smartEditor-attachmentuploader", templateString: widgetTemplate, widgetsInTemplate: true, _inputCount: 0, _inputIndex: 1, currentAction: null, constructor: function () { this.nls = lang.mixin(this.nls, esriBundle.widgets.attachmentEditor); }, _fileSelected: function (source) { var target = source.target || source.srcElement; if (target.value.length > 0) { dojo.style(target.parentNode.childNodes[0], "display", "inline-block"); this._addInput(); //Remove required message if one or more attachments are added if (domStyle.get(this.attachmentsRequiredMsg, "display") === "block") { domStyle.set(this.attachmentsRequiredMsg, "display", "none"); this.emit("attachmentAdded"); } } }, clear: function () { if (this._attachmentList !== undefined && this._attachmentList !== null) { while (this._attachmentList.firstChild) { this._attachmentList.removeChild(this._attachmentList.firstChild); } this._addInput(); } }, _deleteAttachment: function (source) { var target = source.target || source.srcElement; target.parentNode.parentNode.removeChild(target.parentNode); if (!this._hasAddedAnyAttachments() && this.currentAction === "Required") { //Remove required message if one or more attachments are added if (domStyle.get(this.attachmentsRequiredMsg, "display") === "none") { domStyle.set(this.attachmentsRequiredMsg, "display", "block"); this.emit("attachmentDeleted"); } } }, _reflect: function (promise) { return promise.then(function (v) { return { state: "fulfilled", value: v }; }, function (e) { return { state: "rejected", error: e }; }); }, _addInput: function () { for (var i = 0; i < this._attachmentList.childNodes.length; i++) { if (this._attachmentList.childNodes[i].childNodes[this._inputIndex].value) { if (this._attachmentList.childNodes[i].childNodes[this._inputIndex].value.length === 0) { return; } } else { return; } } var newDelete = domConstruct.create("div", { "id": 'delInput' + String(this._inputCount), "class": 'deleteAttachment', "tabindex": "0", "aria-label": this.nls.deleteAttachment || this.deleteAttachmentText || "", "role": "button" }); newDelete.innerHTML = 'X'; dojo.style(newDelete, "display", "none"); this.own(on(newDelete, "click", lang.hitch(this, this._deleteAttachment))); this.own(on(newDelete, "keydown", lang.hitch(this, function (evt) { if (evt.keyCode === keys.ENTER || evt.keyCode === keys.SPACE) { this._deleteAttachment(evt); } }))); var newForm = domConstruct.create("form", { "id": 'formInput' + String(this._inputCount) }); var newInput = domConstruct.create("input", { "id": 'fileInput' + String(this._inputCount), "type": 'file', "class": 'attInput', "name": 'attachment' }); newForm.appendChild(newDelete); newForm.appendChild(newInput); this._attachmentList.appendChild(newForm); this.own(on(newInput, "change", lang.hitch(this, this._fileSelected))); this._inputCount = this._inputCount + 1; }, startup: function () { this._addInput(); }, destroy: function () { this.inherited(arguments); }, postAttachments: function (featureLayer, oid) { if (!featureLayer) { return; } if (featureLayer.declaredClass !== "esri.layers.FeatureLayer" || !featureLayer.getEditCapabilities) { return; } if (!featureLayer.addAttachment) { return; } var defs = []; for (var i = 0; i < this._attachmentList.childNodes.length; i++) { if (this._attachmentList.childNodes[i].childNodes[this._inputIndex].value.length > 0) { //if (defs === null) { // defs = {} //} defs.push(featureLayer.addAttachment(oid, this._attachmentList.childNodes[i])); } } if (defs.length === 0) { return null; } return defs.map(this._reflect); }, _hasAddedAnyAttachments: function () { var hasAttachments = false; for (var i = 0; i < this._attachmentList.childNodes.length; i++) { if (this._attachmentList.childNodes[i].childNodes[this._inputIndex].value) { if (this._attachmentList.childNodes[i].childNodes[this._inputIndex].value.length > 0) { hasAttachments = true; break; } } } return hasAttachments; } }); });
{signal: [ {name: 'clk', wave: 'p.....|...'}, {name: 'dat', wave: 'x.345x|=.x', data: ['head', 'body', 'tail', 'data']}, {name: 'req', wave: '0.1..0|1.0'}, {name: 'ack', wave: '1.....|01.'} ]}
angular.module('abMaterial').controller('TableCtrl', function ($scope, $mdToast, $mdDialog, RestService, $ocLazyLoad, $timeout, $q, $log) { var tableDataService = new RestService('app/data/tabledata.json'); $scope.appCfg.loading = true; $scope.tableData = []; $scope.maxSize = 5; $scope.totalItems = 0; $scope.currentPage = 1; $timeout(function () { tableDataService.get({}, function (result) { $scope.tableData = result.list; $scope.appCfg.loading = false; $scope.totalItems = $scope.tableData.length * 10 / 5; }); }, 3000); $scope.pageChanged = function () { $scope.itemsSwitch = false; angular.forEach($scope.tableData, function (item) { item.selected = $scope.itemsSwitch; }); }; $scope.onChange = function () { for (var i = ($scope.currentPage - 1) * 5; i < $scope.currentPage * 5; i++) { if ($scope.tableData[i]) { $scope.tableData[i].selected = $scope.itemsSwitch; } } }; });
{ "name": "logToServer.js", "url": "https://github.com/mperdeck/JSNLog.AngularJS.git" }
<script> function enableNext() { $("#next_button").prop("disabled", false); $("#next_button").css("background-color", "white"); $("#next_button").css("border", "solid 3px white"); $("#next_button").css("cursor", "pointer"); } function disableNext() { $("#next_button").prop("disabled", true); $("#next_button").css("background-color", "#6C69D1"); $("#next_button").css("border", "solid 3px #6C69D1"); } $("#next_button").click( function() { window.location = 'index.php?page=selection&id=<?php echo $id; ?>'; }); $(document).ready( function() { disableNext(); setTimeout("enableNext()", 20000); }); </script>
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 11.13.2-24-s description: > Strict Mode - TypeError is thrown if The LeftHandSide of a Compound Assignment operator(/=) is a reference to a data property with the attribute value {[[Writable]]:false} flags: [onlyStrict] includes: [runTestCase.js] ---*/ function testcase() { "use strict"; var obj = {}; Object.defineProperty(obj, "prop", { value: 10, writable: false, enumerable: true, configurable: true }); try { obj.prop /= 20; return false; } catch (e) { return e instanceof TypeError && obj.prop === 10; } } runTestCase(testcase);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.7.3_A2.4_T1; * @section: 11.7.3; * @assertion: First expression is evaluated first, and then second expression; * @description: Checking with "="; */ //CHECK#1 var x = 0; if ((x = 1) >>> x !== 0) { $ERROR('#1: var x = 0; (x = 1) >>> x === 0. Actual: ' + ((x = 1) >>> x)); } //CHECK#2 var x = -4; if (x >>> (x = 1) !== 2147483646) { $ERROR('#2: var x = -4; x >>> (x = 1) === 2147483646. Actual: ' + (x >>> (x = 1))); }
//controller var controller = require('../controllers/static'); module.exports = [ { method: 'GET', path: '/partials/{path*}', config: controller.partials }, { method: 'GET', path: '/images/{path*}', config: controller.images }, { method: 'GET', path: '/css/{path*}', config: controller.css }, { method: 'GET', path: '/js/{path*}', config: controller.js }, { method: 'GET', path: '/bower_components/{path*}', config: controller.bower_components }, { method: 'GET', path: '/elements/{path*}', config: controller.elements }, { method: 'GET', path: '/{path*}', config: controller.public }, ]
'use strict'; module.exports = exports = require('./lib/config'); exports.Action = require('./lib/action'); exports.Command = require('./lib/command');
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Depends on jsonlint.view from https://github.com/zaach/jsonlint // declare global: jsonlint (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("lint", "json", function(text) { var found = []; jsonlint.parseError = function(str, hash) { var loc = hash.loc; found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column), to: CodeMirror.Pos(loc.last_line - 1, loc.last_column), message: str}); }; try { jsonlint.parse(text); } catch(e) {} return found; }); });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M3 20h18V8H3v12zm6-10 7 4-7 4v-8z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9 10v8l7-4zm12-4h-7.58l3.29-3.29L16 2l-4 4h-.03l-4-4-.69.71L10.56 6H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 14H3V8h18v12z" }, "1")], 'LiveTvTwoTone'); exports.default = _default;
/* * response-stream.js: A Stream focused on writing any relevant information to * a raw http.ServerResponse object. * * (C) 2011, Nodejitsu Inc. * MIT LICENSE * */ var util = require('util'), HttpStream = require('./http-stream'); // // ### function ResponseStream (options) // // var ResponseStream = module.exports = function (options) { var self = this, key; options = options || {}; HttpStream.call(this, options); this.writeable = true; this.response = options.response; if (options.headers) { for (key in options.headers) { this.response.setHeader(key, options.headers[key]); } } // // Proxy `statusCode` changes to the actual `response.statusCode`. // Object.defineProperty(this, 'statusCode', { get: function () { return self.response.statusCode; }, set: function (value) { self.response.statusCode = value; }, enumerable: true, configurable: true }); if (this.response) { this._headers = this.response._headers = this.response._headers || {}; // Patch to node core this.response._headerNames = this.response._headerNames || {}; // // Proxy to emit "header" event // this._renderHeaders = this.response._renderHeaders; this.response._renderHeaders = function () { if (!self._emittedHeader) { self._emittedHeader = true; self.headerSent = true; self._header = true; self.emit('header'); } return self._renderHeaders.call(self.response); }; } }; util.inherits(ResponseStream, HttpStream); ResponseStream.prototype.writeHead = function (statusCode, headers) { if (headers) { for (var key in headers) { this.response.setHeader(key, headers[key]); } } this.response.statusCode = statusCode; }; // // Create pass-thru for the necessary // `http.ServerResponse` methods. // ['setHeader', 'getHeader', 'removeHeader', '_implicitHeader', 'addTrailers'].forEach(function (method) { ResponseStream.prototype[method] = function () { return this.response[method].apply(this.response, arguments); }; }); ResponseStream.prototype.json = function (obj) { if (!this.response.writable) { return; } if (typeof obj === 'number') { this.response.statusCode = obj; obj = arguments[1]; } this.modified = true; if (!this.response._header && this.response.getHeader('content-type') !== 'application/json') { this.response.setHeader('content-type', 'application/json'); } this.end(obj ? JSON.stringify(obj) : ''); }; ResponseStream.prototype.html = function (str) { if (!this.response.writable) { return; } if (typeof str === 'number') { this.response.statusCode = str; str = arguments[1]; } this.modified = true; if (!this.response._header && this.response.getHeader('content-type') !== 'text/html') { this.response.setHeader('content-type', 'text/html'); } this.end(str ? str: ''); }; ResponseStream.prototype.text = function (str) { if (!this.response.writable) { return; } if (typeof str === 'number') { this.response.statusCode = str; str = arguments[1]; } this.modified = true; if (!this.response._header && this.response.getHeader('content-type') !== 'text/plain') { this.response.setHeader('content-type', 'text/plain'); } this.end(str ? str: ''); }; ResponseStream.prototype.end = function (data) { if (data && this.writable) { this.emit('data', data); } this.modified = true; this.emit('end'); }; ResponseStream.prototype.write = function (data) { this.modified = true; if (this.writable) { this.emit('data', data); } }; ResponseStream.prototype.redirect = function (path, status) { var url = ''; if (~path.indexOf('://')) { url = path; } else { url += this.req.connection.encrypted ? 'https://' : 'http://'; url += this.req.headers.host; url += (path[0] === '/') ? path : '/' + path; } this.res.writeHead(status || 302, { 'Location': url }); this.end(); };
var pagerInstance = ( <Pager> <PageItem previous href="#">&larr; Previous</PageItem> <PageItem disabled next href="#">Next &rarr;</PageItem> </Pager> ); React.render(pagerInstance, mountNode);
define([ "dojo/_base/declare", "dijit/_Widget", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "plugins/form/DndSource", "dojo/domReady!", "dijit/TitlePane" ], function (declare, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, DndSource) { return declare("plugins.workflow.Apps.AppSource", [ _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, DndSource ], { templateString: dojo.cache("plugins", "workflow/Apps/templates/appsource.html"), // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // CONTEXT MENU contextMenu : null, // ROW CLASS rowClass : "plugins.workflow.Apps.AppRow", // AVATAR ITEMS avatarItems : ["name", "description"], // FORM INPUTS (DATA ITEMS TO BE ADDED TO ROWS) formInputs : { name: 1, owner: 1, type: 1, version: 1, executor: 1, localonly: 1, location: 1, description: 1, notes: 1, url : 1 }, /////}}} constructor : function(args) { //console.log("AppSource.constructor plugins.workflow.AppSource.constructor()"); this.parentWidget = args.parentWidget; this.itemArray = args.itemArray; this.contextMenu = args.contextMenu; }, postCreate : function() { //console.log("AppSource.postCreate plugins.workflow.AppSource.postCreate()"); this.startup(); }, startup : function () { //console.log("AppSource.startup plugins.workflow.AppSource.startup()"); //console.log("AppSource.startup this.parentWidget: " + this.parentWidget); //this.inherited(arguments); //console.log("AppSource.startup DOING this.setDragSource()"); this.setDragSource(); }, getItemArray : function () { ////console.log("AppSource.getItemArray plugins.workflow.AppSource.getItemArray()"); ////console.log("AppSource.getItemArray.length this.itemArray.length: " + this.itemArray.length); return this.itemArray; } }); // end declare }); // end define
(function () { 'use strict'; angular.module('app.modelSettings', [ 'app.core', 'app.widgets' ]); })();
const SystemMetadata = Object.freeze({ maxAge: '$maxAge', maxCount: '$maxCount', truncateBefore: '$tb', cacheControl: '$cacheControl', acl: '$acl', aclRead: '$r', aclWrite: '$w', aclDelete: '$d', aclMetaRead: '$mr', aclMetaWrite: '$mw', userStreamAcl: '$userStreamAcl', systemStreamAcl: '$systemStreamAcl' }); module.exports = SystemMetadata;
/*! * Chart.js * http://chartjs.org/ * * Copyright 2013 Nick Downie * Released under the MIT license * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md */ //Define the global Chart Variable as a class. window.Chart = function(context, options){ var chart = this; //Easing functions adapted from Robert Penner's easing equations //http://www.robertpenner.com/easing/ var animationOptions = { linear : function (t){ return t; }, easeInQuad: function (t) { return t*t; }, easeOutQuad: function (t) { return -1 *t*(t-2); }, easeInOutQuad: function (t) { if ((t/=1/2) < 1) return 1/2*t*t; return -1/2 * ((--t)*(t-2) - 1); }, easeInCubic: function (t) { return t*t*t; }, easeOutCubic: function (t) { return 1*((t=t/1-1)*t*t + 1); }, easeInOutCubic: function (t) { if ((t/=1/2) < 1) return 1/2*t*t*t; return 1/2*((t-=2)*t*t + 2); }, easeInQuart: function (t) { return t*t*t*t; }, easeOutQuart: function (t) { return -1 * ((t=t/1-1)*t*t*t - 1); }, easeInOutQuart: function (t) { if ((t/=1/2) < 1) return 1/2*t*t*t*t; return -1/2 * ((t-=2)*t*t*t - 2); }, easeInQuint: function (t) { return 1*(t/=1)*t*t*t*t; }, easeOutQuint: function (t) { return 1*((t=t/1-1)*t*t*t*t + 1); }, easeInOutQuint: function (t) { if ((t/=1/2) < 1) return 1/2*t*t*t*t*t; return 1/2*((t-=2)*t*t*t*t + 2); }, easeInSine: function (t) { return -1 * Math.cos(t/1 * (Math.PI/2)) + 1; }, easeOutSine: function (t) { return 1 * Math.sin(t/1 * (Math.PI/2)); }, easeInOutSine: function (t) { return -1/2 * (Math.cos(Math.PI*t/1) - 1); }, easeInExpo: function (t) { return (t==0) ? 1 : 1 * Math.pow(2, 10 * (t/1 - 1)); }, easeOutExpo: function (t) { return (t==1) ? 1 : 1 * (-Math.pow(2, -10 * t/1) + 1); }, easeInOutExpo: function (t) { if (t==0) return 0; if (t==1) return 1; if ((t/=1/2) < 1) return 1/2 * Math.pow(2, 10 * (t - 1)); return 1/2 * (-Math.pow(2, -10 * --t) + 2); }, easeInCirc: function (t) { if (t>=1) return t; return -1 * (Math.sqrt(1 - (t/=1)*t) - 1); }, easeOutCirc: function (t) { return 1 * Math.sqrt(1 - (t=t/1-1)*t); }, easeInOutCirc: function (t) { if ((t/=1/2) < 1) return -1/2 * (Math.sqrt(1 - t*t) - 1); return 1/2 * (Math.sqrt(1 - (t-=2)*t) + 1); }, easeInElastic: function (t) { var s=1.70158;var p=0;var a=1; if (t==0) return 0; if ((t/=1)==1) return 1; if (!p) p=1*.3; if (a < Math.abs(1)) { a=1; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (1/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )); }, easeOutElastic: function (t) { var s=1.70158;var p=0;var a=1; if (t==0) return 0; if ((t/=1)==1) return 1; if (!p) p=1*.3; if (a < Math.abs(1)) { a=1; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (1/a); return a*Math.pow(2,-10*t) * Math.sin( (t*1-s)*(2*Math.PI)/p ) + 1; }, easeInOutElastic: function (t) { var s=1.70158;var p=0;var a=1; if (t==0) return 0; if ((t/=1/2)==2) return 1; if (!p) p=1*(.3*1.5); if (a < Math.abs(1)) { a=1; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (1/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )); return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )*.5 + 1; }, easeInBack: function (t) { var s = 1.70158; return 1*(t/=1)*t*((s+1)*t - s); }, easeOutBack: function (t) { var s = 1.70158; return 1*((t=t/1-1)*t*((s+1)*t + s) + 1); }, easeInOutBack: function (t) { var s = 1.70158; if ((t/=1/2) < 1) return 1/2*(t*t*(((s*=(1.525))+1)*t - s)); return 1/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2); }, easeInBounce: function (t) { return 1 - animationOptions.easeOutBounce (1-t); }, easeOutBounce: function (t) { if ((t/=1) < (1/2.75)) { return 1*(7.5625*t*t); } else if (t < (2/2.75)) { return 1*(7.5625*(t-=(1.5/2.75))*t + .75); } else if (t < (2.5/2.75)) { return 1*(7.5625*(t-=(2.25/2.75))*t + .9375); } else { return 1*(7.5625*(t-=(2.625/2.75))*t + .984375); } }, easeInOutBounce: function (t) { if (t < 1/2) return animationOptions.easeInBounce (t*2) * .5; return animationOptions.easeOutBounce (t*2-1) * .5 + 1*.5; } }; this.tooltips = [], defaults = { tooltips: { background: 'rgba(0,0,0,0.6)', fontFamily : "'Arial'", fontStyle : "normal", fontColor: 'white', fontSize: '12px', labelTemplate: '<%=label%>: <%=value%>', padding: { top: 10, right: 10, bottom: 10, left: 10 }, offset: { left: 0, top: 0 }, border: { width: 0, color: '#000' }, showHighlight: true, highlight: { stroke: { width: 1, color: 'rgba(230,230,230,0.25)' }, fill: 'rgba(255,255,255,0.25)' } } }, options = (options) ? mergeChartConfig(defaults, options) : defaults; function registerTooltip(ctx,areaObj,data,type) { chart.tooltips.push(new Tooltip( ctx, areaObj, data, type )); } var Tooltip = function(ctx, areaObj, data, type) { this.ctx = ctx; this.areaObj = areaObj; this.data = data; this.savedState = null; this.highlightState = null; this.x = null; this.y = null; this.inRange = function(x,y) { if(this.areaObj.type) { switch(this.areaObj.type) { case 'rect': return (x >= this.areaObj.x && x <= this.areaObj.x+this.areaObj.width) && (y >= this.areaObj.y && y <= this.areaObj.y+this.areaObj.height); break; case 'circle': return ((Math.pow(x-this.areaObj.x, 2)+Math.pow(y-this.areaObj.y, 2)) < Math.pow(this.areaObj.r,2)); break; case 'shape': var poly = this.areaObj.points; for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) ((poly[i].y <= y && y < poly[j].y) || (poly[j].y <= y && y < poly[i].y)) && (x < (poly[j].x - poly[i].x) * (y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x) && (c = !c); return c; break; } } } this.render = function(x,y) { if(this.savedState == null) { this.ctx.putImageData(chart.savedState,0,0); this.savedState = this.ctx.getImageData(0,0,this.ctx.canvas.width,this.ctx.canvas.height); } this.ctx.putImageData(this.savedState,0,0); if(options.tooltips.showHighlight) { if(this.highlightState == null) { this.ctx.strokeStyle = options.tooltips.highlight.stroke.color; this.ctx.lineWidth = options.tooltips.highlight.stroke.width; this.ctx.fillStyle = options.tooltips.highlight.fill; switch(this.areaObj.type) { case 'rect': this.ctx.strokeRect(this.areaObj.x, this.areaObj.y, this.areaObj.width, this.areaObj.height); this.ctx.fillStyle = options.tooltips.highlight.fill; this.ctx.fillRect(this.areaObj.x, this.areaObj.y, this.areaObj.width, this.areaObj.height); break; case 'circle': this.ctx.beginPath(); this.ctx.arc(this.areaObj.x, this.areaObj.y, this.areaObj.r, 0, 2*Math.PI, false); this.ctx.stroke(); this.ctx.fill(); break; case 'shape': this.ctx.beginPath(); this.ctx.moveTo(this.areaObj.points[0].x, this.areaObj.points[0].y); for(var p in this.areaObj.points) { this.ctx.lineTo(this.areaObj.points[p].x, this.areaObj.points[p].y); } this.ctx.stroke(); this.ctx.fill(); break; } this.highlightState = this.ctx.getImageData(0,0,this.ctx.canvas.width,this.ctx.canvas.height); } else { this.ctx.putImageData(this.highlightState,0,0); } } //if(this.x != x || this.y != y) { var posX = x+options.tooltips.offset.left, posY = y+options.tooltips.offset.top, tpl = tmpl(options.tooltips.labelTemplate, this.data), rectWidth = options.tooltips.padding.left+this.ctx.measureText(tpl).width+options.tooltips.padding.right; if(posX + rectWidth > ctx.canvas.width) { posX -= posX-rectWidth < 0 ? posX : rectWidth; } if(posY + 24 > ctx.canvas.height) { posY -= 24; } this.ctx.fillStyle = options.tooltips.background; this.ctx.fillRect(posX, posY, rectWidth, 24); if(options.tooltips.border.width > 0) { this.ctx.fillStyle = options.tooltips.order.color; this.ctx.lineWidth = options.tooltips.border.width; this.ctx.strokeRect(posX, posY, rectWidth, 24); } this.ctx.font = options.tooltips.fontStyle+ " "+options.tooltips.fontSize+" " + options.tooltips.fontFamily; this.ctx.fillStyle = options.tooltips.fontColor; this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; this.ctx.fillText(tpl, posX+rectWidth/2, posY+12); this.x = x; this.y = y; //} } } //Variables global to the chart var width = context.canvas.width, height = context.canvas.height; this.savedState = null; function getPosition(e) { var xPosition = 0; var yPosition = 0; while(e) { xPosition += (e.offsetLeft + e.clientLeft); yPosition += (e.offsetTop + e.clientTop); e = e.offsetParent; } if(window.pageXOffset > 0 || window.pageYOffset > 0) { xPosition -= window.pageXOffset; yPosition -= window.pageYOffset; } else if(document.body.scrollLeft > 0 || document.body.scrollTop > 0) { xPosition -= document.body.scrollLeft; yPosition -= document.body.scrollTop; } return { x: xPosition, y: yPosition }; } function tooltipEventHandler(e) { if(chart.tooltips.length > 0) { chart.savedState = chart.savedState == null ? context.getImageData(0,0,context.canvas.width,context.canvas.height) : chart.savedState; var rendered = 0; for(var i in chart.tooltips) { var position = getPosition(context.canvas), mx = (e.clientX)-position.x, my = (e.clientY)-position.y; if(chart.tooltips[i].inRange(mx,my)) { chart.tooltips[i].render(mx,my); rendered++; } } if(rendered == 0) { context.putImageData(chart.savedState,0,0); } } } if(window.Touch) { context.canvas.ontouchstart = function(e) { e.clientX = e.targetTouches[0].clientX; e.clientY = e.targetTouches[0].clientY; tooltipEventHandler(e); } context.canvas.ontouchmove = function(e) { e.clientX = e.targetTouches[0].clientX; e.clientY = e.targetTouches[0].clientY; tooltipEventHandler(e); } } else { context.canvas.onmousemove = function(e) { tooltipEventHandler(e); } } context.canvas.onmouseout = function(e) { if(chart.savedState != null) { context.putImageData(chart.savedState,0,0); } } //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale. if (window.devicePixelRatio) { context.canvas.style.width = width + "px"; context.canvas.style.height = height + "px"; context.canvas.height = height * window.devicePixelRatio; context.canvas.width = width * window.devicePixelRatio; context.scale(window.devicePixelRatio, window.devicePixelRatio); } this.PolarArea = function(data,options){ chart.PolarArea.defaults = { scaleOverlay : true, scaleOverride : false, scaleSteps : null, scaleStepWidth : null, scaleStartValue : null, scaleShowLine : true, scaleLineColor : "rgba(0,0,0,.1)", scaleLineWidth : 1, scaleShowLabels : true, scaleLabel : "<%=value%>", scaleFontFamily : "'Arial'", scaleFontSize : 12, scaleFontStyle : "normal", scaleFontColor : "#666", scaleShowLabelBackdrop : true, scaleBackdropColor : "rgba(255,255,255,0.75)", scaleBackdropPaddingY : 2, scaleBackdropPaddingX : 2, segmentShowStroke : true, segmentStrokeColor : "#fff", segmentStrokeWidth : 2, animation : true, animationSteps : 100, animationEasing : "easeOutBounce", animateRotate : true, animateScale : false, onAnimationComplete : null, showTooltips : true }; var config = (options)? mergeChartConfig(chart.PolarArea.defaults,options) : chart.PolarArea.defaults; return new PolarArea(data,config,context); }; this.Radar = function(data,options){ chart.Radar.defaults = { scaleOverlay : false, scaleOverride : false, scaleSteps : null, scaleStepWidth : null, scaleStartValue : null, scaleShowLine : true, scaleLineColor : "rgba(0,0,0,.1)", scaleLineWidth : 1, scaleShowLabels : false, scaleLabel : "<%=value%>", scaleFontFamily : "'Arial'", scaleFontSize : 12, scaleFontStyle : "normal", scaleFontColor : "#666", scaleShowLabelBackdrop : true, scaleBackdropColor : "rgba(255,255,255,0.75)", scaleBackdropPaddingY : 2, scaleBackdropPaddingX : 2, angleShowLineOut : true, angleLineColor : "rgba(0,0,0,.1)", angleLineWidth : 1, pointLabelFontFamily : "'Arial'", pointLabelFontStyle : "normal", pointLabelFontSize : 12, pointLabelFontColor : "#666", pointDot : true, pointDotRadius : 3, pointDotStrokeWidth : 1, datasetStroke : true, datasetStrokeWidth : 2, datasetFill : true, animation : true, animationSteps : 60, animationEasing : "easeOutQuart", onAnimationComplete : null, showTooltips : true }; var config = (options)? mergeChartConfig(chart.Radar.defaults,options) : chart.Radar.defaults; return new Radar(data,config,context); }; this.Pie = function(data,options){ chart.Pie.defaults = { segmentShowStroke : true, segmentStrokeColor : "#fff", segmentStrokeWidth : 2, animation : true, animationSteps : 100, animationEasing : "easeOutBounce", animateRotate : true, animateScale : false, onAnimationComplete : null, labelFontFamily : "'Arial'", labelFontStyle : "normal", labelFontSize : 12, labelFontColor : "#666", labelAlign : 'right', showTooltips : true }; var config = (options)? mergeChartConfig(chart.Pie.defaults,options) : chart.Pie.defaults; return new Pie(data,config,context); }; this.Doughnut = function(data,options){ chart.Doughnut.defaults = { segmentShowStroke : true, segmentStrokeColor : "#fff", segmentStrokeWidth : 2, percentageInnerCutout : 50, animation : true, animationSteps : 100, animationEasing : "easeOutBounce", animateRotate : true, animateScale : false, onAnimationComplete : null, showTooltips : true }; var config = (options)? mergeChartConfig(chart.Doughnut.defaults,options) : chart.Doughnut.defaults; return new Doughnut(data,config,context); }; this.Line = function(data,options){ chart.Line.defaults = { scaleOverlay : false, scaleOverride : false, scaleSteps : null, scaleStepWidth : null, scaleStartValue : null, scaleLineColor : "rgba(0,0,0,.1)", scaleLineWidth : 1, scaleShowLabels : true, scaleLabel : "<%=value%>", scaleFontFamily : "'Arial'", scaleFontSize : 12, scaleFontStyle : "normal", scaleFontColor : "#666", scaleShowGridLines : true, scaleGridLineColor : "rgba(0,0,0,.05)", scaleGridLineWidth : 1, bezierCurve : true, pointDot : true, pointDotRadius : 4, pointDotStrokeWidth : 2, datasetStroke : true, datasetStrokeWidth : 2, datasetFill : true, animation : true, animationSteps : 60, animationEasing : "easeOutQuart", onAnimationComplete : null, showTooltips : true }; var config = (options) ? mergeChartConfig(chart.Line.defaults,options) : chart.Line.defaults; return new Line(data,config,context); } this.Bar = function(data,options){ chart.Bar.defaults = { scaleOverlay : false, scaleOverride : false, scaleSteps : null, scaleStepWidth : null, scaleStartValue : null, scaleLineColor : "rgba(0,0,0,.1)", scaleLineWidth : 1, scaleShowLabels : true, scaleLabel : "<%=value%>", scaleFontFamily : "'Arial'", scaleFontSize : 12, scaleFontStyle : "normal", scaleFontColor : "#666", scaleShowGridLines : true, scaleGridLineColor : "rgba(0,0,0,.05)", scaleGridLineWidth : 1, barShowStroke : true, barStrokeWidth : 2, barValueSpacing : 5, barDatasetSpacing : 1, animation : true, animationSteps : 60, animationEasing : "easeOutQuart", onAnimationComplete : null, showTooltips : true }; var config = (options) ? mergeChartConfig(chart.Bar.defaults,options) : chart.Bar.defaults; return new Bar(data,config,context); } var clear = function(c){ c.clearRect(0, 0, width, height); }; var PolarArea = function(data,config,ctx){ var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString; calculateDrawingSizes(); valueBounds = getValueBounds(); labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null; //Check and set the scale if (!config.scaleOverride){ calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); } else { calculatedScale = { steps : config.scaleSteps, stepValue : config.scaleStepWidth, graphMin : config.scaleStartValue, labels : [] } populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); } scaleHop = maxSize/(calculatedScale.steps); //Wrap in an animation loop wrapper animationLoop(config,drawScale,drawAllSegments,ctx); function calculateDrawingSizes(){ maxSize = (Min([width,height])/2); //Remove whatever is larger - the font size or line width. maxSize -= Max([config.scaleFontSize*0.5,config.scaleLineWidth*0.5]); labelHeight = config.scaleFontSize*2; //If we're drawing the backdrop - add the Y padding to the label height and remove from drawing region. if (config.scaleShowLabelBackdrop){ labelHeight += (2 * config.scaleBackdropPaddingY); maxSize -= config.scaleBackdropPaddingY*1.5; } scaleHeight = maxSize; //If the label height is less than 5, set it to 5 so we don't have lines on top of each other. labelHeight = Default(labelHeight,5); } function drawScale(){ for (var i=0; i<calculatedScale.steps; i++){ //If the line object is there if (config.scaleShowLine){ ctx.beginPath(); ctx.arc(width/2, height/2, scaleHop * (i + 1), 0, (Math.PI * 2), true); ctx.strokeStyle = config.scaleLineColor; ctx.lineWidth = config.scaleLineWidth; ctx.stroke(); } if (config.scaleShowLabels){ ctx.textAlign = "center"; ctx.font = config.scaleFontStyle + " " + config.scaleFontSize + "px " + config.scaleFontFamily; var label = calculatedScale.labels[i]; //If the backdrop object is within the font object if (config.scaleShowLabelBackdrop){ var textWidth = ctx.measureText(label).width; ctx.fillStyle = config.scaleBackdropColor; ctx.beginPath(); ctx.rect( Math.round(width/2 - textWidth/2 - config.scaleBackdropPaddingX), //X Math.round(height/2 - (scaleHop * (i + 1)) - config.scaleFontSize*0.5 - config.scaleBackdropPaddingY),//Y Math.round(textWidth + (config.scaleBackdropPaddingX*2)), //Width Math.round(config.scaleFontSize + (config.scaleBackdropPaddingY*2)) //Height ); ctx.fill(); } ctx.textBaseline = "middle"; ctx.fillStyle = config.scaleFontColor; ctx.fillText(label,width/2,height/2 - (scaleHop * (i + 1))); } } } function drawAllSegments(animationDecimal){ var startAngle = -Math.PI/2, angleStep = (Math.PI*2)/data.length, scaleAnimation = 1, rotateAnimation = 1; if (config.animation) { if (config.animateScale) { scaleAnimation = animationDecimal; } if (config.animateRotate){ rotateAnimation = animationDecimal; } } for (var i=0; i<data.length; i++){ ctx.beginPath(); ctx.arc(width/2,height/2,scaleAnimation * calculateOffset(data[i].value,calculatedScale,scaleHop),startAngle, startAngle + rotateAnimation*angleStep, false); ctx.lineTo(width/2,height/2); ctx.closePath(); ctx.fillStyle = data[i].color; ctx.fill(); if(animationDecimal >= 1 && config.showTooltips) { var points = [{x:width/2,y:height/2}], pAmount = 50, radius = calculateOffset(data[i].value,calculatedScale,scaleHop); points.push({x:width/2+radius*Math.cos(startAngle),y:height/2+radius*Math.sin(startAngle)}); for(var p = 0; p <= pAmount; p++) { points.push({x:width/2+radius*Math.cos(startAngle+p/pAmount*rotateAnimation*angleStep),y:height/2+radius*Math.sin(startAngle+p/pAmount*rotateAnimation*angleStep)}); } registerTooltip(ctx,{type:'shape',points:points},{label:data[i].label,value:data[i].value},'PolarArea'); } if(config.segmentShowStroke){ ctx.strokeStyle = config.segmentStrokeColor; ctx.lineWidth = config.segmentStrokeWidth; ctx.stroke(); } startAngle += rotateAnimation*angleStep; } } function getValueBounds() { var upperValue = Number.MIN_VALUE; var lowerValue = Number.MAX_VALUE; for (var i=0; i<data.length; i++){ if (data[i].value > upperValue) {upperValue = data[i].value;} if (data[i].value < lowerValue) {lowerValue = data[i].value;} }; var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); return { maxValue : upperValue, minValue : lowerValue, maxSteps : maxSteps, minSteps : minSteps }; } } var Radar = function (data,config,ctx) { var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString; //If no labels are defined set to an empty array, so referencing length for looping doesn't blow up. if (!data.labels) data.labels = []; calculateDrawingSizes(); var valueBounds = getValueBounds(); labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null; //Check and set the scale if (!config.scaleOverride){ calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); } else { calculatedScale = { steps : config.scaleSteps, stepValue : config.scaleStepWidth, graphMin : config.scaleStartValue, labels : [] } populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); } scaleHop = maxSize/(calculatedScale.steps); animationLoop(config,drawScale,drawAllDataPoints,ctx); //Radar specific functions. function drawAllDataPoints(animationDecimal){ var rotationDegree = (2*Math.PI)/data.datasets[0].data.length; ctx.save(); //translate to the centre of the canvas. ctx.translate(width/2,height/2); //We accept multiple data sets for radar charts, so show loop through each set for (var i=0; i<data.datasets.length; i++){ var offset = calculateOffset(data.datasets[i].data[0],calculatedScale,scaleHop); ctx.beginPath(); ctx.moveTo(0,animationDecimal*(-1*offset)); if(animationDecimal >= 1 && config.showTooltips) { var curX = width/2+offset*Math.cos(0-Math.PI/2), curY = height/2+offset*Math.sin(0-Math.PI/2), pointRadius = config.pointDot ? config.pointDotRadius+config.pointDotStrokeWidth : 10, ttData = data.labels[0].trim() != "" ? data.labels[0]+": "+data.datasets[i].data[0] : data.datasets[i].data[0]; registerTooltip(ctx,{type:'circle',x:curX,y:curY,r:pointRadius},{label:data.labels[0],value:data.datasets[i].data[0]},'Radar'); } for (var j=1; j<data.datasets[i].data.length; j++){ offset = calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop); ctx.rotate(rotationDegree); ctx.lineTo(0,animationDecimal*(-1*offset)); if(animationDecimal >= 1 && config.showTooltips) { var curX = width/2+offset*Math.cos(j*rotationDegree-Math.PI/2), curY = height/2+offset*Math.sin(j*rotationDegree-Math.PI/2), pointRadius = config.pointDot ? config.pointDotRadius+config.pointDotStrokeWidth : 10, ttData = data.labels[j].trim() != "" ? data.labels[j]+": "+data.datasets[i].data[j] : data.datasets[i].data[j]; registerTooltip(ctx,{type:'circle',x:curX,y:curY,r:pointRadius},{label:data.labels[j],value:data.datasets[i].data[j]},'Radar'); } } ctx.closePath(); ctx.fillStyle = data.datasets[i].fillColor; ctx.strokeStyle = data.datasets[i].strokeColor; ctx.lineWidth = config.datasetStrokeWidth; ctx.fill(); ctx.stroke(); if (config.pointDot){ ctx.fillStyle = data.datasets[i].pointColor; ctx.strokeStyle = data.datasets[i].pointStrokeColor; ctx.lineWidth = config.pointDotStrokeWidth; for (var k=0; k<data.datasets[i].data.length; k++){ ctx.rotate(rotationDegree); ctx.beginPath(); ctx.arc(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[k],calculatedScale,scaleHop)),config.pointDotRadius,2*Math.PI,false); ctx.fill(); ctx.stroke(); } } ctx.rotate(rotationDegree); } ctx.restore(); } function drawScale(){ var rotationDegree = (2*Math.PI)/data.datasets[0].data.length; ctx.save(); ctx.translate(width / 2, height / 2); if (config.angleShowLineOut){ ctx.strokeStyle = config.angleLineColor; ctx.lineWidth = config.angleLineWidth; for (var h=0; h<data.datasets[0].data.length; h++){ ctx.rotate(rotationDegree); ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(0,-maxSize); ctx.stroke(); } } for (var i=0; i<calculatedScale.steps; i++){ ctx.beginPath(); if(config.scaleShowLine){ ctx.strokeStyle = config.scaleLineColor; ctx.lineWidth = config.scaleLineWidth; ctx.moveTo(0,-scaleHop * (i+1)); for (var j=0; j<data.datasets[0].data.length; j++){ ctx.rotate(rotationDegree); ctx.lineTo(0,-scaleHop * (i+1)); } ctx.closePath(); ctx.stroke(); } if (config.scaleShowLabels){ ctx.textAlign = 'center'; ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; ctx.textBaseline = "middle"; if (config.scaleShowLabelBackdrop){ var textWidth = ctx.measureText(calculatedScale.labels[i]).width; ctx.fillStyle = config.scaleBackdropColor; ctx.beginPath(); ctx.rect( Math.round(- textWidth/2 - config.scaleBackdropPaddingX), //X Math.round((-scaleHop * (i + 1)) - config.scaleFontSize*0.5 - config.scaleBackdropPaddingY),//Y Math.round(textWidth + (config.scaleBackdropPaddingX*2)), //Width Math.round(config.scaleFontSize + (config.scaleBackdropPaddingY*2)) //Height ); ctx.fill(); } ctx.fillStyle = config.scaleFontColor; ctx.fillText(calculatedScale.labels[i],0,-scaleHop*(i+1)); } } for (var k=0; k<data.labels.length; k++){ ctx.font = config.pointLabelFontStyle + " " + config.pointLabelFontSize+"px " + config.pointLabelFontFamily; ctx.fillStyle = config.pointLabelFontColor; var opposite = Math.sin(rotationDegree*k) * (maxSize + config.pointLabelFontSize); var adjacent = Math.cos(rotationDegree*k) * (maxSize + config.pointLabelFontSize); if(rotationDegree*k == Math.PI || rotationDegree*k == 0){ ctx.textAlign = "center"; } else if(rotationDegree*k > Math.PI){ ctx.textAlign = "right"; } else{ ctx.textAlign = "left"; } ctx.textBaseline = "middle"; ctx.fillText(data.labels[k],opposite,-adjacent); } ctx.restore(); }; function calculateDrawingSizes(){ maxSize = (Min([width,height])/2); labelHeight = config.scaleFontSize*2; var labelLength = 0; for (var i=0; i<data.labels.length; i++){ ctx.font = config.pointLabelFontStyle + " " + config.pointLabelFontSize+"px " + config.pointLabelFontFamily; var textMeasurement = ctx.measureText(data.labels[i]).width; if(textMeasurement>labelLength) labelLength = textMeasurement; } //Figure out whats the largest - the height of the text or the width of what's there, and minus it from the maximum usable size. maxSize -= Max([labelLength,((config.pointLabelFontSize/2)*1.5)]); maxSize -= config.pointLabelFontSize; maxSize = CapValue(maxSize, null, 0); scaleHeight = maxSize; //If the label height is less than 5, set it to 5 so we don't have lines on top of each other. labelHeight = Default(labelHeight,5); }; function getValueBounds() { var upperValue = Number.MIN_VALUE; var lowerValue = Number.MAX_VALUE; for (var i=0; i<data.datasets.length; i++){ for (var j=0; j<data.datasets[i].data.length; j++){ if (data.datasets[i].data[j] > upperValue){upperValue = data.datasets[i].data[j]} if (data.datasets[i].data[j] < lowerValue){lowerValue = data.datasets[i].data[j]} } } var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); return { maxValue : upperValue, minValue : lowerValue, maxSteps : maxSteps, minSteps : minSteps }; } } var Pie = function(data,config,ctx){ var segmentTotal = 0; //In case we have a canvas that is not a square. Minus 5 pixels as padding round the edge. var pieRadius = Min([height/2,width/2]) - 5; for (var i=0; i<data.length; i++){ segmentTotal += data[i].value; } ctx.fillStyle = 'black'; ctx.textBaseline = 'base'; animationLoop(config,null,drawPieSegments,ctx); function drawPieSegments (animationDecimal){ var cumulativeAngle = -Math.PI/2, scaleAnimation = 1, rotateAnimation = 1; if (config.animation) { if (config.animateScale) { scaleAnimation = animationDecimal; } if (config.animateRotate){ rotateAnimation = animationDecimal; } } for (var i=0; i<data.length; i++){ var segmentAngle = rotateAnimation * ((data[i].value/segmentTotal) * (Math.PI*2)); ctx.beginPath(); ctx.arc(width/2,height/2,scaleAnimation * pieRadius,cumulativeAngle,cumulativeAngle + segmentAngle); ctx.lineTo(width/2,height/2); ctx.closePath(); ctx.fillStyle = data[i].color; ctx.fill(); if(data[i].label && scaleAnimation*pieRadius*2*segmentAngle/(2*Math.PI) > config.labelFontSize) { function getPieLabelX(align, r) { switch(align) { case 'left': return -r+20; break; case 'center': return -r/2; break; } return -10; } function reversePieLabelAlign(align) { switch(align) { case 'left': return 'right'; break; case 'right': return 'left'; break; case 'center': return align; break; } } var fontSize = data[i].labelFontSize || config.labelFontSize+'px'; if(fontSize.match(/^[0-9]+$/g) != null) { fontSize = fontSize+'px'; } ctx.font = config.labelFontStyle+ " " +fontSize+" " + config.labelFontFamily; ctx.fillStyle = getFadeColor(animationDecimal, data[i].labelColor || 'black', data[i].color); ctx.textBaseline = 'middle'; // rotate text, so it perfectly fits in segments var textRotation = -(cumulativeAngle + segmentAngle)+segmentAngle/2, tX = width/2+scaleAnimation*pieRadius*Math.cos(textRotation), tY = height/2-scaleAnimation*pieRadius*Math.sin(textRotation); ctx.textAlign = data[i].labelAlign || config.labelAlign; textX = getPieLabelX(ctx.textAlign, scaleAnimation*pieRadius); if(textRotation < -Math.PI/2) { textRotation -= Math.PI; ctx.textAlign = reversePieLabelAlign(ctx.textAlign); textX = -textX; } ctx.translate(tX, tY); ctx.rotate(-textRotation); ctx.fillText(data[i].label, textX, 0); ctx.rotate(textRotation); ctx.translate(-tX, -tY); } if(animationDecimal >= 1 && config.showTooltips) { var points = [{x:width/2,y:height/2}], pAmount = 50; points.push({x:width/2+pieRadius*Math.cos(cumulativeAngle),y:height/2+pieRadius*Math.sin(cumulativeAngle)}); for(var p = 0; p <= pAmount; p++) { points.push({x:width/2+pieRadius*Math.cos(cumulativeAngle+p/pAmount*segmentAngle),y:height/2+pieRadius*Math.sin(cumulativeAngle+p/pAmount*segmentAngle)}); } registerTooltip(ctx,{type:'shape',points:points},{label:data[i].label,value:(data[i].value * 100) + "%"},'Pie'); } if(config.segmentShowStroke){ ctx.lineWidth = config.segmentStrokeWidth; ctx.strokeStyle = config.segmentStrokeColor; ctx.stroke(); } cumulativeAngle += segmentAngle; } } } var Doughnut = function(data,config,ctx){ var segmentTotal = 0; //In case we have a canvas that is not a square. Minus 5 pixels as padding round the edge. var doughnutRadius = Min([height/2,width/2]) - 5; var cutoutRadius = doughnutRadius * (config.percentageInnerCutout/100); for (var i=0; i<data.length; i++){ segmentTotal += data[i].value; } animationLoop(config,null,drawPieSegments,ctx); function drawPieSegments (animationDecimal){ var cumulativeAngle = -Math.PI/2, scaleAnimation = 1, rotateAnimation = 1; if (config.animation) { if (config.animateScale) { scaleAnimation = animationDecimal; } if (config.animateRotate){ rotateAnimation = animationDecimal; } } for (var i=0; i<data.length; i++){ var segmentAngle = rotateAnimation * ((data[i].value/segmentTotal) * (Math.PI*2)); ctx.beginPath(); ctx.arc(width/2,height/2,scaleAnimation * doughnutRadius,cumulativeAngle,cumulativeAngle + segmentAngle,false); ctx.arc(width/2,height/2,scaleAnimation * cutoutRadius,cumulativeAngle + segmentAngle,cumulativeAngle,true); ctx.closePath(); ctx.fillStyle = data[i].color; ctx.fill(); if(animationDecimal >= 1 && config.showTooltips) { var points = [], pAmount = 50; points.push({x:width/2+doughnutRadius*Math.cos(cumulativeAngle),y:height/2+doughnutRadius*Math.sin(cumulativeAngle)}); for(var p = 0; p <= pAmount; p++) { points.push({x:width/2+doughnutRadius*Math.cos(cumulativeAngle+p/pAmount*segmentAngle),y:height/2+doughnutRadius*Math.sin(cumulativeAngle+p/pAmount*segmentAngle)}); } points.push({x:width/2+cutoutRadius*Math.cos(cumulativeAngle+segmentAngle),y:height/2+cutoutRadius*Math.sin(cumulativeAngle+segmentAngle)}); for(var p = pAmount; p >= 0; p--) { points.push({x:width/2+cutoutRadius*Math.cos(cumulativeAngle+p/pAmount*segmentAngle),y:height/2+cutoutRadius*Math.sin(cumulativeAngle+p/pAmount*segmentAngle)}); } registerTooltip(ctx,{type:'shape',points:points},{label:data[i].label,value:data[i].value},'Doughnut'); } if(config.segmentShowStroke){ ctx.lineWidth = config.segmentStrokeWidth; ctx.strokeStyle = config.segmentStrokeColor; ctx.stroke(); } cumulativeAngle += segmentAngle; } } } var Line = function(data,config,ctx){ var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY, rotateLabels = 0; calculateDrawingSizes(); valueBounds = getValueBounds(); //Check and set the scale labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : ""; if (!config.scaleOverride){ calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); } else { calculatedScale = { steps : config.scaleSteps, stepValue : config.scaleStepWidth, graphMin : config.scaleStartValue, labels : [] } populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); } scaleHop = Math.floor(scaleHeight/calculatedScale.steps); calculateXAxisSize(); animationLoop(config,drawScale,drawLines,ctx); function drawLines(animPc){ for (var i=0; i<data.datasets.length; i++){ ctx.strokeStyle = data.datasets[i].strokeColor; ctx.lineWidth = config.datasetStrokeWidth; ctx.beginPath(); ctx.moveTo(yAxisPosX, xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[0],calculatedScale,scaleHop))) for (var j=1; j<data.datasets[i].data.length; j++){ if (config.bezierCurve){ ctx.bezierCurveTo(xPos(j-0.5),yPos(i,j-1),xPos(j-0.5),yPos(i,j),xPos(j),yPos(i,j)); } else{ ctx.lineTo(xPos(j),yPos(i,j)); } } var pointRadius = config.pointDot ? config.pointDotRadius+config.pointDotStrokeWidth : 10; for(var j = 0; j < data.datasets[i].data.length; j++) { if(animPc >= 1 && config.showTooltips) { // register tooltips registerTooltip(ctx,{type:'circle',x:xPos(j),y:yPos(i,j),r:pointRadius},{label:data.labels[j],value:data.datasets[i].data[j]},'Line'); } } ctx.stroke(); if (config.datasetFill){ ctx.lineTo(yAxisPosX + (valueHop*(data.datasets[i].data.length-1)),xAxisPosY); ctx.lineTo(yAxisPosX,xAxisPosY); ctx.closePath(); ctx.fillStyle = data.datasets[i].fillColor; ctx.fill(); } else{ ctx.closePath(); } if(config.pointDot){ ctx.fillStyle = data.datasets[i].pointColor; ctx.strokeStyle = data.datasets[i].pointStrokeColor; ctx.lineWidth = config.pointDotStrokeWidth; for (var k=0; k<data.datasets[i].data.length; k++){ ctx.beginPath(); ctx.arc(yAxisPosX + (valueHop *k),xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[k],calculatedScale,scaleHop)),config.pointDotRadius,0,Math.PI*2,true); ctx.fill(); ctx.stroke(); } } } function yPos(dataSet,iteration){ return xAxisPosY - animPc*(calculateOffset(data.datasets[dataSet].data[iteration],calculatedScale,scaleHop)); } function xPos(iteration){ return yAxisPosX + (valueHop * iteration); } } function drawScale(){ //X axis line ctx.lineWidth = config.scaleLineWidth; ctx.strokeStyle = config.scaleLineColor; ctx.beginPath(); ctx.moveTo(width-widestXLabel/2+5,xAxisPosY); ctx.lineTo(width-(widestXLabel/2)-xAxisLength-5,xAxisPosY); ctx.stroke(); if (rotateLabels > 0){ ctx.save(); ctx.textAlign = "right"; } else{ ctx.textAlign = "center"; } ctx.fillStyle = config.scaleFontColor; for (var i=0; i<data.labels.length; i++){ ctx.save(); if (rotateLabels > 0){ ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize); ctx.rotate(-(rotateLabels * (Math.PI/180))); ctx.fillText(data.labels[i], 0,0); ctx.restore(); } else{ ctx.fillText(data.labels[i], yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize+3); } ctx.beginPath(); ctx.moveTo(yAxisPosX + i * valueHop, xAxisPosY+3); //Check i isnt 0, so we dont go over the Y axis twice. if(config.scaleShowGridLines && i>0){ ctx.lineWidth = config.scaleGridLineWidth; ctx.strokeStyle = config.scaleGridLineColor; ctx.lineTo(yAxisPosX + i * valueHop, 5); } else{ ctx.lineTo(yAxisPosX + i * valueHop, xAxisPosY+3); } ctx.stroke(); } //Y axis ctx.lineWidth = config.scaleLineWidth; ctx.strokeStyle = config.scaleLineColor; ctx.beginPath(); ctx.moveTo(yAxisPosX,xAxisPosY+5); ctx.lineTo(yAxisPosX,5); ctx.stroke(); ctx.textAlign = "right"; ctx.textBaseline = "middle"; for (var j=0; j<calculatedScale.steps; j++){ ctx.beginPath(); ctx.moveTo(yAxisPosX-3,xAxisPosY - ((j+1) * scaleHop)); if (config.scaleShowGridLines){ ctx.lineWidth = config.scaleGridLineWidth; ctx.strokeStyle = config.scaleGridLineColor; ctx.lineTo(yAxisPosX + xAxisLength + 5,xAxisPosY - ((j+1) * scaleHop)); } else{ ctx.lineTo(yAxisPosX-0.5,xAxisPosY - ((j+1) * scaleHop)); } ctx.stroke(); if (config.scaleShowLabels){ ctx.fillText(calculatedScale.labels[j],yAxisPosX-8,xAxisPosY - ((j+1) * scaleHop)); } } } function calculateXAxisSize(){ var longestText = 1; //if we are showing the labels if (config.scaleShowLabels){ ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; for (var i=0; i<calculatedScale.labels.length; i++){ var measuredText = ctx.measureText(calculatedScale.labels[i]).width; longestText = (measuredText > longestText)? measuredText : longestText; } //Add a little extra padding from the y axis longestText +=10; } xAxisLength = width - longestText - widestXLabel; valueHop = Math.floor(xAxisLength/(data.labels.length-1)); yAxisPosX = width-widestXLabel/2-xAxisLength; xAxisPosY = scaleHeight + config.scaleFontSize/2; } function calculateDrawingSizes(){ maxSize = height; //Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees. ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; widestXLabel = 1; for (var i=0; i<data.labels.length; i++){ var textLength = ctx.measureText(data.labels[i]).width; //If the text length is longer - make that equal to longest text! widestXLabel = (textLength > widestXLabel)? textLength : widestXLabel; } if (width/data.labels.length < widestXLabel){ rotateLabels = 45; if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){ rotateLabels = 90; maxSize -= widestXLabel; } else{ maxSize -= Math.sin(rotateLabels) * widestXLabel; } } else{ maxSize -= config.scaleFontSize; } //Add a little padding between the x line and the text maxSize -= 5; labelHeight = config.scaleFontSize; maxSize -= labelHeight; //Set 5 pixels greater than the font size to allow for a little padding from the X axis. scaleHeight = maxSize; //Then get the area above we can safely draw on. } function getValueBounds() { var upperValue = Number.MIN_VALUE; var lowerValue = Number.MAX_VALUE; for (var i=0; i<data.datasets.length; i++){ for (var j=0; j<data.datasets[i].data.length; j++){ if ( data.datasets[i].data[j] > upperValue) { upperValue = data.datasets[i].data[j] }; if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] }; } }; var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); return { maxValue : upperValue, minValue : lowerValue, maxSteps : maxSteps, minSteps : minSteps }; } } var Bar = function(data,config,ctx){ var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY,barWidth, rotateLabels = 0; calculateDrawingSizes(); valueBounds = getValueBounds(); //Check and set the scale labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : ""; if (!config.scaleOverride){ calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); } else { calculatedScale = { steps : config.scaleSteps, stepValue : config.scaleStepWidth, graphMin : config.scaleStartValue, labels : [] } populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); } scaleHop = Math.floor(scaleHeight/calculatedScale.steps); calculateXAxisSize(); animationLoop(config,drawScale,drawBars,ctx); function drawBars(animPc){ ctx.lineWidth = config.barStrokeWidth; for (var i=0; i<data.datasets.length; i++){ ctx.fillStyle = data.datasets[i].fillColor; ctx.strokeStyle = data.datasets[i].strokeColor; for (var j=0; j<data.datasets[i].data.length; j++){ var barOffset = yAxisPosX + config.barValueSpacing + valueHop*j + barWidth*i + config.barDatasetSpacing*i + config.barStrokeWidth*i; ctx.beginPath(); ctx.moveTo(barOffset, xAxisPosY); ctx.lineTo(barOffset, xAxisPosY - animPc*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)+(config.barStrokeWidth/2)); ctx.lineTo(barOffset + barWidth, xAxisPosY - animPc*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)+(config.barStrokeWidth/2)); ctx.lineTo(barOffset + barWidth, xAxisPosY); if(config.barShowStroke){ ctx.stroke(); } ctx.closePath(); ctx.fill(); if(animPc >= 1 && config.showTooltips) { // register tooltips var x = barOffset, height = calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop), y = xAxisPosY-height, width = barWidth; registerTooltip(ctx,{type:'rect',x:x,y:y,width:width,height:height},{label:data.labels[j],value:data.datasets[i].data[j]},'Bar'); } } } } function drawScale(){ //X axis line ctx.lineWidth = config.scaleLineWidth; ctx.strokeStyle = config.scaleLineColor; ctx.beginPath(); ctx.moveTo(width-widestXLabel/2+5,xAxisPosY); ctx.lineTo(width-(widestXLabel/2)-xAxisLength-5,xAxisPosY); ctx.stroke(); if (rotateLabels > 0){ ctx.save(); ctx.textAlign = "right"; } else{ ctx.textAlign = "center"; } ctx.fillStyle = config.scaleFontColor; for (var i=0; i<data.labels.length; i++){ ctx.save(); if (rotateLabels > 0){ ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize); ctx.rotate(-(rotateLabels * (Math.PI/180))); ctx.fillText(data.labels[i], 0,0); ctx.restore(); } else{ ctx.fillText(data.labels[i], yAxisPosX + i*valueHop + valueHop/2,xAxisPosY + config.scaleFontSize+3); } ctx.beginPath(); ctx.moveTo(yAxisPosX + (i+1) * valueHop, xAxisPosY+3); //Check i isnt 0, so we dont go over the Y axis twice. ctx.lineWidth = config.scaleGridLineWidth; ctx.strokeStyle = config.scaleGridLineColor; ctx.lineTo(yAxisPosX + (i+1) * valueHop, 5); ctx.stroke(); } //Y axis ctx.lineWidth = config.scaleLineWidth; ctx.strokeStyle = config.scaleLineColor; ctx.beginPath(); ctx.moveTo(yAxisPosX,xAxisPosY+5); ctx.lineTo(yAxisPosX,5); ctx.stroke(); ctx.textAlign = "right"; ctx.textBaseline = "middle"; for (var j=0; j<calculatedScale.steps; j++){ ctx.beginPath(); ctx.moveTo(yAxisPosX-3,xAxisPosY - ((j+1) * scaleHop)); if (config.scaleShowGridLines){ ctx.lineWidth = config.scaleGridLineWidth; ctx.strokeStyle = config.scaleGridLineColor; ctx.lineTo(yAxisPosX + xAxisLength + 5,xAxisPosY - ((j+1) * scaleHop)); } else{ ctx.lineTo(yAxisPosX-0.5,xAxisPosY - ((j+1) * scaleHop)); } ctx.stroke(); if (config.scaleShowLabels){ ctx.fillText(calculatedScale.labels[j],yAxisPosX-8,xAxisPosY - ((j+1) * scaleHop)); } } } function calculateXAxisSize(){ var longestText = 1; //if we are showing the labels if (config.scaleShowLabels){ ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; for (var i=0; i<calculatedScale.labels.length; i++){ var measuredText = ctx.measureText(calculatedScale.labels[i]).width; longestText = (measuredText > longestText)? measuredText : longestText; } //Add a little extra padding from the y axis longestText +=10; } xAxisLength = width - longestText - widestXLabel; valueHop = Math.floor(xAxisLength/(data.labels.length)); barWidth = (valueHop - config.scaleGridLineWidth*2 - (config.barValueSpacing*2) - (config.barDatasetSpacing*data.datasets.length-1) - ((config.barStrokeWidth/2)*data.datasets.length-1))/data.datasets.length; yAxisPosX = width-widestXLabel/2-xAxisLength; xAxisPosY = scaleHeight + config.scaleFontSize/2; } function calculateDrawingSizes(){ maxSize = height; //Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees. ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; widestXLabel = 1; for (var i=0; i<data.labels.length; i++){ var textLength = ctx.measureText(data.labels[i]).width; //If the text length is longer - make that equal to longest text! widestXLabel = (textLength > widestXLabel)? textLength : widestXLabel; } if (width/data.labels.length < widestXLabel){ rotateLabels = 45; if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){ rotateLabels = 90; maxSize -= widestXLabel; } else{ maxSize -= Math.sin(rotateLabels) * widestXLabel; } } else{ maxSize -= config.scaleFontSize; } //Add a little padding between the x line and the text maxSize -= 5; labelHeight = config.scaleFontSize; maxSize -= labelHeight; //Set 5 pixels greater than the font size to allow for a little padding from the X axis. scaleHeight = maxSize; //Then get the area above we can safely draw on. } function getValueBounds() { var upperValue = Number.MIN_VALUE; var lowerValue = Number.MAX_VALUE; for (var i=0; i<data.datasets.length; i++){ for (var j=0; j<data.datasets[i].data.length; j++){ if ( data.datasets[i].data[j] > upperValue) { upperValue = data.datasets[i].data[j] }; if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] }; } }; var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); return { maxValue : upperValue, minValue : lowerValue, maxSteps : maxSteps, minSteps : minSteps }; } } function calculateOffset(val,calculatedScale,scaleHop){ var outerValue = calculatedScale.steps * calculatedScale.stepValue; var adjustedValue = val - calculatedScale.graphMin; var scalingFactor = CapValue(adjustedValue/outerValue,1,0); return (scaleHop*calculatedScale.steps) * scalingFactor; } function animationLoop(config,drawScale,drawData,ctx){ var animFrameAmount = (config.animation)? 1/CapValue(config.animationSteps,Number.MAX_VALUE,1) : 1, easingFunction = animationOptions[config.animationEasing], percentAnimComplete =(config.animation)? 0 : 1; if (typeof drawScale !== "function") drawScale = function(){}; requestAnimFrame(animLoop); function animateFrame(){ var easeAdjustedAnimationPercent =(config.animation)? CapValue(easingFunction(percentAnimComplete),null,0) : 1; clear(ctx); if(config.scaleOverlay){ drawData(easeAdjustedAnimationPercent); drawScale(); } else { drawScale(); drawData(easeAdjustedAnimationPercent); } } function animLoop(){ //We need to check if the animation is incomplete (less than 1), or complete (1). percentAnimComplete += animFrameAmount; animateFrame(); //Stop the loop continuing forever if (percentAnimComplete <= 1){ requestAnimFrame(animLoop); } else{ if (typeof config.onAnimationComplete == "function") config.onAnimationComplete(); } } } //Declare global functions to be called within this namespace here. // shim layer with setTimeout fallback var requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); function calculateScale(drawingHeight,maxSteps,minSteps,maxValue,minValue,labelTemplateString){ var graphMin,graphMax,graphRange,stepValue,numberOfSteps,valueRange,rangeOrderOfMagnitude,decimalNum; valueRange = maxValue - minValue; rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange); graphMin = Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude); graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude); graphRange = graphMax - graphMin; stepValue = Math.pow(10, rangeOrderOfMagnitude); numberOfSteps = Math.round(graphRange / stepValue); //Compare number of steps to the max and min for that size graph, and add in half steps if need be. while(numberOfSteps < minSteps || numberOfSteps > maxSteps) { if (numberOfSteps < minSteps){ stepValue /= 2; numberOfSteps = Math.round(graphRange/stepValue); } else{ stepValue *=2; numberOfSteps = Math.round(graphRange/stepValue); } } var labels = []; populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue); return { steps : numberOfSteps, stepValue : stepValue, graphMin : graphMin, labels : labels } function calculateOrderOfMagnitude(val){ return Math.floor(Math.log(val) / Math.LN10); } } //Populate an array of all the labels by interpolating the string. function populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue) { if (labelTemplateString) { //Fix floating point errors by setting to fixed the on the same decimal as the stepValue. for (var i = 1; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, {value: (graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))})); } } } //Max value from array function Max( array ){ return Math.max.apply( Math, array ); }; //Min value from array function Min( array ){ return Math.min.apply( Math, array ); }; //Default if undefined function Default(userDeclared,valueIfFalse){ if(!userDeclared){ return valueIfFalse; } else { return userDeclared; } }; //Is a number function function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } //Apply cap a value at a high or low number function CapValue(valueToCap, maxValue, minValue){ if(isNumber(maxValue)) { if( valueToCap > maxValue ) { return maxValue; } } if(isNumber(minValue)){ if ( valueToCap < minValue ){ return minValue; } } return valueToCap; } function getDecimalPlaces (num){ var numberOfDecimalPlaces; if (num%1!=0){ return num.toString().split(".")[1].length } else{ return 0; } } function mergeChartConfig(defaults,userDefined){ var returnObj = {}; for (var attrname in defaults) { returnObj[attrname] = defaults[attrname]; } for (var attrname in userDefined) { if(typeof(userDefined[attrname]) === "object" && defaults[attrname]) { returnObj[attrname] = mergeChartConfig(defaults[attrname], userDefined[attrname]); } else { returnObj[attrname] = userDefined[attrname]; } } return returnObj; } //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/ var cache = {}; function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; function getFadeColor(percent, primColor, secColor) { var pseudoEl = document.createElement('div'), rgbPrim, rgbSec; pseudoEl.style.color = primColor; document.body.appendChild(pseudoEl); rgbPrim = window.getComputedStyle(pseudoEl).color; pseudoEl.style.color = secColor; rgbSec = window.getComputedStyle(pseudoEl).color; var regex = /rgb *\( *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9]{1,3}) *\)/, valuesP = regex.exec(rgbPrim), valuesS = regex.exec(rgbSec), rP = Math.round(parseFloat(valuesP[1])), gP = Math.round(parseFloat(valuesP[2])), bP = Math.round(parseFloat(valuesP[3])), rS = Math.round(parseFloat(valuesS[1])), gS = Math.round(parseFloat(valuesS[2])), bS = Math.round(parseFloat(valuesS[3])), rCur = parseInt((rP-rS)*percent+rS), gCur = parseInt((gP-gS)*percent+gS), bCur = parseInt((bP-bS)*percent+bS); pseudoEl.parentNode.removeChild(pseudoEl); return "rgb("+rCur+','+gCur+','+bCur+')'; } }
{ "translatorID": "3f73f0aa-f91c-4192-b0d5-907312876cb9", "translatorType": 4, "label": "ThesesFR", "creator": "TFU, Mathis EON", "target": "^https?://(www\\.)?theses\\.fr/([a-z]{2}/)?((s\\d+|\\d{4}.{8}|\\d{8}X|\\d{9})(?!\\.(rdf|xml)$)|(sujets/\\?q=|\\?q=))(?!.*&format=(json|xml))", "minVersion": "3.0", "maxVersion": null, "priority": 100, "inRepository": true, "browserSupport": "gcsibv", "lastUpdated": "2020-05-17 01:40:00" } /* ***** BEGIN LICENSE BLOCK ***** theses.fr This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ function detectWeb(doc, url) { // Match against a results page or a Ph. D/supervisor/organization page which might contains multiple records e.g. // http://www.theses.fr/fr/?q=zotero // http://www.theses.fr/fr/154750417 if (url.includes('/?q=') || url.match(/\d{8}(\d|X)/)) { return 'multiple'; } else { return 'thesis'; } } function getSearchResults(doc, checkOnly) { let items = {}; let found = false; let rows = ZU.xpath(doc, '//div[contains(@class, "encart arrondi-10")]//h2/a'); rows.forEach((row) => { let href = row.href; let title = ZU.trimInternal(row.textContent); if (checkOnly) return true; found = true; items[href] = title; return row; }); return found ? items : false; } function doWeb(doc, url) { if (detectWeb(doc, url) === 'multiple') { Zotero.selectItems(getSearchResults(doc, false), (items) => { if (!items) return; let records = []; let item = null; for (item in items) { records.push(item); } ZU.processDocuments(records, scrape); }); } else { scrape(doc, url); } } function scrape(doc, url) { let xmlDocumentUrl = `${url}.rdf`; // Each thesis record has an underlying .rdf file Zotero.Utilities.HTTP.doGet(xmlDocumentUrl, function (text) { let parser = new DOMParser(); let xmlDoc = parser.parseFromString(text, 'application/xml'); // Skiping invalid or empty RDF files : prevents crashes while importing multiple records if (xmlDoc.getElementsByTagName('parsererror')[0] || xmlDoc.children[0].childElementCount === 0) { throw new Error("Invalid or empty RDF file"); } // Importing XML namespaces for parsing purposes let ns = { bibo: 'http://purorg/ontology/bibo/', dc: 'http://purl.org/dc/elements/1.1/', dcterms: 'http://purl.org/dc/terms/', foaf: 'http://xmlns.com/foaf/0.1/', marcrel: 'http://www.loc.gov/loc.terms/relators/', rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' }; let title = ZU.xpathText(xmlDoc, '//dc:title', ns); if (!title) throw new Error("Reccord must contains a title to be imported"); let newItem = new Zotero.Item(); newItem.itemType = 'thesis'; newItem.title = title; ZU.xpath(xmlDoc, '//marcrel:aut//foaf:Person/foaf:name | //marcrel:dis//foaf:Person/foaf:name', ns).forEach((auth) => { let author = ZU.cleanAuthor(auth.textContent, 'author', true); newItem.creators.push(author); }); // Supervisor(s) must be considered as contributor(s) for french thesis ZU.xpath(xmlDoc, '//marcrel:ths//foaf:Person/foaf:name', ns).forEach((sup) => { let supervisor = ZU.cleanAuthor(sup.textContent, 'contributor', true); newItem.creators.push(supervisor); }); newItem.abstractNote = ZU.xpathText(xmlDoc, '(//dcterms:abstract)[1]', ns); // '/s + digit' in url means thesis in preparation newItem.thesisType = url.match(/\/s\d+/) ? 'These en préparation' : 'These de doctorat'; newItem.university = ZU.xpathText(xmlDoc, '(//marcrel:dgg/foaf:Organization/foaf:name)[1]', ns); let fullDate = ZU.xpathText(xmlDoc, '//dcterms:dateAccepted', ns); let year = ZU.xpathText(xmlDoc, '//dc:date', ns); // Some old records doesn't have a full date instead we can use the defense year newItem.date = fullDate ? fullDate : year; newItem.url = url; newItem.libraryCatalog = 'theses.fr'; newItem.rights = 'Licence Etalab'; // Keep extra information such as laboratory, graduate schools, etc. in a note for thesis not yet defended let notePrepa = Array.from(doc.getElementsByClassName('donnees-ombreprepa2')).map((description) => { return Array.from(description.getElementsByTagName('p')).map(description => description.textContent.replace(/\n/g, ' ').trim()); }).join(' '); if (notePrepa) { newItem.notes.push({ note: notePrepa }); } // Keep extra information such as laboratory, graduate schools, etc. in a note for defended thesis let note = Array.from(doc.getElementsByClassName('donnees-ombre')).map((description) => { return Array.from(description.getElementsByTagName('p')).map(description => description.textContent.replace(/\n/g, ' ').trim()); }).join(' '); if (note) { newItem.notes.push({ note: note }); } ZU.xpath(xmlDoc, '//dc:subject', ns).forEach((t) => { let tag = t.textContent; newItem.tags.push(tag); }); newItem.complete(); }); } /** BEGIN TEST CASES **/ var testCases = [ { "type": "web", "url": "http://theses.fr/?q=Mesure+de+masse+de+noyau#", "items": "multiple" }, { "type": "web", "url": "http://www.theses.fr/fr/154750417", "items": "multiple" }, { "type": "web", "url": "http://www.theses.fr/fr/188120777", "items": "multiple" }, { "type": "web", "url": "http://www.theses.fr/2016SACLS590", "items": [ { "itemType": "thesis", "title": "Measurement of the W boson mass with the ATLAS detector", "creators": [ { "firstName": "Oleh", "lastName": "Kivernyk", "creatorType": "author" }, { "firstName": "Maarten", "lastName": "Boonekamp", "creatorType": "contributor" } ], "date": "2016-09-19", "abstractNote": "Cette thèse décrit une mesure de la masse du boson W avec le détecteur ATLAS. La mesure exploite les données enregistrées par ATLAS en 2011, a une énergie dans le centre de masse de 7 TeV et correspondant à une luminosité intégrée de 4.6 inverse femtobarn. Les mesures sont faites par ajustement aux données de distributions en énergie transverse des leptons charges et en masse transverse du boson W obtenues par simulation, dans les canaux électron et muon, et dans plusieurs catégories cinématiques. Les différentes mesures sont en bon accord et leur combinaison donne une valeur de m_W = 80371.1 ± 18.6 MeV. La valeur mesurée est compatible avec la moyenne mondiale des mesures existantes, m_W = 80385 ± 15 MeV, et l'incertitude obtenue est compétitive avec les mesures les plus précises réalisées par les collaborations CDF et D0.", "libraryCatalog": "theses.fr", "thesisType": "These de doctorat", "university": "Université Paris-Saclay (ComUE)", "url": "http://www.theses.fr/2016SACLS590", "attachments": [], "tags": [ { "tag": "ATLAS" }, { "tag": "ATLAS" }, { "tag": "Bosons W -- Masse" }, { "tag": "Grand collisionneur de hadrons" }, { "tag": "LHC" }, { "tag": "LHC" }, { "tag": "Masse du boson W" }, { "tag": "Modèle standard" }, { "tag": "Modèle standard (physique nucléaire)" }, { "tag": "Standard Model" }, { "tag": "W boson mass" } ], "rights": "Licence Etalab", "notes": [ { "note": "Sous la direction de Maarten Boonekamp. Soutenue le 19-09-2016,à l'Université Paris-Saclay (ComUE) , dans le cadre de École doctorale Particules, Hadrons, Énergie et Noyau : Instrumentation, Imagerie, Cosmos et Simulation (Orsay, Essonne ; 2015-....) , en partenariat avec Département de physique des particules (Gif-sur-Yvette, Essonne) (laboratoire) , Centre européen pour la recherche nucléaire (laboratoire) et de Université Paris-Sud (1970-2019) (établissement opérateur d'inscription) ." } ], "seeAlso": [] } ] }, { "type": "web", "url": "http://www.theses.fr/s128743", "items": [ { "itemType": "thesis", "creators": [ { "firstName": "Alice", "lastName": "Cartier", "creatorType": "author" }, { "firstName": "Gilles J.", "lastName": "Guglielmi", "creatorType": "contributor" } ], "notes": [ { "note": "Thèses en préparation à Paris 2 , dans le cadre de Ecole doctorale Georges Vedel Droit public interne, science administrative et science politique (Paris) depuis le 01-10-2014 ." } ], "tags": [], "seeAlso": [], "attachments": [], "title": "Les relations bilatérales France-Québec à l'épreuve de l'OMC et de l'UE", "abstractNote": "Champ territorial: les fondements juridiques France/Québec/Canada/Europe, approches croisées européen/international. 1ère partie orientée histoire du droit: analyse relation bilatérale France/Québec: prémices enjeux diplomatiques et culturels pour la France de \"Gesta Dei per Francos\" aux échanges particuliers France/Québec (1910-1860), puis enjeux diplomatiques et culturels pour la France dans les années 1960 de Gaulle, Malraux, Québec et francophonie), Trente Glorieuses et période de guerre froide, tournant sur le plan international influant et restructurant les bases juridiques. Pour le Canada: période de \"crise majeure de son histoire\" avec la Révolution tranquille et remise en cause des rapports/accords diplomatiques avec la France qui existaient depuis Napoléon III, apparition ouverte d'un rapport triangulaire (Paris-Ottawa-Québec). Le Québec s'éveille, s'affirme, rêve d'indépendance.", "thesisType": "These en préparation", "university": "Paris 2", "date": "2014", "url": "http://www.theses.fr/s128743", "libraryCatalog": "theses.fr", "rights": "Licence Etalab" } ] } ] /** END TEST CASES **/
define(['./_baseForOwnRight', './_baseIteratee'], function(baseForOwnRight, baseIteratee) { /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, baseIteratee(iteratee, 3)); } return forOwnRight; });
import { OpaqueToken } from '@angular/core'; import { ObservableWrapper } from '../facade/async'; import { StringMapWrapper } from '../facade/collection'; import { isBlank, isPresent, isString } from '../facade/lang'; import { PromiseWrapper } from '../facade/promise'; /** * Providers for validators to be used for {@link Control}s in a form. * * Provide this using `multi: true` to add validators. * * ### Example * * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'} * @experimental */ export const NG_VALIDATORS = new OpaqueToken('NgValidators'); /** * Providers for asynchronous validators to be used for {@link Control}s * in a form. * * Provide this using `multi: true` to add validators. * * See {@link NG_VALIDATORS} for more details. * * @experimental */ export const NG_ASYNC_VALIDATORS = /*@ts2dart_const*/ new OpaqueToken('NgAsyncValidators'); /** * Provides a set of validators used by form controls. * * A validator is a function that processes a {@link Control} or collection of * controls and returns a map of errors. A null map means that validation has passed. * * ### Example * * ```typescript * var loginControl = new Control("", Validators.required) * ``` * * @experimental */ export class Validators { /** * Validator that requires controls to have a non-empty value. */ static required(control) { return isBlank(control.value) || (isString(control.value) && control.value == '') ? { 'required': true } : null; } /** * Validator that requires controls to have a value of a minimum length. */ static minLength(minLength) { return (control) => { if (isPresent(Validators.required(control))) return null; var v = control.value; return v.length < minLength ? { 'minlength': { 'requiredLength': minLength, 'actualLength': v.length } } : null; }; } /** * Validator that requires controls to have a value of a maximum length. */ static maxLength(maxLength) { return (control) => { if (isPresent(Validators.required(control))) return null; var v = control.value; return v.length > maxLength ? { 'maxlength': { 'requiredLength': maxLength, 'actualLength': v.length } } : null; }; } /** * Validator that requires a control to match a regex to its value. */ static pattern(pattern) { return (control) => { if (isPresent(Validators.required(control))) return null; let regex = new RegExp(`^${pattern}$`); let v = control.value; return regex.test(v) ? null : { 'pattern': { 'requiredPattern': `^${pattern}$`, 'actualValue': v } }; }; } /** * No-op validator. */ static nullValidator(c) { return null; } /** * Compose multiple validators into a single function that returns the union * of the individual error maps. */ static compose(validators) { if (isBlank(validators)) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function (control) { return _mergeErrors(_executeValidators(control, presentValidators)); }; } static composeAsync(validators) { if (isBlank(validators)) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function (control) { let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); return PromiseWrapper.all(promises).then(_mergeErrors); }; } } function _convertToPromise(obj) { return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); } function _executeValidators(control, validators) { return validators.map(v => v(control)); } function _executeAsyncValidators(control, validators) { return validators.map(v => v(control)); } function _mergeErrors(arrayOfErrors) { var res = arrayOfErrors.reduce((res, errors) => { return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res; }, {}); return StringMapWrapper.isEmpty(res) ? null : res; } //# sourceMappingURL=validators.js.map
/* */ module.exports = function(hljs) { return { subLanguage: 'xml', contains: [ hljs.COMMENT('<%#', '%>'), { begin: '<%[%=-]?', end: '[%-]?%>', subLanguage: 'ruby', excludeBegin: true, excludeEnd: true } ] }; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _Toggle = require('material-ui/Toggle'); var _Toggle2 = _interopRequireDefault(_Toggle); var _createComponent = require('./createComponent'); var _createComponent2 = _interopRequireDefault(_createComponent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } exports.default = (0, _createComponent2.default)(_Toggle2.default, function (_ref) { var _ref$input = _ref.input, onChange = _ref$input.onChange, value = _ref$input.value, inputProps = _objectWithoutProperties(_ref$input, ['onChange', 'value']), meta = _ref.meta, props = _objectWithoutProperties(_ref, ['input', 'meta']); return _extends({}, inputProps, props, { toggled: value ? true : false, onToggle: onChange }); });
define( [ 'ufojs/tools/pens/BasePen' , 'ufojs/tools/misc/arrayTools' ], function( Parent , arrayTools ) { "use strict"; var updateBounds = arrayTools.updateBounds; /** * javascript port based on the original python sources from: * https://github.com/robofab-developers/robofab/blob/445e45d75567efccd51574c4aa2a14d15eb1d4db/Lib/robofab/pens/boundsPen.py * * but also check the boundsPen.py file in the master branch: * https://github.com/robofab-developers/robofab/blob/master/Lib/robofab/pens/boundsPen.py * as it seems more actively mantained even though the code in their ufo3k branch is the primary source for ufoJS. * * Pen to calculate the 'control bounds' of a shape. This is the * bounding box of all control points __on closed paths__, so may * be larger than the actual bounding box if there are curves that * don't have points on their extremes. * * Single points, or anchors, are ignored. * * When the shape has been drawn, the bounds are available as the * 'bounds' attribute of the pen object. It's a 4-tuple: * * (xMin, yMin, xMax, yMax) * * This replaces fontTools/pens/boundsPen (temporarily?) * The fontTools bounds pen takes lose anchor points into account, * this one doesn't. */ /* constructor */ function ControlBoundsPen (glyphSet) { Parent.call(this, glyphSet); this.bounds = undefined; this._start = undefined; } /* inheritance */ var _p = ControlBoundsPen.prototype = Object.create(Parent.prototype); _p._moveTo = function (pt, kwargs/* optional, object contour attributes*/){ this._start = pt; }; _p._addMoveTo = function (){ if (this._start == undefined) return; if (this.bounds){ this.bounds = updateBounds(this.bounds, this._start); } else { var x = this._start[0] , y = this._start[1] ; this.bounds = [x, y, x, y]; } this._start = undefined; }; _p._lineTo = function (pt){ this._addMoveTo(); this.bounds = updateBounds(this.bounds, pt); }; _p._curveToOne = function (bcp1, bcp2, pt){ this._addMoveTo(); this.bounds = updateBounds(this.bounds, bcp1); this.bounds = updateBounds(this.bounds, bcp2); this.bounds = updateBounds(this.bounds, pt); }; _p._qCurveToOne = function (bcp, pt){ this._addMoveTo(); this.bounds = updateBounds(this.bounds, bcp); this.bounds = updateBounds(this.bounds, pt); }; return ControlBoundsPen; });
import Head from 'next/head' import clientPromise from '../lib/mongodb' export default function Home({ isConnected }) { return ( <div className="container"> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> <main> <h1 className="title"> Welcome to <a href="https://nextjs.org">Next.js with MongoDB!</a> </h1> {isConnected ? ( <h2 className="subtitle">You are connected to MongoDB</h2> ) : ( <h2 className="subtitle"> You are NOT connected to MongoDB. Check the <code>README.md</code>{' '} for instructions. </h2> )} <p className="description"> Get started by editing <code>pages/index.js</code> </p> <div className="grid"> <a href="https://nextjs.org/docs" className="card"> <h3>Documentation &rarr;</h3> <p>Find in-depth information about Next.js features and API.</p> </a> <a href="https://nextjs.org/learn" className="card"> <h3>Learn &rarr;</h3> <p>Learn about Next.js in an interactive course with quizzes!</p> </a> <a href="https://github.com/vercel/next.js/tree/canary/examples" className="card" > <h3>Examples &rarr;</h3> <p>Discover and deploy boilerplate example Next.js projects.</p> </a> <a href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" className="card" > <h3>Deploy &rarr;</h3> <p> Instantly deploy your Next.js site to a public URL with Vercel. </p> </a> </div> </main> <footer> <a href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > Powered by{' '} <img src="/vercel.svg" alt="Vercel Logo" className="logo" /> </a> </footer> <style jsx>{` .container { min-height: 100vh; padding: 0 0.5rem; display: flex; flex-direction: column; justify-content: center; align-items: center; } main { padding: 5rem 0; flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; } footer { width: 100%; height: 100px; border-top: 1px solid #eaeaea; display: flex; justify-content: center; align-items: center; } footer img { margin-left: 0.5rem; } footer a { display: flex; justify-content: center; align-items: center; } a { color: inherit; text-decoration: none; } .title a { color: #0070f3; text-decoration: none; } .title a:hover, .title a:focus, .title a:active { text-decoration: underline; } .title { margin: 0; line-height: 1.15; font-size: 4rem; } .title, .description { text-align: center; } .subtitle { font-size: 2rem; } .description { line-height: 1.5; font-size: 1.5rem; } code { background: #fafafa; border-radius: 5px; padding: 0.75rem; font-size: 1.1rem; font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace; } .grid { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; max-width: 800px; margin-top: 3rem; } .card { margin: 1rem; flex-basis: 45%; padding: 1.5rem; text-align: left; color: inherit; text-decoration: none; border: 1px solid #eaeaea; border-radius: 10px; transition: color 0.15s ease, border-color 0.15s ease; } .card:hover, .card:focus, .card:active { color: #0070f3; border-color: #0070f3; } .card h3 { margin: 0 0 1rem 0; font-size: 1.5rem; } .card p { margin: 0; font-size: 1.25rem; line-height: 1.5; } .logo { height: 1em; } @media (max-width: 600px) { .grid { width: 100%; flex-direction: column; } } `}</style> <style jsx global>{` html, body { padding: 0; margin: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; } * { box-sizing: border-box; } `}</style> </div> ) } export async function getServerSideProps(context) { try { // client.db() will be the default database passed in the MONGODB_URI // You can change the database by calling the client.db() function and specifying a database like: // const db = client.db("myDatabase"); // Then you can execute queries against your database like so: // db.find({}) or any of the MongoDB Node Driver commands await clientPromise return { props: { isConnected: true }, } } catch (e) { console.error(e) return { props: { isConnected: false }, } } }
module.exports = { entry: './index.jsx', output: { publicPath: '/assets' }, module: { loaders: require('./loaders.config') }, externals: { 'react': 'React' }, resolve: { extensions: ['', '.js', '.jsx'] } }
import {Decorators} from './decorators'; /** * Chain mutator * Makes a class method chainable by always returning `this` automatically. */ export function _chain(fn){ return function(){ fn.apply(this, arguments); return this; } } //create a decorator from the mutator export var chain = Decorators.mutator(_chain);
/* Copyright (C) 2012-2014 Kurt Milam - http://xioup.com | Source: https://gist.github.com/1868955 * * 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. **/ // Based conceptually on the _.extend() function in underscore.js ( see http://documentcloud.github.com/underscore/#extend for more details ) var _ = require('../common')._; module.exports = function deepExtend(obj) { var parentRE = /#{\s*?_\s*?}/, slice = Array.prototype.slice; _.each(slice.call(arguments, 1), function (source) { for (var prop in source) { if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop]) || _.isDate(source[prop])) { obj[prop] = source[prop]; } else if (_.isString(source[prop]) && parentRE.test(source[prop])) { if (_.isString(obj[prop])) { obj[prop] = source[prop].replace(parentRE, obj[prop]); } } else if (_.isArray(obj[prop]) || _.isArray(source[prop])) { if (!_.isArray(obj[prop]) || !_.isArray(source[prop])) { throw new Error('Trying to combine an array with a non-array (' + prop + ')'); } else { obj[prop] = _.reject(_.deepExtend(_.clone(obj[prop]), source[prop]), function (item) { return _.isNull(item); }); } } else if (_.isObject(obj[prop]) || _.isObject(source[prop])) { if (!_.isObject(obj[prop]) || !_.isObject(source[prop])) { throw new Error('Trying to combine an object with a non-object (' + prop + ')'); } else { obj[prop] = _.deepExtend(_.clone(obj[prop]), source[prop]); } } else { obj[prop] = source[prop]; } } }); return obj; }; /** * Dependency: underscore.js ( http://documentcloud.github.com/underscore/ ) * * Mix it in with underscore.js: * _.mixin({deepExtend: deepExtend}); * * Call it like this: * var myObj = _.deepExtend(grandparent, child, grandchild, greatgrandchild) * * Notes: * Keep it DRY. * This function is especially useful if you're working with JSON config documents. It allows you to create a default * config document with the most common settings, then override those settings for specific cases. It accepts any * number of objects as arguments, giving you fine-grained control over your config document hierarchy. * * Special Features and Considerations: * - parentRE allows you to concatenate strings. example: * var obj = _.deepExtend({url: "www.example.com"}, {url: "http://#{_}/path/to/file.html"}); * console.log(obj.url); * output: "http://www.example.com/path/to/file.html" * * - parentRE also acts as a placeholder, which can be useful when you need to change one value in an array, while * leaving the others untouched. example: * var arr = _.deepExtend([100, {id: 1234}, true, "foo", [250, 500]], * ["#{_}", "#{_}", false, "#{_}", "#{_}"]); * console.log(arr); * output: [100, {id: 1234}, false, "foo", [250, 500]] * * - The previous example can also be written like this: * var arr = _.deepExtend([100, {id:1234}, true, "foo", [250, 500]], * ["#{_}", {}, false, "#{_}", []]); * console.log(arr); * output: [100, {id: 1234}, false, "foo", [250, 500]] * * - And also like this: * var arr = _.deepExtend([100, {id:1234}, true, "foo", [250, 500]], * ["#{_}", {}, false]); * console.log(arr); * output: [100, {id: 1234}, false, "foo", [250, 500]] * * - Array order is important. example: * var arr = _.deepExtend([1, 2, 3, 4], [1, 4, 3, 2]); * console.log(arr); * output: [1, 4, 3, 2] * * - You can remove an array element set in a parent object by setting the same index value to null in a child object. * example: * var obj = _.deepExtend({arr: [1, 2, 3, 4]}, {arr: ["#{_}", null]}); * console.log(obj.arr); * output: [1, 3, 4] * **/
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- module.exports = function (req, res, next) { var format = req.query.format || 'json'; var status = req.query.status || 200; var output = { method: req.method }; for (var q in req.query) { if (q !== 'format' && q !== 'status' && req.query.hasOwnProperty(q)) { var val = req.query[q]; if (typeof val === 'string') { if (!output.query) output.query = {}; output.query[q] = req.query[q]; } } } var reqHeaders = req.headers; for (var reqHeader in reqHeaders) { if (reqHeaders.hasOwnProperty(reqHeader) && reqHeader.indexOf('x-test-zumo-') === 0) { res.set(reqHeader, reqHeaders[reqHeader]); } } if (req.body && Object.keys(req.body).length) { output.body = req.body; } //output.user = JSON.parse(JSON.stringify(req.user)); // remove functions output.user = { level: 'anonymous' }; switch (format) { case 'json': break; // nothing to do case 'xml': res.set('Content-Type', 'text/xml'); output = objToXml(output); break; default: res.set('Content-Type', 'text/plain'); output = JSON.stringify(output) .replace(/{/g, '__{__') .replace(/}/g, '__}__') .replace(/\[/g, '__[__') .replace(/\]/g, '__]__'); break; } res.status(status).send(output); res.end(); } function objToXml(obj) { return '<root>' + jsToXml(obj) + '</root>'; } function jsToXml(value) { if (value === null) return 'null'; var type = typeof value; var result = ''; var i = 0; switch (type.toLowerCase()) { case 'string': case 'boolean': case 'number': return value.toString(); case 'function': case 'object': if (Object.prototype.toString.call( value ) === '[object Array]') { result = result + '<array>'; for (i = 0; i < value.length; i++) { result = result + '<item>' + jsToXml(value[i]) + '</item>'; } result = result + '</array>'; } else { var k; var keys = []; for (k in value) { if (value.hasOwnProperty(k)) { if (typeof value[k] !== 'function') { keys.push(k); } } } keys.sort(); for (i = 0; i < keys.length; i++) { k = keys[i]; result = result + '<' + k + '>' + jsToXml(value[k]) + '</' + k + '>'; } } } return result; }
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class example extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('example', () => example);
define(['marionette'], function(marionette) { return marionette.Behavior.extend({ defaults: { width: '1px', color: 'red', style: 'solid' }, events: { 'mouseenter': 'onMouseEnter', 'mouseleave': 'onMouseLeave' }, onMouseEnter: function() { this.previousWidth = this.$el.css('border-width'); this.previousColor = this.$el.css('border-color'); this.previousStyle = this.$el.css('border-style'); this.$el.css('border-width', this.options.width); this.$el.css('border-color', this.options.color); this.$el.css('border-style', this.options.style); }, onMouseLeave: function() { this.$el.css('border-width', this.previousWidth); this.$el.css('border-color', this.previousColor); this.$el.css('border-style', this.previousStyle); } }); });
;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Packages initialization: sigma.utils.pkg('sigma.settings'); var settings = { /** * GRAPH SETTINGS: * *************** */ // {boolean} Indicates if the data have to be cloned in methods to add // nodes or edges. clone: true, // {boolean} Indicates if nodes "id" values and edges "id", "source" and // "target" values must be set as immutable. immutable: true, // {boolean} Indicates if sigma can log its errors and warnings. verbose: false, /** * RENDERERS SETTINGS: * ******************* */ // {string} defaultLabelColor: '#000', // {string} defaultEdgeColor: '#000', // {string} defaultNodeColor: '#000', // {string} defaultLabelSize: 14, // {string} Indicates how to choose the edges color. Available values: // "source", "target", "default" edgeColor: 'source', // {string} font: 'arial', // {string} Example: 'bold' fontStyle: '', // {string} Indicates how to choose the labels color. Available values: // "node", "default" labelColor: 'default', // {string} Indicates how to choose the labels size. Available values: // "fixed", "proportional" labelSize: 'fixed', // {string} The ratio between the font size of the label and the node size. labelSizeRatio: 1, // {number} The minimum size a node must have to see its label displayed. labelThreshold: 8, // {number} The oversampling factor used in WebGL renderer. webglOversamplingRatio: 2, // {number} The size of the border of hovered nodes. borderSize: 0, // {number} The default hovered node border's color. defaultNodeBorderColor: '#000', // {number} The hovered node's label font. If not specified, will heritate // the "font" value. hoverFont: '', // {boolean} If true, then only one node can be hovered at a time. singleHover: false, // {string} Example: 'bold' hoverFontStyle: '', // {string} Indicates how to choose the hovered nodes shadow color. // Available values: "node", "default" labelHoverShadow: 'default', // {string} labelHoverShadowColor: '#000', // {string} Indicates how to choose the hovered nodes color. // Available values: "node", "default" nodeHoverColor: 'node', // {string} defaultNodeHoverColor: '#000', // {string} Indicates how to choose the hovered nodes background color. // Available values: "node", "default" labelHoverBGColor: 'default', // {string} defaultHoverLabelBGColor: '#fff', // {string} Indicates how to choose the hovered labels color. // Available values: "node", "default" labelHoverColor: 'default', // {string} defaultLabelHoverColor: '#000', // {booleans} The different drawing modes: // false: Layered not displayed. // true: Layered displayed. drawLabels: true, drawEdges: true, drawNodes: true, // {boolean} Indicates if the edges must be drawn in several frames or in // one frame, as the nodes and labels are drawn. batchEdgesDrawing: false, // {boolean} Indicates if the edges must be hidden during dragging and // animations. hideEdgesOnMove: false, // {numbers} The different batch sizes, when elements are displayed in // several frames. canvasEdgesBatchSize: 500, webglEdgesBatchSize: 1000, /** * RESCALE SETTINGS: * ***************** */ // {string} Indicates of to scale the graph relatively to its container. // Available values: "inside", "outside" scalingMode: 'inside', // {number} The margin to keep around the graph. sideMargin: 0, // {number} Determine the size of the smallest and the biggest node / edges // on the screen. This mapping makes easier to display the graph, // avoiding too big nodes that take half of the screen, or too // small ones that are not readable. If the two parameters are // equals, then the minimal display size will be 0. And if they // are both equal to 0, then there is no mapping, and the radius // of the nodes will be their size. minEdgeSize: 0.5, maxEdgeSize: 1, minNodeSize: 1, maxNodeSize: 8, /** * CAPTORS SETTINGS: * ***************** */ // {boolean} touchEnabled: true, // {boolean} mouseEnabled: true, // {boolean} doubleClickEnabled: true, // {boolean} Defines whether the custom events such as "clickNode" can be // used. eventsEnabled: true, // {number} Defines by how much multiplicating the zooming level when the // user zooms with the mouse-wheel. zoomingRatio: 1.7, // {number} Defines by how much multiplicating the zooming level when the // user zooms by double clicking. doubleClickZoomingRatio: 2.2, // {number} The minimum zooming level. zoomMin: 0.0625, // {number} The maximum zooming level. zoomMax: 2, // {number} The duration of animations following a mouse scrolling. mouseZoomDuration: 200, // {number} The duration of animations following a mouse double click. doubleClickZoomDuration: 200, // {number} The duration of animations following a mouse dropping. mouseInertiaDuration: 200, // {number} The inertia power (mouse captor). mouseInertiaRatio: 3, // {number} The duration of animations following a touch dropping. touchInertiaDuration: 200, // {number} The inertia power (touch captor). touchInertiaRatio: 3, // {number} The maximum time between two clicks to make it a double click. doubleClickTimeout: 300, // {number} The maximum time between two taps to make it a double tap. doubleTapTimeout: 300, // {number} The maximum time of dragging to trigger intertia. dragTimeout: 200, /** * GLOBAL SETTINGS: * **************** */ // {boolean} Determines whether the instance has to refresh itself // automatically when a "resize" event is dispatched from the // window object. autoResize: true, // {boolean} Determines whether the "rescale" middleware has to be called // automatically for each camera on refresh. autoRescale: true, // {boolean} If set to false, the camera method "goTo" will basically do // nothing. enableCamera: true, // {boolean} If set to false, the nodes cannot be hovered. enableHovering: true, // {boolean} If set to true, the rescale middleware will ignore node sizes // to determine the graphs boundings. rescaleIgnoreSize: false, // {boolean} Determines if the core has to try to catch errors on // rendering. skipErrors: false, /** * CAMERA SETTINGS: * **************** */ // {number} The power degrees applied to the nodes/edges size relatively to // the zooming level. Basically: // > onScreenR = Math.pow(zoom, nodesPowRatio) * R // > onScreenT = Math.pow(zoom, edgesPowRatio) * T nodesPowRatio: 0.5, edgesPowRatio: 0.5, /** * ANIMATIONS SETTINGS: * ******************** */ // {number} The default animation time. animationsTime: 200 }; // Export the previously designed settings: sigma.settings = sigma.utils.extend(sigma.settings || {}, settings); }).call(this);
import {base64} from '@ciscospark/common'; export const eventNames = { SPACES_READ: `rooms:read`, SPACES_UNREAD: `rooms:unread`, MESSAGES_CREATED: `messages:created` }; /** * Constructs an event detail object for messages:created * @export * @param {Object} activity from mercury * @param {Object} toUser * @returns {Object} constructed event */ export function constructMessagesEventData(activity, toUser) { const roomType = activity.target.tags.includes(`ONE_ON_ONE`) ? `direct` : `group`; let files, toPersonEmail, toPersonId; if (roomType === `direct` && toUser) { toPersonEmail = toUser.emailAddress; toPersonId = constructHydraId(`PEOPLE`, toUser.id); } let mentionedPeople = activity.object.mentions; if (mentionedPeople && mentionedPeople.items.length) { mentionedPeople = mentionedPeople.items.map((people) => ({ id: constructHydraId(`PEOPLE`, people.id) })); } // Files need to be decrypted and converted into a usable URL if (activity.object.files && activity.object.files.items.length) { files = activity.object.files.items; } const personId = constructHydraId(`PEOPLE`, activity.actor.id); return { actorId: personId, actorName: activity.actor.displayName, id: constructHydraId(`MESSAGE`, activity.id), roomId: constructHydraId(`ROOM`, activity.target.id), roomType: activity.target.tags.includes(`ONE_ON_ONE`) ? `direct` : `group`, text: activity.object.displayName, html: activity.object.content, files, personId, personEmail: activity.actor.emailAddress, created: activity.published, mentionedPeople, toPersonId, toPersonEmail }; } /** * Creates an room data object for DOM and event hooks * * @export * @param {Object} space * @param {Object} activity * @returns {Object} */ export function constructRoomsEventData(space, activity) { return { id: constructHydraId(`ROOM`, space.id), actorId: constructHydraId(`PEOPLE`, activity.actor.id), actorName: activity.actor.displayName, title: space.name, type: space.type, isLocked: space.isLocked, teamId: constructHydraId(`TEAM`, space.teamId), lastActivity: activity && activity.published || space.lastActivityTimestamp, created: space.published }; } function constructHydraId(type, id) { return base64.encode(`ciscospark://us/${type.toUpperCase()}/${id}`); }
/** * Copyright <%= year %> Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([ "./kendo.mobile.pane" ], f); })(function(){ (function($, undefined) { var kendo = window.kendo, ui = kendo.mobile.ui, Widget = ui.Widget, EXPANED_PANE_SHIM = "<div class='km-expanded-pane-shim' />", View = ui.View; var SplitView = View.extend({ init: function(element, options) { var that = this, pane; Widget.fn.init.call(that, element, options); element = that.element; $.extend(that, options); that._id(); that._layout(); that._overlay(); that._style(); kendo.mobile.init(element.children(kendo.roleSelector("modalview"))); that.panes = []; that._paramsHistory = []; that.element.children(kendo.roleSelector("pane")).each(function() { pane = kendo.initWidget(this, {}, ui.roles); that.panes.push(pane); }); that.expandedPaneShim = $(EXPANED_PANE_SHIM).appendTo(that.element); that._shimUserEvents = new kendo.UserEvents(that.expandedPaneShim, { tap: function() { that.collapsePanes(); } }); }, options: { name: "SplitView", style: "horizontal" }, expandPanes: function() { this.element.addClass("km-expanded-splitview"); }, collapsePanes: function() { this.element.removeClass("km-expanded-splitview"); }, // Implement view interface _layout: function() { var that = this, element = that.element; element.data("kendoView", that).addClass("km-view km-splitview"); that.transition = kendo.attrValue(element, "transition"); $.extend(that, { header: [], footer: [], content: element }); }, _style: function () { var style = this.options.style, element = this.element, styles; if (style) { styles = style.split(" "); $.each(styles, function () { element.addClass("km-split-" + this); }); } }, showStart: function() { var that = this; that.element.css("display", ""); if (!that.inited) { that.inited = true; $.each(that.panes, function() { if (this.options.initial) { this.navigateToInitial(); } else { this.navigate(""); } }); that.trigger("init", {view: that}); } that.trigger("show", {view: that}); } }); ui.plugin(SplitView); })(window.kendo.jQuery); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
import React from 'react' import Icon from 'react-icon-base' const FaAngleDoubleLeft = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m22 30.7q0 0.3-0.2 0.5l-1.1 1.1q-0.3 0.3-0.6 0.3t-0.5-0.3l-10.4-10.4q-0.2-0.2-0.2-0.5t0.2-0.5l10.4-10.4q0.3-0.2 0.5-0.2t0.6 0.2l1.1 1.1q0.2 0.3 0.2 0.5t-0.2 0.6l-8.8 8.7 8.8 8.8q0.2 0.2 0.2 0.5z m8.6 0q0 0.3-0.3 0.5l-1.1 1.1q-0.2 0.3-0.5 0.3t-0.5-0.3l-10.4-10.4q-0.2-0.2-0.2-0.5t0.2-0.5l10.4-10.4q0.2-0.2 0.5-0.2t0.5 0.2l1.1 1.1q0.3 0.3 0.3 0.5t-0.3 0.6l-8.7 8.7 8.7 8.8q0.3 0.2 0.3 0.5z"/></g> </Icon> ) export default FaAngleDoubleLeft
/*! * remark v1.0.6 (http://getbootstrapadmin.com/remark) * Copyright 2015 amazingsurge * Licensed under the Themeforest Standard Licenses */ $.components.register("selectpicker", { mode: "default", defaults: { style: "btn-select", iconBase: "icon", tickIcon: "wb-check" } });
var express = require('express'); var client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN); var app = express(); var port = process.env.PORT || 4000; app.listen(port); app.use(express.static('public')); app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Authorization'); next(); }); var sendMessage = function(text) { //Send an SMS text message client.sendMessage({ to:'+15108472341', // Any number Twilio can deliver to from: '+14157924052', // A number you bought from Twilio and can use for outbound communication body: text // body of the SMS message }, function(err, responseData) { //this function is executed when a response is received from Twilio if (!err) { // "err" is an error received during the request, if any // "responseData" is a JavaScript object containing data received from Twilio. // A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript): // http://www.twilio.com/docs/api/rest/sending-sms#example-1 console.log(responseData.from); // outputs "+14506667788" console.log(responseData.body); // outputs "word to your mother." } else { console.log(err); } }); }; app.all('/', function(req, res) { res.send('Hey there'); }); app.get('/message/:text', function(req, res){ var message = req.params.text; sendMessage(message); res.send('Sending the following message:' + message); });
define([ "backbonejs/views/sites/item", "backbonejs/Collections/sites", "backbonejs/mediator", "hbs!Tmpl/Sites/List", "jquery", "backbone" ],function( ViewSiteItem, CollectionSites, Mediator, TmplSiteList ){ return Backbone.View.extend({ // el:".sites-list", tmpl: TmplSiteList, events: { }, initialize: function () { _.bindAll(this,'create'); this.$el.html(this.tmpl()); this.table = this.$('tbody'); this.siteList = new CollectionSites(); this.siteList.fetch({ success:function(){ console.log('success'); }, error:function(){ console.log('error'); }, }); this.listenTo(this.siteList, 'add', this.addOne); this.listenTo(this.siteList, 'reset', this.addAll); this.listenTo(this.siteList, 'sort', this.reOrder); Mediator.on('site:create',this.create); }, addAll:function(){ this.siteList.each(this.addOne, this); }, addOne: function(site){ var view = new ViewSiteItem({model:site}); this.table.append(view.render().el); }, create:function(data){ this.siteList.create(data,{ success: function(model, response, options){ console.log(model); Mediator.trigger('site:editCancel'); // model.sync_id(response.id); }, error: function(){ }, }); }, }); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.1.4_A1.4; * @section: 11.1.4; * @assertion: Evaluate the production ArrayLiteral: [ Elision, AssignmentExpression ]; * @description: Checking various properteis and content of the array defined with "var array = [,,,1,2]"; */ var array = [,,,1,2]; //CHECK#1 if (typeof array !== "object") { $ERROR('#1: var array = [,,,1,2]; typeof array === "object". Actual: ' + (typeof array)); } //CHECK#2 if (array instanceof Array !== true) { $ERROR('#2: var array = [,,,1,2]; array instanceof Array === true'); } //CHECK#3 if (array.toString !== Array.prototype.toString) { $ERROR('#3: var array = [,,,1,2]; array.toString === Array.prototype.toString. Actual: ' + (array.toString)); } //CHECK#4 if (array.length !== 5) { $ERROR('#4: var array = [,,,1,2]; array.length === 5. Actual: ' + (array.length)); } //CHECK#5 if (array[0] !== undefined) { $ERROR('#5: var array = [,,,1,2]; array[0] === undefined. Actual: ' + (array[0])); } //CHECK#6 if (array[1] !== undefined) { $ERROR('#6: var array = [,,,1,2]; array[1] === undefined. Actual: ' + (array[1])); } //CHECK#7 if (array[2] !== undefined) { $ERROR('#7: var array = [,,,1,2]; array[2] === undefined. Actual: ' + (array[2])); } //CHECK#8 if (array[3] !== 1) { $ERROR('#8: var array = [,,,1,2]; array[3] === 1. Actual: ' + (array[3])); } //CHECK#9 if (array[4] !== 2) { $ERROR('#9: var array = [,,,1,2]; array[4] === 2. Actual: ' + (array[4])); }
import Route from "../../../lib/http/routing/route" import Bag from "../../../lib/bag" import Request from "../../../lib/http/request" var expect = require("chai").expect describe("http/routing/route.js", () => { let route beforeEach(() => { route = new Route() }) it("[getter::options] should return an instance of Bag", () => { expect(route.options instanceof Bag).to.be.true }) it("[setter::options] should allow to set options", () => { let options = {hello: "World"} route.options = options expect(route.options.get("hello")).to.equal("World") options = new Bag(options) route.options = options expect(route.options.get("hello")).to.equal("World") }) it("[preMatch] should perform pre-scanning for demands", () => { route.host = "{country}.domain.com" route.path = "/accounts/{id}-{name}" route.demands = { id: /\d+/, name: "[a-zA-Z]+", country: /^[a-z]{2}/ } route.preMatch() expect(route.matches).to.deep.equal({country: null, id: null, name: null}) }) it("[postMatch] should reset host, path", () => { route.reservedHost = "sample" route.reservedPath = "sample" route.postMatch() expect(route.host).to.equal("sample") expect(route.path).to.equal("sample") expect(route.reservedHost).to.be.null expect(route.reservedPath).to.be.null }) it("[match] should return false at the first, and true in the latter", () => { route.host = "{country}.domain.com" route.path = "/accounts/{id}-{name}" route.demands = { id: /\d+/, name: "[a-zA-Z]+", country: /[a-z]{2}/ } let request = new Request() request.path = "/accounts/1988-longdo" request.method = "GET" request.host = "vn1.domain.com" expect(route.match(request)).to.be.false request.host = "vn.domain.com" expect(route.match(request)).to.be.true expect(route.matches).to.deep.equal({id: "1988", name: "longdo", country: "vn"}) }) it("[match] should allow to match even if host or port is null", () => { route.name = "route_without_host_and_port" route.host = null route.port = null route.path = "/accounts/{gender}/{id}-{name}" let request = new Request() request.host = "localhost" request.path = "/accounts/male/1988-longdo" request.method = "GET" expect(route.match(request)).to.be.true expect(route.matches).to.deep.equal({id: "1988", name: "longdo", "gender": "male"}) route.name = "route_without_port" route.host = "localhost" expect(route.match(request)).to.be.true }) })
"use strict";var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var $=_interopRequire(require("jquery"));var React=require("react");var marked=require("marked");var _=require("lodash");module.exports=React.createClass({displayName:"Markdown2HTML",propTypes:{src:React.PropTypes.string.isRequired},getInitialState:function getInitialState(){return{md:""}},componentWillMount:function componentWillMount(){$.get(this.props.src,_.bind(function(data){this.setState({md:marked(data)})},this))},render:function render(){return React.createElement("div",{ref:"md",dangerouslySetInnerHTML:{__html:this.state.md}})}});
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createMount; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var React = _interopRequireWildcard(require("react")); var ReactDOM = _interopRequireWildcard(require("react-dom")); var PropTypes = _interopRequireWildcard(require("prop-types")); var _enzyme = require("enzyme"); /** * Can't just mount <React.Fragment>{node}</React.Fragment> * because that swallows wrapper.setProps * * why class component: * https://github.com/airbnb/enzyme/issues/2043 */ // eslint-disable-next-line react/prefer-stateless-function var Mode = /*#__PURE__*/function (_React$Component) { (0, _inherits2.default)(Mode, _React$Component); function Mode() { (0, _classCallCheck2.default)(this, Mode); return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Mode).apply(this, arguments)); } (0, _createClass2.default)(Mode, [{ key: "render", value: function render() { // Excess props will come from e.g. enzyme setProps var _this$props = this.props, __element = _this$props.__element, __strict = _this$props.__strict, other = (0, _objectWithoutProperties2.default)(_this$props, ["__element", "__strict"]); var Component = __strict ? React.StrictMode : React.Fragment; return React.createElement(Component, null, React.cloneElement(__element, other)); } }]); return Mode; }(React.Component); // Generate an enhanced mount function. process.env.NODE_ENV !== "production" ? Mode.propTypes = { /** * this is essentially children. However we can't use children because then * using `wrapper.setProps({ children })` would work differently if this component * would be the root. */ __element: PropTypes.element.isRequired, __strict: PropTypes.bool.isRequired } : void 0; function createMount() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$mount = options.mount, mount = _options$mount === void 0 ? _enzyme.mount : _options$mount, globalStrict = options.strict, globalEnzymeOptions = (0, _objectWithoutProperties2.default)(options, ["mount", "strict"]); var attachTo = document.createElement('div'); attachTo.className = 'app'; attachTo.setAttribute('id', 'app'); document.body.insertBefore(attachTo, document.body.firstChild); var mountWithContext = function mountWithContext(node) { var localOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _localOptions$disable = localOptions.disableUnnmount, disableUnnmount = _localOptions$disable === void 0 ? false : _localOptions$disable, _localOptions$strict = localOptions.strict, strict = _localOptions$strict === void 0 ? globalStrict : _localOptions$strict, localEnzymeOptions = (0, _objectWithoutProperties2.default)(localOptions, ["disableUnnmount", "strict"]); if (!disableUnnmount) { ReactDOM.unmountComponentAtNode(attachTo); } // some tests require that no other components are in the tree // e.g. when doing .instance(), .state() etc. return mount(strict == null ? node : React.createElement(Mode, { __element: node, __strict: Boolean(strict) }), (0, _extends2.default)({ attachTo: attachTo }, globalEnzymeOptions, {}, localEnzymeOptions)); }; mountWithContext.attachTo = attachTo; mountWithContext.cleanUp = function () { ReactDOM.unmountComponentAtNode(attachTo); attachTo.parentElement.removeChild(attachTo); }; return mountWithContext; }
/** * Returns a new Int32Array based upon *this* */ sc.define("asInt32Array", { Array: function() { return new Int32Array(this); } });
jQuery(document).ready(function($){ $('.dropcapText').each(function(index,element) { var dropcapped_letter = $(element).text().charAt(0).slice(0); var custom_css = $(element).attr('style'); $(element).text($(element).text().substring(1)); $(element).prepend('<span class="dropcap" style="'+custom_css+'">'+dropcapped_letter+'</span>'); }); $('.dropcapLight').each(function(index,element) { var dropcapped_letter = $(element).text().charAt(0).slice(0); $(element).text($(element).text().substring(1)); $(element).prepend('<span class="colored left drop">'+dropcapped_letter+'</span>'); }); });
// Generated by CoffeeScript 1.9.0 (function() { angular.module("ocNgRepeat", []).directive('ngRepeatOwlCarousel', function() { return { restrict: 'A', scope: { carouselInit: '&' }, link: function(scope, element, attrs) { if ((scope.$parent != null) && scope.$parent.$last) { return scope.carouselInit()(); } } }; }); }).call(this); //# sourceMappingURL=ngRepeatOwlCarousel.js.map
// http://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, extends: 'qlfe', // required to lint *.vue files plugins: [ 'html' ], // check if imports actually resolve 'settings': { 'import/resolver': { 'webpack': { 'config': 'build/webpack.base.conf.js' } } }, // add your custom rules here 'rules': { // allow optionalDependencies 'import/no-extraneous-dependencies': ['error', { 'optionalDependencies': ['test/unit/index.js'] }], // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 } }
var https = require('https'); var http = require('http'); var Watchdog = require('./watchdog'); var HttpAgent = require('agentkeepalive'); var HttpsAgent = HttpAgent.HttpsAgent; HttpsAgent.prototype.getName = HttpAgent.prototype.getName; function Upstream(upstreamURL, statsdClient, agentOpts) { if (typeof upstreamURL === 'string') { upstreamURL = require('url').parse(upstreamURL); } this.host = upstreamURL.hostname; this.protocol = upstreamURL.protocol; this.port = parseInt(upstreamURL.port, 10) || (this.protocol == 'https:' ? 443 : 80); this.httpModule = this.protocol == 'http:' ? http : https; this.agent = agentOpts ? createAgent(this.protocol, agentOpts) : false; this.forwardAgent = agentOpts ? agentOpts.forwardAgent : false; this.dog = new Watchdog(this.port, this.host); this.statsdClient = statsdClient; if (!this.statsdClient.fake) { this.statsdTimer = setInterval(this.recordPoolStats.bind(this), 1000); } // Fully close the socket straightaway and remove it from the pool. // (Perhaps we should consider submitting a patch to agentkeepalive) this.agent && this.agent.on('free', function (socket, options) { if (!socket._closeWatch) { socket.on('close', function () { var freeSock = this.agent.freeSockets[this._agentName]; if (freeSock) { var index = freeSock.indexOf(socket); if (index > -1) { freeSock.splice(index, 1); } } socket.destroy(); }.bind(this)); socket._closeWatch = true; } }.bind(this)); this._agentName = this.agent ? this.agent.getName({ host: this.host, port: this.port, rejectUnauthorized: agentOpts.rejectUnauthorized }) : ''; }; Upstream.prototype.setTimeout = function(msecs) { this.timeout = msecs; }; Upstream.prototype.allowPerRequestTimeout = function () { this._allowPerRequestTimeout = true; }; Upstream.prototype.request = function(options, cb) { var request = new UpstreamRequest(options, this); request.send(cb); }; Upstream.prototype.isHealthy = function() { return this.dog.isHealthy(); }; Upstream.prototype.stop = function () { clearInterval(this.statsdTimer); }; Upstream.prototype.getConnectionPoolStats = function () { var freeSockets = (this.agent.freeSockets[this._agentName] || []).length; return { socketPoolSize: (this.agent.sockets[this._agentName] || []).length + freeSockets, freeSockets: freeSockets, queuedRequests: (this.agent.requests[this._agentName] || []).length, keepAliveLimit: this.agent.maxFreeSockets, socketLimit: this.agent.maxSockets }; }; Upstream.prototype.recordPoolStats = function () { this.statsdClient.gauge('sockets.free', (this.agent.freeSockets[this._agentName] || []).length); this.statsdClient.gauge('sockets.used', (this.agent.sockets[this._agentName] || []).length); this.statsdClient.gauge('queueLength', (this.agent.request[this._agentName] || []).length); }; Upstream.prototype.setPoolSizes = function (sizes) { sizes = sizes || {}; if (sizes.keepalive) { this.agent.maxFreeSockets = parseInt(sizes.keepalive, 10); } if (sizes.max) { this.agent.maxSockets = parseInt(sizes.max, 10); } }; Upstream.prototype._purge = function () { this.agent.destroy(); if (this.agent.freeSockets[this._agentName]) { delete this.agent.freeSockets[this._agentName]; } }; Upstream.prototype._buildRequestOptions = function(opts) { return { method: opts.method, hostname: this.host, port: this.port, path: opts.uri, agent: this.agent, headers: this._buildHeaders(opts.headers) }; }; Upstream.prototype._buildHeaders = function(downstreamHeaders) { downstreamHeaders = downstreamHeaders ? downstreamHeaders : {}; var headers = {}; for (var key in downstreamHeaders) { headers[key] = downstreamHeaders[key]; } if (!this.forwardAgent) { headers['user-agent'] = 'Mallorca'; } headers.host = this.host; return headers; }; function measureElapsedTime(startTime) { var elapsed = process.hrtime(startTime); var elapsedS = elapsed[0]; var elapsedNS = elapsed[1]; return (elapsedS * 1e9 + elapsedNS) / 1e6; }; function createAgent(protocol, agentOpts) { if (protocol === 'http:') { return new HttpAgent(agentOpts); } else { return new HttpsAgent(agentOpts); } } function UpstreamRequest(options, parent) { this.parent = parent; this.startTime = process.hrtime(); this.timedOut = false; this.attempts = 0; this.attemptLimit = options.attemptLimit || 5; this.options = this.parent._buildRequestOptions(options); this.body = options.body; this.headers = options.headers; }; UpstreamRequest.prototype.recordTimingStats = function (response) { this.parent.statsdClient.timing('waitTime', response.waitTime); this.parent.statsdClient.timing('responseTime', response.responseTime); }; UpstreamRequest.prototype.send = function(cb) { if (++this.attempts > this.attemptLimit) { return cb(new Error("Too many retries"), { attempts: this.attempts }, null); } var req = this.parent.httpModule.request(this.options, function (response) { var upstreamBodyChunkBuffers = []; response.setEncoding('binary'); response .on('data', function (data) { if (!(data instanceof Buffer)) { data = new Buffer(data, "binary"); } upstreamBodyChunkBuffers.push(data); }) .on('end', function () { response.responseTime = measureElapsedTime(this.startTime); response.waitTime = this.socketWait; response.attempts = this.attempts; this.recordTimingStats(response); if (!this.timedOut) { cb(null, response, Buffer.concat(upstreamBodyChunkBuffers)); } }.bind(this)); }.bind(this)); if (this.getTimeout() > 0) { req.setTimeout(this.getTimeout(), function () { this.timedOut = true; cb(new Error('Request Timeout')); }.bind(this)); } req.on('socket', this.parent.dog.watch.bind(this.parent.dog)) .on('socket', function () { this.socketWait = measureElapsedTime(this.startTime); }.bind(this)) .on('error', this.handleError(cb)); if (this.body) { req.write(this.body, 'utf8'); } req.end(); }; UpstreamRequest.prototype.requestTimeoutHeader = function () { var value = 0; if (typeof this.headers === 'object') { Object.keys(this.headers).forEach(function (key) { if (key.toLowerCase() == 'x-mallorca-timeout') { value = parseInt(this.headers[key], 10) || 0; } }.bind(this)); } return value; }; UpstreamRequest.prototype.getTimeout = function () { var timeout = 0; if (this.parent._allowPerRequestTimeout) { timeout = this.requestTimeoutHeader(); } if (timeout == 0 && this.parent.timeout > 0) { timeout = this.parent.timeout; } return timeout; }; UpstreamRequest.prototype.handleError = function(cb) { return function (err) { if (!this.timedOut) { if (err.message === 'socket hang up' || err.message === 'read ECONNRESET') { this.send(cb); } else { cb(err); } } }.bind(this); }; module.exports = Upstream;
$A.bind(window, 'load', function(){ // Popup AccDC Object var popupId = $A.setPopup( { // Set a unique ID for the popup AccDC Object, which can be referenced through $A.reg['uniqueId'] id: 'myPopup', // Set the screen reader accessible boundary text values role: 'Language Selector', accStart: 'Start', accEnd: 'End', // Set the triggering element using a DOM node or a CSS Selector trigger: 'a#myPopup', // Set the file path and container ID for the popup content source: 'files/popup.html #popup-lang', // Position the popup on the right of the triggering element autoPosition: 3, // Move the Popup AccDC Object 10px to the right when opened offsetLeft: 10, // Set the class name for the top level container element className: 'popup', // Set the class name for the screen reader accessible close link // This must match the class name for any close links or buttons within the popup content, which will cause Close Method Binding to automatically occur when the content is rendered. closeClassName: 'popupClose', // Set a visually hidden close link for screen reader users to appear at the end of the popup content showHiddenClose: true, // Set the visually hidden close link to appear onFocus (required for 508 compliance if no other keyboard accessible close method is available) displayHiddenClose: true, // Set the heading level that will be accessible for screen reader users ariaLevel: 2, // Choose a different insertion point in the DOM; must be a DOM node; defaults to the triggering element if not specified. targetObj: null, // Choose a different focus element in the DOM for CSS autoPositioning; may be a DOM node or CSS Selector; defaults to the triggering element if not specified. posAnchor: '', // Disable auto announcement of popup content for screen reader users announce: false, // Disable auto focus to the beginning of the new content, since we are going to set focus to the first language in the listbox instead forceFocus: false, // Run script after the Popup AccDC Object finishes loading runAfter: function(dc){ // 'dc' is the Popup AccDC Object // dc.containerDiv is the DOM node where the newly rendered popup content is contained // All other AccDC API properties and methods are similarly available for the 'dc' object // Set aria-pressed on the triggering element $A.setAttr(dc.triggerObj, 'aria-pressed', 'true'); // Set the listbox and save the instance in the variable 'myListbox' var myListbox = new $A.Listbox($A.getEl('standardLB'), { defaultIndex: 0, label: 'Choose Language', callback: function(optionNode, optionsArray){ // Toggle the class "selected" when a list option receives focus $A.query(optionsArray, function(i, o){ if (o == optionNode) $A.addClass(o, 'selected'); else $A.remClass(o, 'selected'); }); } }); // Now add additional bindings to all listbox options so that we can click or press Enter on an option to choose it $A.bind(myListbox.options, { click: function(ev){ // Save the Language node text within the Span with id="valueText" $A.getEl('valueText').innerHTML = $A.getText(this); // Then close the Popup AccDC Object dc.close(); ev.preventDefault(); }, keydown: function(ev){ var k = ev.which || ev.keyCode; // Check if Enter is pressed if (k == 13){ // Save the Language node text within the Span with id="valueText" $A.getEl('valueText').innerHTML = $A.getText(this); // Then close the Popup AccDC Object dc.close(); ev.preventDefault(); } } }); // Now, set focus to the first language in the listbox myListbox.options[0].focus(); }, // Run script after the Popup AccDC Object finishes closing runAfterClose: function(dc){ // Unset aria-pressed on the triggering element $A.setAttr(dc.triggerObj, 'aria-pressed', 'false'); } }); });
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ // ProjectViews.js // Project creation / import functionality for AIM. define(function (require) { "use strict"; var $ = require('jquery'), Underscore = require('underscore'), ta = require('typeahead'), Backbone = require('backbone'), Handlebars = require('handlebars'), Marionette = require('marionette'), cp = require('colorpicker'), cpb = require('circularProgressBar'), tplEditProject = require('text!tpl/EditProject.html'), tplNewProject = require('text!tpl/NewProject.html'), tplCopyOrImport = require('text!tpl/CopyOrImport.html'), tplCases = require('text!tpl/ProjectCases.html'), tplFonts = require('text!tpl/ProjectFonts.html'), tplFont = require('text!tpl/ProjectFont.html'), tplLoadingPleaseWait = require('text!tpl/LoadingPleaseWait.html'), tplPunctuation = require('text!tpl/ProjectPunctuation.html'), tplSourceLanguage = require('text!tpl/ProjectSourceLanguage.html'), tplTargetLanguage = require('text!tpl/ProjectTargetLanguage.html'), tplUSFMFiltering = require('text!tpl/ProjectUSFMFiltering.html'), tplEditorPrefs = require('text!tpl/EditorPrefs.html'), tplManageProjs = require('text!tpl/ManageProjects.html'), tplProjList = require('text!tpl/ProjectList.html'), projList = Handlebars.compile(tplProjList), i18n = require('i18n'), usfm = require('utils/usfm'), langs = require('utils/languages'), fontModel = require('app/models/font'), innerHtml = "", step = 1, currentView = null, languages = null, USFMMarkers = null, theFont = null, template = null, lines = [], fileList = [], //// // Helper methods //// // Helper method that returns the RFC5646 code based on the ISO639 code and variant buildFullLanguageCode = function (langCode, langVariant) { var fullCode = ""; // only build if there's a language code defined console.log("buildFullLanguageCode: " + langCode + "," + langVariant); if (langCode.length > 0) { // is there anything in the language variant? if (langVariant.length === 0) { // nothing in the variant -- use just the iso639 code with no -x- if (langCode.indexOf("-x-") > 0) { fullCode = langCode.substr(0, langCode.indexOf("-x-")); } else { fullCode = langCode; // just the iso 639 code } } else { // variant is defined --- code is in the form [is0639]-x-[variant], where [variant] has // a max length of 8 chars if (langCode.indexOf("-x-") > 0) { // replace the existing variant fullCode = langCode.substr(0, langCode.indexOf("-x-") + 3) + langVariant.toLowerCase().substr(0, 8); } else { // add a new variant fullCode = langCode + "-x-" + langVariant.toLowerCase().substr(0, 8); } } } return fullCode; }, // Helper method to hide the prev/next buttons and increase the scroller size // if the screen is too small // (Issue #232) HideTinyUI = function () { if ((window.innerHeight / 2) < ($("#WizStepTitle").height() + $("#StepInstructions").height() + $("#StepContainer").height() + $("#WizardSteps").height())) { if (navigator.notification && device.platform === "iOS") { $(".scroller-bottom-tb").css({bottom: "calc(env(safe-area-inset-bottom))"}); } else { $(".scroller-bottom-tb").css({bottom: "0"}); } $(".bottom-tb").hide(); $("#Spacer").show(); } }, // Helper method to show the prev/next buttons and decrease the scroller size ShowTinyUI = function () { if (navigator.notification && device.platform === "iOS") { $(".scroller-bottom-tb").css({bottom: "calc(env(safe-area-inset-bottom) + 61px)"}); } else { $(".scroller-bottom-tb").css({bottom: "61px"}); } $(".bottom-tb").show(); $("#Spacer").hide(); }, // Helper to import the KB file associated with the specified project // (overriding any existing KB). This gets called from both mobileImportAIC // and browserImportAIC // importKBFile = function (file, project) { // var reader = new FileReader(); // reader.onloadend = function (evt) { // // }; // reader.readAsText(file, "UTF-8"); // }, // Helper to import the selected file into the specified // project object (overridding any existing values). This gets called // from both mobileImportAIC and browserImportAIC. importSettingsFile = function (file, project) { var reader = new FileReader(); reader.onloadend = function (evt) { var value = "", value2 = "", value3 = "", value4 = "", i = 0, s = null, t = null, arrPunct = [], arrCases = []; // helper method to convert .aic color values to an html hex color string: // .aic --> bbggrr (in base 10) // .html --> #rrggbb (in hex) var getColorValue = function (strValue) { var intValue = parseInt(strValue, 10); var rValue = ("00" + (intValue & 0xff).toString(16)).slice(-2); var gValue = ("00" + ((intValue >> 8) & 0xff).toString(16)).slice(-2); var bValue = ("00" + ((intValue >> 16) & 0xff).toString(16)).slice(-2); // format in html hex, padded with leading zeroes var theValue = "#" + rValue + gValue + bValue; return theValue; }; // Helper method to pull out the value corresponding to the named setting from the .aic file contents // (the array "lines"). If the named setting isn't found at that line, it searches FORWARD to the end -- // returning an empty string if not found. var getSettingValue = function (expectedIndex, aicSetting) { var i = 0, value = ""; if (lines[expectedIndex].indexOf(aicSetting) !== -1) { // the value is the rest of the line AFTER the aicsetting + space value = lines[expectedIndex].substr(aicSetting.length + 1); } else { // This setting is NOT at the line we expected. It could be on a different // line, or not in the .aic file at all for (i = 0; i < lines.length; i++) { if (lines[i].indexOf(aicSetting) === 0) { // Found! The value is the rest of the line AFTER the aicsetting + space value = lines[i].substr(aicSetting.length + 1); // finish searching break; } } } return value; }; // split out the .aic file into an array (one entry per line of the file) lines = evt.target.result.split("\n"); // We've successfully opened an Adapt It project file (.aic) - // populate our AIM model object with values // from the .aic file project.set("SourceLanguageName", getSettingValue(55, "SourceLanguageName"), {silent: true}); project.set("TargetLanguageName", getSettingValue(56, "TargetLanguageName"), {silent: true}); project.set("SourceLanguageCode", getSettingValue(59, "SourceLanguageCode"), {silent: true}); project.set("TargetLanguageCode", getSettingValue(60, "TargetLanguageCode"), {silent: true}); project.set("SourceDir", (getSettingValue(115, "SourceIsRTL") === "1") ? "rtl" : "ltr", {silent: true}); project.set("TargetDir", (getSettingValue(116, "TargetIsRTL") === "1") ? "rtl" : "ltr", {silent: true}); value = getSettingValue(124, "ProjectName"); if (value.length > 0) { project.set("name", value, {silent: true}); } else { // project name not found -- build it from the source & target languages project.set("name", i18n.t("view.lblSourceToTargetAdaptations", { source: (project.get("SourceVariant").length > 0) ? project.get("SourceVariant") : project.get("SourceLanguageName"), target: (project.get("TargetVariant").length > 0) ? project.get("TargetVariant") : project.get("TargetLanguageName")}), {silent: true}); } // filters (USFM only -- other settings are ignored) value = getSettingValue(124, "UseSFMarkerSet"); if (value === "UsfmOnly") { value = getSettingValue(123, "UseFilterMarkers"); if (value !== project.get("FilterMarkers")) { project.set("UseCustomFilters", "true", {silent: true}); project.set("FilterMarkers", value, {silent: true}); } } // value = model.get("SourceLanguageCode") + "." + model.get("TargetLanguageCode"); value = Underscore.uniqueId(); project.set("projectid", value, {silent: true}); // The following settings require some extra work // Punctuation pairs value = getSettingValue(79, "PunctuationPairsSourceSet(stores space for an empty cell)"); value2 = getSettingValue(80, "PunctuationPairsTargetSet(stores space for an empty cell)"); for (i = 0; i < value.length; i++) { s = value.charAt(i); t = value2.charAt(i); if (s && s.length > 0) { arrPunct[arrPunct.length] = {s: s, t: t}; } } // add double punctuation pairs as well value = getSettingValue(81, "PunctuationTwoCharacterPairsSourceSet(ditto)"); value2 = getSettingValue(82, "PunctuationTwoCharacterPairsTargetSet(ditto)"); i = 0; while (i < value.length) { s = value.substr(i, 2); t = value2.substr(i, 2); if (s && s.length > 0) { arrPunct[arrPunct.length] = {s: s, t: t}; } i = i + 2; // advance to the next item (each set is 2 chars in length) } project.set({PunctPairs: arrPunct}, {silent: true}); // Auto capitalization value = getSettingValue(115, "LowerCaseSourceLanguageChars"); value2 = getSettingValue(116, "UpperCaseSourceLanguageChars"); value3 = getSettingValue(117, "LowerCaseTargetLanguageChars"); value4 = getSettingValue(118, "UpperCaseTargetLanguageChars"); for (i = 0; i < value.length; i++) { s = value.charAt(i) + value2.charAt(i); t = value3.charAt(i) + value4.charAt(i); if (s && s.length > 0) { arrCases[arrCases.length] = {s: s, t: t}; } } project.set({CasePairs: arrCases}, {silent: true}); value = getSettingValue(121, "AutoCapitalizationFlag"); project.set("AutoCapitalization", (value === "1") ? "true" : "false", {silent: true}); value = getSettingValue(122, "SourceHasUpperCaseAndLowerCase"); project.set("SourceHasUpperCase", (value === "1") ? "true" : "false", {silent: true}); // Fonts, if they're installed on this device (getFontList is async) if (navigator.Fonts) { navigator.Fonts.getFontList( function (fontList) { if (fontList) { // Source Font value = getSettingValue(16, "FaceName"); if ($.inArray(value, fontList) > -1) { project.set("SourceFont", value, {silent: true}); } // Target Font value = getSettingValue(34, "FaceName"); if ($.inArray(value, fontList) > -1) { project.set("TargetFont", value, {silent: true}); } } }, function (error) { console.log("FontList error: " + error); } ); } // font colors project.set("SourceColor", getColorValue(getSettingValue(17, "Color")), {silent: true}); project.set("TargetColor", getColorValue(getSettingValue(34, "Color")), {silent: true}); project.set("NavColor", getColorValue(getSettingValue(53, "Color")), {silent: true}); project.set("SpecialTextColor", getColorValue(getSettingValue(87, "SpecialTextColor")), {silent: true}); project.set("RetranslationColor", getColorValue(getSettingValue(88, "RetranslationTextColor")), {silent: true}); project.set("TextDifferencesColor", getColorValue(getSettingValue(89, "TargetDifferencesTextColor")), {silent: true}); // done -- display the OK button project.set("projectid", Underscore.uniqueId(), {silent: true}); $("#status").html(i18n.t("view.dscStatusImportSuccess", {document: project.get("name")})); if ($("#loading").length) { $("#loading").hide(); $("#waiting").hide(); $("#OK").show(); } $("#OK").removeAttr("disabled"); }; reader.readAsText(file, "UTF-8"); }, // CopyProjectView // Copy a project file from an .aic file on the device. CopyProjectView = Marionette.ItemView.extend({ template: Handlebars.compile(tplCopyOrImport), localURLs: null, initialize: function () { document.addEventListener("resume", this.onResume, false); }, //// // Event Handlers //// events: { "change #selFile": "browserImportAIC", "click .topcoat-list__item": "mobileImportAIC", "click #OK": "onOK" }, // Resume handler -- user placed the app in the background, then resumed. // Assume the file list could have changed, and reload this page onResume: function () { // refresh the view Backbone.history.loadUrl(Backbone.history.fragment); }, // Handler for the OK button click -- // saves any changes and goes back to the home page onOK: function () { // save the model this.model.save(); if (window.Application.currentProject !== null) { // There's already a project defined, so there might be some local // chapter/book/sourcephrase/KB stuff -- clear it out so it reloads info from // our new project instead. window.Application.BookList.length = 0; window.Application.ChapterList.length = 0; window.Application.spList.length = 0; window.Application.kbList.length = 0; } // Set the current project to our new one window.Application.currentProject = this.model; localStorage.setItem("CurrentProjectID", window.Application.currentProject.get("projectid")); // head back to the home page window.location.replace(""); }, // Handler for the click event on the project file list (mobile only) - // reconstitutes the file object from the path and calls importSettingsFile() mobileImportAIC: function (event) { console.log("mobileImportAIC"); // replace the selection UI with the import UI $("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait)); // open selected .aic file var index = $(event.currentTarget).attr('id').trim(); var model = this.model; console.log("index: " + index + ", FileList[index]: " + fileList[index]); // request the persistent file system window.resolveLocalFileSystemURL(fileList[index], function (entry) { entry.file( function (file) { $("#status").html(i18n.t("view.dscStatusReading", {document: file.name})); importSettingsFile(file, model); }, function (error) { console.log("FileEntry.file error: " + error.code); } ); }, function (error) { console.log("resolveLocalFileSystemURL error: " + error.code); }); }, // Handler for the click event on the Select html <input type=file> button element - // just calls importSettingsFile() to import the selected file browserImportAIC: function (event) { // click on the html <input type=file> element (browser only) -- // file selection is in event.currentTarget.files[0] (no multi-select for project files) console.log("browserImportAIC"); $("#status").html(i18n.t("view.dscStatusReading", {document: event.currentTarget.files[0]})); importSettingsFile(event.currentTarget.files[0], this.model); }, // Show event handler (from MarionetteJS) - // - For mobile devices, uses the cordova-plugin-file API to iterate through // known directories on the mobile device in search of project settings files. // Any found files are listed as <div> elements // - For browsers, uses the html <input type=file> element to allow the user // to select an .aic file from the local PC. onShow: function () { $("#selFile").attr("accept", ".aic"); $("#selFile").removeAttr("multiple"); $("#title").html(i18n.t('view.lblCopyProject')); $(".topcoat-progress-bar").hide(); $("#lblDirections").html(i18n.t('view.dscCopyProjInstructions')); // cheater way to tell if running on mobile device if (device && (device.platform !== "browser")) { // running on device -- use cordova file plugin to select file $("#browserGroup").hide(); $("#mobileSelect").html(Handlebars.compile(tplLoadingPleaseWait)); var DirsRemaining = window.Application.localURLs.length; var index = 0; var i; var statusStr = ""; var addFileEntry = function (entry) { var dirReader = entry.createReader(); dirReader.readEntries( function (entries) { var fileStr = ""; var i; for (i = 0; i < entries.length; i++) { if (entries[i].isDirectory === true) { // Recursive -- call back into this subdirectory DirsRemaining++; addFileEntry(entries[i]); } else { if (entries[i].name.toLowerCase().indexOf(".aic") > 0) { fileList[index] = entries[i].toURL(); fileStr += "<li class='topcoat-list__item' id=" + index + ">" + entries[i].fullPath + "<span class='chevron'></span></li>"; index++; } } } statusStr += fileStr; DirsRemaining--; if (DirsRemaining <= 0) { if (statusStr.length > 0) { $("#mobileSelect").html("<div class='wizard-instructions'>" + i18n.t('view.dscCopyProjInstructions') + "</div><div class='topcoat-list__container chapter-list'><ul class='topcoat-list__container chapter-list'>" + statusStr + "</ul></div>"); $("#OK").attr("disabled", true); } else { // nothing to select -- inform the user $("#status").html(i18n.t("view.dscNoDocumentsFound")); if ($("#loading").length) { $("#loading").hide(); $("#waiting").hide(); $("#OK").show(); } $("#OK").removeAttr("disabled"); } } }, function (error) { console.log("readEntries error: " + error.code); statusStr += "<p>readEntries error: " + error.code + "</p>"; } ); }; var addError = function (error) { // log the error and continue processing console.log("getDirectory error: " + error.code); DirsRemaining--; }; for (i = 0; i < window.Application.localURLs.length; i++) { if (window.Application.localURLs[i] === null || window.Application.localURLs[i].length === 0) { DirsRemaining--; continue; // skip blank / non-existent paths for this platform } window.resolveLocalFileSystemURL(window.Application.localURLs[i], addFileEntry, addError); } } else { // running in browser -- use html <input> to select file $("#mobileSelect").hide(); $("#btnClipboard").hide(); // for now, no clipboard .aic import for the browser } $("#OK").attr("disabled", true); } }), // CasesView // View / edit the upper/lowercase equivlencies for the source and target // languages, and whether to automatically copy cases. CasesView = Marionette.ItemView.extend({ template: Handlebars.compile(tplCases), events: { "focus .topcoat-text-input": "onFocusInput", "blur .topcoat-text-input": "onBlurInput", "click #SourceHasCases": "onClickSourceHasCases", "click #AutoCapitalize": "onClickAutoCapitalize" }, onFocusInput: function (event) { // HideTinyUI(); window.Application.scrollIntoViewCenter(event.currentTarget); // event.currentTarget.scrollIntoView(true); }, onBlurInput: function () { // ShowTinyUI(); }, onClickDeleteRow: function (event) { // find the current row var index = event.currentTarget.id.substr(2); // remove the item from the UI var element = "#r-" + index; $(element).remove(); }, // Handler for when the user starts typing on the last row input fields; // adds one more row, shows the delete button on the current ond, and removes the new-row class // from the current row so this method doesn't get called on this row again. addNewRow: function (event) { var newID = Underscore.uniqueId(); var index = event.currentTarget.id.substr(2); // remove the class from this row $(("#s-" + index)).removeClass("new-row"); $(("#t-" + index)).removeClass("new-row"); // show the delete button $(("#d-" + index)).removeClass("hide"); // add a new row (with the .new-row class) $("table").append("<tr id='r-" + newID + "'><td><input type='text' class='topcoat-text-input new-row' id='s-" + newID + "' style='width:100%;' maxlength='2' value=''></td><td><input type='text' id='t-" + newID + "' class='topcoat-text-input new-row' style='width:100%;' maxlength='2' value=''></td><td><button class='topcoat-icon-button--quiet delete-row hide' title='" + i18n.t('view.ttlDelete') + "' id='d-" + newID + "'><span class='topcoat-icon topcoat-icon--item-delete'></span></button></td></tr>"); }, // returns an array of objects corresponding to the current s/t values in the table // (i.e., in the CasePairs format) getRows: function () { var arr = [], s = null, t = null; $("tr").each(function () { s = $(this).find(".s").val(); t = $(this).find(".t").val(); if (s && s.length > 0) { // s = Handlebars.Utils.escapeExpression(s); // t = Handlebars.Utils.escapeExpression(t); arr[arr.length] = {s: s, t: t}; } }); return arr; }, onClickSourceHasCases: function () { // enable / disable the autocapitalize checkbox based on the value if ($("#SourceHasCases").is(':checked') === true) { $("#AutoCapitalize").prop('disabled', false); if ($("#AutoCapitalize").is(':checked') === true) { $("#CaseEquivs").prop('hidden', false); } else { $("#CaseEquivs").prop('hidden', true); } } else { $("#AutoCapitalize").prop('disabled', true); $("#CaseEquivs").prop('hidden', true); } }, onClickAutoCapitalize: function () { // show / hide the cases list based on the value if ($("#AutoCapitalize").is(':checked') === true) { $("#CaseEquivs").prop('hidden', false); } else { $("#CaseEquivs").prop('hidden', true); } } }), // FontsView - display the fonts for source, target and navigation. Clicking on a link // opens the FontView FontsView = Marionette.ItemView.extend({ template: Handlebars.compile(tplFonts) }), // FontView - view / edit a single font FontView = Marionette.ItemView.extend({ template: Handlebars.compile(tplFont), events: { "change #font": "updateSample", "change #FontSize": "updateSample", "change #color": "updateSample" }, updateSample: function () { $('#sample').attr('style', 'font-size:' + $('#FontSize').val() + 'px; font-family:\'' + $('#font').val() + '\'; color:' + $('#color').val() + ';'); }, onShow: function () { var theColor = 0; // populate the font drop-down and color picker if the model is set if (this.model) { // font drop-down if ($("#font").length) { // only if UI is shown var typefaces = null, curFont = this.model.get('typeface'), i = 0; // start with fonts installed on device if (navigator.Fonts) { // console.log("Fonts object in navigator"); navigator.Fonts.getFontList( function (fontList) { typefaces = fontList; console.log(fontList); if (typefaces) { for (i = 0; i < typefaces.length; i++) { $("#font").append($("<option></option>") .attr("value", typefaces[i]) .text(typefaces[i])); } } // (async case) select the current font $("#font option[value=\'" + curFont + "\']").attr('selected', 'selected'); }, function (error) { console.log("FontList error: " + error); console.log(error); } ); console.log("FontList: exit"); } else { console.log("Plugin error: Fonts plugin not found (is it installed?)"); } // add the fonts we've embedded with AIM $("#font").append($('<option>', {value : 'Andika'}).text('Andika')); $("#font").append($('<option>', {value : 'Gentium'}).text('Gentium')); $("#font").append($('<option>', {value : 'Scheherazade'}).text('Scheherazade')); $("#font").append($('<option>', {value : 'Source Sans'}).text('Source Sans')); // select the current font $("#font option[value=\'" + curFont + "\']").attr('selected', 'selected'); // color variations if (innerHtml.length > 0) { $('#variations').html(innerHtml); } } // color pickers $("#color").val(this.model.get('color')); $("#color").spectrum({ showPaletteOnly: true, showPalette: true, hideAfterPaletteSelect: true, color: this.model.get('color'), palette: [ ["#000000", "#444444", "#666666", "#999999", "#cccccc", "#eeeeee", "#f3f3f3", "#ffffff"], ["#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#9900ff", "#ff00ff"], ["#cc0000", "#e69138", "#cccc00", "#00cc00", "#00cccc", "#0000cc", "#674ea7", "#cc00cc"], ["#aa0000", "#aa6600", "#aaaa00", "#00aa00", "#00aaaa", "#0000aa", "#6600aa", "#aa00aa"], ["#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#0b5394", "#351c75", "#741b47"], ["#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#073763", "#20124d", "#4c1130"] ] }); if ($("#spcolor").length) { theColor = $('#spcolor').val(); $("#spcolor").val(theColor); $("#spcolor").spectrum({ showPaletteOnly: true, showPalette: true, hideAfterPaletteSelect: true, color: theColor, palette: [ ["#000000", "#444444", "#666666", "#999999", "#cccccc", "#eeeeee", "#f3f3f3", "#ffffff"], ["#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#9900ff", "#ff00ff"], ["#cc0000", "#e69138", "#cccc00", "#00cc00", "#00cccc", "#0000cc", "#674ea7", "#cc00cc"], ["#aa0000", "#aa6600", "#aaaa00", "#00aa00", "#00aaaa", "#0000aa", "#6600aa", "#aa00aa"], ["#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#0b5394", "#351c75", "#741b47"], ["#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#073763", "#20124d", "#4c1130"] ] }); theColor = $('#retranscolor').val(); $("#retranscolor").val(theColor); $("#retranscolor").spectrum({ showPaletteOnly: true, showPalette: true, hideAfterPaletteSelect: true, color: theColor, palette: [ ["#000000", "#444444", "#666666", "#999999", "#cccccc", "#eeeeee", "#f3f3f3", "#ffffff"], ["#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#9900ff", "#ff00ff"], ["#cc0000", "#e69138", "#cccc00", "#00cc00", "#00cccc", "#0000cc", "#674ea7", "#cc00cc"], ["#aa0000", "#aa6600", "#aaaa00", "#00aa00", "#00aaaa", "#0000aa", "#6600aa", "#aa00aa"], ["#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#0b5394", "#351c75", "#741b47"], ["#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#073763", "#20124d", "#4c1130"] ] }); } if ($('#diffcolor').length) { theColor = $('#diffcolor').val(); $("#diffcolor").val(theColor); $("#diffcolor").spectrum({ showPaletteOnly: true, showPalette: true, hideAfterPaletteSelect: true, color: theColor, palette: [ ["#000000", "#444444", "#666666", "#999999", "#cccccc", "#eeeeee", "#f3f3f3", "#ffffff"], ["#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#9900ff", "#ff00ff"], ["#cc0000", "#e69138", "#cccc00", "#00cc00", "#00cccc", "#0000cc", "#674ea7", "#cc00cc"], ["#aa0000", "#aa6600", "#aaaa00", "#00aa00", "#00aaaa", "#0000aa", "#6600aa", "#aa00aa"], ["#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#0b5394", "#351c75", "#741b47"], ["#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#073763", "#20124d", "#4c1130"] ] }); } } } }), // PunctuationView - view / edit the punctuation pairs, and specify whether to copy the punctuation from // source to target PunctuationView = Marionette.ItemView.extend({ template: Handlebars.compile(tplPunctuation), events: { "focus .topcoat-text-input": "onFocusInput", "blur .topcoat-text-input": "onBlurInput", "click #CopyPunctuation": "onClickCopyPunctuation" }, onFocusInput: function (event) { // HideTinyUI(); window.Application.scrollIntoViewCenter(event.currentTarget); // event.currentTarget.scrollIntoView(true); }, onBlurInput: function () { // ShowTinyUI(); }, onClickDeleteRow: function (event) { // find the current row var index = event.currentTarget.id.substr(2); // remove the item from the UI var element = "#r-" + index; $(element).remove(); }, onClickCopyPunctuation: function () { // enable / disable the autocapitalize checkbox based on the value if ($("#CopyPunctuation").is(':checked') === true) { $("#PunctMappings").prop('hidden', false); } else { $("#PunctMappings").prop('hidden', true); } }, // Handler for when the user starts typing on the last row input fields; // adds one more row, shows the delete button on the current ond, and removes the new-row class // from the current row so this method doesn't get called on this row again. addNewRow: function (event) { var newID = Underscore.uniqueId(); var index = event.currentTarget.id.substr(2); // remove the class from this row $(("#s-" + index)).removeClass("new-row"); $(("#t-" + index)).removeClass("new-row"); // show the delete button $(("#d-" + index)).removeClass("hide"); // add a new row (with the .new-row class) $("table").append("<tr id='r-" + newID + "'><td><input type='text' class='topcoat-text-input new-row s' id='s-" + newID + "' style='width:100%;' maxlength='2' value=''></td><td><input type='text' id='t-" + newID + "' class='topcoat-text-input new-row t' style='width:100%;' maxlength='2' value=''></td><td><button class='topcoat-icon-button--quiet delete-row hide' title='" + i18n.t('view.ttlDelete') + "' id='d-" + newID + "'><span class='topcoat-icon topcoat-icon--item-delete'></span></button></td></tr>"); }, // returns an array of objects corresponding to the current s/t values in the table // (i.e., in the PunctPairs format) getRows: function () { var arr = [], s = null, t = null; $("tr").each(function () { s = $(this).find(".s").val(); t = $(this).find(".t").val(); if (s && s.length > 0) { // escape the punctuation chars (avoids injection attacks) // s = Handlebars.Utils.escapeExpression(s); // t = Handlebars.Utils.escapeExpression(t); // update the array arr[arr.length] = {s: s, t: t}; } }); return arr; } }), // SourceLanguageView - view / edit the source language name and code, as well as // any variants. Also specify whether the language is LTR. SourceLanguageView = Marionette.ItemView.extend({ theLangs: null, languageMatches: function(coll) { return function findMatches(query, callback) { var theQuery = query.toLowerCase(); coll.fetch({reset: true, data: {name: theQuery}}); var matches = coll.filter(function (item) { return (item.attributes.Ref_Name.toLowerCase().indexOf(theQuery) !== -1); }); coll.comparator = function (model) { return [((model.get("Part1").length === 0) ? "zzz" : model.get("Part1")), model.get("Ref_Name")] } coll.sort(); callback(matches); }; }, template: Handlebars.compile(tplSourceLanguage), onShow: function () { this.theLangs = new langs.LanguageCollection(); this.theLangs.fetch({reset: true, data: {name: ""}}); $("#LanguageName").typeahead( { hint: true, highlight: true, minLength: 1 }, { name: 'languages', display: function (data) { return data.attributes.Ref_Name; }, source: this.languageMatches(this.theLangs), limit: 20, templates: { empty: ['<div>No languages found</div>'].join('\n'), pending: ['<div>Searching...</div>'].join('\n'), suggestion: function (data) { if (data.attributes.Part1.length > 0) { return '<div class=\"autocomplete-suggestion\" id=\"' + data.attributes.Part1 + '\">' + data.attributes.Ref_Name + '&nbsp;(' + data.attributes.Part1 + ')</div>'; } else { return '<div class=\"autocomplete-suggestion\" id=\"' + data.attributes.Id + '\">' + data.attributes.Ref_Name + '&nbsp;(' + data.attributes.Id + ')</div>'; } } } }); } }), // TargetLanguageView - view / edit the target language name and code, as well as // any variants. Also specify whether the language is LTR. TargetLanguageView = Marionette.ItemView.extend({ theLangs: null, languageMatches: function(coll) { return function findMatches(query, callback) { var theQuery = query.toLowerCase(); coll.fetch({reset: true, data: {name: theQuery}}); var matches = coll.filter(function (item) { return (item.attributes.Ref_Name.toLowerCase().indexOf(theQuery) !== -1); }); coll.comparator = function (model) { return [((model.get("Part1").length === 0) ? "zzz" : model.get("Part1")), model.get("Ref_Name")] } coll.sort(); callback(matches); }; }, template: Handlebars.compile(tplTargetLanguage), onShow: function () { this.theLangs = new langs.LanguageCollection(); this.theLangs.fetch({reset: true, data: {name: ""}}); $("#LanguageName").typeahead( { hint: true, highlight: true, minLength: 1 }, { name: 'languages', display: function (data) { return data.attributes.Ref_Name; }, source: this.languageMatches(this.theLangs), limit: 20, templates: { empty: ['<div>No languages found</div>'].join('\n'), pending: ['<div>Searching...</div>'].join('\n'), suggestion: function (data) { if (data.attributes.Part1.length > 0) { return '<div class=\"autocomplete-suggestion\" id=\"' + data.attributes.Part1 + '\">' + data.attributes.Ref_Name + '&nbsp;(' + data.attributes.Part1 + ')</div>'; } else { return '<div class=\"autocomplete-suggestion\" id=\"' + data.attributes.Id + '\">' + data.attributes.Ref_Name + '&nbsp;(' + data.attributes.Id + ')</div>'; } } } }); } }), // USFMFilteringView // View / edit the USFM markers that are filtered from the UI when // adapting. USFMFilteringView = Marionette.ItemView.extend({ template: Handlebars.compile(tplUSFMFiltering), events: { "click #UseCustomFilters": "onClickCustomFilters" }, // Build the body rows of the usfm filter table, with any items from the filterMarkers checked. // This method gets called the first time that the table is about to be displayed. BuildFilterTable: function () { var htmlstring = "", filter = this.model.get('FilterMarkers'), value = "false"; USFMMarkers.each(function (item, index) { if (item.get('userCanSetFilter') && item.get('userCanSetFilter') === '1') { value = (filter.indexOf("\\" + item.get('name') + " ") >= 0) ? "true" : "false"; htmlstring += "<tr><td><label class='topcoat-checkbox'><input class='c' type='checkbox' id='filter-" + index + " value='" + value; if (value === "true") { htmlstring += " checked"; } htmlstring += "><div class='topcoat-checkbox__checkmark'></div></label></td><td><span class='n'>" + item.get('name') + "</span></td><td>" + item.get('description') + "</td></tr>"; } }); $("#tb").html(htmlstring); }, // Extracts a filter string (for the filterMarkers property) from the items that are // checked in the usfm filter table. getFilterString: function () { var filterString = ""; $("tr").each(function () { if ($(this).find(".c").is(':checked') === true) { filterString += "\\" + $(this).find(".n").html() + " "; } }); // add always-on filters filterString += "\\lit \\_table_grid \\_header \\_intro_base \\r \\cp \\_horiz_rule \\ie \\rem \\_unknown_para_style \\_normal_table \\note \\_heading_base \\_hidden_note \\_footnote_caller \\_dft_para_font \\va \\_small_para_break \\_footer \\_vernacular_base \\pro \\_notes_base \\__normal \\ide \\mr \\_annotation_ref \\_annotation_text \\_peripherals_base \\_gls_lang_interlinear \\free \\rq \\_nav_lang_interlinear \\_body_text \\cl \\efm \\bt \\_unknown_char_style \\_double_boxed_para \\_hdr_ftr_interlinear \\_list_base \\ib \\fig \\restore \\_src_lang_interlinear \\vp \\_tgt_lang_interlinear \\ef \\ca \\_single_boxed_para \\sts \\hr \\loc \\cat \\des"; return filterString; }, onClickCustomFilters: function () { // enable / disable the autocapitalize checkbox based on the value if ($("#UseCustomFilters").is(':checked') === true) { if ($("#tb").html().length === 0) { this.BuildFilterTable(); } $("#USFMFilters").prop('hidden', false); } else { $("#USFMFilters").prop('hidden', true); } }, onShow: function () { // enable / disable the autocapitalize checkbox based on the value if ($("#UseCustomFilters").is(':checked') === true) { if ($("#tb").html().length === 0) { this.BuildFilterTable(); } $("#USFMFilters").prop('hidden', false); } else { $("#USFMFilters").prop('hidden', true); } } }), ManageProjsView = Marionette.ItemView.extend({ template: Handlebars.compile(tplManageProjs), events: { "click #btnNewProject": "onAddProject", "click .projList": "onClickProject", "click #btnProjSelect": "onSelectProject", "click #btnProjDelete": "onDeleteProject" }, // User clicked the "switch to this project" button. Sets the current project to the selected project, clears the // local translation stuff (so it reloads the proper project info from the DB), and navigates to the home screen. onSelectProject: function (event) { event.stopPropagation(); var index = event.currentTarget.parentElement.parentElement.id.substr(4); window.Application.currentProject = window.Application.ProjectList.at(index); localStorage.setItem("CurrentProjectID", window.Application.currentProject.get("projectid")); // Clear out any local chapter/book/sourcephrase/KB stuff so it loads // from our new project instead window.Application.BookList.length = 0; window.Application.ChapterList.length = 0; window.Application.spList.length = 0; window.Application.kbList.length = 0; // head back to the home page window.location.replace(""); }, // User clicked the Delete project. Confirms the delete intent, and then calls reallyDeleteProj() to actually delete it. onDeleteProject: function (event) { event.stopPropagation(); var index = event.currentTarget.parentElement.parentElement.id.substr(4); var ProjDomID = event.currentTarget.parentElement.parentElement.parentElement.id; var proj = window.Application.ProjectList.at(index); var bCurrentProject = false; if (proj.get('name') === $("#lblCurName").html()) { bCurrentProject = true; } // confirm with the user -- this nukes the project and everything related to it // (translation work and KB) if (navigator.notification) { // on mobile device navigator.notification.confirm(i18n.t('view.dscWarnRemoveProject'), function (buttonIndex) { if (buttonIndex === 1) { window.Application.ProjectList.remove(proj); // remove from the collection proj.destroy(); // also deletes everything associated with this project if (bCurrentProject === true) { // just deleted the current project -- if there is a project in the project list // (i.e., if we didn't nuke all the projects), set the current to the first in the list; // then navigate us home if (window.Application.ProjectList.length > 0) { // we have at least one project defined -- set the current to the first in the list window.Application.currentProject = window.Application.ProjectList.at(0); // save the value for later localStorage.setItem("CurrentProjectID", window.Application.currentProject.get("projectid")); } // navigate to the home screen window.location.replace(""); } else { // didn't delete the current project -- just remove the item from the UI // (We're in a callback, so just hide the item rather than redrawing) $("#" + ProjDomID).addClass('hide'); } } }, i18n.t('view.lblRemoveProject')); } else { // in browser if (confirm(i18n.t('view.dscWarnRemoveProject'))) { window.Application.ProjectList.remove(proj); // remove from the collection proj.destroy(); // also deletes everything associated with this project if (bCurrentProject === true) { // just deleted the current project -- if there is a project in the project list // (i.e., if we didn't nuke all the projects), set the current to the first in the list; // then navigate us home if (window.Application.ProjectList.length > 0) { // we have at least one project defined -- set the current to the first in the list window.Application.currentProject = window.Application.ProjectList.at(0); // save the value for later localStorage.setItem("CurrentProjectID", window.Application.currentProject.get("projectid")); } // navigate to the home screen window.location.replace(""); } else { // didn't delete the current project -- just redraw the UI this.showProjects(); } } } }, // User clicked the Add Project... toggle button. Just shows/hides the clickable area where the user can either // create or copy a project onAddProject: function () { // Toggle "create new from..." action area $("#projNewActions").toggleClass("hide"); }, // User clicked on a project in the list -- shows / hides the available actions for the selected project. onClickProject: function (event) { var SELECT_BTN = "<div class=\"control-row\"><button id=\"btnProjSelect\" class=\"btnSelect\" title=\"" + i18n.t("view.lblSelectProject") + "\"><span class=\"btn-check\" role=\"img\"></span>" + i18n.t("view.lblSelectProject") + "</button></div>", DELETE_BTN = "<div class=\"control-row\"><button id=\"btnProjDelete\" title=\"" + i18n.t("view.lblRemoveProject") + "\" class=\"btnDelete danger\"><span class=\"btn-delete\" role=\"img\"></span>" + i18n.t("view.lblRemoveProject") + "</button></div>", index = event.currentTarget.id.substr(3); // Toggle the visibility of the action menu bar if ($("#lia-" + index).hasClass("show")) { // hide it $("#li-" + index).toggleClass("li-selected"); $(".liActions").html(""); // clear out any old html actions for this refstring $("#lia-" + index).toggleClass("show"); } else { // get rid of any other visible action bars $(".topcoat-list__item").removeClass("li-selected"); $(".liActions").html(""); // clear out any old html actions for this refstring $(".liActions").removeClass("show"); // now show this one $("#li-" + index).toggleClass("li-selected"); $("#lia-" + index).toggleClass("show"); if ($("#proj-" + index).html() === $("#lblCurName").html()) { // this is the current project $("#lia-" + index).html(DELETE_BTN); // can only delete } else { $("#lia-" + index).html(SELECT_BTN + DELETE_BTN); // can select and delete } } }, // iterates through the project list. If there's only one, hides the list showProjects: function () { var projHtml = ""; if (window.Application.ProjectList.length === 1) { $("#ProjList").html(""); $("#hdrAllProjects").hide(); } else { // more than one project defined -- add them here window.Application.ProjectList.each(function (item, index) { projHtml += "<li class=\"topcoat-list__item projList\" id=\"li-" + index + "\"><div class=\"big-link chap-list__item\" id=\"proj-" + index + "\">" + item.get('name') + "</div><div class=\"liActions\" id=\"lia-" + index + "\"></div></li>"; }); // update the project list $("#ProjList").html(projHtml); } }, onShow: function () { this.showProjects(); } }), EditorAndUIView = Marionette.ItemView.extend({ template: Handlebars.compile(tplEditorPrefs), events: { "click #EditBlankPiles": "onEditBlankPiles", "change #language": "onSelectCustomLanguage" }, onEditBlankPiles: function () { // TODO: warning that turning this on can cause conflicts during subsequent merges }, onSelectCustomLanguage: function () { // change the radio button selection $("#customLanguage").prop("checked", true); }, onShow: function () { if (localStorage.getItem("CopySource")) { $("#CopySource").prop("checked", localStorage.getItem("CopySource") === "true"); } else { $("#CopySource").prop("checked", true); // default is selected } if (localStorage.getItem("WrapUSFM")) { $("#WrapAtMarker").prop("checked", localStorage.getItem("WrapUSFM") === "true"); } else { $("#WrapAtMarker").prop("checked", true); // default is selected } if (localStorage.getItem("StopAtBoundaries")) { $("#StopAtBoundaries").prop("checked", localStorage.getItem("StopAtBoundaries") === "true"); } else { $("#StopAtBoundaries").prop("checked", true); // default is selected } if (localStorage.getItem("AllowEditBlankSP")) { $("#EditBlankPiles").prop("checked", localStorage.getItem("AllowEditBlankSP") === "true"); } else { $("#EditBlankPiles").prop("checked", false); // default is false (disabled) } if (localStorage.getItem("UILang")) { // use custom language -- select the language used $('#language').val(localStorage.getItem("UILang")); $("#customLanguage").prop("checked", true); // onSelectCustomLanguage() should already do this, but just in case... } else { // use device language $("#deviceLanguage").prop("checked", true); } } }), EditProjectView = Marionette.LayoutView.extend({ template: Handlebars.compile(tplEditProject), initialize: function () { this.OnEditProject(); }, //// // Event Handlers //// modelEvents: { 'change': 'render' }, events: { "click #EditorUIPrefs": "OnEditorUIPrefs", "click #CurrentProject": "OnCurrentProject", "click #SourceLanguage": "OnEditSourceLanguage", "click #TargetLanguage": "OnEditTargetLanguage", "click #sourceFont": "OnEditSourceFont", "click #targetFont": "OnEditTargetFont", "click #navFont": "OnEditNavFont", "click #Punctuation": "OnEditPunctuation", "click #Cases": "OnEditCases", "click #Filtering": "OnEditFiltering", "focus #LanguageName": "onFocusLanguageName", "focus #LanguageVariant": "onFocusLanguageVariant", "keyup #LanguageVariant": "onkeyupLanguageVariant", "focus #LanguageCode": "onFocusLanguageCode", "typeahead:select .typeahead": "selectLanguage", "typeahead:cursorchange .typeahead": "selectLanguage", "click .delete-row": "onClickDeleteRow", "keyup .new-row": "addNewRow", "click #CopyPunctuation": "OnClickCopyPunctuation", "click #SourceHasCases": "OnClickSourceHasCases", "click #AutoCapitalize": "OnClickAutoCapitalize", "click #UseCustomFilters": "OnClickCustomFilters", "click #Cancel": "OnCancel", "click #OK": "OnOK" }, OnEditorUIPrefs: function () { step = 9; this.ShowView(step); }, OnCurrentProject: function () { step = 10; this.ShowView(step); }, onFocusLanguageName: function (event) { window.Application.scrollIntoViewCenter(event.currentTarget); }, onFocusLanguageVariant: function (event) { window.Application.scrollIntoViewCenter(event.currentTarget); }, onFocusLanguageCode: function (event) { window.Application.scrollIntoViewCenter(event.currentTarget); }, onkeyupLanguageVariant: function () { var newLangCode = ""; newLangCode = buildFullLanguageCode(currentView.langCode, $('#LanguageVariant').val().trim().replace(/\s+/g, '')); currentView.langCode = newLangCode; $('#LanguageCode').val(newLangCode); }, addNewRow: function (event) { currentView.addNewRow(event); }, searchTarget: function (event) { currentView.search(event); }, onkeypressTargetName: function (event) { currentView.onkeypress(event); }, selectLanguage: function (event, suggestion) { if (suggestion) { var newLangCode = ""; currentView.langName = suggestion.attributes.Ref_Name; newLangCode = (suggestion.attributes.Part1.length > 0) ? suggestion.attributes.Part1 : suggestion.attributes.Id; currentView.langCode = buildFullLanguageCode(newLangCode, $('#LanguageVariant').val().trim().replace(/\s+/g, '')); $('#LanguageCode').val(currentView.langCode); } else { // no suggestion passed -- clear out the language name and code currentView.langName = ""; currentView.langCode = ""; $('#LanguageCode').val(currentView.langCode); } }, onClickDeleteRow: function (event) { currentView.onClickDeleteRow(event); }, OnClickCopyPunctuation: function (event) { currentView.onClickCopyPunctuation(event); }, OnClickSourceHasCases: function (event) { currentView.onClickSourceHasCases(event); }, OnClickAutoCapitalize: function (event) { currentView.onClickAutoCapitalize(event); }, OnClickCustomFilters: function (event) { currentView.onClickCustomFilters(event); }, OnEditSourceLanguage: function () { step = 1; this.ShowView(step); }, OnEditTargetLanguage: function () { step = 2; this.ShowView(step); }, OnEditSourceFont: function () { step = 3; this.ShowView(step); }, OnEditTargetFont: function () { step = 4; this.ShowView(step); }, OnEditNavFont: function () { step = 5; this.ShowView(step); }, OnEditPunctuation: function () { step = 6; this.ShowView(step); }, OnEditCases: function () { step = 7; this.ShowView(step); }, OnEditFiltering: function () { step = 8; this.ShowView(step); }, OnCancel: function () { // just display the project settings list (don't save) $("#WizStepTitle").hide(); $("#StepInstructions").addClass("hide"); $("#tbBottom").addClass("hide"); $('#ProjectItems').removeClass("hide"); $("#StepTitle").html(i18n.t('view.lblProjectSettings')); $(".container").attr("style", "height: calc(100% - 70px);"); $("#editor").removeClass("scroller-bottom-tb"); $("#editor").addClass("scroller-notb"); this.removeRegion("container"); }, OnOK: function () { // save the info from the current step this.UpdateProject(step); // show / hide the appropriate UI elements $("#WizStepTitle").hide(); $("#StepInstructions").addClass("hide"); $("#tbBottom").addClass("hide"); $('#ProjectItems').removeClass("hide"); $("#StepTitle").html(i18n.t('view.lblProjectSettings')); $(".container").attr("style", "height: calc(100% - 70px);"); $("#editor").removeClass("scroller-bottom-tb"); $("#editor").addClass("scroller-notb"); this.removeRegion("container"); }, UpdateProject: function (step) { var tempfont = "", tempSize = "", tempColor = "", loc = "", locale = ""; switch (step) { case 1: // source language this.model.set("SourceLanguageName", currentView.langName, {silent: true}); this.model.set("SourceLanguageCode", $("#LanguageCode").val().trim(), {silent: true}); this.model.set("SourceVariant", Handlebars.Utils.escapeExpression($('#LanguageVariant').val().trim()), {silent: true}); this.model.set("SourceDir", ($('#RTL').is(':checked') === true) ? "rtl" : "ltr", {silent: true}); break; case 2: // target language this.model.set("TargetLanguageName", currentView.langName, {silent: true}); this.model.set("TargetLanguageCode", $("#LanguageCode").val().trim(), {silent: true}); this.model.set("TargetVariant", Handlebars.Utils.escapeExpression($('#LanguageVariant').val().trim()), {silent: true}); this.model.set("TargetDir", ($('#RTL').is(':checked') === true) ? "rtl" : "ltr", {silent: true}); this.model.set("name", i18n.t("view.lblSourceToTargetAdaptations", { source: (this.model.get("SourceVariant").length > 0) ? this.model.get("SourceVariant") : this.model.get("SourceLanguageName"), target: (this.model.get("TargetVariant").length > 0) ? this.model.get("TargetVariant") : this.model.get("TargetLanguageName")}), {silent: true}); break; case 3: // source font tempfont = $('#font').val(); tempSize = $('#FontSize').val(); tempColor = $('#color').spectrum('get').toHexString(); this.model.set('SourceFont', tempfont, {silent: true}); this.model.set('SourceFontSize', tempSize, {silent: true}); this.model.set('SourceColor', tempColor, {silent: true}); tempColor = $('#spcolor').spectrum('get').toHexString(); this.model.set('SpecialTextColor', tempColor, {silent: true}); tempColor = $('#retranscolor').spectrum('get').toHexString(); this.model.set('RetranslationColor', tempColor, {silent: true}); break; case 4: // target font tempfont = $('#font').val(); tempSize = $('#FontSize').val(); tempColor = $('#color').spectrum('get').toHexString(); this.model.set('TargetFont', tempfont, {silent: true}); this.model.set('TargetFontSize', tempSize, {silent: true}); this.model.set('TargetColor', tempColor, {silent: true}); tempColor = $('#diffcolor').spectrum('get').toHexString(); this.model.set('TextDifferencesColor', tempColor, {silent: true}); break; case 5: // navigation font tempfont = $('#font').val(); tempSize = $('#FontSize').val(); tempColor = $('#color').spectrum('get').toHexString(); this.model.set('NavigationFont', tempfont, {silent: true}); this.model.set('NavigationFontSize', tempSize, {silent: true}); this.model.set('NavigationColor', tempColor, {silent: true}); break; case 6: // punctuation this.model.set("CopyPunctuation", ($('#CopyPunctuation').is(':checked') === true) ? "true" : "false", {silent: true}); if ($('#CopyPunctuation').is(':checked')) { // don't need to update this if we aren't copying punctuation this.model.set({PunctPairs: currentView.getRows()}, {silent: true}); } break; case 7: // cases this.model.set("SourceHasUpperCase", ($('#SourceHasCases').is(':checked') === true) ? "true" : "false", {silent: true}); this.model.set("AutoCapitalization", ($('#AutoCapitalize').is(':checked') === true) ? "true" : "false", {silent: true}); if ($('#AutoCapitalize').is(':checked')) { // don't need to update this if we aren't capitalizing the target this.model.set({CasePairs: currentView.getRows()}, {silent: true}); } break; case 8: // USFM filtering this.model.set("CustomFilters", ($('#UseCustomFilters').is(':checked') === true) ? "true" : "false", {silent: true}); if (($('#UseCustomFilters').is(':checked') === true)) { this.model.set("FilterMarkers", currentView.getFilterString(), {silent: true}); } break; case 9: // editor and UI language localStorage.setItem(("CopySource"), $("#CopySource").is(":checked") ? true : false); localStorage.setItem(("WrapUSFM"), $("#WrapAtMarker").is(":checked") ? true : false); localStorage.setItem(("StopAtBoundaries"), $("#StopAtBoundaries").is(":checked") ? true : false); localStorage.setItem(("AllowEditBlankSP"), $("#EditBlankPiles").is(":checked") ? true : false); if ($("#customLanguage").is(":checked")) { // Use a custom language loc = $('#language').val(); // set the language in local storage localStorage.setItem(("UILang"), loc); // set the locale, then return i18n.setLng(loc, function (err, t) { // do nothing? }); } else { // use the mobile device's setting // remove the language in local storage (so we get it dynamically the next time the app is launched) localStorage.removeItem("UILang"); // get the user's locale - mobile or web if (window.Intl && typeof window.Intl === 'object') { // device supports ECMA Internationalization API locale = navigator.language.split("-")[0]; i18n.setLng(locale, function (err, t) { // do nothing? }); } else { // fallback - use web browser's language metadata var lang = (navigator.languages) ? navigator.languages[0] : (navigator.language || navigator.userLanguage); locale = lang.split("-")[0]; // set the locale, then return i18n.setLng(locale, function (err, t) { // do nothing? }); } } break; } this.model.save(); this.model.trigger('change'); }, OnEditProject: function () { // create a new project model object //this.openDB(); languages = new langs.LanguageCollection(); USFMMarkers = new usfm.MarkerCollection(); USFMMarkers.fetch({reset: true, data: {name: ""}}); // return all results // title this.$("#StepTitle").html(i18n.t('view.lblProjectSettings')); }, ShowView: function (number) { innerHtml = ""; // Display the frame UI this.addRegions({ container: "#StepContainer" }); // hide the project list items $("#WizStepTitle").show(); $("#StepInstructions").removeClass("hide"); $("#editor").addClass("scroller-bottom-tb"); $("#editor").removeClass("scroller-notb"); $("#tbBottom").removeClass("hide"); $('#ProjectItems').addClass("hide"); // clear out the old view (if any) currentView = null; switch (number) { case 1: // source language languages.fetch({reset: true, data: {name: " "}}); // clear out languages collection filter currentView = new SourceLanguageView({ model: this.model, collection: languages }); currentView.langName = this.model.get("SourceLanguageName"); currentView.langCode = this.model.get("SourceLanguageCode"); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectSourceLanguage')); $("#StepInstructions").html(i18n.t('view.dscEditProjectSourceLanguage')); break; case 2: // target language languages.fetch({reset: true, data: {name: " "}}); // clear out languages collection filter currentView = new TargetLanguageView({ model: this.model, collection: languages }); currentView.langName = this.model.get("TargetLanguageName"); currentView.langCode = this.model.get("TargetLanguageCode"); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectTargetLanguage')); $("#StepInstructions").html(i18n.t('view.dscEditProjectTargetLanguage')); break; case 3: // source font theFont = new fontModel.Font(); theFont.set("name", i18n.t('view.lblSourceFont')); theFont.set("typeface", this.model.get('SourceFont')); theFont.set("size", parseInt(this.model.get('SourceFontSize'), 10)); theFont.set("color", this.model.get('SourceColor')); currentView = new FontView({ model: theFont}); Marionette.triggerMethodOn(currentView, 'show'); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectFonts')); $("#StepInstructions").html(i18n.t('view.dscProjectFonts')); // color variations for source font -- special text and retranslations innerHtml = "<div class='control-row' id='dscVariations'><h3>" + i18n.t('view.lblSourceFontVariations'); innerHtml += "</h3></div><div id='varItems'>"; innerHtml += "<div class=\'control-row\'>" + i18n.t('view.lblSpecialTextColor') + " <input type=\"text\" name=\"color\" id=\'spcolor\' value=\"" + this.model.get('SpecialTextColor') + "\" /></div>"; innerHtml += "<div class=\'control-row\'>" + i18n.t('view.lblRetranslationColor') + " <input type=\"text\" name=\"color\" id=\'retranscolor\' value=\"" + this.model.get('RetranslationColor') + "\" /></div></div>"; break; case 4: // target font theFont = new fontModel.Font(); theFont.set("name", i18n.t('view.lblTargetFont')); theFont.set("typeface", this.model.get('TargetFont')); theFont.set("size", parseInt(this.model.get('TargetFontSize'), 10)); theFont.set("color", this.model.get('TargetColor')); currentView = new FontView({ model: theFont}); Marionette.triggerMethodOn(currentView, 'show'); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectFonts')); $("#StepInstructions").html(i18n.t('view.dscProjectFonts')); // color variations for target font -- text differences innerHtml = "<div class='control-row' id='dscVariations'><h3>" + i18n.t('view.lblSourceFontVariations'); innerHtml += "</h3></div><div id='varItems'>"; innerHtml += "<div class=\'control-row\'>" + i18n.t('view.lblDifferenceColor') + " <input type=\"text\" name=\"color\" id=\'diffcolor\' value=\"" + this.model.get('TextDifferencesColor') + "\" /></div></div>"; break; case 5: // navigation font theFont = new fontModel.Font(); theFont.set("name", i18n.t('view.lblNavFont')); theFont.set("typeface", this.model.get('NavigationFont')); theFont.set("size", parseInt(this.model.get('NavigationFontSize'), 10)); theFont.set("color", this.model.get('NavigationColor')); currentView = new FontView({ model: theFont}); Marionette.triggerMethodOn(currentView, 'show'); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectFonts')); $("#StepInstructions").html(i18n.t('view.dscProjectFonts')); break; case 6: // punctuation currentView = new PunctuationView({ model: this.model}); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectPunctuation')); $("#StepInstructions").html(i18n.t('view.dscProjectPunctuation')); break; case 7: // cases currentView = new CasesView({ model: this.model}); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectCases')); $("#StepInstructions").html(i18n.t('view.dscProjectCases')); break; case 8: // USFM filtering currentView = new USFMFilteringView({ model: this.model}); // instructions $("#StepTitle").html(i18n.t('view.ttlProjectFiltering')); $("#StepInstructions").html(i18n.t('view.dscProjectUSFMFiltering')); break; case 9: // editor and UI language currentView = new EditorAndUIView({model: this.model}); break; case 10: // current project // instructions currentView = new ManageProjsView({model: this.model}); $("#StepTitle").html(i18n.t('view.ttlProject')); $("#ProjList").html(projList(window.Application.ProjectList)); break; } this.container.show(currentView); if (number === 1 || number === 2) { // the source and target language pages normally wouldn't be messed with once they're set up; // it's possible that the user needs to correct something in the dialect? At any rate, tell the user // that new projects can be created in the settings / manage projects page. if (navigator.notification) { navigator.notification.alert(i18n.t('view.dscWarnChangeProject')); } else { alert(i18n.t('view.dscWarnChangeProject')); } } } }), NewProjectView = Marionette.LayoutView.extend({ template: Handlebars.compile(tplNewProject), regions: { container: "#StepContainer" }, initialize: function () { this.OnNewProject(); }, render: function () { template = Handlebars.compile(tplNewProject); this.$el.html(template()); return this; }, onShow: function () { this.ShowStep(step); }, //// // Event Handlers //// events: { "click #sourceFont": "OnEditSourceFont", "click #targetFont": "OnEditTargetFont", "click #navFont": "OnEditNavFont", "focus #LanguageName": "onFocusLanguageName", "blur #LanguageName": "onBlurLanguageName", "typeahead:select .typeahead": "selectLanguage", "typeahead:cursorchange .typeahead": "selectLanguage", "focus #LanguageVariant": "onFocusLanguageVariant", "keyup #LanguageVariant": "onkeyupLanguageVariant", "focus #LanguageCode": "onFocusLanguageCode", "blur #LanguageVariant": "onBlurLanguageVariant", "click #btnLangAdvanced": "onClickLanguageAdvanced", "click .delete-row": "onClickDeleteRow", "keyup .new-row": "addNewRow", "click #CopyPunctuation": "OnClickCopyPunctuation", "click #SourceHasCases": "OnClickSourceHasCases", "click #AutoCapitalize": "OnClickAutoCapitalize", "click #UseCustomFilters": "OnClickCustomFilters", "click #Cancel": "OnCancel", "click #OK": "OnOK", "click #Prev": "OnPrevStep", "click #Next": "OnNextStep" }, MaybeHideUIStuff: function (bHide) { var Hgt = $(window).height(); // check to see if we're on a mobile device if (navigator.notification && !Keyboard.isVisible) { // on mobile device AND the keyboard hasn't displayed yet: // the viewport height is going to shrink when the software keyboard displays // HACK: subtract the software keyboard from the visible area end - // We can only get the keyboard height programmatically on ios, using the keyboard plugin's // keyboardHeightWillChange event. Ugh. Fudge it here until we can come up with something that can // work cross-platform if (window.orientation === 90 || window.orientation === -90) { // landscape Hgt -= 162; // observed / hard-coded "best effort" value } else { // portrait Hgt -= 248; // observed / hard-coded "best effort" value } } // test overall screen length if (bHide === true) { if (Hgt > 375) { // height is big enough -- exit out return; } else { // not enough room -- hide the instructions $("#StepInstructions").hide(); } } else { // make sure the instructions are visible $("#StepInstructions").show(); } }, onFocusLanguageName: function (event) { this.MaybeHideUIStuff(true); // hide the instructions if we're on a small screen window.Application.scrollIntoViewCenter(event.currentTarget); }, onBlurLanguageName: function () { this.MaybeHideUIStuff(false); // show the instructions UI again }, onFocusLanguageVariant: function (event) { window.Application.scrollIntoViewCenter(event.currentTarget); }, onFocusLanguageCode: function (event) { window.Application.scrollIntoViewCenter(event.currentTarget); }, onkeyupLanguageVariant: function () { var newLangCode = ""; newLangCode = buildFullLanguageCode(currentView.langCode, $('#LanguageVariant').val().trim().replace(/\s+/g, '')); currentView.langCode = newLangCode; $('#LanguageCode').val(newLangCode); }, searchTarget: function (event) { currentView.search(event); }, onkeypressTargetName: function (event) { currentView.onkeypress(event); }, selectLanguage: function (event, suggestion) { if (suggestion) { var newLangCode = ""; currentView.langName = suggestion.attributes.Ref_Name; newLangCode = (suggestion.attributes.Part1.length > 0) ? suggestion.attributes.Part1 : suggestion.attributes.Id; currentView.langCode = buildFullLanguageCode(newLangCode, $('#LanguageVariant').val().trim().replace(/\s+/g, '')); $('#LanguageCode').val(currentView.langCode); } else { // no suggestion passed -- clear out the language name and code currentView.langName = ""; currentView.langCode = ""; $('#LanguageCode').val(currentView.langCode); } }, onClickDeleteRow: function (event) { currentView.onClickDeleteRow(event); }, addNewRow: function (event) { currentView.addNewRow(event); }, onClickVariant: function (event) { currentView.onClickVariant(event); }, OnClickCopyPunctuation: function (event) { currentView.onClickCopyPunctuation(event); }, OnClickSourceHasCases: function (event) { currentView.onClickSourceHasCases(event); }, OnClickAutoCapitalize: function (event) { currentView.onClickAutoCapitalize(event); }, OnClickCustomFilters: function (event) { currentView.onClickCustomFilters(event); }, OnEditSourceFont: function () { var theFont = new fontModel.Font(); theFont.set("name", i18n.t('view.lblSourceFont')); theFont.set("typeface", this.model.get('SourceFont')); theFont.set("size", parseInt(this.model.get('SourceFontSize'), 10)); theFont.set("color", this.model.get('SourceColor')); currentView = new FontView({ model: theFont}); Marionette.triggerMethodOn(currentView, 'show'); // color variations for source font -- special text and retranslations innerHtml = "<div class='control-row' id='dscVariations'><h3>" + i18n.t('view.lblSourceFontVariations'); innerHtml += "</h3></div><div id='varItems'>"; innerHtml += "<div class=\'control-row\'>" + i18n.t('view.lblSpecialTextColor') + " <input type=\"text\" name=\"color\" id=\'spcolor\' value=\"" + this.model.get('SpecialTextColor') + "\" /></div>"; innerHtml += "<div class=\'control-row\'>" + i18n.t('view.lblRetranslationColor') + " <input type=\"text\" name=\"color\" id=\'retranscolor\' value=\"" + this.model.get('RetranslationColor') + "\" /></div></div>"; this.container.show(currentView); $('#WizStepTitle').hide(); $('#StepInstructions').hide(); $('#WizardSteps').hide(); $('#OKCancelButtons').show(); }, OnEditTargetFont: function () { var theFont = new fontModel.Font(); theFont.set("name", i18n.t('view.lblTargetFont')); theFont.set("typeface", this.model.get('TargetFont')); theFont.set("size", parseInt(this.model.get('TargetFontSize'), 10)); theFont.set("color", this.model.get('TargetColor')); currentView = new FontView({ model: theFont}); Marionette.triggerMethodOn(currentView, 'show'); // color variations for target font -- text differences innerHtml = "<div class='control-row' id='dscVariations'><h3>" + i18n.t('view.lblTargetFontVariations'); innerHtml += "</h3></div><div id='varItems'>"; innerHtml += "<div class=\'control-row\'>" + i18n.t('view.lblDifferenceColor') + " <input type=\"text\" name=\"color\" id=\'diffcolor\' value=\"" + this.model.get('TextDifferencesColor') + "\" /></div></div>"; $('#VarItems').html(innerHtml); this.container.show(currentView); $('#WizStepTitle').hide(); $('#StepInstructions').hide(); $('#WizardSteps').hide(); $('#OKCancelButtons').show(); }, OnEditNavFont: function () { var theFont = new fontModel.Font(); theFont.set("name", i18n.t('view.lblNavFont')); theFont.set("typeface", this.model.get('NavigationFont')); theFont.set("size", parseInt(this.model.get('NavigationFontSize'), 10)); theFont.set("color", this.model.get('NavigationColor')); currentView = new FontView({ model: theFont}); Marionette.triggerMethodOn(currentView, 'show'); innerHtml = ""; this.container.show(currentView); $('#WizStepTitle').hide(); $('#StepInstructions').hide(); $('#WizardSteps').hide(); $('#OKCancelButtons').show(); }, OnCancel: function () { // just display the project settings list (don't save) $('#WizStepTitle').show(); $('#StepInstructions').show(); $("#OKCancelButtons").hide(); $('#WizardSteps').show(); this.ShowStep(step); }, OnOK: function () { // save the info from the current step switch ($('#ttlFont').html()) { // font steps (okay, not technically steps in the work case i18n.t('view.lblSourceFont'): // source font this.model.set('SourceFont', $('#font').val(), {silent: true}); this.model.set('SourceFontSize', $('#FontSize').val(), {silent: true}); this.model.set('SourceColor', $('#color').spectrum('get').toHexString(), {silent: true}); this.model.set('SpecialTextColor', $('#spcolor').spectrum('get').toHexString(), {silent: true}); this.model.set('RetranslationColor', $('#retranscolor').spectrum('get').toHexString(), {silent: true}); break; case i18n.t('view.lblTargetFont'): // target font this.model.set('TargetFont', $('#font').val(), {silent: true}); this.model.set('TargetFontSize', $('#FontSize').val(), {silent: true}); this.model.set('TargetColor', $('#color').spectrum('get').toHexString(), {silent: true}); this.model.set('TextDifferencesColor', $('#diffcolor').spectrum('get').toHexString(), {silent: true}); break; case i18n.t('view.lblNavFont'): // navigation font default: this.model.set('NavigationFont', $('#font').val(), {silent: true}); this.model.set('NavigationFontSize', $('#FontSize').val(), {silent: true}); this.model.set('NavigationColor', $('#color').spectrum('get').toHexString(), {silent: true}); break; } this.model.save(); // save the changes // display the project settings list $('#WizStepTitle').show(); $('#StepInstructions').show(); $("#OKCancelButtons").hide(); $('#WizardSteps').show(); this.ShowStep(step); }, OnPrevStep: function () { // special case -- first screen doesn't validate -- it just returns to the welcome screen if (step === 1) { // delete the project window.Application.ProjectList.remove(this.model); // remove from the collection if (this.model.get("projectid") !== "") { // it's been saved to the DB -- delete it from the DB as well this.model.destroy(); } window.history.go(-1); // return to welcome screen } else { // pull the info from the current step (must pass validation) if (this.GetProjectInfo(step) === true) { step--; this.ShowStep(step); } } }, OnNextStep: function () { // pull the info from the current step (must pass validation) if (this.GetProjectInfo(step) === true) { if (step < this.numSteps) { step++; this.ShowStep(step); } else { // last step -- finish up // save the model this.model.save(); if (window.Application.currentProject !== null) { // There's already a project defined. Clear out any local // chapter/book/sourcephrase/KB stuff so it loads from our new project instead window.Application.BookList.length = 0; window.Application.ChapterList.length = 0; window.Application.spList.length = 0; window.Application.kbList.length = 0; } // set the current project to our new one window.Application.currentProject = this.model; localStorage.setItem("CurrentProjectID", window.Application.currentProject.get("projectid")); // head back to the home page window.location.replace(""); // head back to the home page // window.history.go(-1); // window.Application.home(); } } }, // Pull project information from the current step // Returns true if validation passes, false if it fails // (currently just checks for non-null language names in source/target language) GetProjectInfo: function (step) { var value = null, langstr = ""; var getLanguageString = function () { var value = null; if (currentView.langName.trim().length === 0) { // fail - no language set // Is there something in the language edit field? if ($("#LanguageName").val().length > 0) { // something in the language field -- attempt to get the nearest match in the languages list value = languages.at(0); if (languages.length > 0) { // found something that matches the search text -- suggest it if (navigator.notification) { // on mobile device -- use notification plugin API navigator.notification.confirm( i18n.t('view.lblUseLanguage', {language: value.get("Ref_Name")}), function (btnIndex) { if (btnIndex === 1) { // set the language and ID currentView.langName = value.get("Ref_Name"); currentView.langCode = buildFullLanguageCode(value.get("Id"), $('#LanguageVariant').val().trim()); } else { // user rejected this suggestion -- tell them to enter // a language name and finish up navigator.notification.alert(i18n.t('view.errEnterLanguageName')); } }, i18n.t('view.ttlMain'), [i18n.t('view.lblYes'), i18n.t('view.lblNo')] ); } else { // in browser -- use window.confirm / window.alert if (window.confirm(i18n.t('view.lblUseLanguage', {language: value.get("Ref_Name")}))) { // use the suggested language currentView.langName = value.get("Ref_Name"); currentView.langCode = buildFullLanguageCode(value.get("Id"), $('#LanguageVariant').val().trim()); } else { // user rejected this suggestion -- tell them to enter // a language name and finish up alert(i18n.t('view.errEnterLanguageName')); } } } else { // no suggestion found (user fell on his keyboard?) // just tell them to enter something if (navigator.notification) { // on mobile device -- use notification plugin API navigator.notification.alert(i18n.t('view.errEnterLanguageName')); } else { // in browser -- use window.confirm / window.alert alert(i18n.t('view.errEnterLanguageName')); } } } else { // user didn't type anything in // just tell them to enter something if (navigator.notification) { // on mobile device -- use notification plugin API navigator.notification.alert(i18n.t('view.errEnterLanguageName')); } else { // in browser -- use window.confirm / window.alert alert(i18n.t('view.errEnterLanguageName')); } } } // return whatever we got (could be empty) return currentView.langName; }; switch (step) { case 1: // source language // get / validate the language string langstr = getLanguageString(); if (langstr.length === 0) { // unable to get the language string (or the user didn't like the suggestion we gave) $("#LanguageName").focus(); return false; } this.model.set("SourceLanguageName", currentView.langName, {silent: true}); this.model.set("SourceLanguageCode", $("#LanguageCode").val().trim(), {silent: true}); this.model.set("SourceDir", ($('#RTL').is(':checked') === true) ? "rtl" : "ltr", {silent: true}); this.model.set("SourceVariant", $('#LanguageVariant').val().trim(), {silent: true}); break; case 2: // target language // get / validate the language string langstr = getLanguageString(); if (langstr.length === 0) { // unable to get the language string (or the user didn't like the suggestion we gave) $("#LanguageName").focus(); return false; } this.model.set("TargetLanguageName", currentView.langName, {silent: true}); this.model.set("TargetLanguageCode", $("#LanguageCode").val().trim(), {silent: true}); this.model.set("TargetVariant", $('#LanguageVariant').val().trim(), {silent: true}); this.model.set("TargetDir", ($('#RTL').is(':checked') === true) ? "rtl" : "ltr", {silent: true}); // also set the ID and name of the project, now that we (should) have both source and target defined // Do this only if we don't already have an ID if (this.model.get("projectid") === "") { value = Underscore.uniqueId(); this.model.set("projectid", value, {silent: true}); } this.model.set("name", i18n.t("view.lblSourceToTargetAdaptations", { source: (this.model.get("SourceVariant").length > 0) ? this.model.get("SourceVariant") : this.model.get("SourceLanguageName"), target: (this.model.get("TargetVariant").length > 0) ? this.model.get("TargetVariant") : this.model.get("TargetLanguageName")}), {silent: true}); console.log("id: " + value); break; case 3: // fonts break; case 4: // punctuation this.model.set("CopyPunctuation", ($('#CopyPunctuation').is(':checked') === true) ? "true" : "false", {silent: true}); this.model.set({PunctPairs: currentView.getRows()}, {silent: true}); break; case 5: // cases this.model.set("SourceHasUpperCase", ($('#SourceHasCases').is(':checked') === true) ? "true" : "false", {silent: true}); this.model.set("AutoCapitalization", ($('#AutoCapitalize').is(':checked') === true) ? "true" : "false", {silent: true}); this.model.set({CasePairs: currentView.getRows()}, {silent: true}); break; case 6: // USFM filtering this.model.set("CustomFilters", ($('#UseCustomFilters').is(':checked') === true) ? "true" : "false", {silent: true}); if (($('#UseCustomFilters').is(':checked') === true)) { this.model.set("FilterMarkers", currentView.getFilterString(), {silent: true}); } break; } if (this.model.get("projectid") !== "") { this.model.save(); } return true; }, OnNewProject: function () { // create a new project model object //this.openDB(); this.numSteps = 6; step = 1; languages = new langs.LanguageCollection(); USFMMarkers = new usfm.MarkerCollection(); USFMMarkers.fetch({reset: true, data: {name: ""}}); // return all results }, ShowStep: function (number) { var totalSteps = 6; var progressPct = ((number * 1.0 / totalSteps) * 100).toFixed(1); // clear out the old view (if any) currentView = null; innerHtml = ""; // set the progress bar $("#progress").html(""); // clear out the old pie var dp = JSON.parse($("#progress").attr("data-pie")); dp.percent = progressPct; // update progress value $("#progress").attr("data-pie", JSON.stringify(dp)); $("#progress").attr("style", ""); var progress = new CircularProgressBar('pie'); // create the progress bar switch (number) { case 1: // source language languages.fetch({reset: true, data: {name: " "}}); // clear out languages collection filter currentView = new SourceLanguageView({ model: this.model, collection: languages }); currentView.langName = this.model.get("SourceLanguageName"); currentView.langCode = this.model.get("SourceLanguageCode"); // title this.$("#StepTitle").html(i18n.t('view.lblCreateProject')); // instructions this.$("#WizStepTitle").html(i18n.t('view.ttlProjectSourceLanguage')); this.$("#StepInstructions").html(i18n.t('view.dscProjectSourceLanguage')); this.$("#lblPrev").html(i18n.t('view.lblPrev')); this.$("#lblNext").html(i18n.t('view.lblNext')); // controls if (this.model.get("SourceDir") === "rtl") { this.$("#RTL").checked = true; } this.$("#LanguageVariant").html(this.model.get("SourceVariant")); break; case 2: // target language languages.fetch({reset: true, data: {name: " "}}); // clear out languages collection filter currentView = new TargetLanguageView({ model: this.model, collection: languages }); currentView.langName = this.model.get("TargetLanguageName"); currentView.langCode = this.model.get("TargetLanguageCode"); // title this.$("#StepTitle").html(i18n.t('view.lblCreateProject')); // instructions this.$("#WizStepTitle").html(i18n.t('view.ttlProjectTargetLanguage')); this.$("#StepInstructions").html(i18n.t('view.dscProjectTargetLanguage')); // controls if (this.model.get("TargetDir") === "rtl") { this.$("#RTL").checked = true; } this.$("#LanguageVariant").html(this.model.get("TargetVariant")); this.$("#Prev").removeAttr('disabled'); break; case 3: // fonts currentView = new FontsView({ model: this.model}); // title $("#StepTitle").html(i18n.t('view.lblCreateProject')); // instructions $("#WizStepTitle").html(i18n.t('view.ttlProjectFonts')); $("#StepInstructions").html(i18n.t('view.dscProjectFonts')); break; case 4: // punctuation currentView = new PunctuationView({ model: this.model}); // title this.$("#StepTitle").html(i18n.t('view.lblCreateProject')); // instructions this.$("#WizStepTitle").html(i18n.t('view.ttlProjectPunctuation')); this.$("#StepInstructions").html(i18n.t('view.dscProjectPunctuation')); break; case 5: // cases currentView = new CasesView({ model: this.model}); // title this.$("#StepTitle").html(i18n.t('view.lblCreateProject')); // instructions this.$("#WizStepTitle").html(i18n.t('view.ttlProjectCases')); this.$("#StepInstructions").html(i18n.t('view.dscProjectCases')); // controls // Penultimate step -- enable the next button (only needed // if the user happens to back up from the last one) this.$("#lblNext").html(i18n.t('view.lblNext')); this.$("#imgNext").removeAttr("style"); break; case 6: // USFM filtering currentView = new USFMFilteringView({ model: this.model}); // title this.$("#StepTitle").html(i18n.t('view.lblCreateProject')); // instructions this.$("#WizStepTitle").html(i18n.t('view.ttlProjectFiltering')); this.$("#StepInstructions").html(i18n.t('view.dscProjectUSFMFiltering')); // controls // Last step -- change the text of the Next button to "finish" this.$("#lblNext").html(i18n.t('view.lblFinish')); this.$("#imgNext").attr("style", "display:none"); break; } this.container.show(currentView); } }); return { EditProjectView: EditProjectView, CopyProjectView: CopyProjectView, NewProjectView: NewProjectView, CasesView: CasesView, FontsView: FontsView, FontView: FontView, PunctuationView: PunctuationView, SourceLanguageView: SourceLanguageView, TargetLanguageView: TargetLanguageView, USFMFilteringView: USFMFilteringView }; });
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("lang/console_ja",function(e){e.Intl.add("console","ja",{title:"\u30ed\u30b0\u30b3\u30f3\u30bd\u30fc\u30eb",pause:"\u4e00\u6642\u505c\u6b62",clear:"\u30af\u30ea\u30a2",collapse:"\u9589\u3058\u308b",expand:"\u958b\u304f"})},"3.7.2");
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ name: String, password: String }); var User = mongoose.model('User', userSchema); module.exports = User;
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index', ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/', }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, include: __dirname, }, ], }, };
import forEach from '../../util/forEach' /** Index for Nodes. Node indexes are first-class citizens in {@link model/data/Data}. I.e., they are updated after each operation, and before any other listener is notified. @abstract */ class NodeIndex { /** Check if a node should be indexed. Used internally only. Override this in subclasses to achieve a custom behavior. @private @param {Node} @returns {Boolean} true if the given node should be added to the index. */ select(node) { // eslint-disable-line no-unused-vars throw new Error('This method is abstract.') } /** Called when a node has been created. @param {Node} node */ create(node) { // eslint-disable-line no-unused-vars throw new Error('This method is abstract.') } /** Called when a node has been deleted. @param {model/data/Node} node */ delete(node) { // eslint-disable-line no-unused-vars throw new Error('This method is abstract.') } set(node, path, newValue, oldValue) { this.update(node, path, newValue, oldValue) } /** Called when a property has been updated. @private @param {Node} node */ update(node, path, newValue, oldValue) { // eslint-disable-line no-unused-vars throw new Error('This method is abstract.') } /** Reset the index using a Data instance. @private */ reset(data) { this._clear() this._initialize(data) } /** Clone this index. @return A cloned NodeIndex. */ clone() { var NodeIndexClass = this.constructor var clone = new NodeIndexClass() return clone } _clear() { throw new Error('This method is abstract') } _initialize(data) { forEach(data.getNodes(), function(node) { if (this.select(node)) { this.create(node) } }.bind(this)) } } /** Create a new NodeIndex using the given prototype as mixin. @param {Object} prototype @returns {NodeIndex} A customized NodeIndex. */ NodeIndex.create = function(prototype) { var index = Object.assign(new NodeIndex(), prototype) index.clone = function() { return NodeIndex.create(prototype) } return index } /** Create a filter to filter nodes by type. @param {String} type @returns {function} */ NodeIndex.filterByType = function(type) { return function(node) { return node.isInstanceOf(type) } } export default NodeIndex
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M13 16h-2c-1.65 0-3 1.35-3 3v1h8v-1c0-1.65-1.35-3-3-3zm-1 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M16.13 15.13 18 3h-4V2h-4v1H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h2.23l.64 4.13C6.74 16.05 6 17.43 6 19v1c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2v-1c0-1.57-.74-2.95-1.87-3.87zM5 9V5h1.31l.62 4H5zm10.67-4-1.38 9H9.72L8.33 5h7.34zM16 20H8v-1c0-1.65 1.35-3 3-3h2c1.65 0 3 1.35 3 3v1z" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "12", cy: "18", r: "1" }, "2")], 'BlenderTwoTone'); exports.default = _default;
import { get } from "ember-metal/property_get"; import { forEach } from "ember-metal/enumerable_utils"; import normalizeSelf from "ember-htmlbars/utils/normalize-self"; import decodeEachKey from "ember-htmlbars/utils/decode-each-key"; export default function legacyEachWithControllerHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; // TODO: Correct falsy semantics if (!list || get(list, 'length') === 0) { if (blocks.inverse.yield) { blocks.inverse.yield(); } return; } forEach(list, function(item, i) { var self; if (blocks.template.arity === 0) { Ember.deprecate(deprecation); self = normalizeSelf(item); self = bindController(self, true); } var key = decodeEachKey(item, keyPath, i); blocks.template.yieldItem(key, [item, i], self); }); } function bindController(controller, isSelf) { return { controller: controller, hasBoundController: true, self: controller ? controller : undefined }; } export var deprecation = "Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead.";
(function() { CCJS.addPlugin({ title: 'table-generator', action: function(){ /* @TODO this is main task now. build table generator that's easy to use and very flexible. supposed to generate: the table elements and also a style element that's specially for the table */ var me = this, template = [ '<div data-button="" data-close-button="true">',this.language['close-popup'],'</div>', '<div data-content="">', '</div>' ]; me.showPopupElement(template.join(''), function(evt) { if (! evt.target.getAttribute('data-close-button')) return; }, me, true); }, category: "element", checkForSelectedElement: true }); })();
/* ========================================================== * bootstrap-carousel.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery);