code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import React from 'react'; export function MessagePanel(props, context) { let message = context.messenger.getMessage(); let messagePanel; if (message !== undefined) { messagePanel = ( <div className={ 'alert alert-' + message.type }> { message.text } </div> ); context.messenger.clearMessages(); } else { messagePanel = ( <div style={{ 'display': 'none' }}></div> ); } return messagePanel; } MessagePanel.contextTypes = { messenger: React.PropTypes.object };
mapkiwiz/sectorisation
src/client/app/panels/message.panel.js
JavaScript
agpl-3.0
534
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var Event = new Schema({ name: String, description: String, sport: String, place: { name: String, coords: { longitude: { type: Number }, latitude: { type: Number } }, address: {type: String, default: '', unique: true, trim: true}, landmarks: [{type: String, default: '', trim: true}], city : {type: String, default: '', trim: true}, }, when: Date, organizer: {type: Schema.ObjectId, ref: 'User'}, players: { 'yes': [{type: Schema.ObjectId, ref: 'User'}], 'no': [{type: Schema.ObjectId, ref: 'User'}], 'maybe': [{type: Schema.ObjectId, ref: 'User'}], 'none': [{type: Schema.ObjectId, ref: 'User'}] }, subscribers: [{type: Schema.ObjectId, ref: 'User'}], score: String, comments: [{ comment: String, commented_on: Date, by: {type: Schema.ObjectId, ref: 'User'} }], created_at: {type: Date, default: Date.now}, modified_at: {type: Date, default: Date.now} }); module.exports = mongoose.model('Event', Event);
asm-products/sportiz-backend
models/event.js
JavaScript
agpl-3.0
1,155
/* Places, Copyright 2014 Ansamb. This file is part of Places By Ansamb. Places By Ansamb is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Places By Ansamb 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 Affero GNU General Public License for more details. You should have received a copy of the Affero GNU General Public License along with Places By Ansamb. If not, see <http://www.gnu.org/licenses/>. */ module.exports = { up: function(migration, DataTypes, done) { migration.addColumn('places','request_id',{ type:DataTypes.STRING, allowNull:true, defaultValue:null }).success(function(res){ console.log("Migration to v0.0.4: Added request_id into table places",res); done() }); // add altering commands here, calling 'done' when finished }, down: function(migration, DataTypes, done) { // add reverting commands here, calling 'done' when finished done() } }
ansamb-places/places-application-runtime
core/migrations/application/20140402160700-migration-from-0.0.3-to-0.0.4.js
JavaScript
agpl-3.0
1,271
/*! jQuery UI - v1.10.3 - 2014-01-12 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.accordion.js, jquery.ui.progressbar.js, jquery.ui.slider.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.10.3", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.extend( $.ui, { // $.ui.plugin is deprecated. Use $.widget() extensions instead. plugin: { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args ) { var i, set = instance.plugins[ name ]; if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; } }); })( jQuery ); (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.10.3", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown."+this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click."+this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("."+this.widgetName); if ( this._mouseMoveDelegate ) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; $(document) .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) .bind("mouseup."+this.widgetName, this._mouseUpDelegate); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); })(jQuery); (function( $, undefined ) { $.ui = $.ui || {}; var cachedScrollbarWidth, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ); return { element: withinElement, isWindow: isWindow, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !$.support.offsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem : elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function () { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); }( jQuery ) ); (function( $, undefined ) { var uid = 0, hideProps = {}, showProps = {}; hideProps.height = hideProps.paddingTop = hideProps.paddingBottom = hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide"; showProps.height = showProps.paddingTop = showProps.paddingBottom = showProps.borderTopWidth = showProps.borderBottomWidth = "show"; $.widget( "ui.accordion", { version: "1.10.3", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next(), content: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); this._destroyIcons(); // clean up content panels contents = this.headers.next() .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { /*jshint maxcomplexity:15*/ if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown : function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter(":not(.ui-accordion-content-active)") .hide(); }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(), accordionId = this.accordionId = "ui-accordion-" + (this.element.attr( "id" ) || ++uid); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function( i ) { var header = $( this ), headerId = header.attr( "id" ), panel = header.next(), panelId = panel.attr( "id" ); if ( !headerId ) { headerId = accordionId + "-header-" + i; header.attr( "id", headerId ); } if ( !panelId ) { panelId = accordionId + "-panel-" + i; panel.attr( "id", panelId ); } header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", tabIndex: -1 }) .next() .attr({ "aria-expanded": "false", "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", tabIndex: 0 }) .next() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr({ "aria-expanded": "true", "aria-hidden": "false" }) .prev() .attr({ "aria-selected": "true", tabIndex: 0 }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[0].className = toHide.parent()[0].className; } this._trigger( "activate", null, data ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "ui.progressbar", { version: "1.10.3", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); })( jQuery ); (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { this.range = $([]); } }, _setupEvents: function() { var elements = this.handles.add( this.range ).filter( "a" ); this._off( elements ); this._on( elements, this._handleEvents ); this._hoverable( elements ); this._focusable( elements ); }, _destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal, true ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length-1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { /*jshint maxcomplexity:25*/ var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, click: function( event ) { event.preventDefault(); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); }(jQuery));
nccgroup/typofinder
TypoMagic/js/jquery-ui-1.10.3.custom.js
JavaScript
agpl-3.0
78,447
// This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. CKEDITOR.plugins.setLang('GeSHi', 'en', { langGeSHi : { title: 'GeSHi', label: 'Post syntax highlighted code', langLbl: 'Select language' } });
aarkerio/Centauro
webroot/js/ckeditor/plugins/GeSHi/lang/en.js
JavaScript
agpl-3.0
818
OC.L10N.register( "encryption", { "Missing recovery key password" : "Palautusavaimen salasana puuttuu", "Please repeat the recovery key password" : "Toista palautusavaimen salasana", "Repeated recovery key password does not match the provided recovery key password" : "Toistamiseen annettu palautusavaimen salasana ei täsmää annettua palautusavaimen salasanaa", "Recovery key successfully enabled" : "Palautusavain kytketty päälle onnistuneesti", "Could not enable recovery key. Please check your recovery key password!" : "Palautusavaimen käyttöönotto epäonnistui. Tarkista palautusavaimesi salasana!", "Recovery key successfully disabled" : "Palautusavain poistettu onnistuneesti käytöstä", "Could not disable recovery key. Please check your recovery key password!" : "Palautusavaimen poistaminen käytöstä ei onnistunut. Tarkista palautusavaimesi salasana!", "Missing parameters" : "Puuttuvat parametrit", "Please provide the old recovery password" : "Anna vanha palautussalasana", "Please provide a new recovery password" : "Anna uusi palautussalasana", "Please repeat the new recovery password" : "Toista uusi palautussalasana", "Password successfully changed." : "Salasana vaihdettiin onnistuneesti.", "Could not change the password. Maybe the old password was not correct." : "Salasanan vaihto epäonnistui. Kenties vanha salasana oli väärin.", "Recovery Key disabled" : "Palautusavain poistettu käytöstä", "Recovery Key enabled" : "Palautusavain käytössä", "Could not enable the recovery key, please try again or contact your administrator" : "Palautusavaimen käyttöönotto epäonnistui, yritä myöhemmin uudelleen tai ota yhteys ylläpitäjään", "Could not update the private key password." : "Yksityisen avaimen salasanaa ei voitu päivittää.", "The old password was not correct, please try again." : "Vanha salasana oli väärin, yritä uudelleen.", "The current log-in password was not correct, please try again." : "Nykyinen kirjautumiseen käytettävä salasana oli väärin, yritä uudelleen.", "Private key password successfully updated." : "Yksityisen avaimen salasana päivitettiin onnistuneesti.", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please run 'occ encryption:migrate' or contact your administrator" : "Salausavaimet tulee siirtää vanhasta salaustavasta (ownCloud <= 8.0) uuteen salaustapaan. Suorita 'occ encryption:migrate' tai ota yhteys ylläpitoon", "Invalid private key for Encryption App. Please update your private key password in your personal settings to recover access to your encrypted files." : "Salaussovelluksen salausavain on virheellinen. Ole hyvä ja päivitä salausavain henkilökohtaisissa asetuksissasi jotta voit taas avata salatuskirjoitetut tiedostosi.", "Encryption App is enabled and ready" : "Salaussovellus on käytössä ja valmis", "Bad Signature" : "Virheellinen allekirjoitus", "Missing Signature" : "Puuttuva allekirjoitus", "one-time password for server-side-encryption" : "kertakäyttöinen salasana palvelinpään salausta varten", "Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "Tämän tiedoston salauksen purkaminen ei onnistu. Kyseessä on luultavasti jaettu tiedosto. Pyydä tiedoston omistajaa jakamaan tiedosto kanssasi uudelleen.", "Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "Tiedostoa ei voi lukea, se on luultavasti jaettu tiedosto. Pyydä tiedoston omistajaa jakamaan tiedosto uudelleen kanssasi.", "The share will expire on %s." : "Jakaminen päättyy %s.", "Cheers!" : "Kiitos!", "Encryption App is enabled but your keys are not initialized, please log-out and log-in again" : "Salaussovellus on käytössä, mutta salausavaimia ei ole alustettu. Ole hyvä ja kirjaudu sisään uudelleen.", "Encrypt the home storage" : "Salaa oma kotitila", "Enable recovery key" : "Ota palautusavain käyttöön", "Disable recovery key" : "Poista palautusavain käytöstä", "The recovery key is an extra encryption key that is used to encrypt files. It allows recovery of a user's files if the user forgets his or her password." : "Palautusavain on ylimääräinen salausavain, jota käytetään tiedostojen salaamiseen. Sen avulla on mahdollista palauttaa käyttäjien tiedostot, vaikka käyttäjä unohtaisi oman salasanansa.", "Recovery key password" : "Palautusavaimen salasana", "Repeat recovery key password" : "Toista salausavaimen salasana", "Change recovery key password:" : "Vaihda palautusavaimen salasana:", "Old recovery key password" : "Vanha salausavaimen salasana", "New recovery key password" : "Uusi salausavaimen salasana", "Repeat new recovery key password" : "Toista uusi salausavaimen salasana", "Change Password" : "Vaihda salasana", "ownCloud basic encryption module" : "ownCloudin perussalausmoduuli", "Your private key password no longer matches your log-in password." : "Salaisen avaimesi salasana ei enää vastaa kirjautumissalasanaasi.", "Set your old private key password to your current log-in password:" : "Aseta yksityisen avaimen vanha salasana vastaamaan nykyistä kirjautumissalasanaasi:", " If you don't remember your old password you can ask your administrator to recover your files." : "Jos et muista vanhaa salasanaasi, voit pyytää ylläpitäjää palauttamaan tiedostosi.", "Old log-in password" : "Vanha kirjautumissalasana", "Current log-in password" : "Nykyinen kirjautumissalasana", "Update Private Key Password" : "Päivitä yksityisen avaimen salasana", "Enable password recovery:" : "Ota salasanan palautus käyttöön:", "Enabling this option will allow you to reobtain access to your encrypted files in case of password loss" : "Tämän valinnan käyttäminen mahdollistaa pääsyn salattuihin tiedostoihisi, jos salasana unohtuu", "Enabled" : "Käytössä", "Disabled" : "Ei käytössä" }, "nplurals=2; plural=(n != 1);");
jacklicn/owncloud
apps/encryption/l10n/fi_FI.js
JavaScript
agpl-3.0
6,194
'use strict'; import Flickity from 'flickity-imagesloaded' export default function LessonHeader() { console.log("-- LessonHeader initialized") let photosSelector = '.LessonHeader__photos' let $photos = $(photosSelector) if ($photos.length > 0) { let photoSelector = '.LessonHeader__photo' let $status = $('.LessonHeader__photos__status') let $current = $status.find('.current') let $total = $status.find('.total') // Init flickity for all carousels let flkty = new Flickity(photosSelector, { cellAlign: 'left', cellSelector: photoSelector, contain: true, pageDots: false, prevNextButtons: false, wrapAround: true, imagesLoaded: true, percentPosition: false, }) document.addEventListener("turbolinks:request-start", function() { flkty.destroy() }) $total.html($(photoSelector).length) flkty.on( 'select', function() { $current.html(flkty.selectedIndex + 1) }) return flkty } }
fablabbcn/SCOPESdf
assets/javascripts/components/LessonHeader.js
JavaScript
agpl-3.0
973
define([], function () { return function (distributor) { var container = document.createElement("ul") container.classList.add("filters") var div = document.createElement("div") function render(el) { el.appendChild(div) } function filtersChanged(filters) { while (container.firstChild) container.removeChild(container.firstChild) filters.forEach( function (d) { var li = document.createElement("li") container.appendChild(li) d.render(li) var button = document.createElement("button") button.textContent = "" button.onclick = function () { distributor.removeFilter(d) } li.appendChild(button) }) if (container.parentNode === div && filters.length === 0) div.removeChild(container) else if (filters.length > 0) div.appendChild(container) } return { render: render, filtersChanged: filtersChanged } } })
srauscher/hopglass
lib/filters/filtergui.js
JavaScript
agpl-3.0
1,004
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/> */ /* eslint-disable no-magic-numbers, camelcase */ import { DISCLOSURE_TYPE, DISCLOSURE_STEP, ROLES } from '../coi-constants'; import hashCode from '../hash'; export function createProject(sourceIdentifier) { return { title: 'TEST TITLE', typeCode: 1, sourceSystem: 'KC-PD', sourceIdentifier, sourceStatus: '1', sponsors: [ { sponsorCode: '000340', sponsorName: 'NIH', sourceSystem: 'KC-PD', sourceIdentifier } ], startDate: '2017-01-01', endDate: '2017-1-31' }; } export async function insertProject(knex, project) { const id = await knex('project').insert({ title: project.title, type_cd: project.typeCode, source_system: project.sourceSystem, source_identifier: project.sourceIdentifier, source_status: project.sourceStatus, start_date: new Date(project.startDate), end_date: new Date(project.endDate) }, 'id'); await knex('project_sponsor').insert({ project_id: id[0], source_identifier: project.sourceIdentifier, source_system: project.sourceSystem, sponsor_cd: project.sponsors[0].sponsorCode, sponsor_name: project.sponsors[0].sponsorName }); return id[0]; } export function createPerson(personId, roleCode, active) { return { personId, sourcePersonType: 'EMPLOYEE', roleCode, active }; } export async function insertProjectPerson(knex, projectPerson, projectId, dispositionTypeCd, isNew) { const id = await knex('project_person') .insert({ project_id: projectId, person_id: projectPerson.personId, source_person_type: projectPerson.sourcePersonType, role_cd: projectPerson.roleCode, active: projectPerson.active, disposition_type_cd: dispositionTypeCd, new: isNew !== undefined ? isNew : true },'id'); return id[0]; } export function createDisclosure(statusCd) { return { typeCd: DISCLOSURE_TYPE.ANNUAL, statusCd, startDate: new Date(), configId: 1 }; } export async function insertDisclosure(knex, disclosure, user_id) { const id = await knex('disclosure').insert({ type_cd: disclosure.typeCd, status_cd: disclosure.statusCd, user_id, start_date: new Date(disclosure.startDate), config_id: disclosure.configId, submitted_by: user_id }, 'id'); return id[0]; } export function createComment(disclosureId, user) { return { disclosureId, topicSection: DISCLOSURE_STEP.QUESTIONNAIRE, topicId: 1, text: 'blah', userId: hashCode(user), author: user, date: new Date(), piVisible: true, reviewerVisible: true }; } export async function insertComment(knex, disclosure_id, user, text) { const id = await knex('review_comment').insert({ disclosure_id, text: text || 'I like this.', topic_section: DISCLOSURE_STEP.QUESTIONNAIRE, topic_id: 1, date: new Date(), user_id: hashCode(user), user_role: ROLES.USER, author: user, pi_visible: false, reviewer_visible: true }, 'id'); return id[0]; } export async function getComment(knex, id) { const comments = await knex('review_comment') .select( 'id', 'disclosure_id as disclosureId', 'topic_section as topicSection', 'topic_id as topicId', 'text', 'user_id as userId', 'author', 'date', 'pi_visible as piVisible', 'reviewer_visible as reviewerVisible', 'user_role as userRole', 'editable', 'current' ) .where('id', id); return comments[0]; } export function createDeclaration(disclosureId, finEntityId, projectId) { return { disclosureId, finEntityId, projectId }; } export async function insertDeclaration(knex, declaration) { const id = await knex('declaration').insert({ disclosure_id: declaration.disclosureId, fin_entity_id: declaration.finEntityId, project_id: declaration.projectId }, 'id'); return id[0]; } export function createEntity(disclosureId, status, active) { return { disclosureId, status, active }; } export async function insertEntity(knex, entity) { const id = await knex('fin_entity') .insert({ disclosure_id: entity.disclosureId, status: entity.status, active: entity.active }, 'id'); return id[0]; } export function randomInteger(max = 1000000) { return Math.floor(Math.random() * max); } export async function asyncThrows(fn, ...params) { let errorThrown = false; try { await fn(...params); } catch (err) { errorThrown = true; } return errorThrown; } export async function cleanUp(knex, tableName, id, idColumnName = 'id') { await knex(tableName) .del() .where({ [idColumnName]: id }); }
kuali/research-coi
test/test-utils.js
JavaScript
agpl-3.0
5,482
import test from 'ava'; import {big64, get64} from '../../src/index.js'; function macro(t, a, o, expected) { expected = get64(...expected); t.deepEqual(big64(a, o), expected); } macro.title = (providedTitle, a, o, expected) => `${providedTitle || ''} big64(${a}, ${o}) === ${expected}`.trim(); test( macro, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 0, [0x00_00_00_00, 0x00_00_00_00], ); test( macro, [0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 0, [0xff_00_00_00, 0x00_00_00_00], ); test( macro, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00], 0, [0xff_ff_ff_ff, 0xff_ff_ff_00], ); test( macro, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 0, [0xff_ff_ff_ff, 0xff_ff_ff_ff], ); test( macro, [0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00], 0, [0x00_00_ff_00, 0x00_00_00_00], ); test( macro, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00], 0, [0x00_00_00_00, 0x00_00_01_00], ); test( macro, [0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x00], 0, [0x00_00_00_a0, 0x00_00_00_00], ); test( macro, [0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0c], 1, [0x00_00_a0_00, 0x00_00_00_03], );
aureooms/js-uint64
test/src/big64.js
JavaScript
agpl-3.0
1,153
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program 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 version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ var status = -1; function start(mode, type, selection) { if (mode == -1) { qm.dispose(); } else { if(mode == 0 && type > 0) { qm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { qm.sendNext("We're a pack of wolves looking for our lost child. I hear you are taking care of our baby. We appreciate your kindness, but it's time to return our baby to us.", 9); } else if (status == 1) { qm.sendNextPrev("Werewolf is my friend, I can't just hand over a friend.", 3); } else if (status == 2) { qm.sendAcceptDecline("We understand, but we won't leave without our pup. Tell you what, we'll test you to see if you are worthy of raising a wolf. #rGet ready to be tested by wolves.#k"); } else if (status == 3) { var em = qm.getEventManager("Aran_3rdmount"); if (em == null) { qm.sendOk("Sorry, but the 3rd mount quest (Wolves) is closed."); return; } else { var em = qm.getEventManager("Aran_3rdmount"); if (!em.startInstance(qm.getPlayer())) { qm.sendOk("There is currently someone in this map, come back later."); } else { qm.forceStartQuest(); } } } else if (status == 4) { qm.dispose(); } } }
ronancpl/MapleSolaxiaV2
scripts/quest/21613.js
JavaScript
agpl-3.0
2,413
bpmnGatewayInclusive=function(width,_30ab){ VectorFigure.call(this); this.stroke =1; }; bpmnGatewayInclusive.prototype=new VectorFigure; bpmnGatewayInclusive.prototype.type="bpmnGatewayInclusive"; bpmnGatewayInclusive.prototype.paint=function(){ VectorFigure.prototype.paint.call(this); if(typeof workflow.zoomfactor == 'undefined') workflow.zoomfactor = 1; //Set the Task Limitation if(typeof this.limitFlag == 'undefined' || this.limitFlag == false) { this.originalWidth = 40; this.originalHeight = 40; this.orgXPos = this.getX(); this.orgYPos = this.getY(); this.orgFontSize =this.fontSize; } this.width = this.originalWidth * workflow.zoomfactor; this.height = this.originalHeight * workflow.zoomfactor; var cw = this.getWidth(); var ch = this.getHeight(); var x=new Array(0,cw*0.5,cw,cw*0.5); var y=new Array(ch*0.5,ch,ch*0.5,0); //var x=new Array(0,this.width/2,this.width,this.width/2); //var y=new Array(this.height/2,this.height,this.height/2,0); var x2 = new Array(); var y2 = new Array(); for(var i=0;i<x.length;i++){ x2[i]=x[i]+4; y2[i]=y[i]+1; } this.graphics.setStroke(this.stroke); this.graphics.setColor( "#c0c0c0" ); this.graphics.fillPolygon(x2,y2); this.graphics.setStroke(1); this.graphics.setColor( "#ffffe5" ); this.graphics.fillPolygon(x,y); this.graphics.setColor("#c8c865"); this.graphics.drawPolygon(x,y); var x_cir = 15; var y_cir = 15; this.graphics.setColor("#c8c865"); this.graphics.drawEllipse(this.getWidth()/4,this.getHeight()/4,this.getWidth()/2,this.getHeight()/2); this.graphics.paint(); if (this.input1 != null) { this.input1.setPosition(0, this.height / 2); } if (this.input2 != null) { this.input2.setPosition(this.width / 2, 0); } if (this.output1 != null) { this.output1.setPosition(this.height / 2, this.width); } if (this.output2 != null) { this.output2.setPosition(this.width, this.height / 2); } if (this.output3 != null) { this.output3.setPosition(0, this.height /2 ); } }; bpmnGatewayInclusive.prototype.setWorkflow=function(_40c5){ VectorFigure.prototype.setWorkflow.call(this,_40c5); if(_40c5!=null){ var h2 = this.height/2; var w2 = this.width/2; var gatewayPortName = ['output1', 'output2', 'output3', 'input1', 'input2' ]; var gatewayPortType = ['OutputPort','OutputPort','OutputPort','InputPort','InputPort']; var gatewayPositionX= [w2, this.width, 0 , 0, w2 ]; var gatewayPositionY= [this.width, h2, h2, h2, 0 ]; for(var i=0; i< gatewayPortName.length ; i++){ eval('this.'+gatewayPortName[i]+' = new '+gatewayPortType[i]+'()'); //Create New Port eval('this.'+gatewayPortName[i]+'.setWorkflow(_40c5)'); //Add port to the workflow eval('this.'+gatewayPortName[i]+'.setName("'+gatewayPortName[i]+'")'); //Set PortName eval('this.'+gatewayPortName[i]+'.setZOrder(-1)'); //Set Z-Order of the port to -1. It will be below all the figure eval('this.'+gatewayPortName[i]+'.setBackgroundColor(new Color(255, 255, 255))'); //Setting Background of the port to white eval('this.'+gatewayPortName[i]+'.setColor(new Color(255, 255, 255))'); //Setting Border of the port to white eval('this.addPort(this.'+gatewayPortName[i]+','+gatewayPositionX[i]+', '+gatewayPositionY[i]+')'); //Setting Position of the port } } }; bpmnGatewayInclusive.prototype.getContextMenu=function(){ if(this.id != null){ this.workflow.handleContextMenu(this); } };
carbonadona/pm
workflow/engine/templates/bpmn/GatewayInclusive.js
JavaScript
agpl-3.0
3,734
/* This file is part of Archivematica. Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com> Archivematica is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Archivematica 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 General Public License for more details. You should have received a copy of the GNU General Public License along with Archivematica. If not, see <http://www.gnu.org/licenses/>. */ var enableElements = function(cssSelectors) { for (var index in cssSelectors) { $(cssSelectors[index]).removeAttr('disabled'); } }; var disableElements = function(cssSelectors) { for (var index in cssSelectors) { $(cssSelectors[index]).attr('disabled', 'disabled'); } }; function setupBacklogBrowser() { var backlogBrowserEntryClickHandler = function(event) { if (typeof event.data != 'undefined') { var explorer = event.data.self.container , explorerId = explorer.id var entryEl = this , entryId = $(this).attr('id') , borderCssSpec = '1px solid red'; if (explorer.selectedEntryId == entryId) { // un-highlight selected entry $(entryEl).css('border', ''); // remove selected entry explorer.selectedEntryId = undefined; } else { // remove highlighting of existing entries $('#' + explorerId).find('.backbone-file-explorer-entry').css('border', ''); // highlight selected entry $(entryEl).css('border', borderCssSpec); // change selected entry explorer.selectedEntryId = entryId; // enable/disable arrange panel action buttons if (explorer.id == 'originals') { enableOrDisableOriginalsPanelActionButtons(explorer); } // enable/disable arrange panel action buttons if (explorer.id == 'arrange') { enableOrDisableArrangePanelActionButtons(explorer); } } } } function enableOrDisableOriginalsPanelActionButtons(originals) { var selectedType = originals.getTypeForCssId(originals.selectedEntryId); // enable/disable hide button if (typeof originals.selectedEntryId !== 'undefined') { enableElements(['#originals_hide_button']); } else { disableElements(['#originals_hide_button']); } // enable/disable buttons for actions that only work with files if (typeof originals.selectedEntryId !== 'undefined' && selectedType == 'file') { enableElements(['#open_originals_file_button']); } else { disableElements(['#open_originals_file_button']); } } function enableOrDisableArrangePanelActionButtons(arrange) { var selectedType = arrange.getTypeForCssId(arrange.selectedEntryId); // enable/disable delete button if (typeof arrange.selectedEntryId !== 'undefined') { enableElements(['#arrange_delete_button']); } else { disableElements(['#arrange_delete_button']); } // enable/disable create SIP button if (selectedType == 'directory') { enableElements(['#arrange_create_sip_button']); } else { disableElements(['#arrange_create_sip_button']); } // enable/disable metadata button if (typeof arrange.selectedEntryId !== 'undefined') { enableElements(['#arrange_edit_metadata_button']); } else { disableElements(['#arrange_edit_metadata_button']); } // enable/disable create directory button // (if nothing is selected, it'll create in top level) if (typeof arrange.selectedEntryId === 'undefined' || selectedType == 'directory') { enableElements(['#arrange_create_directory_button']); } else { disableElements(['#arrange_create_directory_button']); } } function moveHandler(move) { // don't allow moving anything into the originals directory if (move.self.id == 'originals') { move.self.alert('Error', "You can't copy into the originals directory."); return; } if (!move.allowed) { move.self.alert('Error', "You can't move a directory into its subdirectory."); return; } // move.self is the arrange browser move.self.busy(); // determine whether a move or copy should be performed var source, actionUrlPath = '/filesystem/copy_to_arrange/', arrangeDir = '/'+Base64.decode(move.self.structure.name); // do a move if drag and drop occurs within the arrange pane if ( move.droppedPath.indexOf(arrangeDir) == 0 && move.containerPath.indexOf(arrangeDir) == 0 ) { // arrange -> arrange source = move.self.getByPath(move.droppedPath) } else { // originals -> arrange // TODO don't use global if possible source = originals.getByPath(move.droppedPath) } var destination = move.self.getByPath(move.containerPath); // Add trailing / to directories if (source.type() == 'directory') { move.droppedPath+='/' } if (typeof destination == 'undefined') { // Moving into the parent directory arrange/ // Error if source is a file if (source.type() != 'directory') { move.self.alert('Error', "Files must go in a SIP, not the parent directory."); } move.containerPath = arrangeDir+'/' } else if (destination.type() == 'directory') { move.containerPath+='/' } else if (destination.type() == 'file') { move.containerPath = move.containerPath.match(/.*\//)[0]; } $.post( actionUrlPath, { filepath: Base64.encode(move.droppedPath), destination: Base64.encode(move.containerPath) }, function(result) { if (result.error == undefined) { move.self.idle(); move.self.render(); $('#search_submit').click(); // Fetches from backlog again and renders it } else { alert(result.message); move.self.idle(); } } ); } var originals = new FileExplorer({ el: $('#originals'), levelTemplate: $('#template-dir-level').html(), entryTemplate: $('#template-dir-entry').html(), entryClickHandler: backlogBrowserEntryClickHandler, nameClickHandler: backlogBrowserEntryClickHandler, // Data will be populated by backlog.js when a search is conducted }); originals.structure = { 'name': Base64.encode('originals'), 'parent': '', 'children': [] }; originals.itemsPerPage = 10; originals.moveHandler = moveHandler; originals.options.actionHandlers = []; originals.render(); enableOrDisableOriginalsPanelActionButtons(originals); var arrange = new FileExplorer({ el: $('#arrange'), levelTemplate: $('#template-dir-level').html(), entryTemplate: $('#template-dir-entry').html(), entryClickHandler: backlogBrowserEntryClickHandler, nameClickHandler: backlogBrowserEntryClickHandler, ajaxDeleteUrl: '/filesystem/delete/arrange/', ajaxChildDataUrl: '/filesystem/contents/arrange/' }); arrange.structure = { 'name': Base64.encode('arrange'), 'parent': '', 'children': [] }; arrange.itemsPerPage = 10; arrange.options.actionHandlers = []; arrange.moveHandler = moveHandler; arrange.render(); enableOrDisableArrangePanelActionButtons(arrange); // search results widget var originals_search_results = new fileBrowser.EntryList({ el: $('#originals_search_results'), moveHandler: moveHandler, levelTemplate: $('#template-dir-level').html(), entryTemplate: $('#template-dir-entry').html(), itemsPerPage: 20 }); return { 'originals': originals, 'arrange': arrange }; } // spawn browsers var originals_browser, arrange_browser; $(document).ready(function() { // Monkey-patch entry toggling logic to allow auto-search of backlog (function(originalToggleDirectoryLogic) { var backlogSearched = false; fileBrowser.EntryView.prototype.toggleDirectory = function($el) { var result = originalToggleDirectoryLogic.apply(this, arguments); // if toggling in the original panels, check to see if backlog entries have been // added to it yet and, if not, perform search if (this.container.id == 'originals' && this.container.structure.children.length == 0 && backlogSearched == false ) { backlogSearched = true; $('#search_submit').click(); } return result; }; })(fileBrowser.EntryView.prototype.toggleDirectory); var browsers = setupBacklogBrowser(); originals_browser = browsers['originals']; arrange_browser = browsers['arrange']; originals_browser.display_data = function(data) { // Accept and display data from an external source // Assumes it is properly formatted already this.structure.children = data; // Open top level folder this.openFolder($('#'+this.id+'__'+Base64.decode(this.structure.name))) this.render(); } $('#arrange_edit_metadata_button').click(function() { // if metadata button isn't disabled, execute if (typeof $('#arrange_edit_metadata_button').attr('disabled') === 'undefined') { if (typeof arrange_browser.selectedEntryId === 'undefined') { arrange_browser.alert('Edit metadata', 'Please select a directory or file to edit.'); return; } var path = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId); directoryMetadataForm.show(path, function(levelOfDescription) { var entry = arrange_browser.getByPath(path); entry.set({'levelOfDescription': levelOfDescription}); arrange_browser.render(); }); } }); $('#arrange_create_directory_button').click(function() { // if create directory button isn't disabled, execute if (typeof $('#arrange_create_directory_button').attr('disabled') === 'undefined') { var selectedType = arrange_browser.getTypeForCssId(arrange_browser.selectedEntryId); if (selectedType != 'directory' && typeof arrange_browser.selectedEntryId !== 'undefined') { arrange_browser.alert('Create Directory', "You can't create a directory in a file."); } else { var path = prompt('Name of new directory?'); if (path) { var path_root = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId) || '/' + Base64.decode(arrange_browser.structure.name) , relative_path = path_root + '/' + path; $.ajax({ url: '/filesystem/create_directory_within_arrange/', type: 'POST', async: false, cache: false, data: { path: Base64.encode(relative_path) }, success: function(results) { arrange_browser.dirView.model.addDir({'name': path}); arrange_browser.render(); }, error: function(results) { originals_browser.alert('Error', results.message); } }); } } } }); $('#arrange_delete_button').click(function() { if (typeof arrange_browser.selectedEntryId === 'undefined') { arrange_browser.alert('Delete', 'Please select a directory or file to delete.'); return; } var path = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId) , type = arrange_browser.getTypeForCssId(arrange_browser.selectedEntryId); arrange_browser.confirm( 'Delete', 'Are you sure you want to delete this directory or file?', function() { if( type == 'directory') { path += '/' } arrange_browser.deleteEntry(path, type); arrange_browser.selectedEntryId = undefined; $('#search_submit').click(); } ); }); // Hide the selected object $('#originals_hide_button').click(function () { // Have to hide all its children too or weird behaviour $('#' + originals_browser.selectedEntryId).next().hide(); $('#' + originals_browser.selectedEntryId).hide(); }); // create SIP button functionality $('#arrange_create_sip_button').click(function() { // if create SIP button isn't disabled, execute if (typeof $('#arrange_create_sip_button').attr('disabled') === 'undefined') { if (typeof arrange_browser.selectedEntryId === 'undefined') { arrange_browser.alert('Create SIP', 'Please select a directory before creating a SIP.'); return } var entryDiv = $('#' + arrange_browser.selectedEntryId) , path = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId) , entryObject = arrange_browser.getByPath(path) if (entryObject.type() != 'directory') { arrange_browser.alert('Create SIP', 'SIPs can only be created from directories, not files.') return } arrange_browser.confirm( 'Create SIP', 'Are you sure you want to create a SIP?', function() { $('.activity-indicator').show(); $.post( '/filesystem/copy_from_arrange/', {filepath: Base64.encode(path+'/')}, function(result) { $('.activity-indicator').hide(); var title = (result.error) ? 'Error' : '' arrange_browser.alert( title, result.message ) if (!result.error) { $(entryDiv).next().hide() $(entryDiv).hide() } } ) } ) } }); var createOpenHandler = function(buttonCssSelector, browser) { return function() { // if view button isn't disabled, execute if (typeof $(buttonCssSelector).attr('disabled') === 'undefined') { if (typeof browser.selectedEntryId === 'undefined') { browser.alert('Error', 'Please specifiy a file to view.'); } else { var entryDiv = $('#' + browser.selectedEntryId) , path = browser.getPathForCssId(browser.selectedEntryId) , type = browser.getTypeForCssId(browser.selectedEntryId); if (type == 'directory') { browser.alert('Error', 'Please specifiy a file to view.'); } else { window.open( '/filesystem/download_ss/?filepath=' + encodeURIComponent(Base64.encode(path)), '_blank' ); } } } }; }; // open originals file button functionality $('#open_originals_file_button').click(createOpenHandler('#open_originals_file_button', originals_browser)); });
sevein/archivematica
src/dashboard/src/media/js/ingest/ingest_file_browser.js
JavaScript
agpl-3.0
14,811
import SPELLS from 'common/SPELLS/index'; /* * Fields: * int: spell scales with Intellect * crit: spell scales with (is able to or procced from) Critical Strike * hasteHpm: spell does more healing due to Haste, e.g. HoTs that gain more ticks * hasteHpct: spell can be cast more frequently due to Haste, basically any spell except for non haste scaling CDs * mastery: spell is boosted by Mastery * masteryStack: spell's HoT counts as a Mastery Stack * vers: spell scales with Versatility * multiplier: spell scales with whatever procs it, should be ignored for purpose of weights and for 'total healing' number * ignored: spell should be ignored for purpose of stat weights */ // This only works with actual healing events; casts are not recognized. export default { [SPELLS.LEECH.id]: { // procs a percent of all your healing, so we ignore for weights and total healing multiplier: true, }, [SPELLS.XAVARICS_MAGNUM_OPUS.id]: { // Prydaz int: false, crit: false, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.HEALTHSTONE.id]: { int: false, crit: false, hasteHpct: false, mastery: false, vers: true, // confirmed }, [SPELLS.COASTAL_HEALING_POTION.id]: { int: false, crit: false, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.MARK_OF_THE_ANCIENT_PRIESTESS.id]: { int: false, crit: true, hasteHpct: false, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/zxXDd7CJFbLQpHGM/#fight=12&source=3&type=summary [SPELLS.RESOUNDING_PROTECTION_ABSORB.id]: { // General Azerite Power int: false, crit: false, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.IMPASSIVE_VISAGE_HEAL.id]: { int: false, crit: true, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.VAMPIRIC_SPEED_HEAL.id]: { // General(?) Azerite trait int: false, crit: true, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.STALWART_PROTECTOR.id]: { // General Paladin Azerite Power int: false, crit: false, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.REJUVENATING_TIDES.id]: { // Darkmoon Deck: Tides int: false, crit: true, hasteHpct: false, mastery: false, vers: true, }, [SPELLS.TOUCH_OF_THE_VOODOO.id]: { // Revitalizing Voodoo Totem int: false, crit: true, hasteHpct: false, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/zxXDd7CJFbLQpHGM/#fight=12&source=3 [SPELLS.CONCENTRATED_MENDING_HEALING.id]: { // Healing Azerite Power int: false, crit: true, hasteHpm: true, mastery: true, // TODO: Re-evaluate, going on word of mouth and I have my doubts vers: true, }, // https://www.warcraftlogs.com/reports/cXnPABVbLjk68qyM#fight=6&type=healing&source=10 271682: { // Harmonious Chord - Lady Waycrest's Music Box (trinket) int: false, crit: true, hasteHpct: false, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/cXnPABVbLjk68qyM#fight=6&type=healing&source=10&ability=267537&view=events 267537: { // Coastal Surge (Weapon enchant) int: false, crit: true, hasteHpct: false, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/axKCmGyfgXFw6QVL/#fight=28&source=156 [SPELLS.BLESSED_PORTENTS_HEAL.id]: { // General Azerite Power int: false, crit: true, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/axKCmGyfgXFw6QVL/#fight=28&source=156 [SPELLS.BRACING_CHILL_HEAL.id]: { // General Azerite Power int: false, crit: true, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/fKaZdyWcQYAwTtz2/#fight=4&source=9&type=healing&options=8 [SPELLS.AZERITE_FORTIFICATION.id]: { // General Azerite Power int: false, crit: true, hasteHpct: false, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/fKaZdyWcQYAwTtz2/#fight=4&source=9&type=healing&options=8 [SPELLS.AZERITE_VEINS.id]: { // General Azerite Power int: false, crit: true, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/fKaZdyWcQYAwTtz2/#fight=4&source=9&type=healing&options=8 [SPELLS.SAVIOR.id]: { // General Azerite Power int: false, crit: true, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/LpM43CgfYQ9ntXyz/#fight=4&source=3 [SPELLS.LASER_MATRIX_HEAL.id]: { // General Azerite trait int: false, crit: true, hasteHpm: true, mastery: false, vers: true, }, // https://www.warcraftlogs.com/reports/LpM43CgfYQ9ntXyz/#fight=4&source=3 [SPELLS.MUTATING_ANTIBODY.id]: { // Inoculating Extract int: false, crit: true, hasteHpct: false, mastery: false, vers: true, }, };
FaideWW/WoWAnalyzer
src/parser/shared/modules/features/SpellInfo.js
JavaScript
agpl-3.0
5,070
/** * @author Anakeen * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License */ // Utility function to add an event listener function addEvent(o,e,f){ if (o.addEventListener){ o.addEventListener(e,f,true); return true; } else if (o.attachEvent){ return o.attachEvent("on"+e,f); } else { return false; } } // Utility function to send an event // o the object // en the event name : mouseup, mouseodwn function sendEvent(o,en) { if (o) { if( document.createEvent ) { // var ne=document.createEvent("HTMLEvents"); var ne; if ((en.indexOf('mouse') > -1)||(en.indexOf('click') > -1)) ne=document.createEvent("MouseEvents"); else ne=document.createEvent("HTMLEvents"); ne.initEvent(en,true,true); o.dispatchEvent(ne); } else { try { o.fireEvent( "on"+en ); } catch (ex) { ; } } } } Ext.fdl.Document = Ext.extend(Ext.Panel, { document: null, context: null, mode: 'view', forceExt: false, forceClassic: false, displayToolbar: true, displaynotes: true, notes: [], layout: 'fit', toString: function(){ return 'Ext.fdl.Document'; }, initComponent: function(){ if(!this.document){ console.log('Ext.fdl.Document is not provided a document.'); } this.context = this.document.context; if(this.displayToolbar){ this.tbar = new Ext.Toolbar({ enableOverflow: true, hidden: true, height: 28 }); } Ext.fdl.Document.superclass.initComponent.call(this); this.on({ afterrender: { fn: function(){ this.switchMode(this.mode); var o = this; (function(){ o.viewNotes(); }).defer(1000); fdldoc = this.document; (function(){ fdldoc.addUserTag({ tag: 'VIEWED' }); }).defer(1000); }, scope: this } }); }, setDocument: function(document){ this.document = document ; }, reload: function(){ this.switchMode(this.mode); }, switchMode: function(mode){ var me = this ; if (this.showMask) { this.showMask(); } this.removeAll(); switch (mode) { case 'view': if ((this.document.getProperty('generateVersion') == 3 && !this.forceClassic)|| this.forceExt) { var dcv = this.document.getDefaultConsultationView(); var subPanel = new Ext.fdl.SubDocument({ document: this.document, config: this.config }); subPanel.on('close',function(){ this.fireEvent('close',this); },this); subPanel.switchMode = function(mode){ me.switchMode(mode); }; if (dcv) { if (!eval('window.' + dcv.extwidget)) { // Dynamically add Javascript file this.includeJS(dcv.extsrc); } // Override document with extended behaviours Ext.apply(subPanel, eval('window.' + dcv.extwidget)); } else { Ext.apply(subPanel, Ext.fdl.DocumentDefaultView); } this.add(subPanel); subPanel.on('afterrender',function(){ subPanel.display(); }); } else { this.renderViewClassic(); } break; case 'edit': case 'create': //var dev = this.document.getDefaultEditionView(); if ((this.document.getProperty('generateVersion') == 3 && !this.forceClassic) || this.forceExt) { var dev = this.document.getDefaultEditionView(); var subPanel = new Ext.fdl.SubDocument({ document: this.document, mode: mode, config: this.config }); subPanel.on('close',function(){ this.fireEvent('close',this); },this); subPanel.switchMode = function(mode){ me.switchMode(mode); }; if (dev) { if (!eval('window.' + dev.extwidget)) { // Dynamically add Javascript file this.includeJS(dev.extsrc); } // Override document with extended behaviours Ext.apply(subPanel, eval('window.' + dev.extwidget)); } else { Ext.apply(subPanel, Ext.fdl.DocumentDefaultEdit); } this.add(subPanel); subPanel.on('afterrender',function(){ subPanel.display(); }); } else { this.renderEditClassic(); } break; default: break; }; this.mode = mode; // Do layout will not work on render. It must not be called first time. if (this.firstLayout) { this.doLayout(); } this.firstLayout = true; if (this.hideMask) { this.hideMask(); } }, generateMenu: function(panel,menu,mediaObject){ var me = this ; //console.log('GENERATE MENU',panel,menu,mediaObject.dom); //panel.getTopToolbar().removeAll(); menu.removeAll(); var documentMenu = mediaObject.dom.contentWindow.documentMenu; //console.log('DOCUMENT MENU',documentMenu); var documentId = (mediaObject.dom.contentWindow.document.getElementsByName('document-id').length > 0) ? mediaObject.dom.contentWindow.document.getElementsByName('document-id')[0].content : '' ; //console.log('DOCUMENT ID', documentId); var document = this.context.getDocument({ id: documentId, useCache:true, latest: false }); if(document && document.id){ this.setDocument(document); //console.log('DOCUMENT',documentId,me.document.getTitle()); //me.publish('modifydocument',me.document); } for(var name in documentMenu){ var menuObject = documentMenu[name]; var menuItem = Ext.fdl.MenuManager.getMenuItem(menuObject,{ widgetDocument:me, documentId:documentId, panel: panel, mediaObject: mediaObject, context: this.context, menu: menu }); console.log('MENU ITEM',menuItem); menu.add(menuItem); } menu.add(new Ext.Toolbar.Fill()); var toolbarStatus = me.documentToolbarStatus(); for (var i = 0; i < toolbarStatus.length; i++) { if (toolbarStatus[i]) { menu.add(toolbarStatus[i]); } } menu.doLayout(); menu.show(); mediaObject.dom.contentWindow.displaySaveForce = function(){ if (mediaObject.dom.contentWindow.documentMenu.saveforce) { mediaObject.dom.contentWindow.documentMenu.saveforce.visibility = 1 ; me.generateMenu(panel,menu,mediaObject); } }; }, // If this function returns a string, confirm when closing this document displaying this string. // This method is used in Ext.fdl.Window to check if document can be closed with ou without confirm. closeConfirm: function(){ if(this.mediaObject){ try { if(this.mediaObject.dom.contentWindow.beforeUnload){ var beforeUnload = this.mediaObject.dom.contentWindow.beforeUnload(); return beforeUnload ; } } catch(exception) { } } return false; }, renderViewClassic: function(){ //console.log('RENDER VIEW CLASSIC DOCUMENT ID',this.document.id); var me = this ; if(!this.config){ this.config = {}; } if(!this.config.targetRelation){ //this.config.targetRelation = 'Ext.fdl.Document.prototype.publish("opendocument",null,%V%,"view")'; } console.log('CONFIG',this.config); delete this.config.opener ; var sconf=''; if (this.config && this.document.context) sconf=JSON.stringify(this.config); //console.log(this.config); //console.log(JSON.stringify(this.config)); if(this.config.url){ var url = this.config.url ; url = url.replace(new RegExp("(action=FDL_CARD)","i"),"action=VIEWEXTDOC"); //url = this.document.context.url + url ; console.log('Calculated URL',url); } else { url = this.document.context.url + '?app=FDL&action=VIEWEXTDOC&id=' + this.document.getProperty('id') + '&extconfig='+encodeURI(sconf); } var mediaPanel = new Ext.ux.MediaPanel({ style: 'height:100%;', bodyStyle: 'height:100%;', border: false, autoScroll: false, mediaCfg: { mediaType: 'HTM', url: url }, listeners : { mediaload : function(panel,mediaObject){ me.mediaObject = mediaObject; var menu = me.getTopToolbar(); console.log('MEDIA OBJECT',mediaObject); me.generateMenu(panel,menu,mediaObject); addEvent(mediaObject.dom,'load',function(){ var menu = me.getTopToolbar(); console.log('MEDIA OBJECT',mediaObject); me.generateMenu(panel,menu,mediaObject); }); } } }); this.add(mediaPanel); this.doLayout(); }, renderEditClassic: function(){ var me = this ; if(!this.config){ this.config = {}; } if(this.config.url){ var url = this.config.url ; url = url.replace(new RegExp("(app=GENERIC)","i"),"app=FDL"); url = url.replace(new RegExp("(action=GENERIC_EDIT)","i"),"action=EDITEXTDOC"); //url = this.document.context.url + url ; console.log('Calculated URL',url); } else { var url = this.document.context.url + '?app=FDL&action=EDITEXTDOC&classid=' + this.document.getProperty('fromid') + '&id=' + this.document.getProperty('id'); } var mediaPanel = new Ext.ux.MediaPanel({ style: 'height:100%;', bodyStyle: 'height:100%;', border: false, autoScroll: false, mediaCfg: { mediaType: 'HTM', url: url }, listeners : { mediaload : function(panel,mediaObject){ me.mediaObject = mediaObject; var menu = me.getTopToolbar(); console.log('MEDIA OBJECT(1)',mediaObject); me.generateMenu(panel,menu,mediaObject); addEvent(mediaObject.dom,'load',function(){ var menu = me.getTopToolbar(); console.log('MEDIA OBJECT(2)',mediaObject); me.generateMenu(panel,menu,mediaObject); }); } } }); this.add(mediaPanel); this.doLayout(); }, displayUrl: function(url,target,config){ this.publish('openurl',url,target,config); }, addNote: function(){ var note = this.document.context.createDocument({ familyId: 'SIMPLENOTE', mode: 'view' }); if (note) { note.setValue('note_pasteid', this.document.getProperty('initid')); note.setValue('note_width', 200); note.setValue('note_height', 200); note.setValue('note_top', 50); note.setValue('note_left', 50); note.save(); this.document.reload(); var nid=note.getProperty('initid'); this.viewNotes(); var wnid = this.notes[nid]; if (wnid) { var p = wnid.items.itemAt(0); //console.log("note",p); setTimeout(function(){ p.items.itemAt(0).items.itemAt(0).setVisible(false); p.items.itemAt(0).items.itemAt(1).setVisible(true); p.items.itemAt(0).items.itemAt(2).setVisible(true); p.items.itemAt(0).items.itemAt(3).setVisible(true); p.items.itemAt(0).items.itemAt(1).focus(); }, 1000); } } }, viewNotes: function(config){ var noteids = this.document.getProperty('postitid'); if (noteids.length > 0) { for (var i = 0; i < noteids.length; i++) { if (noteids[i] > 0) { var note; if (!this.notes[noteids[i]]) { note = this.document.context.getDocument({ id: noteids[i] }); var wd = new Ext.fdl.Document({ style: 'padding:0px;margin:0px;', bodyStyle: 'padding:0px;margin:0px;', document: note, anchor: '100% 100%', displayToolbar: false, listeners: {close: function (panel) { panel.ownerCt.close(); }} }); this.notes[noteids[i]] = wd; } else { note = this.notes[noteids[i]].document; } if (note.isAlive()) { var color = 'yellow'; var nocolor = note.getValue('note_color'); if (nocolor) color = nocolor; var x = parseInt(note.getValue('note_left')); var y = parseInt(note.getValue('note_top')); if ((!this.notes[noteids[i]].window) || (this.notes[noteids[i]].window.getWidth() == 0)) { var notewin = new Ext.Window({ layout: 'fit', cls: 'x-fdl-note', style: 'padding:0px;margin:0px;background-color:' + color, title: note.getTitle(), closeAction: 'hide', width: parseInt(note.getValue('note_width')), height: parseInt(note.getValue('note_height')), resizable: true, note: note, tools: [{ id: 'close', qtip: 'Cacher la note', // hidden:true, handler: function(event, toolEl, panel){ panel.setVisible(false); } }], plain: true, renderTo: this.body, constrain: true, items: [this.notes[note.id]], x: x, y: y, listeners: { move: function(o){ if (this.note && (this.note.getProperty('owner') == this.note.context.getUser().id)) { var xy = o.getPosition(true); if ((o.getWidth() > 0) && (xy[0] > 0)) { this.note.setValue('note_width', o.getWidth()); this.note.setValue('note_height', o.getHeight()); this.note.setValue('note_left', xy[0]); this.note.setValue('note_top', xy[1]); this.note.save(); } } }, close: function(o){ } } }); this.notes[noteids[i]].window = notewin; notewin.show(); } else { if (config && config.undisplay) this.notes[noteids[i]].window.setVisible(false); else this.notes[noteids[i]].window.setVisible(true); } } } } } }, includeJS: function(url){ console.log('Include JS', url); if (window.XMLHttpRequest) { var XHR = new XMLHttpRequest(); } else { var XHR = new ActiveXObject("Microsoft.XMLHTTP"); } if (XHR) { XHR.open("GET", (this.document.context.url + url), false); XHR.send(null); eval(XHR.responseText); } else { return false; } }, detailSearch: function(){ return new Ext.fdl.DSearch({ document: this.document, hidden: true, border: false }); }, documentToolbarStatus: function(){ // If document is in creation mode, no toolbar status to display if(!this.document.id){ return false ; } var u = this.document.context.getUser(); var info = u.getInfo(); var statestatus = null; var statestatustext = ''; if(this.document.getProperty('version')){ console.log('VERSION',this.document.getProperty('version')); statestatustext = 'version ' + this.document.getProperty('version')+' '; } if (this.document.hasWorkflow()){ if(this.document.isFixed()) { statestatustext += '<i>' + '<span style="padding-left:10px;margin-right:3px;background-color:' + this.document.getColorState() + '">&nbsp;</span>' + this.document.getLocalisedState() + '</i>'; } else { if (this.document.getActivityState()) { statestatustext += '<i>' + this.document.getActivityState() + '</i>'; } else { statestatustext += '<i>' + this.document.getLocalisedState() + '</i>'; } } } if(statestatustext){ statestatus = new Ext.Toolbar.TextItem(statestatustext); } var lockstatus = null; if (this.document.getProperty('locked') > 0) { if (this.document.getProperty('locked') == info['id']) { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Verrouillé par ' + this.document.getProperty('locker') + '" src="' + this.document.context.url + 'FDL/Images/greenlock.png" style="height:16px" />'); } else { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Vérrouillé par ' + this.document.getProperty('locker') + '" src="' + this.document.context.url + 'FDL/Images/redlock.png" style="height:16px" />'); } } var readstatus = null; if (this.document.getProperty('locked') == -1) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Figé" src="' + this.document.context.url + 'FDL/Images/readfixed.png" style="height:16px" />'); } else if (!this.document.canEdit()) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Lecture seule" src="' + this.document.context.url + 'FDL/Images/readonly.png" style="height:16px" />'); } var postitstatus = null; if (this.document.getProperty('postitid').length > 0) { //console.log(this.document.getProperty('postitid')); postitstatus = new Ext.Button({ tooltip: 'Afficher/Cacher les notes', text: 'Notes', icon: this.document.context.url + 'Images/simplenote16.png', scope: this, handler: function(b, e){ this.displaynotes = (!this.displaynotes); this.viewNotes({ undisplay: (!this.displaynotes) }); } }); } // TODO Correct the icon path var allocatedstatus = null; if (this.document.getProperty('allocated')) { var an = this.document.getProperty('allocatedname'); var aimg = this.document.context.url + "Images/allocatedred16.png"; if (this.document.getProperty('allocated') == this.document.context.getUser().id) { aimg = this.document.context.url + "Images/allocatedgreen16.png"; } allocatedstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Affecté à ' + an + '" src="' + aimg + '" style="height:16px" />'); } return [statestatus,lockstatus, readstatus, postitstatus, allocatedstatus]; } }); Ext.reg('fdl-document', Ext.fdl.Document); Ext.fdl.SubDocument = Ext.extend(Ext.form.FormPanel, { document: null, context: null, mode: 'view', // Force Ext default rendering, ignoring generateVersion property forceExt: false, displayToolbar: true, border: false, bodyStyle: 'overflow-y:auto; padding: 0px;', //frame: true, autoHeight: false, layout: 'form', method: 'POST', enctype: 'multipart/form-data', fileUpload: true, initComponent: function(){ if(!this.document){ console.log('Ext.fdl.Document is not provided a document.'); } this.context = this.document.context; Ext.fdl.SubDocument.superclass.initComponent.call(this); }, close: function(){ console.log('DOCUMENT CLOSE'); this.fireEvent('close',this); }, getHtmlValue: function(attrid, tag){ var as = this.document.getAttributes(); var ht = ''; for (var aid in as) { oa = as[aid]; if (oa.parentId == attrid && oa.getValue) { if (oa.getValue() != '') ht += '<' + tag + '>' + oa.getLabel() + ' : ' + oa.getValue() + '</' + tag + '>'; } } return ht; }, applyLink: function(attrid){ var me = this; if (attrid) { var text = me.document.getValue(attrid) || ''; var reg = new RegExp("", "ig"); reg.compile("\\[ADOC ([0-9]*)\\]", "ig"); var getLink = function(str, id){ var value = me.document.getValue(id); var display = me.document.getDisplayValue(id); return "<a class='docid' oncontextmenu='window.Fdl.ApplicationManager.displayDocument(" + value + ");return false;' href='javascript:window.Fdl.ApplicationManager.displayDocument(" + value + ");'> " + // me.context.getDocument({ // id: id // }).getTitle() + display + "</a>"; }; text = text.replace(reg, getLink); } return text; }, orderAttribute: function(){ if (!this.ordered) { function sortAttribute(attr1, attr2){ return attr1.rank - attr2.rank; }; function giveRank(type){ for (var i = 0; i < ordered.length; i++) { if (ordered[i].type == type) { for (var j = 0; j < ordered.length; j++) { if ((ordered[i].id == ordered[j].parentId) && (ordered[i].rank > ordered[j].rank || ordered[i].rank == 0)) { ordered[i].rank = ordered[j].rank; } } } } }; var ordered = new Array(); var as = this.document.getAttributes(); for (var aid in as) { ordered.push(as[aid]); } //ordered = ordered.slice(); // Makes an independant copy of attribute array // Each structuring attribute is given its children lowest rank giveRank('array'); giveRank('frame'); giveRank('tab'); ordered.sort(sortAttribute); this.ordered = ordered; } return this.ordered; }, documentToolbarButton: function(){ var button = new Ext.Button({ text: 'Document', menu: [{ xtype: 'menuitem', text: this.context._("eui::ToEdit"), scope: this, handler: function(){ this.switchMode('edit'); }, disabled: !this.document.canEdit() }, { xtype: 'menuitem', text: 'Verrouiller', scope: this, handler: function(){ this.document.lock(); Ext.Info.msg(this.document.getTitle(), "Verrouillage"); this.switchMode(this.mode); }, disabled: !this.document.canEdit(), hidden: (this.document.getProperty('locked') > 0 || this.document.getProperty('locked') == -1) }, { xtype: 'menuitem', text: 'Déverrouiller', scope: this, handler: function(){ this.document.unlock(); Ext.Info.msg(this.document.getTitle(), "Déverrouillage"); this.switchMode(this.mode); }, disabled: !this.document.canEdit(), hidden: (this.document.getProperty('locked') == 0 || this.document.getProperty('locked') == -1) }, { xtype: 'menuitem', text: 'Actualiser', scope: this, handler: function(){ this.document.reload(); this.switchMode(this.mode); } }, { xtype: 'menuitem', text: 'Supprimer', scope: this, handler: function(){ this.document.remove(); updateDesktop(); this.ownerCt.destroy(); } }, { xtype: 'menuitem', text: 'Historique', scope: this, handler: function(){ var histowin = Ext.fdl.viewDocumentHistory(this.document); histowin.show(); } }, { xtype: 'menuitem', text: 'Ajouter une note', scope: this, handler: function(){ var nid = this.addNote(); this.viewNotes(); var wnid = this.notes[nid]; if (wnid) { var p = wnid.items.itemAt(0); setTimeout(function(){ p.items.itemAt(0).setVisible(false); p.items.itemAt(1).setVisible(true); p.items.itemAt(2).setVisible(true); p.items.itemAt(3).setVisible(true); p.items.itemAt(1).focus(); }, 1000); } }, hidden: (this.document.getProperty('locked') == -1) }, { xtype: 'menuitem', text: 'Affecter un utilisateur', scope: this, handler: function(){ var o = this; //console.log(o); var oa = new Fdl.RelationAttribute({ relationFamilyId: 'IUSER' }); console.log('THISDOCUMENT', this.document, oa); oa._family = this.document; //console.log(oa); var wu = new Ext.fdl.DocId({ attribute: oa }); var toolbar = new Ext.Toolbar({ scope: this, items: [{ xtype: 'button', text: 'Affecter', scope: this, handler: function(){ var uid = wu.getValue(); if (uid) { if (this.document.allocate({ userId: uid })) { this.switchMode(this.mode); } else { Ext.Msg.alert(Fdl.getLastErrorMessage()); } w.close(); } } }, { xtype: 'button', scope: this, text: 'Enlever l\'affectation', handler: function(){ if (this.document.unallocate()) { this.switchMode(this.mode); } else { Ext.Msg.alert(Fdl.getLastErrorMessage()); } w.close(); } }, { xtype: 'button', text: 'Annuler', handler: function(){ w.close(); } }] }); var w = new Ext.Window({ constrain: true, renderTo: o.ownerCt.body, title: 'Affecter un utilisateur', bbar: toolbar, items: [wu] }); // var f = new Ext.FormPanel({ // items: [wu, toolbar] // }); // w.add(f); w.show(); (function(){ wu.focus(); }).defer(1000); }, disabled: !this.document.canEdit() }, { xtype: 'menuitem', text: 'Enregistrer une version', scope: this, handler: function(){ Ext.Msg.prompt('Version', 'Entrer le nom de la version', function(btn, text){ if (btn == 'ok') { // Fdl.ApplicationManager.closeDocument(this.document.id); var previousId = this.document.id; // Add Revision change document id ... this.document.addRevision({ version: text, volatileVersion: true }); // ... so we need to notify a document //Fdl.ApplicationManager.notifyDocument(this.document, previousId); // this.switchMode(this.mode); // this.doLayout(); } }, this); }, disabled: !this.document.canEdit(), hidden:(this.document.getProperty('doctype')!='F') }] }); return button; }, cycleToolbarButton: function(){ if (this.document.hasWorkflow()) { var menu = Array(); var fs = this.document.getFollowingStates(); for (var i = 0; i < fs.length; i++) { menu.push({ xtype: 'menuitem', text: fs[i].transition ? Ext.util.Format.capitalize(fs[i].transitionLabel) : "Passer à l'état : " + fs[i].label, style: 'background-color:' + fs[i].color + ';', scope: this, to_state: fs[i].state, handler: function(b, e){ var previousId = this.document.id; if (this.document.changeState({ state: b.to_state })) { Fdl.ApplicationManager.notifyDocument(this.document, previousId); Ext.Info.msg(this.document.getTitle(), "Changement d'état"); } else { // Error during state change } // this.switchMode(this.mode); // this.doLayout(); } }); } menu.push({ xtype: 'menuitem', text: 'Voir le graphe', scope: this, handler: function(){ var wid = this.document.getProperty('wid'); new Ext.Window({ title: 'Cycle pour ' + this.document.getTitle(), resizable: true, width: 800, height: 400, border: false, items: [new Ext.ux.MediaPanel({ mediaCfg: { mediaType: 'HTM', url: '/?app=FDL&action=WORKFLOW_GRAPH&id=' + wid, width: '100%', height: '100%' } })] }).show(); } }); var button = new Ext.Button({ text: 'Cycle', menu: menu }); return button; } return null; }, documentToolbarStatus: function(){ var u = this.document.context.getUser(); var info = u.getInfo(); var lockstatus = null; if (this.document.getProperty('locked') > 0) { if (this.document.getProperty('locked') == info['id']) { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Verrouillé par ' + this.document.getProperty('locker') + '" src="FDL/Images/greenlock.png" style="height:16px" />'); } else { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Vérrouillé par ' + this.document.getProperty('locker') + '" src="FDL/Images/redlock.png" style="height:16px" />'); } } var readstatus = null; if (this.document.getProperty('locked') == -1) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Figé" src="FDL/Images/readfixed.png" style="height:16px" />'); } else if (!this.document.canEdit()) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Lecture seule" src="FDL/Images/readonly.png" style="height:16px" />'); } var postitstatus = null; if (this.document.getProperty('postitid').length > 0) { //console.log(this.document.getProperty('postitid')); postitstatus = new Ext.Button({ tooltip: 'Afficher/Cacher les notes', text: 'Notes', icon: 'Images/simplenote16.png', scope: this, handler: function(b, e){ this.displaynotes = (!this.displaynotes); this.viewNotes({ undisplay: (!this.displaynotes) }); } }); } // TODO Correct the icon path var allocatedstatus = null; if (this.document.getProperty('allocated')) { var an = this.document.getProperty('allocatedname'); var aimg = "Images/allocatedred16.png"; if (this.document.getProperty('allocated') == this.document.context.getUser().id) { aimg = "Images/allocatedgreen16.png"; } allocatedstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Affecté à ' + an + '" src="' + aimg + '" style="height:16px" />'); } return [lockstatus, readstatus, postitstatus, allocatedstatus]; }, adminToolbarButton: function(){ var button = new Ext.Button({ text: 'Administration', menu: [{ xtype: 'menuitem', text: 'Famille', scope: this, handler: function(b, e){ Fdl.ApplicationManager.displayFamily(this.document.getProperty('fromid')); } }, { xtype: 'menuitem', text: 'Modifier le Cycle', scope: this, handler: function(b, e){ Fdl.ApplicationManager.displayCycleEditor(this.document.getProperty('wid')); } }, { xtype: 'menuitem', text: 'Administrer le Cycle', scope: this, handler: function(b, e){ Fdl.ApplicationManager.displayDocument(this.document.getProperty('wid'), 'edit'); } }, { xtype: 'menuitem', text: 'Propriétés', handler: function(b, e){ Ext.Msg.alert('Propriétés', 'Pas encore disponible.'); } }] }); return button; }, renderToolbar: function(){ if (!this.displayToolbar) { return false; } var toolbar = new Ext.Toolbar({ style: 'margin-bottom:10px;' }); toolbar.add(this.documentToolbarButton()); // Add cycle toolbar button if applicable var cycleToolbarButton = this.cycleToolbarButton(); if (cycleToolbarButton) { toolbar.add(cycleToolbarButton); } // toolbar.add(this.adminToolbarButton()); toolbar.add(new Ext.Toolbar.Fill()); var toolbarStatus = this.documentToolbarStatus(); for (var i = 0; i < toolbarStatus.length; i++) { if (toolbarStatus[i]) { toolbar.add(toolbarStatus[i]); } } return toolbar; }, /** * * @param {Object} attrid * @param {Object} config (display : if true returns widget even if value is empty) */ getExtValue: function(attrid, config){ if ((config && config.display) || this.alwaysDisplay) { var display = true; } if ((config && config.hideHeader)) { var hideHeader = true; } var attr = this.document.getAttribute(attrid); if (!attr) { return null; } var ordered = this.orderAttribute(); // Handle Visibility switch (attr.getVisibility()) { case 'W': case 'R': case 'S': break; case 'O': case 'H': case 'I': return null; break; case 'U': //For array, prevents add and delete of rows break; } switch (attr.type) { case 'menu': case 'action': return new Ext.Button({ text: attr.getLabel(), handler: this.handleAction }); break; case 'text': case 'longtext': case 'date': case 'integer': case 'int': case 'double': case 'money': if (this.document.getValue(attr.id) || display) { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id) }); } else { return null; } break; case 'htmltext': if (this.document.getValue(attr.id) || display) { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.applyLink(attr.id) }); } else { return null; } break; case 'time': if (this.document.getValue(attr.id) || display) { return new Ext.form.TimeField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), disabled: true }); } else { return null; } break; case 'timestamp': if (this.document.getValue(attr.id) || display) { return new Ext.ux.form.DateTime({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), disabled: true }); } else { return null; } break; case 'password': if (this.document.getValue(attr.id) || display) { return new Ext.form.TextField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), inputType: 'password', value: this.document.getValue(attr.id), disabled: true }); } else { return null; } break; case 'image': // return new Ext.form.FileUploadField({ // fieldLabel: attr.getLabel(), // buttonCfg: { // text: '', // iconCls: 'upload-icon' // }, // disabled: true // }); return null; break; case 'color': // return new Ext.form.ColorField({ // fieldLabel: attr.getLabel() // }) ////console.log('Attribute not represented : ' + attr.type); return null; break; case 'frame': var frame = new Ext.form.FieldSet({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, collapsible: true, width: 'auto', labelWidth: 150, style: 'margin:10px;', bodyStyle: 'padding-left:40px;width:auto;' }); var empty = true; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { var extValue = this.getExtValue(curAttr.id); if (extValue != null) { frame.add(extValue); empty = false; } } } if (!empty || display) { return frame; } else { return null; } break; case 'tab': var tab = new Ext.Panel({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, autoWidth: true, width: 'auto', layout: 'form', border: false, defaults: { //width: 'auto', // as we use deferredRender:false we mustn't // render tabs into display:none containers hideMode: 'offsets' } }); var empty = true; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { var extValue = this.getExtValue(curAttr.id); if (extValue != null) { tab.add(extValue); empty = false; } } } if (!empty || display) { return tab; } else { return null; } break; case 'array': var elements = attr.getElements(); var fields = new Array(); for (var i = 0; i < elements.length; i++) { fields.push(elements[i].id); } //console.log('VALUES',this.document.getValues(attr.id)); //var values = attr.getArrayValues() var values = this.document.getValue(attr.id) || []; if (values.length == 0 && !display) { return null; } for (var i = 0; i < elements.length; i++) { // Transform docid into links if (elements[i].type == 'docid') { for (var j = 0; j < values.length; j++) { if (values[j][elements[i].id]) { values[j][elements[i].id] = "<a class='docid' " + 'href="javascript:window.Fdl.ApplicationManager.displayDocument(' + values[j][elements[i].id] + ');"' + 'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' + values[j][elements[i].id] + ');return false;">' + elements[i].getTitle()[j] + "</a>"; } else { values[j][elements[i].id] = ''; } } } // Transform enum with correct label if (elements[i].type == 'enum') { for (var j = 0; j < values.length; j++) { values[j][elements[i].id] = elements[i].getEnumLabel({ key: values[j][elements[i].id] }); } } } var store = new Ext.data.JsonStore({ fields: fields, data: values }); var columns = []; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { // Handle Visibility switch (curAttr.getVisibility()) { case 'W': case 'R': case 'S': columns.push({ header: Ext.util.Format.capitalize(curAttr.getLabel()), dataIndex: curAttr.id }); break; case 'O': case 'H': case 'I': break; case 'U': //For array, prevents add and delete of rows break; } } } var array = new Ext.grid.GridPanel({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, collapsible: true, titleCollapse: true, viewConfig: { forceFit: true, autoFill: true }, animCollapse: false, disableSelection: true, store: store, columns: columns, style: 'margin-bottom:10px;', header: !hideHeader, border: false }); return array; break; case 'enum': //console.log('Attribute not represented : ' + attr.type); return null; break; case 'docid': if (this.document.getValue(attr.id) || display) { if (attr.getOption('multiple') != 'yes') { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: "<a class='docid' " + 'href="javascript:window.Fdl.ApplicationManager.displayDocument(' + this.document.getValue(attr.id) + ');"' + 'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' + this.document.getValue(attr.id) + ');return false;">' + (this.document.getDisplayValue(attr.id) || '') + "</a>" }); } else { var values = this.document.getValue(attr.id); var displays = this.document.getDisplayValue(attr.id); console.log('Attribute', values, displays); var fieldValue = ''; for (var i = 0; i < values.length; i++) { fieldValue += "<a class='docid' " + 'href="javascript:window.Fdl.ApplicationManager.displayDocument(' + values[i] + ');"' + 'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' + values[i] + ');return false;">' + displays[i] + "</a><br/>"; } return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: fieldValue }); } } else { return null; } break; case 'file': if (this.document.getValue(attr.id) || display) { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: '<a class="docid" ' + 'href="' + this.document.getDisplayValue(attr.id, { url: true, inline: false }) + '" >' + this.document.getDisplayValue(attr.id) + "</a>" }); } else { return null; } break; default: //console.log('Attribute not represented : ' + attr.type); return null; break; } }, getHeader: function(){ return new Ext.Panel({ html: "" /* html: '<img src=' + this.document.getIcon({ width: 48 }) + ' style="float:left;padding:0px 5px 5px 0px;" />' + "<p style='font-size:12;'>" + this.document.getProperty('fromtitle') + '</p>' + '<h1 style="display:inline;font-size:14;text-transform: uppercase;">' + (this.document.getProperty('id') ? this.document.getTitle() : ('Création ' + this.document.getProperty('fromtitle'))) + '</h1>' + '<span style="padding-left:10px">' + (this.document.getProperty('version') ? (' Version ' + this.document.getProperty('version')) : '') + '</span>' + (this.document.hasWorkflow() ? "<p><i style='border-style:none none solid none;border-width:2px;border-color:" + this.document.getColorState() + "'>" + (this.document.isFixed() ? ('(' + this.document.getLocalisedState() + ') ') : '') )+ "<b>" + (this.document.getActivityState() ? Ext.util.Format.capitalize(this.document.getActivityState()) : '') + "</b>" + '</i></p>'*/ }); }, /** * Get Ext default input component for a given id. * @param {Object} attrid * @param {Object} inArray * @param {Object} rank * @param {Object} defaultValue * @param {Object} empty */ getExtInput: function(attrid, inArray, rank, defaultValue, empty){ var attr = this.document.getAttribute(attrid); if (!attr) { return null; } //var name = inArray ? attr.id + '[]' : attr.id; var name = attr.id; var ordered = this.orderAttribute(); // Handle Visibility switch (attr.getVisibility()) { case 'W': case 'O': break; case 'R': case 'H': case 'I': return null; break; case 'S': //Viewable in edit mode but not editable var disabled = true; break; case 'U': //For array, prevents add and delete of rows break; } switch (attr.type) { case 'menu': // return new Ext.Button({ // text: Ext.util.Format.capitalize(attr.getLabel()), // handler: this.handleAction // }); break; case 'text': return new Ext.fdl.Text({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null, name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'longtext': return new Ext.fdl.LongText({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null, name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'htmltext': return new Ext.fdl.HtmlText({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, disabled: disabled }); break; case 'int': case 'integer': return new Ext.fdl.Integer({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'double': return new Ext.fdl.Double({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'money': return new Ext.fdl.Money({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'date': return new Ext.fdl.Date({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), altFormats: 'd-j-Y|d-m-Y', format: 'd/m/Y', value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null, name: name, disabled: disabled }); break; case 'time': return new Ext.form.TimeField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, disabled: disabled }); break; case 'timestamp': return new Ext.ux.form.DateTime({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name, disabled: disabled }); break; case 'password': return new Ext.form.TextField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), inputType: 'password', value: this.document.getValue(attr.id), name: name, disabled: disabled }); break; case 'image': return new Ext.fdl.Image({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name, value: attr.getFileName() }); break; case 'file': return new Ext.fdl.File({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name, value: attr.getFileName() }); break; case 'color': return new Ext.fdl.Color({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name }); break; case 'frame': var frame = new Ext.form.FieldSet({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, autoWidth: true, collapsible: true, labelWidth: 150, //width: 'auto', style: 'margin:10px;', //bodyStyle: 'padding-left:40px;width:auto;' bodyStyle: 'padding-left:20px;', anchor: '100%' }); for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { var ext_input = this.getExtInput(curAttr.id); if (ext_input != null) { frame.add(ext_input); } } } return frame; break; case 'tab': var tab = new Ext.Panel({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, autoWidth: true, //frame: true, layout: 'form', border: false, defaults: { // as we use deferredRender:false we mustn't // render tabs into display:none containers //hideMode: 'offsets' } }); var empty = true; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { tab.add(this.getExtInput(curAttr.id)); empty = false; } } if (!empty) { return tab; } else { return null; } break; // Improvement for using RowEditor with array /* case 'array': var elements = attr.getElements(); var values = attr.getArrayValues(); var docWidget = this; var columns = [new Ext.grid.RowNumberer()]; var fields = []; for (var i = 0; i < elements.length; i++) { var attr = this.document.getAttribute(elements[i].id); var col = Ext.apply({},{ editor: this.getExtInput(elements[i].id, true, null, null, true), header: attr.getLabel(), dataIndex: elements[i].id, hideable: false, viewCfg: { autoFill: true, forceFit: true } }); //should be a method switch(attr.type){ case 'docid': var renderer = attr.getTitle.createDelegate(attr); //this is not the good renderer //the good one would only be fdl.getTitle //that does not exists currently break; default: var renderer = null; break; } if(renderer){ Ext.apply(col, { renderer: renderer }); } //EO method var field = Ext.apply({},{ name: elements[i].id }) columns.push(col); fields.push(field); } var store = new Ext.data.Store({ reader: new Ext.data.JsonReader({ fields: fields }), data: values }) // not forget to include ext/examples/ux/RowEditor.js //maybe work on roweditor about last row... var editor = new Ext.ux.RowEditor({ saveText: 'Update' }); //var arrayPanel = new Ext.grid.EditorGridPanel({ //only gridpanel if using roweditor! var arrayPanel = new Ext.grid.GridPanel({ title: Ext.util.Format.capitalize(attr.getLabel()), frame: true, plugins:[editor], collapsible: true, titleCollapse: true, animCollapse: false, style: 'margin-bottom:10px;', columns: columns, store: store, autoHeight: true, autoScroll: true, bbar: [{ ref: '../addBtn', iconCls: 'icon-row-add', text: 'Add row', handler: function(){ var e = new store.recordType(); editor.stopEditing(); store.insert(0, e); arrayPanel.getView().refresh(); arrayPanel.getSelectionModel().selectRow(0); editor.startEditing(0); } },{ ref: '../removeBtn', iconCls: 'icon-row-delete', text: 'Remove row', disabled: true, handler: function(){ editor.stopEditing(); var s = arrayPanel.getSelectionModel().getSelections(); for(var i = 0, r; r = s[i]; i++){ store.remove(r); } } }] }); arrayPanel.getSelectionModel().on('selectionchange', function(sm){ arrayPanel.removeBtn.setDisabled(sm.getCount() < 1); }); return arrayPanel; break; */ case 'array': var elements = attr.getElements(); var fields = new Array(); for (var i = 0; i < elements.length; i++) { fields.push(elements[i].id); } //var values = attr.getArrayValues(); var values = this.document.getValue(attr.id) || []; var docWidget = this; var columns = 0; for (var i = 0; i < elements.length; i++) { // Handle Visibility switch (elements[i].getVisibility()) { case 'W': case 'O': columns++; break; } } var arrayPanel = new Ext.Panel({ title: Ext.util.Format.capitalize(attr.getLabel()), frame: true, collapsible: true, titleCollapse: true, animCollapse: false, style: 'margin-bottom:10px;', layout: 'table', layoutConfig: { columns: columns }, bbar: [{ text: 'Ajouter', tooltip: 'Ajouter', scope: docWidget, handler: function(){ // For each columnPanel child // Add one row of editor widget var elements = attr.getElements(); for (var i = 0; i < elements.length; i++) { switch (elements[i].getVisibility()) { case 'W': case 'O': var editorWidget = this.getExtInput(elements[i].id, true, null, null, true); arrayPanel.add(editorWidget); break; } } arrayPanel.doLayout(); } }] }); for (var i = 0; i < elements.length; i++) { // Handle Visibility switch (elements[i].getVisibility()) { case 'W': case 'O': switch (elements[i].type) { case 'enum': if (attr.getOption('eformat') == 'bool') { var width = 60; } else { var width = 120; } break; case 'docid': var width = 200; break; case 'date': var width = 110; break; default: var width = 100; break; } var columnPanel = new Ext.Panel({ title: Ext.util.Format.capitalize(elements[i].getLabel()), width: width, style: 'overflow:auto;', bodyStyle: 'text-align:center;margin-top:3px;', frame: false, layout: 'form', hideLabels: true }); arrayPanel.add(columnPanel); break; } } for (var j = 0; j < values.length; j++) { for (var i = 0; i < elements.length; i++) { switch (elements[i].getVisibility()) { case 'W': case 'O': var editorWidget = this.getExtInput(elements[i].id, true, j, values[j][elements[i].id]); arrayPanel.add(editorWidget); } } } return arrayPanel; break; case 'enum': // var label = attr.getEnumLabel({ // key: this.document.getValue(attr.id)[rank] // }); // // if (attr.getOption('eformat') == 'bool') { // // return new Ext.ux.form.XCheckbox({ // fieldLabel: inArray ? ' ' : Ext.util.Format.capitalize(attr.getLabel()), // //boxLabel: inArray ? '' : Ext.util.Format.capitalize(attr.getLabel()) , // checked: this.document.getValue(attr.id)[rank] == 'yes' ? true : false, // submitOnValue: 'yes', // submitOffValue: 'no', // name: name, // style: inArray ? 'margin:auto;' : '' // }); // // } // else { // // var items = attr.getEnumItems(); // // return new Ext.form.ComboBox({ // // fieldLabel: inArray ? ' ' : Ext.util.Format.capitalize(attr.getLabel()), // // valueField: 'key', // displayField: 'label', // // width: 150, // // // Required to give simple select behaviour // //emptyText: '--Famille--', // editable: false, // forceSelection: true, // disableKeyFilter: true, // triggerAction: 'all', // mode: 'local', // // value: items[0].key, // // store: new Ext.data.JsonStore({ // data: items, // fields: ['key', 'label'] // }) // // }); // // } break; case 'docid': if (attr.getOption('multiple') == 'yes') { return new Ext.fdl.MultiDocId({ attribute: attr, fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), docIdList: this.document.getValue(attr.id), docTitleList: this.document.getValue(attr.id + '_title') }); } else { return new Ext.fdl.DocId({ attribute: attr, fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), //value: this.document.getValue(attr.id), value: !empty ? (rank != null ? this.document.getDisplayValue(attr.id)[rank] : this.document.getDisplayValue(attr.id)) : null, //name: attr.id, hiddenName: name, hiddenValue: !empty ? (defaultValue != null ? defaultValue : this.document.getValue(attr.id)) : null, allowBlank: !attr.needed, disabled: disabled }); } break; default: console.log('Attribute not represented : ' + attr.type); return null; break; } } });
Eric-Brison/dynacase-core
Zone/Ui/widget-document.js
JavaScript
agpl-3.0
80,977
var _ = require('lodash'); var fs = require('fs'); var logger = require('./logger'); var jsonLoad = require('./json-load'); var config = module.exports; // defaults - can be overridden in config.json config.startServer = true; config.postgresqlUser = 'postgres'; config.postgresqlPassword = null; config.postgresqlDatabase = 'postgres'; config.postgresqlHost = 'localhost'; config.urlPrefix = '/pl'; config.homeUrl = '/'; config.redisUrl = null; // redis://localhost:6379/ for dev config.logFilename = 'server.log'; config.authType = 'none'; config.serverType = 'http'; config.serverPort = '3000'; config.cronIntervalAutoFinishExamsSec = 10 * 60; config.cronIntervalErrorAbandonedJobsSec = 10 * 60; config.cronIntervalExternalGraderLoadSec = 8; config.cronIntervalServerLoadSec = 8; config.cronIntervalServerUsageSec = 8; config.cronDailySec = 8 * 60 * 60; config.autoFinishAgeMins = 6 * 60; config.questionDefaultsDir = 'question-servers/default-calculation'; config.secretKey = 'THIS_IS_THE_SECRET_KEY'; // override in config.json config.secretSlackOpsBotEndpoint = null; // override in config.json config.gitSshCommand = null; config.secretSlackProctorToken = null; config.secretSlackProctorChannel = null; config.externalGradingUseAws = false; config.externalGradingJobsQueueName = 'grading_jobs_dev'; config.externalGradingResultsQueueName = 'grading_results_dev'; config.externalGradingJobsDeadLetterQueueName = null; config.externalGradingResultsDeadLetterQueueName = null; config.externalGradingAutoScalingGroupName = null; config.externalGradingS3Bucket = 'prairielearn.dev.grading'; config.externalGradingWebhookUrl = null; config.externalGradingDefaultTimeout = 30; // in seconds config.externalGradingLoadAverageIntervalSec = 30; config.externalGradingHistoryLoadIntervalSec = 3600; config.externalGradingCurrentCapacityFactor = 1.5; config.externalGradingHistoryCapacityFactor = 1.5; config.externalGradingSecondsPerSubmissionPerUser = 120; config.useWorkers = true; config.workersCount = null; // if null, use workersPerCpu instead config.workersPerCpu = 1; config.workerWarmUpDelayMS = 1000; config.groupName = 'local'; // used for load reporting config.instanceId = 'server'; // FIXME: needs to be determed dynamically with new config code config.reportIntervalSec = 10; // load reporting config.maxResponseTimeSec = 500; config.serverLoadAverageIntervalSec = 30; config.serverUsageIntervalSec = 10; config.PLpeekUrl = 'https://cbtf.engr.illinois.edu/sched/proctor/plpeek'; config.blockedWarnEnable = false; config.blockedWarnThresholdMS = 100; config.SEBServerUrl = null; config.SEBServerFilter = null; config.SEBDownloadUrl = null; config.hasShib = false; config.hasAzure = false; config.hasOauth = false; config.syncExamIdAccessRules = false; config.checkAccessRulesExamUuid = false; config.questionRenderCacheType = 'none'; // One of none, redis, memory config.hasLti = false; config.ltiRedirectUrl = null; config.filesRoot = null; const azure = { // Required azureIdentityMetadata: 'https://login.microsoftonline.com/common/.well-known/openid-configuration', // azureIdentityMetadata: 'https://login.microsoftonline.com/<tenant_name>.onmicrosoft.com/.well-known/openid-configuration', // or equivalently: 'https://login.microsoftonline.com/<tenant_guid>/.well-known/openid-configuration' // // or you can use the common endpoint // 'https://login.microsoftonline.com/common/.well-known/openid-configuration' // To use the common endpoint, you have to either set `validateIssuer` to false, or provide the `issuer` value. // Required, the client ID of your app in AAD azureClientID: '<your_client_id>', // Required, must be 'code', 'code id_token', 'id_token code' or 'id_token' azureResponseType: 'code id_token', // Required azureResponseMode: 'form_post', // Required, the reply URL registered in AAD for your app azureRedirectUrl: 'http://localhost:3000/auth/openid/return', // Required if we use http for redirectUrl azureAllowHttpForRedirectUrl: false, // Required if `responseType` is 'code', 'id_token code' or 'code id_token'. // If app key contains '\', replace it with '\\'. azureClientSecret: '<your_client_secret>', // Required to set to false if you don't want to validate issuer azureValidateIssuer: false, // Required if you want to provide the issuer(s) you want to validate instead of using the issuer from metadata azureIssuer: null, // Required to set to true if the `verify` function has 'req' as the first parameter azurePassReqToCallback: false, // Recommended to set to true. By default we save state in express session, if this option is set to true, then // we encrypt state and save it in cookie instead. This option together with { session: false } allows your app // to be completely express session free. azureUseCookieInsteadOfSession: true, // Required if `useCookieInsteadOfSession` is set to true. You can provide multiple set of key/iv pairs for key // rollover purpose. We always use the first set of key/iv pair to encrypt cookie, but we will try every set of // key/iv pair to decrypt cookie. Key can be any string of length 32, and iv can be any string of length 12. azureCookieEncryptionKeys: [ { 'key': '12345678901234567890123456789012', 'iv': '123456789012' }, { 'key': 'abcdefghijklmnopqrstuvwxyzabcdef', 'iv': 'abcdefghijkl' }, ], // Optional. The additional scope you want besides 'openid', for example: ['email', 'profile']. azureScope: null, // Optional, 'error', 'warn' or 'info' azureLoggingLevel: 'warn', // Optional. The lifetime of nonce in session or cookie, the default value is 3600 (seconds). azureNonceLifetime: null, // Optional. The max amount of nonce saved in session or cookie, the default value is 10. azureNonceMaxAmount: 5, // Optional. The clock skew allowed in token validation, the default value is 300 seconds. azureClockSkew: null, // Optional. // If you want to get access_token for a specific resource, you can provide the resource here; otherwise, // set the value to null. // Note that in order to get access_token, the responseType must be 'code', 'code id_token' or 'id_token code'. azureResourceURL: 'https://graph.windows.net', // The url you need to go to destroy the session with AAD azureDestroySessionUrl: 'https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri=http://localhost:3000', }; _.assign(config, azure); config.loadConfig = function(file) { if (fs.existsSync(file)) { let fileConfig = jsonLoad.readJSONSyncOrDie(file, 'schemas/serverConfig.json'); _.assign(config, fileConfig); } else { logger.warn(file + ' not found, using default configuration'); } };
parasgithub/PrairieLearn
lib/config.js
JavaScript
agpl-3.0
6,879
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * <h2>Form Controller</h2> * * *General idea* * * The form controller is responsible for connecting a form with a model. If no * model is given, a model can be created. This created model will fit exactly * to the given form and can be used for serialization. All the connections * between the form items and the model are handled by an internal * {@link qx.data.controller.Object}. * * *Features* * * * Connect a form to a model (bidirectional) * * Create a model for a given form * * *Usage* * * The controller only works if both a controller and a model are set. * Creating a model will automatically set the created model. * * *Cross reference* * * * If you want to bind single values, use {@link qx.data.controller.Object} * * If you want to bind a list like widget, use {@link qx.data.controller.List} * * If you want to bind a tree widget, use {@link qx.data.controller.Tree} */ qx.Class.define("qx.data.controller.Form", { extend : qx.core.Object, /** * @param model {qx.core.Object | null} The model to bind the target to. The * given object will be set as {@link #model} property. * @param target {qx.ui.form.Form | null} The form which contains the form * items. The given form will be set as {@link #target} property. * @param selfUpdate {Boolean?false} If set to true, you need to call the * {@link #updateModel} method to get the data in the form to the model. * Otherwise, the data will be synced automatically on every change of * the form. */ construct : function(model, target, selfUpdate) { this.base(arguments); this._selfUpdate = !!selfUpdate; this.__bindingOptions = {}; if (model != null) { this.setModel(model); } if (target != null) { this.setTarget(target); } }, properties : { /** Data object containing the data which should be shown in the target. */ model : { check: "qx.core.Object", apply: "_applyModel", event: "changeModel", nullable: true, dereference: true }, /** The target widget which should show the data. */ target : { check: "qx.ui.form.Form", apply: "_applyTarget", event: "changeTarget", nullable: true, init: null, dereference: true } }, members : { __objectController : null, __bindingOptions : null, /** * The form controller uses for setting up the bindings the fundamental * binding layer, the {@link qx.data.SingleValueBinding}. To achieve a * binding in both directions, two bindings are neede. With this method, * you have the opportunity to set the options used for the bindings. * * @param name {String} The name of the form item for which the options * should be used. * @param model2target {Map} Options map used for the binding from model * to target. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. * @param target2model {Map} Options map used for the binding from target * to model. The possible options can be found in the * {@link qx.data.SingleValueBinding} class. */ addBindingOptions : function(name, model2target, target2model) { this.__bindingOptions[name] = [model2target, target2model]; // return if not both, model and target are given if (this.getModel() == null || this.getTarget() == null) { return; } // renew the affected binding var item = this.getTarget().getItems()[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; // remove the binding this.__objectController.removeTarget(item, targetProperty, name); // set up the new binding with the options this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, model2target, target2model ); }, /** * Creates and sets a model using the {@link qx.data.marshal.Json} object. * Remember that this method can only work if the form is set. The created * model will fit exactly that form. Changing the form or adding an item to * the form will need a new model creation. * * @param includeBubbleEvents {Boolean} Whether the model should support * the bubbling of change events or not. * @return {qx.core.Object} The created model. */ createModel : function(includeBubbleEvents) { var target = this.getTarget(); // throw an error if no target is set if (target == null) { throw new Error("No target is set."); } var items = target.getItems(); var data = {}; for (var name in items) { var names = name.split("."); var currentData = data; for (var i = 0; i < names.length; i++) { // if its the last item if (i + 1 == names.length) { // check if the target is a selection var clazz = items[name].constructor; var itemValue = null; if (qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection)) { // use the first element of the selection because passed to the // marshaler (and its single selection anyway) [BUG #3541] itemValue = items[name].getModelSelection().getItem(0) || null; } else { itemValue = items[name].getValue(); } // call the converter if available [BUG #4382] if (this.__bindingOptions[name] && this.__bindingOptions[name][1]) { itemValue = this.__bindingOptions[name][1].converter(itemValue); } currentData[names[i]] = itemValue; } else { // if its not the last element, check if the object exists if (!currentData[names[i]]) { currentData[names[i]] = {}; } currentData = currentData[names[i]]; } } } var model = qx.data.marshal.Json.createModel(data, includeBubbleEvents); this.setModel(model); return model; }, /** * Responsible for synching the data from entered in the form to the model. * Please keep in mind that this method only works if you create the form * with <code>selfUpdate</code> set to true. Otherwise, this method will * do nothing because updates will be synched automatically on every * change. */ updateModel: function(){ // only do stuff if self update is enabled and a model or target is set if (!this._selfUpdate || !this.getModel() || !this.getTarget()) { return; } var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var sourceProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; options = options && this.__bindingOptions[name][1]; qx.data.SingleValueBinding.updateTarget( item, sourceProperty, this.getModel(), name, options ); } }, // apply method _applyTarget : function(value, old) { // if an old target is given, remove the binding if (old != null) { this.__tearDownBinding(old); } // do nothing if no target is set if (this.getModel() == null) { return; } // target and model are available if (value != null) { this.__setUpBinding(); } }, // apply method _applyModel : function(value, old) { // first, get rid off all bindings (avoids whong data population) if (this.__objectController != null) { var items = this.getTarget().getItems(); for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } } // set the model of the object controller if available if (this.__objectController != null) { this.__objectController.setModel(value); } // do nothing is no target is set if (this.getTarget() == null) { return; } // model and target are available if (value != null) { this.__setUpBinding(); } }, /** * Internal helper for setting up the bindings using * {@link qx.data.controller.Object#addTarget}. All bindings are set * up bidirectional. */ __setUpBinding : function() { // create the object controller if (this.__objectController == null) { this.__objectController = new qx.data.controller.Object(this.getModel()); } // get the form items var items = this.getTarget().getItems(); // connect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; var options = this.__bindingOptions[name]; // try to bind all given items in the form try { if (options == null) { this.__objectController.addTarget(item, targetProperty, name, !this._selfUpdate); } else { this.__objectController.addTarget( item, targetProperty, name, !this._selfUpdate, options[0], options[1] ); } // ignore not working items } catch (ex) { if (qx.core.Environment.get("qx.debug")) { this.warn("Could not bind property " + name + " of " + this.getModel()); } } } }, /** * Internal helper for removing all set up bindings using * {@link qx.data.controller.Object#removeTarget}. * * @param oldTarget {qx.ui.form.Form} The form which has been removed. */ __tearDownBinding : function(oldTarget) { // do nothing if the object controller has not been created if (this.__objectController == null) { return; } // get the items var items = oldTarget.getItems(); // disconnect all items for (var name in items) { var item = items[name]; var targetProperty = this.__isModelSelectable(item) ? "modelSelection[0]" : "value"; this.__objectController.removeTarget(item, targetProperty, name); } }, /** * Returns whether the given item implements * {@link qx.ui.core.ISingleSelection} and * {@link qx.ui.form.IModelSelection}. * * @param item {qx.ui.form.IForm} The form item to check. * * @return {true} true, if given item fits. */ __isModelSelectable : function(item) { return qx.Class.hasInterface(item.constructor, qx.ui.core.ISingleSelection) && qx.Class.hasInterface(item.constructor, qx.ui.form.IModelSelection); } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { // dispose the object controller because the bindings need to be removed if (this.__objectController) { this.__objectController.dispose(); } } });
Seldaiendil/meyeOS
devtools/qooxdoo-1.5-sdk/framework/source/class/qx/data/controller/Form.js
JavaScript
agpl-3.0
11,935
import SPELLS from 'common/SPELLS'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import TalentStatisticBox from 'parser/ui/TalentStatisticBox'; import React from 'react'; const DEATHSTRIKE_COST = 40; class Heartbreaker extends Analyzer { rpGains = []; hsCasts = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.HEARTBREAKER_TALENT.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.HEART_STRIKE), this.onCast); this.addEventListener(Events.energize.spell(SPELLS.HEARTBREAKER), this.onEnergize); } onCast(event) { this.hsCasts += 1; } onEnergize(event) { if (event.resourceChangeType !== RESOURCE_TYPES.RUNIC_POWER.id) { return; } this.rpGains.push(event.resourceChange); } get totalRPGained() { return this.rpGains.reduce((a, b) => a + b, 0); } get averageHearStrikeHits() { return (this.rpGains.length / this.hsCasts).toFixed(2); } statistic() { return ( <TalentStatisticBox talent={SPELLS.HEARTBREAKER_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(1)} value={this.totalRPGained} label="Runic Power gained" tooltip={ <> Resulting in about {Math.floor(this.totalRPGained / DEATHSTRIKE_COST)} extra Death Strikes. <br /> Your Heart Strike hit on average {this.averageHearStrikeHits} targets. </> } /> ); } } export default Heartbreaker;
anom0ly/WoWAnalyzer
analysis/deathknightblood/src/modules/talents/Heartbreaker.js
JavaScript
agpl-3.0
1,692
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":46,"id":86762,"methods":[{"el":38,"sc":2,"sl":36}],"name":"AbstractEigenvectorModel","sl":32}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
cm-is-dog/rapidminer-studio-core
report/html/com/rapidminer/operator/features/transformation/AbstractEigenvectorModel.js
JavaScript
agpl-3.0
629
'use strict'; angular.module('impactApp') .controller('PartenairesEditCtrl', function($scope, $state, partenaire) { $scope.partenaire = partenaire; $scope.update = function() { $scope.partenaire.$save(function() { $state.go('^', {}, {reload: true}); }); }; $scope.delete = function() { $scope.partenaire.$delete(function() { $state.go('^', {}, {reload: true}); }); }; });
sgmap/impact
client/app/dashboard/users/partenaires/edit.controller.js
JavaScript
agpl-3.0
439
'use strict'; const _ = require('underscore'); const Handlebars = require('handlebars'); const moment = require('moment'); const VPREmulatorModel = require('./vprEmulatorModel'); const toFMDateTime = require('../vdmUtils').toFMDateTime; class VPRPatientEmulator extends VPREmulatorModel { template() { return [ "<results version='{{vprDataVersion}}' timeZone='-0500' >", "<demographics total='{{total}}' >", '<patient>', "<bid value='{{bid}}' />", "<dob value='{{toDate dateOfBirth}}' />", '{{{getFacilities}}}', "<familyName value='{{toFamilyName name}}' />", "<fullName value='{{name}}' />", "<gender value='{{toGender sex}}' />", "<givenNames value='{{toGivenName name}}' />", "<id value='{{patientId}}' />", "<inpatient value='{{getInpatient}}' />", "<lrdfn value='{{getLrdfn}}' />", "<sc value='{{sc}}' />", "<ssn value='{{socialSecurityNumber}}' />", "<veteran value='{{veteran}}' />", '</patient>', '</demographics>', '</results>', ]; } compileTemplate(mvdmForm) { Handlebars.registerHelper('toDate', date => toFMDateTime(date.value)); Handlebars.registerHelper('toFamilyName', name => name.substring(0, name.indexOf(','))); Handlebars.registerHelper('toGender', (sex) => { const map = { MALE: 'M', FEMALE: 'F', }; return map[sex]; }); Handlebars.registerHelper('toGivenName', name => name.substring(name.indexOf(',') + 1, name.length)); Handlebars.registerHelper('getInpatient', () => { if (mvdmForm.currentAdmission) { return 'true'; } return 'false'; }); Handlebars.registerHelper('getLrdfn', () => { if (_.has(mvdmForm, 'laboratoryReference')) { return mvdmForm.laboratoryReference.id.split('-')[1]; } return 0; }); Handlebars.registerHelper('getFacilities', () => { /* * Facilities visited by the Patient * * In the general case there may be many facilities (MPI can be called). For an * isolate VISTA, there will be at most one, this VISTA. * * TODO: replace with a Javascript Utility or a computed property in Patient */ const dateStr = moment().format('YYYY-MM-DD'); return `${'<facilities>' + "<facility code='050' name='SOFTWARE SERVICE' latestDate='"}${toFMDateTime(dateStr)}' domain='FOIA.DOMAIN.EXT' />` + '</facilities>'; }); mvdmForm.bid = `C${mvdmForm.socialSecurityNumber.substring(5, 9)}`; mvdmForm.patientId = mvdmForm.id.replace('2-', ''); mvdmForm.sc = mvdmForm.isServiceConnected ? 1 : 0; mvdmForm.veteran = mvdmForm.isVeteran ? 1 : 0; const temp = Handlebars.compile(this.template().join('')); const res = temp(mvdmForm); return res; } getOnePatientDetail(res) { if (res === 'error') { return `<results version='${this.vprDataVersion}' timeZone='-0500' ><demographics total='0' ></demographics></results>`; } res.vprDataVersion = this.vprDataVersion; res.total = 1; const result = this.compileTemplate(res); return result.replace(/"/g, '\''); } toReturnValue(invokeResult) { return this.getOnePatientDetail(invokeResult); } transformIEN(ien) { return `2-${ien}`; } } module.exports = VPRPatientEmulator;
vistadataproject/MVDM
vprEmulator/vprEmulatorPatientModel.js
JavaScript
agpl-3.0
3,784
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'specialchar', 'de-ch', { options: 'Sonderzeichenoptionen', title: 'Sonderzeichen auswählen', toolbar: 'Sonderzeichen einfügen' } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/specialchar/lang/de-ch.js
JavaScript
agpl-3.0
319
/** * This file is part of agora-gui-admin. * Copyright (C) 2015-2016 Agora Voting SL <[email protected]> * agora-gui-admin 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. * agora-gui-admin 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 agora-gui-admin. If not, see <http://www.gnu.org/licenses/>. **/ angular.module('avAdmin') .controller( 'AddCsvModal', function($scope, $modalInstance, election, ConfigService, Plugins) { $scope.election = election; $scope.textarea = ""; $scope.helpurl = ConfigService.helpUrl; $scope.ok = function () { $modalInstance.close($("#csv-textarea").val()); }; // if there's a parent election, add those fields at the end of the example if ($scope.election.children_election_info) { $scope.childrenElections = _.map( $scope.election.children_election_info.natural_order, function (election_id) { return $scope.election.childrenElectionNames[election_id]; } ); } else { $scope.childrenElections = []; } var exhtml = {html: [], scope: {}}; Plugins.hook( 'census-add-csv-modal', { exhtml: exhtml } ); $scope.exhtml = exhtml.html; $scope = _.extend($scope, exhtml.scope); $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; } );
agoravoting/agora-gui-admin
avAdmin/admin-directives/elcensus/add-csv-modal.js
JavaScript
agpl-3.0
1,844
(function() { 'use strict'; angular .module('blocks.logger') .factory('logListeners', logListeners); /** * @ngdoc service * @name spaghetto.logger:logListeners * * @description * Manage different log listeners so that log messages can have various * destinations. * * * The default behaviour is to send log messages to : * * * '$log' : Angular simple logging service, writing into the browser's console * * 'toaster' : Toaster screen notifications * * You can change this behaviour by installing new log listeners and/or removing * the default ones * ## Log listener definition * <pre> * // here instead of an exdample, we should definie the required properties (with ngdoc) of a logListener object * </pre> * */ /* @ngInject */ function logListeners() { var listeners = {}; var service = { addListener: addListener, getListeners: getListeners, removeListener: removeListener }; return service; /////////////// /** * @ngdoc method * @name addListener * @methodOf spaghetto.logger:logListeners * @kind function * * @description * Add log listener * * ## Add a Log listener * <pre> // define my Log Listener var myLogListener = { error : errorLog, info : infoLog, success : successLog, warning : warningLog } function errorLog(msg, data, title) { console.log('Error: ' + title + '\n' + data); } function infoLog(msg, data, title) { console.log('Info: ' + title + '\n' + data); } function successLog(msg, data, title) { console.log('Success: ' + title + '\n' + data); } function warningLog(msg, data, title) { console.log('Warning: ' + title + '\n' + data); } logListeners.addListener('mylog', myLogListener); * </pre> * @param {string} name log listener name * @param {Object} logListener log listener object * @param {Function} logListener.error log an error message * @param {Function} logListener.info log an info message * @param {Function} logListener.success log a success message * @param {Function} logListener.warning log a warning message */ function addListener(name, logListener) { listeners[name] = logListener; } /** * @ngdoc method * @name removeListener * @methodOf spaghetto.logger:logListeners * @kind function * * @description * Remove a log listener * * ## Remove a log listener * <pre> // 'toastr' log listener is installed by default // if you want to remove it, you can do: logListeners.removeListener('toastr'); * </pre> * @param {string} name log listener name */ function removeListener(name) { delete listeners[name]; } /** * @ngdoc method * @name getListeners * @methodOf spaghetto.logger:logListeners * @kind function * * @description * returns all installed log listeners * * @return {Array} keys is the log listener name * and value is the log listener object **/ function getListeners() { return listeners; } } }());
aurelien-rainone/spaghetto
src/client/app/blocks/logger/loglisteners.js
JavaScript
agpl-3.0
3,869
/* Copyright (C) 2014 Härnösands kommun This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Action for print using mapfish. */ Ext.define('OpenEMap.action.Print', { extend : 'OpenEMap.action.Action', require : 'GeoExt.plugins.PrintExtent', constructor : function(config) { var mapPanel = config.mapPanel; var printExtent = mapPanel.plugins[0]; var printProvider = printExtent.printProvider; printProvider.customParams = {attribution: config.mapPanel.config.attribution.trim(), mapTitle: ''}; var printDialog = null; var page = null; var onTransformComplete = function() { var scale = printDialog.down('#scale'); scale.select(page.scale); }; var onBeforedownload = function() { if (printDialog) printDialog.setLoading(false); }; var onPrintexception = function(printProvider, response) { if (printDialog) printDialog.setLoading(false); Ext.Msg.show({ title:'Felmeddelande', msg: 'Print failed.\n\n' + response.responseText, icon: Ext.Msg.ERROR }); }; var close = function() { printProvider.un('beforedownload', onBeforedownload); printProvider.on('printexception', onPrintexception); printExtent.control.events.unregister('transformcomplete', null, onTransformComplete); printExtent.removePage(page); printExtent.hide(); printDialog = null; }; var onClose = function() { close(); control.deactivate(); }; config.iconCls = config.iconCls || 'action-print'; config.tooltip = config.tooltip || 'Skriv ut'; config.toggleGroup = 'extraTools'; var Custom = OpenLayers.Class(OpenLayers.Control, { initialize: function(options) { OpenLayers.Control.prototype.initialize.apply( this, arguments ); }, type: OpenLayers.Control.TYPE_TOGGLE, activate: function() { if (printDialog) { return; } // NOTE: doing a hide/show at first display fixes interaction problems with preview extent for unknown reasons printExtent.hide(); printExtent.show(); page = printExtent.addPage(); printProvider.dpis.data.items.forEach(function(d){ var validDpi = false; if (d.data.name === '72'){ validDpi = true; d.data.name = 'Låg (' +d.data.name + ' dpi)'; } else if (d.data.name === '150'){ validDpi = true; d.data.name = 'Medel (' +d.data.name + ' dpi)'; } else if (d.data.name === '300'){ validDpi = true; d.data.name = 'Hög (' +d.data.name + ' dpi)'; } }); printProvider.layouts.data.items.forEach(function(p){ if (/landscape$/.test(p.data.name)){ p.data.displayName = p.data.name.replace('landscape', 'liggande'); } else if (/portrait$/.test(p.data.name)){ p.data.displayName = p.data.name.replace('portrait', 'stående'); } }); printDialog = new Ext.Window({ autoHeight : true, width : 290, resizable: false, layout : 'fit', bodyPadding : '5 5 0', title: 'Utskriftsinst&auml;llningar', listeners: { close: onClose }, items : [ { xtype : 'form', layout : 'anchor', defaults : { anchor : '100%' }, fieldDefaults : { labelWidth : 120 }, items : [ { xtype : 'textfield', fieldLabel: 'Rubrik', valueField: 'mapTitle', itemId : 'mapTitle', queryMode: 'local', value: printProvider.customParams.mapTitle, listeners: { change: function(textfield){ printProvider.customParams.mapTitle = textfield.value; } } },{ xtype : 'combo', fieldLabel: 'Pappersformat', store : printProvider.layouts, displayField : 'displayName', valueField : 'name', itemId : 'printLayouts', queryMode: 'local', value : printProvider.layouts.getAt(0).get("name"), listeners: { select: function(combo, records, eOpts) { var record = records[0]; printProvider.setLayout(record); } } }, { xtype : 'combo', fieldLabel: 'Kvalité', store : printProvider.dpis, displayField : 'name', valueField : 'value', queryMode: 'local', value: printProvider.dpis.first().get("value"), listeners: { select: function(combo, records, eOpts) { var record = records[0]; printProvider.setDpi(record); } } }, { xtype : 'combo', fieldLabel: 'Skala', store : printProvider.scales, displayField : 'name', valueField : 'value', queryMode: 'local', itemId: 'scale', value: printProvider.scales.first().get("value"), listeners: { select: function(combo, records, eOpts) { var record = records[0]; page.setScale(record, "m"); } } } ] } ], bbar : [ '->', { text : "Skriv ut", handler : function() { printDialog.setLoading(true); printExtent.print(); } } ] }); printDialog.show(); var scale = printDialog.down('#scale'); scale.select(page.scale); var layoutId = 6; var printLayouts = printDialog.down('#printLayouts'); printLayouts.select(printLayouts.store.data.get(layoutId)); var currentPrintLayout = printLayouts.store.data.items[layoutId]; printProvider.setLayout(currentPrintLayout); printExtent.control.events.register('transformcomplete', null, onTransformComplete); printExtent.control.events.register('transformcomplete', null, onTransformComplete); printProvider.on('beforedownload', onBeforedownload); printProvider.on('printexception', onPrintexception); OpenLayers.Control.prototype.activate.apply(this, arguments); }, deactivate: function() { if (printDialog) printDialog.close(); OpenLayers.Control.prototype.deactivate.apply(this, arguments); } }); var control = new Custom({ type: OpenLayers.Control.TYPE_TOGGLE }); config.control = control; this.callParent(arguments); } });
Sundsvallskommun/OpenEMap-WebUserInterface
src/main/javascript/action/Print.js
JavaScript
agpl-3.0
9,608
/* @flow */ import oEmbedStorage from './oEmbedStorage'; import getContentType from './getContentType'; import regexes from './regexes'; import providers from './providers'; import type { Embed } from './oEmbedTypes'; function getProperty(prop: string, type: ?string): RegExp { if (typeof type === 'string') { return new RegExp("<meta[^>]*property[ ]*=[ ]*['|\"]og:" + type + ':' + prop + "['|\"][^>]*[>]", 'i'); } return new RegExp("<meta[^>]*property[ ]*=[ ]*['|\"]og:" + prop + "['|\"][^>]*[>]", 'i'); } function getContent(regex) { return regex[0].match(regexes.content)[0].match(/['|"].*/)[0].slice(1); } function decodeText(text) { return text .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&') .replace(/&quot;/g, '"') .replace(/&nbsp;/g, ' ') .replace(/&#(x?)(\d+);/g, (m, p1, p2) => String.fromCharCode(((p1 === 'x') ? parseInt(p2, 16) : p2))); } function parseHTML(body): ?Embed { const data: Embed = { type: 'link', }; const props = [ 'title', 'description' ]; for (let i = 0; i < props.length; i++) { const match = body.match(getProperty(props[i])); if (match && match.length) { data[props[i]] = decodeText(getContent(match)); } } const propsWithType = [ 'width', 'height' ]; for (let i = 0; i < propsWithType.length; i++) { const types = [ 'video', 'image' ]; for (let j = 0; j < types.length; j++) { const match = body.match(getProperty(propsWithType[i], types[j])); if (match && match.length) { data['thumbnail_' + propsWithType[i]] = parseInt(getContent(match), 10); } } } const imageUrl = body.match(regexes.image); if (imageUrl) { data.thumbnail_url = getContent(imageUrl); } if (!data.title) { const matches = body.match(regexes.title); if (matches && matches.length) { const title = matches[0].match(/[>][^<]*/); if (title && title.length) { data.title = decodeText(title[0].slice(1)); } } } if (!data.description) { const matches = body.match(regexes.description); if (matches && matches.length) { const description = matches[0].match(regexes.content)[0].match(/['|"][^'|^"]*/); if (description && description.length) { data.description = decodeText(description[0].slice(1)); } } } if (Object.keys(data).length > 1) { return data; } return null; } function extractLink(body) { const res = body.match(regexes.link); if (res && res.length) { return res[0].match(/http[s]?:\/\/[^"']*/i)[0].replace(/&amp;/g, '&'); } return null; } async function fetchData(url: string): Promise<Embed> { const body = await fetch(url).then(res => res.text()).then(text => text.replace(/(\r\n|\n|\r)/g, '')); const dataUrl = extractLink(body); let data; if (dataUrl) { data = await (await fetch(dataUrl)).json(); } else { data = parseHTML(body); } if (data) { oEmbedStorage.set(url, data); return data; } else { throw new Error('Failed to get data from HTML'); } } export default async function(url: string): Promise<Embed> { if (typeof url !== 'string') { throw new TypeError('URL must be a string'); } if (!/^https?:\/\//i.test(url)) { throw new Error("URL must start with 'http://' or 'https://'"); } const json = await oEmbedStorage.get(url); if (json) { return json; } let endpoint; for (let i = 0, l = providers.length; i < l; i++) { const provider = providers[i]; if (provider[0].test(url)) { endpoint = provider[1] + '?format=json&maxheight=240&url=' + encodeURIComponent(url); } } if (endpoint) { const data = await fetch(endpoint).then(res => res.json()); oEmbedStorage.set(url, data); return data; } const contentType = await getContentType(url); if (contentType) { if (contentType.indexOf('image') > -1) { return { type: 'link', thumbnail_url: url, }; } else if (contentType.indexOf('text/html') > -1) { return fetchData(url); } } throw new Error('No oEmbed data found for ' + url); }
Anup-Allamsetty/pure
src/modules/oembed/oEmbed.js
JavaScript
agpl-3.0
3,946
(function (factory) { if (typeof define === 'function') { if(define.amd) { define(['common/metastore', 'jslet', 'mock/employee-mock'], factory); } else { define(function(require, exports, module) { module.exports = factory(); }); } } else { factory(); } })(function () { /********************************** 定义数据集 ************************************************/ //datasetMetaStore定义在公共js:common/datasetmetastore.js中 //将数据集定义信息仓库加到datasetFactory中,创建Dataset时会仓库里去定义信息 jslet.data.datasetFactory.addMetaStore(window.datasetMetaStore); //通过工厂方法,可以自动创建主数据集及相关的数据集 jslet.data.datasetFactory.createDataset('employee').done(function() { jslet.ui.install(function() { var dsEmployee = jslet.data.getDataset('employee'); dsEmployee.query(); }); }); //绑定按钮事件 $('#chkShowSeqenceCol').click(function() { var checked = $('#chkShowSeqenceCol')[0].checked; //设置表格是否有序号列 jslet('#tblEmployee').hasSeqCol(checked).renderAll(); }); $('#chkShowSelectCol').click(function() { var checked = $('#chkShowSelectCol')[0].checked; //设置表格是否有选择列 jslet('#tblEmployee').hasSelectCol(checked).renderAll(); }); $('#btnFixedRows').click(function() { var count = parseInt($('#txtFixedRows').val()); //设置表格固定行数 jslet('#tblEmployee').fixedRows(count).renderAll(); }); $('#btnFixedCols').click(function() { var count = parseInt($('#txtFixedCols').val()); //设置表格固定列数 jslet('#tblEmployee').fixedCols(count).renderAll(); }); $('#btnSetRowClick').click(function() { var dsEmployee = jslet.data.getDataset('employee'); //设置表格单击事件 jslet('#tblEmployee').onRowClick(function() { jslet.ui.info('你点击了第:' + (dsEmployee.recno() + 1) + ' 行!', null, null, 1000); }); }); $('#btnClearRowClick').click(function() { //清除表格单击事件 jslet('#tblEmployee').onRowClick(null); }); $('#btnSetRowDblClick').click(function() { var dsEmployee = jslet.data.getDataset('employee'); //设置表格双击事件 jslet('#tblEmployee').onRowClick(null); //先清除单击事件 jslet('#tblEmployee').onRowDblClick(function() { jslet.ui.info('你双击了第:' + (dsEmployee.recno() + 1) + ' 行!', null, null, 1000); }); }); $('#btnClearRowDblClick').click(function() { //清除表格双击事件 jslet('#tblEmployee').onRowDblClick(null); }); $('#btnSetSelect').click(function() { var dsEmployee = jslet.data.getDataset('employee'); //设置表格选择事件, jslet('#tblEmployee').onSelect(function() { jslet.ui.info('你选择了第:' + (dsEmployee.recno() + 1) + ' 行!', null, null, 1000); }); }); $('#btnClearSelect').click(function() { //清除表格选择 jslet('#tblEmployee').onSelect(null); }); $('#btnSelectBy').click(function() { var dsEmployee = jslet.data.getDataset('employee'); var selectBy = $('#txtSelectBy').val(); //设置表格分组选择(相同值一起选择) jslet('#tblEmployee').selectBy(selectBy); }); });
jslet/jslet
democn/dbcontrol/table/basic.js
JavaScript
agpl-3.0
3,253
/** * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'gu', { title: 'એક્ક્ષેબિલિટી ની વિગતો', contents: 'હેલ્પ. આ બંધ કરવા ESC દબાવો.', legend: [ { name: 'જનરલ', items: [ { name: 'એડિટર ટૂલબાર', legend: 'Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT+TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button.' // MISSING }, { name: 'એડિટર ડાયલોગ', legend: 'Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively.' // MISSING }, { name: 'Editor Context Menu', // MISSING legend: 'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.' // MISSING }, { name: 'Editor List Box', // MISSING legend: 'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.' // MISSING }, { name: 'Editor Element Path Bar', // MISSING legend: 'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.' // MISSING } ] }, { name: 'કમાંડસ', items: [ { name: 'અન્ડું કમાંડ', legend: '$ દબાવો {undo}' }, { name: 'ફરી કરો કમાંડ', legend: '$ દબાવો {redo}' }, { name: 'બોલ્દનો કમાંડ', legend: '$ દબાવો {bold}' }, { name: ' Italic command', // MISSING legend: 'Press ${italic}' // MISSING }, { name: ' Underline command', // MISSING legend: 'Press ${underline}' // MISSING }, { name: ' Link command', // MISSING legend: 'Press ${link}' // MISSING }, { name: ' Toolbar Collapse command', // MISSING legend: 'Press ${toolbarCollapse}' // MISSING }, { name: ' Access previous focus space command', // MISSING legend: 'Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING }, { name: ' Access next focus space command', // MISSING legend: 'Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING }, { name: ' Accessibility Help', // MISSING legend: 'Press ${a11yHelp}' // MISSING }, { name: ' Paste as plain text', // MISSING legend: 'Press ${pastetext}', // MISSING legendEdge: 'Press ${pastetext}, followed by ${paste}' // MISSING } ] } ], tab: 'Tab', // MISSING pause: 'Pause', // MISSING capslock: 'Caps Lock', // MISSING escape: 'Escape', // MISSING pageUp: 'Page Up', // MISSING pageDown: 'Page Down', // MISSING leftArrow: 'Left Arrow', // MISSING upArrow: 'Up Arrow', // MISSING rightArrow: 'Right Arrow', // MISSING downArrow: 'Down Arrow', // MISSING insert: 'Insert', // MISSING leftWindowKey: 'Left Windows key', // MISSING rightWindowKey: 'Right Windows key', // MISSING selectKey: 'Select key', // MISSING numpad0: 'Numpad 0', // MISSING numpad1: 'Numpad 1', // MISSING numpad2: 'Numpad 2', // MISSING numpad3: 'Numpad 3', // MISSING numpad4: 'Numpad 4', // MISSING numpad5: 'Numpad 5', // MISSING numpad6: 'Numpad 6', // MISSING numpad7: 'Numpad 7', // MISSING numpad8: 'Numpad 8', // MISSING numpad9: 'Numpad 9', // MISSING multiply: 'Multiply', // MISSING add: 'Add', // MISSING subtract: 'Subtract', // MISSING decimalPoint: 'Decimal Point', // MISSING divide: 'Divide', // MISSING f1: 'F1', // MISSING f2: 'F2', // MISSING f3: 'F3', // MISSING f4: 'F4', // MISSING f5: 'F5', // MISSING f6: 'F6', // MISSING f7: 'F7', // MISSING f8: 'F8', // MISSING f9: 'F9', // MISSING f10: 'F10', // MISSING f11: 'F11', // MISSING f12: 'F12', // MISSING numLock: 'Num Lock', // MISSING scrollLock: 'Scroll Lock', // MISSING semiColon: 'Semicolon', // MISSING equalSign: 'Equal Sign', // MISSING comma: 'Comma', // MISSING dash: 'Dash', // MISSING period: 'Period', // MISSING forwardSlash: 'Forward Slash', // MISSING graveAccent: 'Grave Accent', // MISSING openBracket: 'Open Bracket', // MISSING backSlash: 'Backslash', // MISSING closeBracket: 'Close Bracket', // MISSING singleQuote: 'Single Quote' // MISSING } );
astrobin/astrobin
astrobin/static/astrobin/ckeditor/plugins/a11yhelp/dialogs/lang/gu.js
JavaScript
agpl-3.0
5,574
export default { standard: { credits: { enabled: false }, chart: { spacingBottom: 20, style: { fontFamily: "'proxima', 'Helvetica', sans-serif' ", paddingTop: '20px' // Make room for buttons } }, exporting: { buttons: { contextButton: { onclick: function () { this.exportChart({type: 'jpeg'}) }, symbol: null, text: 'Export', x: -20, y: -30, theme: { style: { color: '#039', textDecoration: 'underline' } } } } }, title: '' } }
unicef/rhizome
webapp/src/components/highchart/themes.js
JavaScript
agpl-3.0
663
/* * Copyright (c) 2014 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function() { OC.Update = { _started : false, /** * Start the upgrade process. * * @param $el progress list element */ start: function($el, options) { if (this._started) { return; } var hasWarnings = false; this.$el = $el; this._started = true; this.addMessage(t( 'core', 'Updating {productName} to version {version}, this may take a while.', { productName: options.productName || 'ownCloud', version: options.version }), 'bold' ).append('<br />'); // FIXME: these should be ul/li with CSS paddings! var updateEventSource = new OC.EventSource(OC.webroot+'/core/ajax/update.php'); updateEventSource.listen('success', function(message) { $('<span>').append(message).append('<br />').appendTo($el); }); updateEventSource.listen('notice', function(message) { $('<span>').addClass('error').append(message).append('<br />').appendTo($el); hasWarnings = true; }); updateEventSource.listen('error', function(message) { $('<span>').addClass('error').append(message).append('<br />').appendTo($el); message = t('core', 'Please reload the page.'); $('<span>').addClass('error').append(message).append('<br />').appendTo($el); updateEventSource.close(); }); updateEventSource.listen('failure', function(message) { $('<span>').addClass('error').append(message).append('<br />').appendTo($el); $('<span>') .addClass('bold') .append(t('core', 'The update was unsuccessful. ' + 'Please report this issue to the ' + '<a href="https://github.com/owncloud/core/issues" target="_blank">ownCloud community</a>.')) .appendTo($el); }); updateEventSource.listen('done', function() { if (hasWarnings) { $('<span>').addClass('bold') .append('<br />') .append(t('core', 'The update was successful. There were warnings.')) .appendTo($el); var message = t('core', 'Please reload the page.'); $('<span>').append('<br />').append(message).append('<br />').appendTo($el); } else { // FIXME: use product name $('<span>').addClass('bold') .append('<br />') .append(t('core', 'The update was successful. Redirecting you to ownCloud now.')) .appendTo($el); setTimeout(function () { OC.redirect(OC.webroot); }, 3000); } }); }, addMessage: function(message, className) { var $span = $('<span>'); $span.addClass(className).append(message).append('<br />').appendTo(this.$el); return $span; } }; })(); $(document).ready(function() { $('.updateButton').on('click', function() { var $updateEl = $('.update'); var $progressEl = $('.updateProgress'); $progressEl.removeClass('hidden'); $('.updateOverview').addClass('hidden'); OC.Update.start($progressEl, { productName: $updateEl.attr('data-productname'), version: $updateEl.attr('data-version'), }); return false; }); });
lrytz/core
core/js/update.js
JavaScript
agpl-3.0
3,085
'use strict'; describe('itemListService', function() { beforeEach(module('superdesk.mocks')); beforeEach(module('superdesk.templates-cache')); beforeEach(module('superdesk.itemList')); beforeEach(module(function($provide) { $provide.service('api', function($q) { return function ApiService(endpoint, endpointParam) { return { query: function(params) { params._endpoint = endpoint; params._endpointParam = endpointParam; return $q.when(params); } }; }; }); })); it('can query with default values', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch() .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams).toEqual({ _endpoint: 'search', _endpointParam: undefined, source: { query: { filtered: {} }, size: 25, from: 0, sort: [{_updated: 'desc'}] } }); })); it('can query with endpoint', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ endpoint: 'archive', endpointParam: 'param' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams._endpoint).toBe('archive'); expect(queryParams._endpointParam).toBe('param'); })); it('can query with page', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ pageSize: 15, page: 3 }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.size).toBe(15); expect(queryParams.source.from).toBe(30); })); it('can query with sort', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ sortField: '_id', sortDirection: 'asc' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.sort).toEqual([{_id: 'asc'}]); })); it('can query with repos', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ repos: ['archive', 'ingest'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.repo).toBe('archive,ingest'); })); it('can query with types', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ types: ['text', 'picture', 'composite'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and[0].terms.type).toEqual( ['text', 'picture', 'composite'] ); })); it('can query with states', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ states: ['spiked', 'published'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and[0].or).toEqual([ {term: {state: 'spiked'}}, {term: {state: 'published'}} ]); })); it('can query with notStates', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ notStates: ['spiked', 'published'] }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and).toEqual([ {not: {term: {state: 'spiked'}}}, {not: {term: {state: 'published'}}} ]); })); it('can query with dates', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ creationDateBefore: 1, creationDateAfter: 2, modificationDateBefore: 3, modificationDateAfter: 4 }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and).toEqual([ {range: {_created: {lte: 1, gte: 2}}}, {range: {_updated: {lte: 3, gte: 4}}} ]); })); it('can query with provider, source and urgency', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ provider: 'reuters', source: 'reuters_1', urgency: 5 }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.filter.and).toEqual([ {term: {provider: 'reuters'}}, {term: {source: 'reuters_1'}}, {term: {urgency: 5}} ]); })); it('can query with headline, subject, keyword, uniqueName and body search', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ headline: 'h', subject: 's', keyword: 'k', uniqueName: 'u', body: 'b' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ query_string: { query: 'headline:(*h*) subject.name:(*s*) slugline:(*k*) unique_name:(*u*) body_html:(*b*)', lenient: false, default_operator: 'AND' } }); })); it('can query with general search', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ search: 's' }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ query_string: { query: 'headline:(*s*) subject.name:(*s*) slugline:(*s*) unique_name:(*s*) body_html:(*s*)', lenient: false, default_operator: 'OR' } }); })); it('can query with saved search', inject(function($rootScope, itemListService, api, $q) { var params; api.get = angular.noop; spyOn(api, 'get').and.returnValue($q.when({filter: {query: {type: '["text"]'}}})); itemListService.fetch({ savedSearch: {_links: {self: {href: 'url'}}} }).then(function(_params) { params = _params; }); $rootScope.$digest(); expect(params.source.post_filter.and).toContain({ terms: {type: ['text']} }); })); it('related items query without hypen', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ keyword: 'kilo', related: true }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ prefix: { 'slugline.phrase': 'kilo' } }); })); it('related items query with hypen', inject(function($rootScope, itemListService, api) { var queryParams = null; itemListService.fetch({ keyword: 'kilo-gram', related: true }) .then(function(params) { queryParams = params; }); $rootScope.$digest(); expect(queryParams.source.query.filtered.query).toEqual({ prefix: { 'slugline.phrase': 'kilo gram' } }); })); });
plamut/superdesk
client/app/scripts/superdesk/itemList/itemList_spec.js
JavaScript
agpl-3.0
8,544
var status = 0; var minlvl = 100; var maxlvl = 255; var minplayers = 1; var maxplayers = 6; var time = 15; var open = true; function start() { status = -1; // and when they click lets fight make it turn to a really cool ifght song :D LOL ok like the Zakum battle song? kk and btw uhm can you add a message like after they click OK to say "Matt: Meet me near the top of the map." ? o-o in other words, a action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else if (mode == 0) { cm.sendOk("I spy a chicken :O"); // lLOL cm.dispose(); } else { if (mode == 1) status++; else status--; if (status == 0) { cm.sendYesNo("Hello #b #h ##k! Would you like to fight #rSuper Horntail?#k He is waiting :)"); } else if (status == 1) { if (cm.getPlayer().warning[1] == false && cm.isLeader()) { cm.getPlayer().warning[1] = true; cm.mapMessage("On behalf of MapleZtory, please defeat Big Puff Daddy! rawrawrawr"); var mf = cm.getPlayer().getMap().getMapFactory(); var bossmap = mf.getMap(240030103); bossmap.removePortals(); var mob = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810018); var mob1 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810002); var mob2 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810003); var mob3 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810004); var mob4 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810005); var mob5 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810006); var mob6 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810007); var mob7 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810008); var mob8 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810009); var overrideStats = new net.sf.odinms.server.life.MapleMonsterStats(); overrideStats.setHp(2147000000); overrideStats.setExp(2147000000); overrideStats.setMp(mob.getMaxMp()); // mob.setOverrideStats(overrideStats); mob1.setOverrideStats(overrideStats); mob2.setOverrideStats(overrideStats); mob3.setOverrideStats(overrideStats); mob4.setOverrideStats(overrideStats); mob5.setOverrideStats(overrideStats); mob6.setOverrideStats(overrideStats); mob7.setOverrideStats(overrideStats); mob8.setOverrideStats(overrideStats); mob.setHp(overrideStats.getHp()); //eim.registerMonster(mob); bossmap.spawnMonsterOnGroudBelow(mob, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob1, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob2, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob3, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob4, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob5, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob6, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob7, new java.awt.Point(-182, -178)); bossmap.spawnMonsterOnGroudBelow(mob8, new java.awt.Point(-182, -178)); // bossmap.killAllMonsters(false); // bossmap.killMonster(8810018); // i like that funkshun :( // this one looks pro though :Dlol ur right XD // spawnMonster(int mobid, int HP, int MP, int level, int EXP, int boss, int undead, int amount, int x, int y); cm.dispose(); } else { cm.sendOk("Super Horntail has already been spawned or you are not leader!"); cm.dispose(); } } } }
ZenityMS/forgottenstorysource
scripts/npc/2102000.js
JavaScript
agpl-3.0
3,619
/** * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'uploadwidget', 'ja', { abort: 'アップロードを中止しました。', doneOne: 'ファイルのアップロードに成功しました。', doneMany: '%1個のファイルのアップロードに成功しました。', uploadOne: 'ファイルのアップロード中 ({percentage}%)...', uploadMany: '{max} 個中 {current} 個のファイルをアップロードしました。 ({percentage}%)...' } );
astrobin/astrobin
astrobin/static/astrobin/ckeditor/plugins/uploadwidget/lang/ja.js
JavaScript
agpl-3.0
624
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2013 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, 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 this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; /** * Provide the notification classes. * * @module views * @submodule views.notifications */ YUI.add('juju-notifications', function(Y) { var views = Y.namespace('juju.views'), widgets = Y.namespace('juju.widgets'), Templates = views.Templates; /** * Abstract base class used to view a ModelList of notifications. * * @class NotificationsBaseView */ var NotificationsBaseView = Y.Base.create('NotificationsBaseView', Y.View, [views.JujuBaseView], { initializer: function() { NotificationsView.superclass.constructor.apply(this, arguments); var notifications = this.get('notifications'), env = this.get('env'); // Bind view to model list in a number of ways notifications.addTarget(this); // Re-render the model list changes notifications.after('add', this.slowRender, this); notifications.after('create', this.slowRender, this); notifications.after('remove', this.slowRender, this); notifications.after('reset', this.slowRender, this); // Bind new notifications to the notifier widget. notifications.after('add', this.addNotifier, this); // Env connection state watcher env.on('connectedChange', this.slowRender, this); }, /** * Create and display a notifier widget when a notification is added. * The notifier is created only if: * - the notifier box exists in the DOM; * - the notification is a local one (not related to the delta stream); * - the notification is an error. * * @method addNotifier * @param {Object} ev An event object (with a "model" attribute). * @return {undefined} Mutates only. */ addNotifier: function(ev) { var notification = ev.model, notifierBox = Y.one('.notifications-nav .notifier-box'); // Show error notifications only if the DOM contain the notifier box. if (notifierBox && !notification.get('isDelta') && (notification.get('level') === 'error' || notification.get('level') === 'important')) { var msg = notification.get('message'); if (msg) { msg = new Y.Handlebars.SafeString(msg); } new widgets.Notifier({ title: notification.get('title'), message: msg }).render(notifierBox); } }, /** * Select/click on a notice. Currently this just removes it from the * model_list. * * @method notificationSelect */ notificationSelect: function(evt) { var notifications = this.get('notifications'), target = evt.target, model; if (!target) { return; } if (target.get('tagName') !== 'LI') { target = target.ancestor('li'); } model = notifications.getByClientId(target.get('id')); if (this.selection.seen) { model.set('seen', true); } if (this.selection.hide) { target.hide(true); } this.slowRender(); }, /** * A flow of events can trigger many renders, from the event system * we debounce render requests with this method. * * @method slowRender */ slowRender: function() { var self = this, container = self.get('container'); clearTimeout(this._renderTimeout); this._renderTimeout = setTimeout(function() { if (!container) { return; } self.render(); }, 200); }, render: function() { var container = this.get('container'), env = this.get('env'), connected = env.get('connected'), notifications = this.get('notifications'), state, open = '', btngroup = container.one('.btn-group'); // Honor the current active state if the view is already // rendered if (btngroup && btngroup.hasClass('open')) { open = 'open'; } // However if the size of the message list is now // zero we can close the dialog if (notifications.size() === 0) { open = ''; } var showable = this.getShowable(), show_count = showable.length || 0; if (!connected) { state = 'btn-warning'; } else if (show_count > 0) { state = 'btn-danger'; } else { state = 'btn-info'; } container.setHTML(this.template({ notifications: showable, count: show_count, state: state, open: open, viewAllUri: this.get('nsRouter').url({ gui: '/notifications' }) })); return this; } }, { ATTRS: { /** Applications router utility methods @attribute nsRouter */ nsRouter: {} } }); /** * The view associated with the notifications indicator. * * @class NotificationsView */ var NotificationsView = Y.Base.create('NotificationsView', NotificationsBaseView, [ Y.Event.EventTracker, Y.juju.Dropdown ], { template: Templates.notifications, /* * Actions associated with events. In this case selection events * represent policy flags inside the 'notificationSelect' callback. * * :hide: should the selected element be hidden on selection */ selection: { hide: false, seen: false }, /** * @method getShowable */ getShowable: function() { var notifications = this.get('notifications'); return notifications.filter(function(n) { return n.get('level') === 'error' && n.get('seen') === false; }).map(function(n) { return n.getAttrs(); }); }, /** Renders the notification view and the dropdown widget. @method render */ render: function() { NotificationsView.superclass.render.apply(this, arguments); // Added by the view-dropdown-extension.js this._addDropdownFunc(); return this; } }); views.NotificationsView = NotificationsView; }, '0.1.0', { requires: [ 'view', 'juju-view-utils', 'node', 'handlebars', 'notifier', 'view-dropdown-extension', 'event-tracker' ] });
jrwren/juju-gui
app/views/notifications.js
JavaScript
agpl-3.0
7,674
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, setRead }; function countForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } return UserNotification.count(q).exec(callback); } function create(usernotification, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } new UserNotification(usernotification).save(callback); } function get(id, callback) { if (!id) { return callback(new Error('id is not defined')); } return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } const mq = UserNotification.find(q); mq.limit(+query.limit || DEFAULT_LIMIT); mq.skip(+query.offset || DEFAULT_OFFSET); mq.sort('-timestamps.creation'); mq.exec(callback); } function remove(query, callback) { UserNotification.remove(query, callback); } function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!usernotifications) { return callback(new Error('usernotification is required')); } async.each(usernotifications, setRead, callback); function setRead(usernotification, cb) { usernotification.read = read; usernotification.save(cb); } } function setRead(usernotification, read, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.read = read; usernotification.save(callback); }
heroandtn3/openpaas-esn
backend/core/notification/usernotification.js
JavaScript
agpl-3.0
2,510
'use strict'; angular.module('hopsWorksApp') .controller('DatasetsCtrl', ['$scope', '$q', '$mdSidenav', '$mdUtil', '$log', 'DataSetService', 'JupyterService', '$routeParams', '$route', 'ModalService', 'growl', '$location', 'MetadataHelperService', '$rootScope', 'DelaProjectService', 'DelaClusterProjectService', function ($scope, $q, $mdSidenav, $mdUtil, $log, DataSetService, JupyterService, $routeParams, $route, ModalService, growl, $location, MetadataHelperService, $rootScope, DelaProjectService, DelaClusterProjectService) { var self = this; self.itemsPerPage = 14; self.working = false; //Some variables to keep track of state. self.files = []; //A list of files currently displayed to the user. self.projectId = $routeParams.projectID; //The id of the project we're currently working in. self.pathArray; //An array containing all the path components of the current path. If empty: project root directory. self.sharedPathArray; //An array containing all the path components of a path in a shared dataset self.highlighted; self.parentDS = $rootScope.parentDS; // Details of the currently selecte file/dir self.selected = null; //The index of the selected file in the files array. self.sharedPath = null; //The details about the currently selected file. self.routeParamArray = []; $scope.readme = null; var dataSetService = DataSetService(self.projectId); //The datasetservice for the current project. var delaHopsService = DelaProjectService(self.projectId); var delaClusterService = DelaClusterProjectService(self.projectId); $scope.all_selected = false; self.selectedFiles = {}; //Selected files self.dir_timing; self.isPublic = undefined; self.shared = undefined; self.status = undefined; self.tgState = true; self.onSuccess = function (e) { growl.success("Copied to clipboard", {title: '', ttl: 1000}); e.clearSelection(); }; self.metadataView = {}; self.availableTemplates = []; self.closeSlider = false; self.breadcrumbLen = function () { if (self.pathArray === undefined || self.pathArray === null) { return 0; } var displayPathLen = 10; if (self.pathArray.length <= displayPathLen) { return self.pathArray.length - 1; } return displayPathLen; }; self.cutBreadcrumbLen = function () { if (self.pathArray === undefined || self.pathArray === null) { return false; } if (self.pathArray.length - self.breadcrumbLen() > 0) { return true; } return false; }; $scope.sort = function (keyname) { $scope.sortKey = keyname; //set the sortKey to the param passed $scope.reverse = !$scope.reverse; //if true make it false and vice versa }; /** * watch for changes happening in service variables from the other controller */ $scope.$watchCollection(MetadataHelperService.getAvailableTemplates, function (availTemplates) { if (!angular.isUndefined(availTemplates)) { self.availableTemplates = availTemplates; } }); $scope.$watch(MetadataHelperService.getDirContents, function (response) { if (response === "true") { getDirContents(); MetadataHelperService.setDirContents("false"); } }); self.isSharedDs = function (name) { var top = name.split("::"); if (top.length === 1) { return false; } return true; }; self.isShared = function () { var top = self.pathArray[0].split("::"); if (top.length === 1) { return false; } return true; }; self.sharedDatasetPath = function () { var top = self.pathArray[0].split("::"); if (top.length === 1) { self.sharedPathArray = []; return; } // /proj::shared_ds/path/to -> /proj/ds/path/to // so, we add '1' to the pathLen self.sharedPathArray = new Array(self.pathArray.length + 1); self.sharedPathArray[0] = top[0]; self.sharedPathArray[1] = top[1]; for (var i = 1; i < self.pathArray.length; i++) { self.sharedPathArray[i + 1] = self.pathArray[i]; } return self.sharedPathArray; }; /* * Get all datasets under the current project. * @returns {undefined} */ self.getAllDatasets = function () { //Get the path for an empty patharray: will get the datasets var path = getPath([]); dataSetService.getContents(path).then( function (success) { self.files = success.data; self.pathArray = []; console.log(success); }, function (error) { console.log("Error getting all datasets in project " + self.projectId); console.log(error); }); }; /** * Get the contents of the directory at the path with the given path components and load it into the frontend. * @param {type} The array of path compontents to fetch. If empty, fetches the current path. * @returns {undefined} */ var getDirContents = function (pathComponents) { //Construct the new path array var newPathArray; if (pathComponents) { newPathArray = pathComponents; } else if (self.routeParamArray) { newPathArray = self.pathArray.concat(self.routeParamArray); } else { newPathArray = self.pathArray; } //Convert into a path var newPath = getPath(newPathArray); self.files = []; self.working = true; self.dir_timing = new Date().getTime(); //Get the contents and load them dataSetService.getContents(newPath).then( function (success) { //Clear any selections self.all_selected = false; self.selectedFiles = {}; //Reset the selected file self.selected = null; self.working = false; //Set the current files and path self.files = success.data; self.pathArray = newPathArray; console.log(success); // alert('Execution time: ' + (new Date().getTime() - self.dir_timing)); console.log('Execution time: ' + (new Date().getTime() - self.dir_timing)); if ($rootScope.selectedFile) { var filePathArray = self.pathArray.concat($rootScope.selectedFile); self.getFile(filePathArray); $rootScope.selectedFile = undefined; } }, function (error) { if (error.data.errorMsg.indexOf("Path is not a directory.") > -1) { var popped = newPathArray.pop(); console.log(popped); self.openDir({name: popped, dir: false, underConstruction: false}); self.pathArray = newPathArray; self.routeParamArray = []; //growl.info(error.data.errorMsg, {title: 'Info', ttl: 2000}); getDirContents(); } else if (error.data.errorMsg.indexOf("Path not found :") > -1) { self.routeParamArray = []; //$route.updateParams({fileName:''}); growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); getDirContents(); } self.working = false; console.log("Error getting the contents of the path " + getPath(newPathArray)); console.log(error); }); }; self.getFile = function (pathComponents) { var newPathArray; newPathArray = pathComponents; //Convert into a path var newPath = getPath(newPathArray); dataSetService.getFile(newPath).then( function (success) { self.highlighted = success.data; self.select(self.highlighted.name, self.highlighted, undefined); $scope.search = self.highlighted.name; }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); }; var init = function () { //Check if the current dataset is set if ($routeParams.datasetName) { //Dataset is set: get the contents self.pathArray = [$routeParams.datasetName]; } else { //No current dataset is set: get all datasets. self.pathArray = []; } if ($routeParams.datasetName && $routeParams.fileName) { //file name is set: get the contents var paths = $routeParams.fileName.split("/"); paths.forEach(function (entry) { if (entry !== "") { self.routeParamArray.push(entry); } }); } getDirContents(); self.tgState = true; }; init(); /** * Upload a file to the specified path. * @param {type} path * @returns {undefined} */ var upload = function (path) { dataSetService.upload(path).then( function (success) { console.log("upload success"); console.log(success); getDirContents(); }, function (error) { console.log("upload error"); console.log(error); }); }; /** * Remove the inode at the given path. If called on a folder, will * remove the folder and all its contents recursively. * @param {type} path. The project-relative path to the inode to be removed. * @returns {undefined} */ var removeInode = function (path) { dataSetService.removeDataSetDir(path).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 1000}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); }; /** * Open a modal dialog for folder creation. The folder is created at the current path. * @returns {undefined} */ self.newDataSetModal = function () { ModalService.newFolder('md', getPath(self.pathArray)).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 1000}); getDirContents(); }, function (error) { //The user changed his/her mind. Don't really need to do anything. // getDirContents(); }); }; /** * Delete the file with the given name under the current path. * If called on a folder, will remove the folder * and all its contents recursively. * @param {type} fileName * @returns {undefined} */ self.deleteFile = function (fileName) { var removePathArray = self.pathArray.slice(0); removePathArray.push(fileName); removeInode('file/' + getPath(removePathArray)); }; /** * Delete the dataset with the given name under the current path. * @param {type} fileName * @returns {undefined} */ self.deleteDataset = function (fileName) { var removePathArray = self.pathArray.slice(0); removePathArray.push(fileName); removeInode(getPath(removePathArray)); }; // self.deleteSelected = function () { // var removePathArray = self.pathArray.slice(0); // for(var fileName in self.selectedFiles){ // removePathArray.push(fileName); // removeInode(getPath(removePathArray)); // } // }; /** * Makes the dataset public for anybody within the local cluster or any outside cluster. * @param id inodeId */ self.sharingDataset = {}; self.shareWithHops = function (id) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet public? \n\ This will make all its files available for any registered user to download and process.').then( function (success) { self.sharingDataset[id] = true; delaHopsService.shareWithHopsByInodeId(id).then( function (success) { self.sharingDataset[id] = false; growl.success(success.data.successMessage, {title: 'The DataSet is now Public(Hops Site).', ttl: 1500}); getDirContents(); }, function (error) { self.sharingDataset[id] = false; growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); } ); }; /** * Makes the dataset public for anybody within the local cluster * @param id inodeId */ self.shareWithCluster = function (id) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet public? \n\ This will make all its files available for any cluster user to share and process.').then( function (success) { self.sharingDataset[id] = true; delaClusterService.shareWithClusterByInodeId(id).then( function (success) { self.sharingDataset[id] = false; growl.success(success.data.successMessage, {title: 'The DataSet is now Public(Cluster).', ttl: 1500}); getDirContents(); }, function (error) { self.sharingDataset[id] = false; growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); } ); }; self.showManifest = function(publicDSId){ delaHopsService.getManifest(publicDSId).then(function(success){ var manifest = success.data; ModalService.json('md','Manifest', manifest).then(function(){ }); }); }; self.unshareFromHops = function (publicDSId) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet private? ').then( function (success) { delaHopsService.unshareFromHops(publicDSId, false).then( function (success) { growl.success(success.data.successMessage, {title: 'The DataSet is not Public(internet) anymore.', ttl: 1500}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); } ); }; self.unshareFromCluster = function (inodeId) { ModalService.confirm('sm', 'Confirm', 'Are you sure you want to make this DataSet private? ').then( function (success) { delaClusterService.unshareFromCluster(inodeId).then( function (success) { growl.success(success.data.successMessage, {title: 'The DataSet is not Public(cluster) anymore.', ttl: 1500}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); } ); }; self.parentPathArray = function () { var newPathArray = self.pathArray.slice(0); var clippedPath = newPathArray.splice(1, newPathArray.length - 1); return clippedPath; }; self.unzip = function (filename) { var pathArray = self.pathArray.slice(0); // pathArray.push(self.selected); pathArray.push(filename); var filePath = getPath(pathArray); growl.info("Started unzipping...", {title: 'Unzipping Started', ttl: 2000, referenceId: 4}); dataSetService.unzip(filePath).then( function (success) { growl.success("Refresh your browser when finished", {title: 'Unzipping in Background', ttl: 5000, referenceId: 4}); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error unzipping file', ttl: 5000, referenceId: 4}); }); }; self.isZippedfile = function () { // https://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript var re = /(?:\.([^.]+))?$/; var ext = re.exec(self.selected)[1]; switch (ext) { case "zip": return true; case "rar": return true; case "tar": return true; case "tgz": return true; case "gz": return true; case "bz2": return true; case "7z": return true; } return false; }; self.convertIPythonNotebook = function (filename) { var pathArray = self.pathArray.slice(0); pathArray.push(filename); //self.selected var filePath = getPath(pathArray); growl.info("Converting...", {title: 'Conversion Started', ttl: 2000, referenceId: 4}); JupyterService.convertIPythonNotebook(self.projectId, filePath).then( function (success) { growl.success("Finished - refresh your browser", {title: 'Converting in Background', ttl: 3000, referenceId: 4}); getDirContents(); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error converting notebook', ttl: 5000, referenceId: 4}); }); }; self.isIPythonNotebook = function () { if (self.selected === null || self.selected === undefined) { return false; } if (self.selected.indexOf('.') == -1) { return false; } var ext = self.selected.split('.').pop(); if (ext === null || ext === undefined) { return false; } switch (ext) { case "ipynb": return true; } return false; }; /** * Preview the requested file in a Modal. If the file is README.md * and the preview flag is false, preview the file in datasets. * @param {type} dataset * @param {type} preview * @returns {undefined} */ self.filePreview = function (dataset, preview, readme) { var fileName = ""; //handle README.md filename for datasets browser viewing here if (readme && !preview) { if (dataset.shared === true) { fileName = dataset.selectedIndex + "/README.md"; } else { fileName = dataset.path.substring(dataset.path.lastIndexOf('/')).replace('/', '') + "/README.md"; } } else { fileName = dataset; } var previewPathArray = self.pathArray.slice(0); previewPathArray.push(fileName); var filePath = getPath(previewPathArray); //If filename is README.md then try fetching it without the modal if (readme && !preview) { dataSetService.filePreview(filePath, "head").then( function (success) { var fileDetails = JSON.parse(success.data.data); var content = fileDetails.filePreviewDTO[0].content; var conv = new showdown.Converter({parseImgDimensions: true}); $scope.readme = conv.makeHtml(content); }, function (error) { //To hide README from UI growl.error(error.data.errorMsg, {title: 'Error retrieving README file', ttl: 5000, referenceId: 4}); $scope.readme = null; }); } else { ModalService.filePreview('lg', fileName, filePath, self.projectId, "head").then( function (success) { }, function (error) { }); } }; self.copy = function (inodeId, name) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then(function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); var finalPath = relPath + "/" + name; dataSetService.copy(inodeId, finalPath).then( function (success) { getDirContents(); growl.success('', {title: 'Copied ' + name + ' successfully', ttl: 5000, referenceId: 4}); }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not copied', ttl: 5000, referenceId: 4}); }); }, function (error) { }); }; self.copySelected = function () { //Check if we are to move one file or many if (Object.keys(self.selectedFiles).length === 0 && self.selectedFiles.constructor === Object) { if (self.selected !== null && self.selected !== undefined) { self.copy(self.selected.id, self.selected.name); } } else if (Object.keys(self.selectedFiles).length !== 0 && self.selectedFiles.constructor === Object) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then( function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); //var finalPath = relPath + "/" + name; var names = []; var i = 0; //Check if have have multiple files for (var name in self.selectedFiles) { names[i] = name; i++; } var errorMsg = ''; for (var name in self.selectedFiles) { dataSetService.copy(self.selectedFiles[name].id, relPath + "/" + name).then( function (success) { //If we copied the last file if (name === names[names.length - 1]) { getDirContents(); for (var i = 0; i < names.length; i++) { delete self.selectedFiles[names[i]]; } self.all_selected = false; } //growl.success('',{title: 'Copied successfully', ttl: 5000, referenceId: 4}); }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not copied', ttl: 5000}); errorMsg = error.data.errorMsg; }); if (errorMsg === 'Can not copy/move to a public dataset.') { break; } } }, function (error) { //The user changed their mind. }); } }; self.move = function (inodeId, name) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then( function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); var finalPath = relPath + "/" + name; dataSetService.move(inodeId, finalPath).then( function (success) { getDirContents(); growl.success(success.data.successMessage, {title: 'Moved successfully. Opened dest dir: ' + relPath, ttl: 2000}); }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not moved', ttl: 5000}); }); }, function (error) { }); }; self.isSelectedFiles = function () { return Object.keys(self.selectedFiles).length; }; self.moveSelected = function () { //Check if we are to move one file or many if (Object.keys(self.selectedFiles).length === 0 && self.selectedFiles.constructor === Object) { if (self.selected !== null && self.selected !== undefined) { self.move(self.selected.id, self.selected.name); } } else if (Object.keys(self.selectedFiles).length !== 0 && self.selectedFiles.constructor === Object) { ModalService.selectDir('lg', "/[^]*/", "problem selecting folder").then( function (success) { var destPath = success; // Get the relative path of this DataSet, relative to the project home directory // replace only first occurrence var relPath = destPath.replace("/Projects/" + self.projectId + "/", ""); //var finalPath = relPath + "/" + name; var names = []; var i = 0; //Check if have have multiple files for (var name in self.selectedFiles) { names[i] = name; i++; } var errorMsg = ''; for (var name in self.selectedFiles) { dataSetService.move(self.selectedFiles[name].id, relPath + "/" + name).then( function (success) { //If we moved the last file if (name === names[names.length - 1]) { getDirContents(); for (var i = 0; i < names.length; i++) { delete self.selectedFiles[names[i]]; } self.all_selected = false; } }, function (error) { growl.error(error.data.errorMsg, {title: name + ' was not moved', ttl: 5000}); errorMsg = error.data.errorMsg; }); if (errorMsg === 'Can not copy/move to a public dataset.') { break; } } }, function (error) { //The user changed their mind. }); } }; var renameModal = function (inodeId, name) { var pathComponents = self.pathArray.slice(0); var newPath = getPath(pathComponents); var destPath = newPath + '/'; ModalService.enterName('sm', "Rename File or Directory", name).then( function (success) { var fullPath = destPath + success.newName; dataSetService.move(inodeId, fullPath).then( function (success) { getDirContents(); self.all_selected = false; self.selectedFiles = {}; self.selected = null; }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); self.all_selected = false; self.selectedFiles = {}; self.selected = null; }); }); }; self.rename = function (inodeId, name) { renameModal(inodeId, name); }; self.renameSelected = function () { if (self.isSelectedFiles() === 1) { var inodeId, inodeName; for (var name in self.selectedFiles) { inodeName = name; } inodeId = self.selectedFiles[inodeName]['id']; renameModal(inodeId, inodeName); } }; /** * Opens a modal dialog for file upload. * @returns {undefined} */ self.uploadFile = function () { var templateId = -1; ModalService.upload('lg', self.projectId, getPath(self.pathArray), templateId).then( function (success) { growl.success(success, {ttl: 5000}); getDirContents(); }, function (error) { // growl.info("Closed without saving.", {title: 'Info', ttl: 5000}); getDirContents(); }); }; /** * Sends a request to erasure code a file represented by the given path. * It checks * .. if the given path resolves to a file or a dir * .. if the given path is an existing file * .. if the given file is large enough (comprises more than 10 blocks) * * If all of the above are met, the compression takes place in an asynchronous operation * and the user gets notified when it finishes via a message * * @param {type} file * @returns {undefined} */ self.compress = function (file) { var pathArray = self.pathArray.slice(0); pathArray.push(file.name); var filePath = getPath(pathArray); //check if the path is a dir dataSetService.isDir(filePath).then( function (success) { var object = success.data.successMessage; switch (object) { case "DIR": ModalService.alert('sm', 'Alert', 'You can only compress files'); break; case "FILE": //if the path is a file go on dataSetService.checkFileExist(filePath).then( function (successs) { //check the number of blocks in the file dataSetService.checkFileBlocks(filePath).then( function (successss) { var noOfBlocks = parseInt(successss.data); console.log("NO OF BLOCKS " + noOfBlocks); if (noOfBlocks >= 10) { ModalService.alert('sm', 'Confirm', 'This operation is going to run in the background').then( function (modalSuccess) { console.log("FILE PATH IS " + filePath); dataSetService.compressFile(filePath); }); } else { growl.error("The requested file is too small to be compressed", {title: 'Error', ttl: 5000, referenceId: 4}); } }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); }); } }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000, referenceId: 4}); }); }; /** * Opens a modal dialog for sharing. * @returns {undefined} */ self.share = function (name) { ModalService.shareDataset('md', name).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 5000}); getDirContents(); }, function (error) { }); }; /** * Opens a modal dialog to make dataset editable * @param {type} name * @param {type} permissions * @returns {undefined} */ self.permissions = function (name, permissions) { ModalService.permissions('md', name, permissions).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 5000}); getDirContents(); }, function (error) { }); }; /** * Opens a modal dialog for unsharing. * @param {type} name * @returns {undefined} */ self.unshare = function (name) { ModalService.unshareDataset('md', name).then( function (success) { growl.success(success.data.successMessage, {title: 'Success', ttl: 5000}); getDirContents(); }, function (error) { }); }; /** * Upon click on a inode in the browser: * + If folder: open folder, fetch contents from server and display. * + If file: open a confirm dialog prompting for download. * @param {type} file * @returns {undefined} */ self.openDir = function (file) { if (file.dir) { var newPathArray = self.pathArray.slice(0); newPathArray.push(file.name); getDirContents(newPathArray); } else if (!file.underConstruction) { ModalService.confirm('sm', 'Confirm', 'Do you want to download this file?').then( function (success) { var downloadPathArray = self.pathArray.slice(0); downloadPathArray.push(file.name); var filePath = getPath(downloadPathArray); //growl.success("Asdfasdf", {title: 'asdfasd', ttl: 5000}); dataSetService.checkFileForDownload(filePath).then( function (success) { dataSetService.fileDownload(filePath); }, function (error) { growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000}); }); } ); } else { growl.info("File under construction.", {title: 'Info', ttl: 5000}); } }; /** * Go up to parent directory. * @returns {undefined} */ self.back = function () { var newPathArray = self.pathArray.slice(0); newPathArray.pop(); if (newPathArray.length === 0) { $location.path('/project/' + self.projectId + '/datasets'); } else { getDirContents(newPathArray); } }; self.goToDataSetsDir = function () { $location.path('/project/' + self.projectId + '/datasets'); }; /** * Go to the folder at the index in the pathArray array. * @param {type} index * @returns {undefined} */ self.goToFolder = function (index) { var newPathArray = self.pathArray.slice(0); newPathArray.splice(index, newPathArray.length - index); getDirContents(newPathArray); }; self.menustyle = { "opacity": 0.2 }; /** * Select an inode; updates details panel. * @param {type} selectedIndex * @param {type} file * @param {type} event * @returns {undefined} */ self.select = function (selectedIndex, file, event) { // 1. Turn off the selected file at the top of the browser. // Add existing selected file (idempotent, if already added) // If file already selected, deselect it. if (event && event.ctrlKey) { } else { self.selectedFiles = {}; } if (self.isSelectedFiles() > 0) { self.selected = null; } else { self.selected = file.name; } self.selectedFiles[file.name] = file; self.selectedFiles[file.name].selectedIndex = selectedIndex; self.menustyle.opacity = 1.0; console.log(self.selectedFiles); }; self.haveSelected = function (file) { if (file === undefined || file === null || file.name === undefined || file.name === null) { return false; } if (file.name in self.selectedFiles) { return true; } return false; }; self.selectAll = function () { var i = 0; var min = Math.min(self.itemsPerPage, self.files.length); for (i = 0; i < min; i++) { var f = self.files[i]; self.selectedFiles[f.name] = f; self.selectedFiles[f.name].selectedIndex = i; } self.menustyle.opacity = 1; self.selected = null; self.all_selected = true; if (Object.keys(self.selectedFiles).length === 1 && self.selectedFiles.constructor === Object) { self.selected = Object.keys(self.selectedFiles)[0]; } }; //TODO: Move files to hdfs trash folder self.trashSelected = function () { }; self.deleteSelected = function () { var i = 0; var names = []; for (var name in self.selectedFiles) { names[i] = name; self.deleteFile(name); } for (var i = 0; i < names.length; i++) { delete self.selectedFiles[names[i]]; } self.all_selected = false; self.selectedFiles = {}; self.selected = null; }; self.deselect = function (selectedIndex, file, event) { var i = 0; if (Object.keys(self.selectedFiles).length === 1 && self.selectedFiles.constructor === Object) { for (var name in self.selectedFiles) { if (file.name === name) { delete self.selectedFiles[name]; //break; } } } else { if (event.ctrlKey) { for (var name in self.selectedFiles) { if (file.name === name) { delete self.selectedFiles[name]; break; } } } else { for (var name in self.selectedFiles) { if (file.name !== name) { delete self.selectedFiles[name]; //break; } } } } if (Object.keys(self.selectedFiles).length === 0 && self.selectedFiles.constructor === Object) { self.menustyle.opacity = 0.2; self.selected = null; } else if (Object.keys(self.selectedFiles).length === 1 && self.selectedFiles.constructor === Object) { self.menustyle.opacity = 1.0; self.selected = Object.keys(self.selectedFiles)[0]; } self.all_selected = false; }; self.deselectAll = function () { self.selectedFiles = {}; self.selected = null; self.sharedPath = null; self.menustyle.opacity = 0.2; }; self.toggleLeft = buildToggler('left'); self.toggleRight = buildToggler('right'); function buildToggler(navID) { var debounceFn = $mdUtil.debounce(function () { $mdSidenav(navID).toggle() .then(function () { MetadataHelperService.fetchAvailableTemplates() .then(function (response) { self.availableTemplates = JSON.parse(response.board).templates; }); }); }, 300); return debounceFn; } ; self.getSelectedPath = function (selectedFile) { if (self.isSelectedFiles() !== 1) { return ""; } return "hdfs://" + selectedFile.path; }; }]); /** * Turn the array <i>pathArray</i> containing, path components, into a path string. * @param {type} pathArray * @returns {String} */ var getPath = function (pathArray) { return pathArray.join("/"); };
FilotasSiskos/hopsworks
hopsworks-web/yo/app/scripts/controllers/datasetsCtrl.js
JavaScript
agpl-3.0
46,695
/** * Carousel controller * * @author Hein Bekker <[email protected]> * @copyright (c) 2015 Hein Bekker * @license http://www.gnu.org/licenses/agpl-3.0.txt AGPLv3 */ (function (window, angular, undefined) { 'use strict'; angular .module('nb.carousel') .controller('nbCarouselController', nbCarouselController); nbCarouselController.$inject = ['$scope', '$element', '$timeout', '$interval', '$animate', 'GSAP', '$window', 'nbWindow', '_']; function nbCarouselController ($scope, $element, $timeout, $interval, $animate, GSAP, $window, nbWindow, _) { /*jshint validthis: true */ var self = this; var $$window = angular.element($window); var deregister = []; var currentInterval; // {Promise} var deferGotoInterval; // {Promise} var deferGotoIndex; var deferGotoDirection; var flags = { skipAnimation: true, // {Boolean} Prevents slide transition during the first gotoIndex(). destroyed: false, // {Boolean} Whether the scope has been destroyed. transitioning: false // {Boolean} Whether there is a transition in progress. }; var oldSlide; // {Scope} var newSlide; // {Scope} var maxWidth = 0, maxHeight = 0; $scope.complete = false; // {Boolean} Whether all slides have loaded or failed to load. $scope.slides = []; $scope.direction = self.direction = 'left'; $scope.currentIndex = -1; $scope.isPlaying = self.isPlaying = false; /** * * @param {int} index * @returns {Boolean} */ $scope.isCurrentSlideIndex = function (index) { return $scope.currentIndex === index; }; /** * * @param {int} index * @param {string} direction left, right */ $scope.gotoIndex = function (index, direction) { cancelDeferGoto(); // Stop here if there is a transition in progress or if the index has not changed. if (flags.transitioning || $scope.currentIndex === index) { return; } oldSlide = $scope.slides[$scope.currentIndex]; newSlide = $scope.slides[index]; // Stop here if the slide is not loaded. if (!newSlide.complete) { // Periodically check if the slide is loaded, and then try gotoIndex() again. deferGoto(index, direction); return; } $animate.addClass(newSlide.$element, 'fade-in', angular.noop); if (angular.isUndefined(direction)) { direction = (index < $scope.currentIndex) ? 'left' : 'right'; } $scope.direction = self.direction = direction; $scope.currentIndex = index; // Reset the timer when changing slides. restartTimer(); if (flags.skipAnimation || $scope.noTransition) { flags.skipAnimation = false; gotoDone(); } else { $timeout(function () { // Stop here if the scope has been destroyed. if (flags.destroyed) { return; } flags.transitioning = true; // Force reflow. var reflow = newSlide.$element[0].offsetWidth; $animate.removeClass(oldSlide.$element, 'active', angular.noop); $animate.addClass(newSlide.$element, 'active', gotoDone) .then(function () { flags.transitioning = false; }); }); } }; /** * Callback function fired after transition has been completed. */ function gotoDone () { // Stop here if the scope has been destroyed. if (flags.destroyed) { return; } if (oldSlide) { oldSlide.$element.removeClass('active'); } if (newSlide) { newSlide.$element.addClass('active'); } } /** * * @param {int} index * @param {string} direction left, right */ function deferGoto (index, direction) { deferGotoIndex = index; deferGotoDirection = direction; deferGotoFn(); } /** * Periodically checks if a slide is loaded. If so, fires gotoIndex(). */ function deferGotoFn () { cancelDeferGoto(); if ($scope.slides[deferGotoIndex].complete) { $scope.gotoIndex(deferGotoIndex, deferGotoDirection); } else { deferGotoInterval = $interval(deferGotoFn, 50); } } function cancelDeferGoto () { if (deferGotoInterval) { $interval.cancel(deferGotoInterval); deferGotoInterval = null; } } /** * Go to previous slide. */ $scope.prev = function () { var newIndex = $scope.currentIndex > 0 ? $scope.currentIndex - 1 : $scope.slides.length - 1; $scope.gotoIndex(newIndex, 'left'); }; /** * Go to next slide. */ $scope.next = function () { var newIndex = $scope.currentIndex < $scope.slides.length - 1 ? $scope.currentIndex + 1 : 0; $scope.gotoIndex(newIndex, 'right'); }; function restartTimer () { cancelTimer(); var interval = +$scope.interval; if (!isNaN(interval) && interval > 0) { currentInterval = $interval(timerFn, interval); } } function cancelTimer () { if (currentInterval) { $interval.cancel(currentInterval); currentInterval = null; } } function timerFn () { var interval = +$scope.interval; if (self.isPlaying && !isNaN(interval) && interval > 0) { $scope.next(); } else { $scope.pause(); } } $scope.play = function () { if (!self.isPlaying) { $scope.isPlaying = self.isPlaying = true; restartTimer(); } }; $scope.pause = function () { if (!$scope.noPause) { $scope.isPlaying = self.isPlaying = false; cancelTimer(); } }; /** * * @param {Scope} slide Slide scope * @param {DOM element} element Slide DOM element */ self.addSlide = function (slide, element) { slide.$element = element; $scope.slides.push(slide); if ($scope.slides.length === 1 || slide.active) { $scope.gotoIndex($scope.slides.length - 1); if ($scope.slides.length == 1) { $scope.play(); } } else { slide.active = false; } }; /** * * @param {Scope} slide */ self.removeSlide = function (slide) { GSAP.TweenMax.killTweensOf(slide.$element); var index = _.indexOf($scope.slides, slide); $scope.slides.splice(index, 1); if ($scope.slides.length > 0 && slide.active) { if (index >= $scope.slides.length) { $scope.gotoIndex(index - 1); } else { $scope.gotoIndex(index); } } else if ($scope.currentIndex > index) { $scope.currentIndex--; } }; /** * Checks if all the slides are loaded and sets the carousel load state. * * @param {Scope} slide */ self.setSlideComplete = function (slide) { var length = $scope.slides.length; var i = 0; angular.forEach($scope.slides, function (slide) { if (slide.complete) { i++; } }); $scope.complete = (length === i); }; /** * Sets maximum width of slides (allows for slides of different sizes). * * @param {int} value */ self.setMaxWidth = function (value) { if (value > maxWidth) { maxWidth = value; resize(); } }; /** * Sets maximum height of slides (allows for slides of different sizes). * * @param {int} value */ self.setMaxHeight = function (value) { if (value > maxHeight) { maxHeight = value; resize(); } }; /** * Resizes carousel and slides. */ function resize (apply) { if (maxWidth && maxHeight) { var windowHeight = nbWindow.windowHeight() * 0.8; var width = $element[0].scrollWidth; var height = Math.min(windowHeight, maxHeight / maxWidth * width); if (width && height) { // Set height of carousel. $element.css('height', height + 'px'); // Set width and height of slides. angular.forEach($scope.slides, function (slide, index) { slide.resize(width, height); }); } } } // Reset the timer when the interval property changes. deregister.push($scope.$watch('interval', restartTimer)); // Gives the $animate service access to carousel properties. deregister.push($scope.$watch('noTransition', function (value) { self.noTransition = value; })); deregister.push($scope.$watch('transitionDuration', function (value) { self.transitionDuration = value; })); deregister.push($scope.$watch('transitionEase', function (value) { self.transitionEase = value; })); var onWindowResize = _.throttle(function () { resize(true); }, 60); // On window resize, resize carousel and slides. $$window.on('resize', onWindowResize); $scope.$on('$destroy', function () { flags.destroyed = true; // Deregister watchers. angular.forEach(deregister, function (fn) { fn(); }); // Cancel deferred goto interval. cancelDeferGoto(); // Cancel timer interval. cancelTimer(); // Unbind window resize event listener. $$window.off('resize', onWindowResize); }); } })(window, window.angular);
netbek/nb-carousel
src/js/nb-carousel.controller.js
JavaScript
agpl-3.0
8,617
/* * (c) Copyright Ascensio System SIA 2010-2014 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ var c_oMainTables = { Main: 255, App: 1, Core: 2, Presentation: 3, ViewProps: 4, VmlDrawing: 5, TableStyles: 6, Themes: 20, ThemeOverride: 21, SlideMasters: 22, SlideLayouts: 23, Slides: 24, NotesMasters: 25, NotesSlides: 26, HandoutMasters: 30, SlideRels: 40, ThemeRels: 41, ImageMap: 42, FontMap: 43, FontsEmbedded: 44 }; function CSeekTableEntry() { this.Type = 0; this.SeekPos = 0; } function GUID() { var S4 = function () { var ret = (((1 + Math.random()) * 65536) | 0).toString(16).substring(1); ret = ret.toUpperCase(); return ret; }; return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); } function CBinaryFileWriter() { this.tableStylesGuides = new Array(); this.Init = function () { var _canvas = document.createElement("canvas"); var _ctx = _canvas.getContext("2d"); this.len = 1024 * 1024 * 5; this.ImData = _ctx.createImageData(this.len / 4, 1); this.data = this.ImData.data; this.pos = 0; delete _canvas; }; this.IsWordWriter = false; this.ImData = null; this.data = null; this.len = 0; this.pos = 0; this.Init(); this.UseContinueWriter = false; this.IsUseFullUrl = false; this.DocumentOrigin = ""; this.PresentationThemesOrigin = ""; var oThis = this; this.Start_UseFullUrl = function (origin) { this.IsUseFullUrl = true; this.DocumentOrigin = origin; }; this.Start_UseDocumentOrigin = function (origin) { this.PresentationThemesOrigin = origin + "/presentationthemes/"; }; this.End_UseFullUrl = function () { this.IsUseFullUrl = false; }; this.Copy = function (oMemory, nPos, nLen) { for (var Index = 0; Index < nLen; Index++) { this.CheckSize(1); this.data[this.pos++] = oMemory.data[Index + nPos]; } }; this.CheckSize = function (count) { if (this.pos + count >= this.len) { var _canvas = document.createElement("canvas"); var _ctx = _canvas.getContext("2d"); var oldImData = this.ImData; var oldData = this.data; var oldPos = this.pos; this.len *= 2; this.ImData = _ctx.createImageData(this.len / 4, 1); this.data = this.ImData.data; var newData = this.data; for (var i = 0; i < this.pos; i++) { newData[i] = oldData[i]; } delete _canvas; } }; this.GetBase64Memory = function () { return Base64Encode(this.data, this.pos, 0); }; this.GetBase64Memory2 = function (nPos, nLen) { return Base64Encode(this.data, nLen, nPos); }; this.GetCurPosition = function () { return this.pos; }; this.Seek = function (nPos) { this.pos = nPos; }; this.Skip = function (nDif) { this.pos += nDif; }; this.WriteBool = function (val) { this.CheckSize(1); if (false == val) { this.data[this.pos++] = 0; } else { this.data[this.pos++] = 1; } }; this.WriteUChar = function (val) { this.CheckSize(1); this.data[this.pos++] = val; }; this.WriteUShort = function (val) { this.CheckSize(2); this.data[this.pos++] = (val) & 255; this.data[this.pos++] = (val >>> 8) & 255; }; this.WriteULong = function (val) { this.CheckSize(4); this.data[this.pos++] = (val) & 255; this.data[this.pos++] = (val >>> 8) & 255; this.data[this.pos++] = (val >>> 16) & 255; this.data[this.pos++] = (val >>> 24) & 255; }; this.WriteDouble = function (val) { this.WriteULong((val * 100000) >> 0); }; this.WriteString = function (text) { var count = text.length & 65535; this.WriteULong(count); this.CheckSize(count); for (var i = 0; i < count; i++) { var c = text.charCodeAt(i) & 255; this.data[this.pos++] = c; } }; this.WriteString2 = function (text) { var count = text.length & 2147483647; var countWrite = 2 * count; this.WriteULong(count); this.CheckSize(countWrite); for (var i = 0; i < count; i++) { var c = text.charCodeAt(i) & 65535; this.data[this.pos++] = c & 255; this.data[this.pos++] = (c >>> 8) & 255; } }; this.WriteBuffer = function (data, _pos, count) { this.CheckSize(count); for (var i = 0; i < count; i++) { this.data[this.pos++] = data[_pos + i]; } }; this.m_arStack = new Array(); this.m_lStackPosition = 0; this.m_arMainTables = new Array(); this.StartRecord = function (lType) { this.m_arStack[this.m_lStackPosition] = this.pos + 5; this.m_lStackPosition++; this.WriteUChar(lType); this.WriteULong(0); }; this.EndRecord = function () { this.m_lStackPosition--; var _seek = this.pos; this.pos = this.m_arStack[this.m_lStackPosition] - 4; this.WriteULong(_seek - this.m_arStack[this.m_lStackPosition]); this.pos = _seek; }; this.StartMainRecord = function (lType) { var oEntry = new CSeekTableEntry(); oEntry.Type = lType; oEntry.SeekPos = this.pos; this.m_arMainTables[this.m_arMainTables.length] = oEntry; }; this.WriteReserved = function (lCount) { this.CheckSize(lCount); var _d = this.data; var _p = this.pos; var _e = this.pos + lCount; while (_p < _e) { _d[_p++] = 0; } this.pos += lCount; }; this.WriteMainPart = function () { var _pos = this.pos; this.pos = 0; var _count = this.m_arMainTables.length; for (var i = 0; i < _count; i++) { this.WriteUChar(this.m_arMainTables[i].Type); this.WriteULong(this.m_arMainTables[i].SeekPos); } this.pos = _pos; }; this._WriteString1 = function (type, val) { this.WriteUChar(type); this.WriteString2(val); }; this._WriteString2 = function (type, val) { if (val != null) { this._WriteString1(type, val); } }; this._WriteUChar1 = function (type, val) { this.WriteUChar(type); this.WriteUChar(val); }; this._WriteUChar2 = function (type, val) { if (val != null) { this._WriteUChar1(type, val); } }; this._WriteBool1 = function (type, val) { this.WriteUChar(type); this.WriteBool(val); }; this._WriteBool2 = function (type, val) { if (val != null) { this._WriteBool1(type, val); } }; this._WriteInt1 = function (type, val) { this.WriteUChar(type); this.WriteULong(val); }; this._WriteInt2 = function (type, val) { if (val != null) { this._WriteInt1(type, val); } }; this._WriteInt3 = function (type, val, scale) { this._WriteInt1(type, val * scale); }; this._WriteInt4 = function (type, val, scale) { if (val != null) { this._WriteInt1(type, (val * scale) >> 0); } }; this._WriteDouble1 = function (type, val) { var _val = val * 10000; this._WriteInt1(type, _val); }; this._WriteDouble2 = function (type, val) { if (val != null) { this._WriteDouble1(type, val); } }; this._WriteLimit1 = this._WriteUChar1; this._WriteLimit2 = this._WriteUChar2; this.WriteRecord1 = function (type, val, func_write) { this.StartRecord(type); func_write(val); this.EndRecord(); }; this.WriteRecord2 = function (type, val, func_write) { if (null != val) { this.StartRecord(type); func_write(val); this.EndRecord(); } }; this.WriteRecord3 = function (type, val, func_write) { if (null != val) { var _start_pos = this.pos; this.StartRecord(type); func_write(val); this.EndRecord(); if ((_start_pos + 5) == this.pos) { this.pos -= 5; return false; } return true; } return false; }; this.WriteRecordArray = function (type, subtype, val_array, func_element_write) { this.StartRecord(type); var len = val_array.length; this.WriteULong(len); for (var i = 0; i < len; i++) { this.WriteRecord1(subtype, val_array[i], func_element_write); } this.EndRecord(); }; this.font_map = {}; this.image_map = {}; this.WriteDocument = function (presentation) { this.font_map = {}; this.image_map = {}; this.WriteReserved(5 * 30); this.StartMainRecord(c_oMainTables.Main); this.WriteULong(1347441753); this.WriteULong(0); if (presentation.App) { this.WriteApp(presentation.App); } if (presentation.Core) { this.WriteCore(presentation.Core); } if (presentation.ViewProps) { this.WriteViewProps(presentation.ViewProps); } this.WritePresentation(presentation); var _dst_themes = []; var _dst_masters = []; var _dst_layouts = []; var _dst_slides = []; var _dst_notes = []; var _dst_notesMasters = []; var _slides_rels = []; var _master_rels = []; var _slides = presentation.Slides; var _slide_count = _slides.length; for (var i = 0; i < _slide_count; i++) { _dst_slides[i] = _slides[i]; var _m = _slides[i].Layout.Master; var is_found = false; var _len_dst = _dst_masters.length; for (var j = 0; j < _len_dst; j++) { if (_dst_masters[j] == _m) { is_found = true; break; } } if (!is_found) { _dst_masters[_len_dst] = _m; var _m_rels = { ThemeIndex: 0, Layouts: new Array() }; var _lay_c = _m.sldLayoutLst.length; var _ind_l = _dst_layouts.length; for (var k = 0; k < _lay_c; k++) { _dst_layouts[_ind_l] = _m.sldLayoutLst[k]; _m_rels.Layouts[k] = _ind_l; _ind_l++; } _master_rels[_len_dst] = _m_rels; } var _layoutsC = _dst_layouts.length; for (var ii = 0; ii < _layoutsC; ii++) { if (_dst_layouts[ii] == _dst_slides[i].Layout) { _slides_rels[i] = ii; } } } var _dst_masters_len = _dst_masters.length; for (var i = 0; i < _dst_masters_len; i++) { var _t = _dst_masters[i].Theme; var is_found = false; var _len_dst = _dst_themes.length; for (var j = 0; j < _len_dst; j++) { if (_dst_themes[j] == _t) { is_found = true; break; } } if (!is_found) { _dst_themes[_len_dst] = _t; _master_rels[i].ThemeIndex = _len_dst; } } var _count_table_styles = presentation.globalTableStyles.length; if (0 < _count_table_styles) { for (var i = 0; i < _count_table_styles; i++) { this.tableStylesGuides[i] = "{" + GUID() + "}"; } this.StartMainRecord(c_oMainTables.TableStyles); this.StartRecord(c_oMainTables.SlideRels); this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, this.tableStylesGuides[0]); this.WriteUChar(g_nodeAttributeEnd); this.StartRecord(0); for (var i = 0; i < _count_table_styles; i++) { this.WriteTableStyle(i, presentation.globalTableStyles[i]); } this.EndRecord(); this.EndRecord(); } this.StartMainRecord(c_oMainTables.SlideRels); this.StartRecord(c_oMainTables.SlideRels); this.WriteUChar(g_nodeAttributeStart); for (var i = 0; i < _slide_count; i++) { this._WriteInt1(i, _slides_rels[i]); } this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); this.StartMainRecord(c_oMainTables.ThemeRels); this.StartRecord(c_oMainTables.ThemeRels); var _master_count = _dst_masters.length; this.WriteULong(_master_count); for (var i = 0; i < _master_count; i++) { this.StartRecord(0); this.WriteUChar(g_nodeAttributeStart); this._WriteInt1(0, _master_rels[i].ThemeIndex); this.WriteUChar(1); this.WriteString(_dst_masters[i].ImageBase64); this.WriteUChar(g_nodeAttributeEnd); var _lay_c = _master_rels[i].Layouts.length; this.WriteULong(_lay_c); for (var j = 0; j < _lay_c; j++) { this.StartRecord(0); this.WriteUChar(g_nodeAttributeStart); var _indL = _master_rels[i].Layouts[j]; this._WriteInt1(0, _indL); this.WriteUChar(1); this.WriteString(_dst_layouts[_indL].ImageBase64); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); } this.EndRecord(); } this.EndRecord(); var _count_arr = 0; _count_arr = _dst_themes.length; this.StartMainRecord(c_oMainTables.Themes); this.WriteULong(_count_arr); for (var i = 0; i < _count_arr; i++) { this.WriteTheme(_dst_themes[i]); } _count_arr = _dst_masters.length; this.StartMainRecord(c_oMainTables.SlideMasters); this.WriteULong(_count_arr); for (var i = 0; i < _count_arr; i++) { this.WriteSlideMaster(_dst_masters[i]); } _count_arr = _dst_layouts.length; this.StartMainRecord(c_oMainTables.SlideLayouts); this.WriteULong(_count_arr); for (var i = 0; i < _count_arr; i++) { this.WriteSlideLayout(_dst_layouts[i]); } _count_arr = _dst_slides.length; this.StartMainRecord(c_oMainTables.Slides); this.WriteULong(_count_arr); for (var i = 0; i < _count_arr; i++) { this.WriteSlide(_dst_slides[i]); } _count_arr = _dst_notes.length; this.StartMainRecord(c_oMainTables.NotesSlides); this.WriteULong(_count_arr); for (var i = 0; i < _count_arr; i++) { this.WriteSlideNote(_dst_notes[i]); } _count_arr = _dst_notesMasters.length; this.StartMainRecord(c_oMainTables.NotesMasters); this.WriteULong(_count_arr); for (var i = 0; i < _count_arr; i++) { this.WriteNoteMaster(_dst_notesMasters[i]); } this.StartMainRecord(c_oMainTables.FontMap); this.StartRecord(c_oMainTables.FontMap); this.WriteUChar(g_nodeAttributeStart); var _index_attr = 0; for (var i in this.font_map) { this.WriteUChar(_index_attr++); this.WriteString2(i); } this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); this.StartMainRecord(c_oMainTables.ImageMap); this.StartRecord(c_oMainTables.ImageMap); this.WriteUChar(g_nodeAttributeStart); _index_attr = 0; for (var i in this.image_map) { this.WriteUChar(_index_attr++); this.WriteString2(i); } this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); this.WriteMainPart(); var ret = "PPTY;v1;" + this.pos + ";"; return ret + this.GetBase64Memory(); }; this.WriteApp = function (app) { this.StartMainRecord(c_oMainTables.App); this.StartRecord(c_oMainTables.App); this.WriteUChar(g_nodeAttributeStart); this._WriteString2(0, app.Template); this._WriteString2(1, app.Application); this._WriteString2(2, app.PresentationFormat); this._WriteString2(3, app.Company); this._WriteString2(4, app.AppVersion); this._WriteInt2(5, app.TotalTime); this._WriteInt2(6, app.Words); this._WriteInt2(7, app.Paragraphs); this._WriteInt2(8, app.Slides); this._WriteInt2(9, app.Notes); this._WriteInt2(10, app.HiddenSlides); this._WriteInt2(11, app.MMClips); this._WriteBool2(12, app.ScaleCrop); this._WriteBool2(13, app.LinksUpToDate); this._WriteBool2(14, app.SharedDoc); this._WriteBool2(15, app.HyperlinksChanged); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); }; this.WriteCore = function (core) { this.StartMainRecord(c_oMainTables.Core); this.StartRecord(c_oMainTables.Core); this.WriteUChar(g_nodeAttributeStart); this._WriteString2(0, core.title); this._WriteString2(1, core.creator); this._WriteString2(2, core.lastModifiedBy); this._WriteString2(3, core.revision); this._WriteString2(4, core.created); this._WriteString2(5, core.modified); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); }; this.WriteViewProps = function (viewprops) { this.StartMainRecord(c_oMainTables.ViewProps); this.StartRecord(c_oMainTables.ViewProps); this.EndRecord(); }; this.WritePresentation = function (presentation) { var pres = presentation.pres; this.StartMainRecord(c_oMainTables.Presentation); this.StartRecord(c_oMainTables.Presentation); this.WriteUChar(g_nodeAttributeStart); this._WriteBool2(0, pres.attrAutoCompressPictures); this._WriteInt2(1, pres.attrBookmarkIdSeed); this._WriteBool2(2, pres.attrCompatMode); this._WriteLimit2(3, pres.attrConformance); this._WriteBool2(4, pres.attrEmbedTrueTypeFonts); this._WriteInt2(5, pres.attrFirstSlideNum); this._WriteBool2(6, pres.attrRemovePersonalInfoOnSave); this._WriteBool2(7, pres.attrRtl); this._WriteBool2(8, pres.attrSaveSubsetFonts); this._WriteString2(9, pres.attrServerZoom); this._WriteBool2(10, pres.attrShowSpecialPlsOnTitleSld); this._WriteBool2(11, pres.attrStrictFirstAndLastChars); this.WriteUChar(g_nodeAttributeEnd); this.WriteRecord2(0, presentation.defaultTextStyle, this.WriteTextListStyle); pres.SldSz.cx = (presentation.Width * c_dScalePPTXSizes) >> 0; pres.SldSz.cy = (presentation.Height * c_dScalePPTXSizes) >> 0; this.StartRecord(5); this.WriteUChar(g_nodeAttributeStart); this._WriteInt1(0, pres.SldSz.cx); this._WriteInt1(1, pres.SldSz.cy); this._WriteLimit2(2, pres.SldSz.type); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); pres.NotesSz = new Object(); pres.NotesSz.cx = (presentation.Height * c_dScalePPTXSizes) >> 0; pres.NotesSz.cy = (presentation.Width * c_dScalePPTXSizes) >> 0; this.StartRecord(3); this.WriteUChar(g_nodeAttributeStart); this._WriteInt1(0, pres.NotesSz.cx); this._WriteInt1(1, pres.NotesSz.cy); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); if (!this.IsUseFullUrl) { var _countAuthors = 0; for (var i in presentation.CommentAuthors) { ++_countAuthors; } if (_countAuthors > 0) { this.StartRecord(6); this.StartRecord(0); this.WriteULong(_countAuthors); for (var i in presentation.CommentAuthors) { var _author = presentation.CommentAuthors[i]; this.StartRecord(0); this.WriteUChar(g_nodeAttributeStart); this._WriteInt1(0, _author.Id); this._WriteInt1(1, _author.LastId); this._WriteInt1(2, _author.Id - 1); this._WriteString1(3, _author.Name); this._WriteString1(4, _author.Initials); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); } this.EndRecord(); this.EndRecord(); } } this.EndRecord(); }; this.WriteTheme = function (_theme) { this.StartRecord(c_oMainTables.Themes); this.WriteUChar(g_nodeAttributeStart); this._WriteString2(0, _theme.name); this.WriteUChar(g_nodeAttributeEnd); this.WriteRecord1(0, _theme.themeElements, this.WriteThemeElements); this.WriteRecord2(1, _theme.spDef, this.WriteDefaultShapeDefinition); this.WriteRecord2(2, _theme.lnDef, this.WriteDefaultShapeDefinition); this.WriteRecord2(3, _theme.txDef, this.WriteDefaultShapeDefinition); this.WriteRecordArray(4, 0, _theme.extraClrSchemeLst, this.WriteExtraClrScheme); this.EndRecord(); }; this.WriteSlideMaster = function (_master) { this.StartRecord(c_oMainTables.SlideMasters); this.WriteUChar(g_nodeAttributeStart); this._WriteBool2(0, _master.preserve); this.WriteUChar(g_nodeAttributeEnd); this.WriteRecord1(0, _master.cSld, this.WriteCSld); this.WriteRecord1(1, _master.clrMap, this.WriteClrMap); this.WriteRecord2(5, _master.hf, this.WriteHF); this.WriteRecord2(6, _master.txStyles, this.WriteTxStyles); this.EndRecord(); }; this.WriteSlideLayout = function (_layout) { this.StartRecord(c_oMainTables.SlideLayouts); this.WriteUChar(g_nodeAttributeStart); this._WriteString2(0, _layout.matchingName); this._WriteBool2(1, _layout.preserve); this._WriteBool2(2, _layout.showMasterPhAnim); this._WriteBool2(3, _layout.showMasterSp); this._WriteBool2(4, _layout.userDrawn); this._WriteLimit2(5, _layout.type); this.WriteUChar(g_nodeAttributeEnd); this.WriteRecord1(0, _layout.cSld, this.WriteCSld); this.WriteRecord2(1, _layout.clrMap, this.WriteClrMapOvr); this.WriteRecord2(4, _layout.hf, this.WriteHF); this.EndRecord(); }; this.WriteSlide = function (_slide) { this.StartRecord(c_oMainTables.Slides); this.WriteUChar(g_nodeAttributeStart); this._WriteBool2(0, _slide.show); this._WriteBool2(1, _slide.showMasterPhAnim); this._WriteBool2(2, _slide.showMasterSp); this.WriteUChar(g_nodeAttributeEnd); this.WriteRecord1(0, _slide.cSld, this.WriteCSld); this.WriteRecord2(1, _slide.clrMap, this.WriteClrMapOvr); this.WriteRecord1(2, _slide.timing, this.WriteSlideTransition); var _countComments = 0; if (!this.IsUseFullUrl) { for (var i in _slide.writecomments) { ++_countComments; } } if (_countComments > 0) { this.StartRecord(4); this.StartRecord(0); this.WriteULong(_countComments); for (var i in _slide.writecomments) { var _comment = _slide.writecomments[i]; this.StartRecord(0); this.WriteUChar(g_nodeAttributeStart); this._WriteInt1(0, _comment.WriteAuthorId); this._WriteString1(1, _comment.WriteTime); this._WriteInt1(2, _comment.WriteCommentId); this._WriteInt1(3, (_comment.x * 25.4) >> 0); this._WriteInt1(4, (_comment.y * 25.4) >> 0); this._WriteString1(5, _comment.Data.m_sText); if (0 != _comment.WriteParentAuthorId) { this._WriteInt1(6, _comment.WriteParentAuthorId); this._WriteInt1(7, _comment.WriteParentCommentId); } this._WriteString1(8, _comment.AdditionalData); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); } this.EndRecord(); this.EndRecord(); } this.EndRecord(); }; this.WriteSlideTransition = function (_timing) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool1(0, _timing.SlideAdvanceOnMouseClick); if (_timing.SlideAdvanceAfter) { oThis._WriteInt1(1, _timing.SlideAdvanceDuration); if (_timing.TransitionType == c_oAscSlideTransitionTypes.None) { oThis._WriteInt1(2, 0); } } else { if (_timing.TransitionType == c_oAscSlideTransitionTypes.None) { oThis._WriteInt1(2, 10); } } if (_timing.TransitionType != c_oAscSlideTransitionTypes.None) { oThis._WriteInt1(2, _timing.TransitionDuration); if (_timing.TransitionDuration < 250) { oThis._WriteUChar1(3, 0); } else { if (_timing.TransitionDuration > 1000) { oThis._WriteUChar1(3, 2); } else { oThis._WriteUChar1(3, 1); } } oThis.WriteUChar(g_nodeAttributeEnd); oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); switch (_timing.TransitionType) { case c_oAscSlideTransitionTypes.Fade: oThis._WriteString2(0, "p:fade"); switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Fade_Smoothly: oThis._WriteString2(1, "thruBlk"); oThis._WriteString2(2, "0"); break; case c_oAscSlideTransitionParams.Fade_Through_Black: oThis._WriteString2(1, "thruBlk"); oThis._WriteString2(2, "1"); break; default: break; } break; case c_oAscSlideTransitionTypes.Push: oThis._WriteString2(0, "p:push"); switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Param_Left: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "r"); break; case c_oAscSlideTransitionParams.Param_Right: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "l"); break; case c_oAscSlideTransitionParams.Param_Top: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "d"); break; case c_oAscSlideTransitionParams.Param_Bottom: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "u"); break; default: break; } break; case c_oAscSlideTransitionTypes.Wipe: switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Param_Left: oThis._WriteString2(0, "p:wipe"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "r"); break; case c_oAscSlideTransitionParams.Param_Right: oThis._WriteString2(0, "p:wipe"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "l"); break; case c_oAscSlideTransitionParams.Param_Top: oThis._WriteString2(0, "p:wipe"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "d"); break; case c_oAscSlideTransitionParams.Param_Bottom: oThis._WriteString2(0, "p:wipe"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "u"); break; case c_oAscSlideTransitionParams.Param_TopLeft: oThis._WriteString2(0, "p:strips"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "rd"); break; case c_oAscSlideTransitionParams.Param_TopRight: oThis._WriteString2(0, "p:strips"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "ld"); break; case c_oAscSlideTransitionParams.Param_BottomLeft: oThis._WriteString2(0, "p:strips"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "ru"); break; case c_oAscSlideTransitionParams.Param_BottomRight: oThis._WriteString2(0, "p:strips"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "lu"); break; default: break; } break; case c_oAscSlideTransitionTypes.Split: oThis._WriteString2(0, "p:split"); switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Split_HorizontalIn: oThis._WriteString2(1, "orient"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "horz"); oThis._WriteString2(2, "in"); break; case c_oAscSlideTransitionParams.Split_HorizontalOut: oThis._WriteString2(1, "orient"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "horz"); oThis._WriteString2(2, "out"); break; case c_oAscSlideTransitionParams.Split_VerticalIn: oThis._WriteString2(1, "orient"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "vert"); oThis._WriteString2(2, "in"); break; case c_oAscSlideTransitionParams.Split_VerticalOut: oThis._WriteString2(1, "orient"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "vert"); oThis._WriteString2(2, "out"); break; default: break; } break; case c_oAscSlideTransitionTypes.UnCover: case c_oAscSlideTransitionTypes.Cover: if (_timing.TransitionType == c_oAscSlideTransitionTypes.Cover) { oThis._WriteString2(0, "p:cover"); } else { oThis._WriteString2(0, "p:pull"); } switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Param_Left: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "r"); break; case c_oAscSlideTransitionParams.Param_Right: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "l"); break; case c_oAscSlideTransitionParams.Param_Top: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "d"); break; case c_oAscSlideTransitionParams.Param_Bottom: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "u"); break; case c_oAscSlideTransitionParams.Param_TopLeft: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "rd"); break; case c_oAscSlideTransitionParams.Param_TopRight: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "ld"); break; case c_oAscSlideTransitionParams.Param_BottomLeft: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "ru"); break; case c_oAscSlideTransitionParams.Param_BottomRight: oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "lu"); break; default: break; } break; case c_oAscSlideTransitionTypes.Clock: switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Clock_Clockwise: oThis._WriteString2(0, "p:wheel"); oThis._WriteString2(1, "spokes"); oThis._WriteString2(2, "1"); break; case c_oAscSlideTransitionParams.Clock_Counterclockwise: oThis._WriteString2(0, "p14:wheelReverse"); oThis._WriteString2(1, "spokes"); oThis._WriteString2(2, "1"); break; case c_oAscSlideTransitionParams.Clock_Wedge: oThis._WriteString2(0, "p:wedge"); break; default: break; } break; case c_oAscSlideTransitionTypes.Zoom: switch (_timing.TransitionOption) { case c_oAscSlideTransitionParams.Zoom_In: oThis._WriteString2(0, "p14:warp"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "in"); break; case c_oAscSlideTransitionParams.Zoom_Out: oThis._WriteString2(0, "p14:warp"); oThis._WriteString2(1, "dir"); oThis._WriteString2(2, "out"); break; case c_oAscSlideTransitionParams.Zoom_AndRotate: oThis._WriteString2(0, "p:newsflash"); break; default: break; } break; default: break; } oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } else { oThis.WriteUChar(g_nodeAttributeEnd); } }; this.WriteSlideNote = function (_note) { this.StartRecord(c_oMainTables.NotesSlides); this.WriteUChar(g_nodeAttributeStart); this._WriteBool2(0, _note.showMasterPhAnim); this._WriteBool2(1, _note.showMasterSp); this.WriteUChar(g_nodeAttributeEnd); this.WriteRecord1(0, _note.cSld, this.WriteCSld); this.WriteRecord2(1, _note.clrMap, this.WriteClrMapOvr); this.EndRecord(); }; this.WriteNoteMaster = function (_master) { this.StartRecord(c_oMainTables.NotesMasters); this.WriteRecord1(0, _master.cSld, this.WriteCSld); this.WriteRecord1(1, _master.clrMap, this.WriteClrMap); this.WriteRecord2(2, _master.hf, this.WriteHF); this.WriteRecord2(3, _master.notesStyle, this.WriteTextListStyle); this.EndRecord(); }; this.WriteThemeElements = function (themeElements) { oThis.WriteRecord1(0, themeElements.clrScheme, oThis.WriteClrScheme); oThis.WriteRecord1(1, themeElements.fontScheme, oThis.WriteFontScheme); oThis.WriteRecord1(2, themeElements.fmtScheme, oThis.WriteFmtScheme); }; this.WriteFontScheme = function (fontScheme) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, fontScheme.name); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord1(0, fontScheme.majorFont, oThis.WriteFontCollection); oThis.WriteRecord1(1, fontScheme.minorFont, oThis.WriteFontCollection); }; this.WriteFontCollection = function (coll) { oThis.WriteRecord1(0, { Name: coll.latin, Index: -1 }, oThis.WriteTextFontTypeface); oThis.WriteRecord1(1, { Name: coll.ea, Index: -1 }, oThis.WriteTextFontTypeface); oThis.WriteRecord1(2, { Name: coll.cs, Index: -1 }, oThis.WriteTextFontTypeface); }; this.WriteFmtScheme = function (fmt) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, fmt.name); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecordArray(0, 0, fmt.fillStyleLst, oThis.WriteUniFill); oThis.WriteRecordArray(1, 0, fmt.lnStyleLst, oThis.WriteLn); oThis.WriteRecordArray(3, 0, fmt.bgFillStyleLst, oThis.WriteUniFill); }; this.WriteDefaultShapeDefinition = function (shapeDef) { oThis.WriteRecord1(0, shapeDef.spPr, oThis.WriteSpPr); oThis.WriteRecord1(1, shapeDef.bodyPr, oThis.WriteBodyPr); oThis.WriteRecord1(2, shapeDef.lstStyle, oThis.WriteTextListStyle); oThis.WriteRecord2(3, shapeDef.style, oThis.WriteShapeStyle); }; this.WriteExtraClrScheme = function (extraScheme) { oThis.WriteRecord1(0, extraScheme.clrScheme, oThis.WriteClrScheme); oThis.WriteRecord2(1, extraScheme.clrMap, oThis.WriteClrMap); }; this.WriteCSld = function (cSld) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString2(0, cSld.name); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord2(0, cSld.Bg, oThis.WriteBg); var spTree = cSld.spTree; var _len = spTree.length; oThis.StartRecord(1); oThis.StartRecord(4); var uniPr = new UniNvPr(); uniPr.cNvPr.id = 1; uniPr.cNvPr.name = ""; var spPr = new CSpPr(); spPr.xfrm.offX = 0; spPr.xfrm.offY = 0; spPr.xfrm.extX = 0; spPr.xfrm.extY = 0; spPr.xfrm.chOffX = 0; spPr.xfrm.chOffY = 0; spPr.xfrm.chExtX = 0; spPr.xfrm.chExtY = 0; spPr.WriteXfrm = spPr.xfrm; oThis.WriteRecord1(0, uniPr, oThis.WriteUniNvPr); oThis.WriteRecord1(1, spPr, oThis.WriteSpPr); if (0 != _len) { oThis.StartRecord(2); oThis.WriteULong(_len); for (var i = 0; i < _len; i++) { oThis.StartRecord(0); if (spTree[i] instanceof CShape) { oThis.WriteShape(spTree[i]); } else { if (spTree[i] instanceof CImageShape) { oThis.WriteImage(spTree[i]); } else { if (spTree[i] instanceof CGroupShape) { oThis.WriteGroupShape(spTree[i]); } else { if (spTree[i] instanceof CGraphicFrame && spTree[i].graphicObject instanceof CTable) { oThis.WriteTable(spTree[i]); } else { if (typeof CChartAsGroup != "undefined" && spTree[i] instanceof CChartAsGroup) { oThis.WriteChart(spTree[i]); } } } } } oThis.EndRecord(); } oThis.EndRecord(); } oThis.EndRecord(); oThis.EndRecord(); }; this.WriteClrMap = function (clrmap) { oThis.WriteUChar(g_nodeAttributeStart); var _len = clrmap.color_map.length; for (var i = 0; i < _len; ++i) { if (null != clrmap.color_map[i]) { oThis.WriteUChar(i); oThis.WriteUChar(clrmap.color_map[i]); } } oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteClrScheme = function (scheme) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, scheme.name); oThis.WriteUChar(g_nodeAttributeEnd); var _len = scheme.colors.length; for (var i = 0; i < _len; i++) { if (null != scheme.colors[i]) { oThis.WriteRecord1(i, scheme.colors[i], oThis.WriteUniColor); } } }; this.WriteClrMapOvr = function (clrmapovr) { oThis.WriteRecord2(0, clrmapovr, oThis.WriteClrMap); }; this.WriteHF = function (hf) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool2(0, hf.dt); oThis._WriteBool2(1, hf.ftr); oThis._WriteBool2(2, hf.hdr); oThis._WriteBool2(3, hf.sldNum); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteTxStyles = function (txStyles) { oThis.WriteRecord2(0, txStyles.titleStyle, oThis.WriteTextListStyle); oThis.WriteRecord2(1, txStyles.bodyStyle, oThis.WriteTextListStyle); oThis.WriteRecord2(2, txStyles.otherStyle, oThis.WriteTextListStyle); }; this.WriteTextListStyle = function (styles) { var _levels = styles.levels; var _count = _levels.length; for (var i = 0; i < _count; ++i) { oThis.WriteRecord2(i, _levels[i], oThis.WriteTextParagraphPr); } }; this.WriteTextParagraphPr = function (tPr) { oThis.WriteUChar(g_nodeAttributeStart); var pPr = tPr.pPr; if (undefined !== pPr && null != pPr) { switch (pPr.Jc) { case align_Left: oThis._WriteUChar1(0, 4); break; case align_Center: oThis._WriteUChar1(0, 0); break; case align_Right: oThis._WriteUChar1(0, 5); break; case align_Justify: oThis._WriteUChar1(0, 2); break; default: break; } var ind = pPr.Ind; if (ind !== undefined && ind != null) { if (ind.FirstLine !== undefined) { oThis._WriteInt1(5, ind.FirstLine * 36000); } if (ind.Left !== undefined) { oThis._WriteInt1(8, ind.Left * 36000); } if (ind.Right !== undefined) { oThis._WriteInt1(9, ind.Right * 36000); } } } if (tPr.lvl !== undefined && tPr.lvl != null) { oThis._WriteInt1(7, tPr.lvl); } oThis.WriteUChar(g_nodeAttributeEnd); if (undefined !== pPr && null != pPr) { var spacing = pPr.Spacing; if (spacing !== undefined && spacing != null) { switch (spacing.LineRule) { case linerule_Auto: oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, (spacing.Line * 100000) >> 0); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); break; case linerule_Exact: oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(1, (spacing.Line / 0.00352777778) >> 0); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); break; default: break; } if (spacing.After !== undefined) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(1, (spacing.After / 0.00352777778) >> 0); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } if (spacing.Before !== undefined) { oThis.StartRecord(2); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(1, (spacing.Before / 0.00352777778) >> 0); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } } } var bullet = tPr.bullet; if (undefined !== bullet && null != bullet) { if (bullet.bulletColor != null && bullet.bulletColor.type != BULLET_TYPE_COLOR_NONE) { oThis.StartRecord(3); if (bullet.bulletColor.type == BULLET_TYPE_COLOR_CLR) { oThis.StartRecord(BULLET_TYPE_COLOR_CLR); oThis.WriteRecord2(0, bullet.bulletColor.UniColor, oThis.WriteUniColor); oThis.EndRecord(); } else { oThis.StartRecord(BULLET_TYPE_COLOR_CLRTX); oThis.EndRecord(); } oThis.EndRecord(); } if (bullet.bulletSize != null && bullet.bulletSize.type != BULLET_TYPE_SIZE_NONE) { oThis.StartRecord(4); if (bullet.bulletSize.type == BULLET_TYPE_SIZE_PTS) { oThis.StartRecord(BULLET_TYPE_SIZE_PTS); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, bullet.bulletSize.val); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } else { if (bullet.bulletSize.type == BULLET_TYPE_SIZE_PCT) { oThis.StartRecord(BULLET_TYPE_SIZE_PCT); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, bullet.bulletSize.val); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } else { oThis.StartRecord(BULLET_TYPE_SIZE_TX); oThis.EndRecord(); } } oThis.EndRecord(); } if (bullet.bulletTypeface != null && bullet.bulletTypeface.type != null && bullet.bulletTypeface.type != BULLET_TYPE_TYPEFACE_NONE) { oThis.StartRecord(5); if (bullet.bulletTypeface.type == BULLET_TYPE_TYPEFACE_BUFONT) { oThis.WriteRecord2(BULLET_TYPE_TYPEFACE_BUFONT, { Name: bullet.bulletTypeface.typeface, Index: -1 }, oThis.WriteTextFontTypeface); } else { oThis.StartRecord(BULLET_TYPE_TYPEFACE_TX); oThis.EndRecord(); } oThis.EndRecord(); } if (bullet.bulletType != null && bullet.bulletType.type != null) { oThis.StartRecord(6); switch (bullet.bulletType.type) { case BULLET_TYPE_BULLET_CHAR: oThis.StartRecord(BULLET_TYPE_BULLET_CHAR); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, bullet.bulletType.Char); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); break; case BULLET_TYPE_BULLET_BLIP: oThis.StartRecord(BULLET_TYPE_BULLET_CHAR); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, "*"); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); break; case BULLET_TYPE_BULLET_AUTONUM: oThis.StartRecord(BULLET_TYPE_BULLET_AUTONUM); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit1(0, bullet.bulletType.AutoNumType); oThis._WriteInt2(1, bullet.bulletType.startAt); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); break; case BULLET_TYPE_BULLET_NONE: oThis.StartRecord(BULLET_TYPE_BULLET_NONE); oThis.EndRecord(); break; } oThis.EndRecord(); } } if (pPr !== undefined && pPr != null && pPr.Tabs !== undefined && pPr.Tabs != null) { if (pPr.Tabs.Tabs != undefined && pPr.Tabs.Tabs != null) { oThis.WriteRecordArray(7, 0, pPr.Tabs.Tabs, oThis.WriteTab); } } if (tPr !== undefined && tPr != null) { oThis.WriteRecord2(8, tPr.rPr, oThis.WriteRunProperties); } }; this.WriteRunProperties = function (rPr, hlinkObj) { if (rPr == null || rPr === undefined) { return; } oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool2(1, rPr.Bold); oThis._WriteBool2(7, rPr.Italic); var _cap = null; if (rPr.Caps === true) { _cap = 0; } else { if (rPr.SmallCaps === true) { _cap = 1; } else { if (rPr.Caps === false && rPr.SmallCaps === false) { _cap = 2; } } } if (null != _cap) { oThis._WriteUChar1(4, _cap); } var _strike = null; if (rPr.DStrikeout === true) { _strike = 0; } else { if (rPr.Strikeout === true) { _strike = 2; } else { if (rPr.DStrikeout === false && rPr.Strikeout === false) { _strike = 1; } } } if (null != _strike) { oThis._WriteUChar1(16, _strike); } if (undefined !== rPr.Underline && null != rPr.Underline) { oThis._WriteUChar1(18, (rPr.Underline === true) ? 13 : 12); } if (undefined !== rPr.FontSize && null != rPr.FontSize) { oThis._WriteInt1(17, rPr.FontSize * 100); } if (vertalign_SubScript == rPr.VertAlign) { oThis._WriteInt1(2, -25000); } else { if (vertalign_SuperScript == rPr.VertAlign) { oThis._WriteInt1(2, 30000); } } oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord1(1, rPr.unifill, oThis.WriteUniFill); oThis.WriteRecord2(3, rPr.FontFamily, oThis.WriteTextFontTypeface); if (hlinkObj != null && hlinkObj !== undefined) { oThis.WriteRecord1(7, hlinkObj, oThis.WriteHyperlink); } }; this.WriteHyperlink = function (hlink) { oThis.WriteUChar(g_nodeAttributeStart); var url = hlink.Value; var action = null; if (url == "ppaction://hlinkshowjump?jump=firstslide") { action = url; url = ""; } else { if (url == "ppaction://hlinkshowjump?jump=lastslide") { action = url; url = ""; } else { if (url == "ppaction://hlinkshowjump?jump=nextslide") { action = url; url = ""; } else { if (url == "ppaction://hlinkshowjump?jump=previousslide") { action = url; url = ""; } else { var mask = "ppaction://hlinksldjumpslide"; var indSlide = url.indexOf(mask); if (0 == indSlide) { var slideNum = parseInt(url.substring(mask.length)); url = "slide" + (slideNum + 1) + ".xml"; action = "ppaction://hlinksldjump"; } } } } } oThis._WriteString1(0, url); oThis._WriteString2(2, action); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteTextFontTypeface = function (typeface) { oThis.WriteUChar(g_nodeAttributeStart); if (!typeface || typeface.Name == null) { oThis.font_map["Arial"] = true; oThis._WriteString1(3, "Arial"); oThis.WriteUChar(g_nodeAttributeEnd); return; } if ((0 != typeface.Name.indexOf("+mj")) && (0 != typeface.Name.indexOf("+mn"))) { oThis.font_map[typeface.Name] = true; } oThis._WriteString1(3, typeface.Name); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteTab = function (tab) { oThis.WriteUChar(g_nodeAttributeStart); var _algn = 2; if (tab.Value == tab_Center) { _algn = 0; } else { if (tab.Value == tab_Right) { _algn = 3; } } oThis._WriteLimit2(0, _algn); if (tab.Pos != undefined && tab.Pos != null) { oThis._WriteInt1(1, tab.Pos * 36000); } oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteBodyPr = function (bodyPr) { if (undefined === bodyPr || null == bodyPr) { return; } oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt2(0, bodyPr.flatTx); oThis._WriteLimit2(1, bodyPr.anchor); oThis._WriteBool2(2, bodyPr.anchorCtr); oThis._WriteInt4(3, bodyPr.bIns, 36000); oThis._WriteBool2(4, bodyPr.compatLnSpc); oThis._WriteBool2(5, bodyPr.forceAA); oThis._WriteBool2(6, bodyPr.fromWordArt); oThis._WriteLimit2(7, bodyPr.horzOverflow); oThis._WriteInt4(8, bodyPr.lIns, 36000); oThis._WriteInt2(9, bodyPr.numCol); oThis._WriteInt4(10, bodyPr.rIns, 36000); oThis._WriteInt2(11, bodyPr.rot); oThis._WriteBool2(12, bodyPr.rtlCol); oThis._WriteInt2(13, bodyPr.spcCol); oThis._WriteBool2(14, bodyPr.spcFirstLastPara); oThis._WriteInt4(15, bodyPr.tIns, 36000); oThis._WriteBool2(16, bodyPr.upright); oThis._WriteLimit2(17, bodyPr.vert); oThis._WriteLimit2(18, bodyPr.vertOverflow); oThis._WriteLimit2(19, bodyPr.wrap); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteUniColor = function (unicolor) { if (undefined === unicolor || null == unicolor || unicolor.color == null) { return; } var color = unicolor.color; switch (color.type) { case COLOR_TYPE_PRST: oThis.StartRecord(COLOR_TYPE_PRST); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, color.id); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteMods(unicolor.Mods); oThis.EndRecord(); break; case COLOR_TYPE_SCHEME: oThis.StartRecord(COLOR_TYPE_SCHEME); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteUChar1(0, color.id); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteMods(unicolor.Mods); oThis.EndRecord(); break; case COLOR_TYPE_SRGB: oThis.StartRecord(COLOR_TYPE_SRGB); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteUChar1(0, color.RGBA.R); oThis._WriteUChar1(1, color.RGBA.G); oThis._WriteUChar1(2, color.RGBA.B); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteMods(unicolor.Mods); oThis.EndRecord(); break; case COLOR_TYPE_SYS: oThis.StartRecord(COLOR_TYPE_SYS); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, color.id); oThis._WriteUChar1(1, color.RGBA.R); oThis._WriteUChar1(2, color.RGBA.G); oThis._WriteUChar1(3, color.RGBA.B); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteMods(unicolor.Mods); oThis.EndRecord(); break; } }; this.WriteMods = function (mods) { var _count = mods.Mods.length; if (0 == _count) { return; } oThis.StartRecord(0); oThis.WriteULong(_count); for (var i = 0; i < _count; ++i) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, mods.Mods[i].name); oThis._WriteInt2(1, mods.Mods[i].val); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } oThis.EndRecord(); }; this.CorrectUniColorAlpha = function (color, trans) { var mods = color.Mods.Mods; var _len = mods.length; if (trans != null) { var nIndex = -1; for (var i = 0; i < _len; i++) { if (mods[i].name == "alpha") { nIndex = i; break; } } if (-1 != nIndex) { --_len; mods.splice(nIndex, 1); } mods[_len] = new CColorMod(); mods[_len].name = "alpha"; mods[_len].val = (trans * 100000 / 255) >> 0; } }; this.WriteUniFill = function (unifill) { if (undefined === unifill || null == unifill) { return; } var trans = ((unifill.transparent != null) && (unifill.transparent != 255)) ? unifill.transparent : null; var fill = unifill.fill; if (undefined === fill || null == fill) { return; } switch (fill.type) { case FILL_TYPE_NOFILL: oThis.StartRecord(FILL_TYPE_NOFILL); oThis.EndRecord(); break; case FILL_TYPE_GRAD: oThis.StartRecord(FILL_TYPE_GRAD); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.StartRecord(0); var len = fill.colors.length; oThis.WriteULong(len); for (var i = 0; i < len; i++) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, fill.colors[i].pos); oThis.WriteUChar(g_nodeAttributeEnd); oThis.CorrectUniColorAlpha(fill.colors[i].color, trans); oThis.WriteRecord1(0, fill.colors[i].color, oThis.WriteUniColor); oThis.EndRecord(); } oThis.EndRecord(); if (fill.lin) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, fill.lin.angle); oThis._WriteBool1(1, fill.lin.scale); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } else { if (fill.path) { oThis.StartRecord(2); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteUChar1(0, fill.path.path); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } } oThis.EndRecord(); break; case FILL_TYPE_PATT: oThis.StartRecord(FILL_TYPE_PATT); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit2(0, fill.ftype); oThis.WriteUChar(g_nodeAttributeEnd); oThis.CorrectUniColorAlpha(fill.fgClr, trans); oThis.CorrectUniColorAlpha(fill.bgClr, trans); oThis.WriteRecord1(0, fill.fgClr, oThis.WriteUniColor); oThis.WriteRecord1(1, fill.bgClr, oThis.WriteUniColor); oThis.EndRecord(); break; case FILL_TYPE_BLIP: oThis.StartRecord(FILL_TYPE_BLIP); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); var api_sheet = window["Asc"]["editor"]; var sFindString; if (api_sheet) { sFindString = api_sheet.wbModel.sUrlPath + "media/"; } else { sFindString = editor.DocumentUrl + "media/"; } var _src = fill.RasterImageId; if (0 == _src.indexOf(sFindString)) { _src = _src.substring(sFindString.length); } oThis.image_map[_src] = true; if (oThis.IsUseFullUrl) { if ((0 == _src.indexOf("theme")) && window.editor) { _src = oThis.PresentationThemesOrigin + _src; } else { if (0 != _src.indexOf("http:") && 0 != _src.indexOf("data:") && 0 != _src.indexOf("https:") && 0 != _src.indexOf("ftp:") && 0 != _src.indexOf("file:")) { _src = oThis.DocumentOrigin + "media/" + _src; } } } oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); if (null != trans) { oThis.StartRecord(2); oThis.WriteULong(1); oThis.StartRecord(3); oThis.StartRecord(21); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, (trans * 100000 / 255) >> 0); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); oThis.EndRecord(); oThis.EndRecord(); } oThis.StartRecord(3); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, _src); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); oThis.EndRecord(); if (fill.srcRect != null) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); if (fill.srcRect.l != null) { var _num = (fill.srcRect.l * 1000) >> 0; oThis._WriteString1(0, "" + _num); } if (fill.srcRect.t != null) { var _num = (fill.srcRect.t * 1000) >> 0; oThis._WriteString1(1, "" + _num); } if (fill.srcRect.l != null) { var _num = ((100 - fill.srcRect.r) * 1000) >> 0; oThis._WriteString1(2, "" + _num); } if (fill.srcRect.l != null) { var _num = ((100 - fill.srcRect.b) * 1000) >> 0; oThis._WriteString1(3, "" + _num); } oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } if (true === fill.tile) { oThis.StartRecord(2); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } else { oThis.StartRecord(3); oThis.EndRecord(); } oThis.EndRecord(); break; case FILL_TYPE_SOLID: oThis.StartRecord(FILL_TYPE_SOLID); oThis.CorrectUniColorAlpha(fill.color, trans); oThis.WriteRecord1(0, fill.color, oThis.WriteUniColor); oThis.EndRecord(); break; default: break; } }; this.WriteLn = function (ln) { if (undefined === ln || null == ln) { return; } oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit2(0, ln.algn); oThis._WriteLimit2(1, ln.cap); oThis._WriteLimit2(2, ln.cmpd); oThis._WriteInt2(3, ln.w); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord2(0, ln.Fill, oThis.WriteUniFill); oThis.WriteRecord1(2, ln.Join, oThis.WriteLineJoin); oThis.WriteRecord2(3, ln.headEnd, oThis.WriteLineEnd); oThis.WriteRecord2(4, ln.tailEnd, oThis.WriteLineEnd); }; this.WriteLineJoin = function (join) { if (join == null || join === undefined) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, 0); oThis.WriteUChar(g_nodeAttributeEnd); return; } oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, (join.type != null && join.type !== undefined) ? join.type : 0); oThis._WriteInt2(1, join.limit); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteLineEnd = function (end) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit2(0, end.type); oThis._WriteLimit2(1, end.w); oThis._WriteLimit2(2, end.len); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteTxBody = function (txBody) { if (txBody.bodyPr) { oThis.WriteRecord2(0, txBody.bodyPr, oThis.WriteBodyPr); } if (txBody.lstStyle) { oThis.WriteRecord2(1, txBody.lstStyle, oThis.WriteTextListStyle); } var _content = txBody.content.Content; oThis.WriteRecordArray(2, 0, _content, oThis.WriteParagraph); }; this.WriteParagraph = function (paragraph, startPos, endPos) { var tPr = new CTextParagraphPr(); if (paragraph.bullet) { tPr.bullet = paragraph.bullet; } tPr.lvl = paragraph.PresentationPr.Level; tPr.pPr = paragraph.Pr; tPr.rPr = null; if (tPr.rPr == null) { tPr.rPr = new CTextPr(); } oThis.WriteRecord1(0, tPr, oThis.WriteTextParagraphPr); oThis.WriteRecord2(1, paragraph.TextPr.Value, oThis.WriteRunProperties); oThis.StartRecord(2); var _position = oThis.pos; oThis.WriteULong(0); var _count = 0; var _par_content = paragraph.Content; var start_pos = startPos != null ? startPos : 0; var end_pos = endPos != undefined ? endPos : _par_content.length; if (paragraph.f_id != undefined || paragraph.f_type != undefined || paragraph.f_text != undefined) { oThis.StartRecord(0); oThis.WriteParagraphField(paragraph.f_id, paragraph.f_type, paragraph.f_text); oThis.EndRecord(); _count++; } var _content_index; var _cur_run_text = ""; _content_index = start_pos; var _cur_run_text_pr = null; var hlinkObj = null; while (_content_index < end_pos) { switch (_par_content[_content_index].Type) { case para_Text: _cur_run_text += _par_content[_content_index].Value; break; case para_Space: _cur_run_text += " "; break; case para_Tab: _cur_run_text += "\t"; break; case para_TextPr: if (("" != _cur_run_text) || (null != _cur_run_text_pr)) { oThis.StartRecord(0); oThis.WriteTextRun((null == _cur_run_text_pr) ? null : _cur_run_text_pr.Value, _cur_run_text, hlinkObj); oThis.EndRecord(); _count++; _cur_run_text = ""; _cur_run_text_pr = null; } _cur_run_text_pr = _par_content[_content_index]; break; case para_NewLine: if (("" != _cur_run_text) || (null != _cur_run_text_pr)) { oThis.StartRecord(0); oThis.WriteTextRun((null == _cur_run_text_pr) ? null : _cur_run_text_pr.Value, _cur_run_text, hlinkObj); oThis.EndRecord(); _count++; _cur_run_text = ""; _cur_run_text_pr = null; } oThis.StartRecord(0); oThis.WriteLineBreak(_cur_run_text_pr, hlinkObj); oThis.EndRecord(); _count++; break; case para_HyperlinkStart: if ("" != _cur_run_text) { oThis.StartRecord(0); oThis.WriteTextRun((null == _cur_run_text_pr) ? null : _cur_run_text_pr.Value, _cur_run_text, hlinkObj); oThis.EndRecord(); _count++; _cur_run_text = ""; } hlinkObj = _par_content[_content_index]; break; case para_HyperlinkEnd: if ("" != _cur_run_text) { oThis.StartRecord(0); oThis.WriteTextRun((null == _cur_run_text_pr) ? null : _cur_run_text_pr.Value, _cur_run_text, hlinkObj); oThis.EndRecord(); _count++; _cur_run_text = ""; } hlinkObj = null; break; } _content_index++; } if (_cur_run_text.length > 0) { oThis.StartRecord(0); oThis.WriteTextRun((null == _cur_run_text_pr) ? null : _cur_run_text_pr.Value, _cur_run_text, hlinkObj); oThis.EndRecord(); _count++; } var _new_pos = oThis.pos; oThis.pos = _position; oThis.WriteULong(_count); oThis.pos = _new_pos; oThis.EndRecord(); }; this.WriteParagraphField = function (id, type, text) { oThis.StartRecord(PARRUN_TYPE_FLD); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, id); oThis._WriteString2(1, type); oThis._WriteString2(2, text); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); }; this.WriteTextRun = function (runPr, text, hlinkObj) { oThis.StartRecord(PARRUN_TYPE_RUN); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString2(0, text); oThis.WriteUChar(g_nodeAttributeEnd); if (runPr !== undefined && runPr != null) { oThis.StartRecord(0); oThis.WriteRunProperties(runPr, hlinkObj); oThis.EndRecord(); } oThis.EndRecord(); }; this.WriteLineBreak = function (runPr, hlinkObj) { oThis.StartRecord(PARRUN_TYPE_BR); if (runPr !== undefined && runPr != null) { oThis.StartRecord(0); oThis.WriteRunProperties(runPr, hlinkObj); oThis.EndRecord(); } oThis.EndRecord(); }; this.WriteShapeStyle = function (style) { oThis.WriteRecord1(0, style.lnRef, oThis.WriteStyleRef); oThis.WriteRecord1(1, style.fillRef, oThis.WriteStyleRef); oThis.WriteRecord1(2, style.effectRef, oThis.WriteStyleRef); oThis.WriteRecord1(3, style.fontRef, oThis.WriteFontRef); }; this.WriteStyleRef = function (ref) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt2(0, ref.idx); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord1(0, ref.Color, oThis.WriteUniColor); }; this.WriteFontRef = function (ref) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteUChar2(0, ref.idx); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord1(0, ref.Color, oThis.WriteUniColor); }; this.WriteBg = function (bg) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit2(0, bg.bwMode); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord2(0, bg.bgPr, oThis.WriteBgPr); oThis.WriteRecord2(1, bg.bgRef, oThis.WriteStyleRef); }; this.WriteBgPr = function (bgPr) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool2(0, bgPr.shadeToTitle); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord1(0, bgPr.Fill, oThis.WriteUniFill); }; this.WriteShape = function (shape) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool2(0, shape.attrUseBgFill); oThis.WriteUChar(g_nodeAttributeEnd); shape.spPr.WriteXfrm = shape.spPr.xfrm; var tmpFill = shape.spPr.Fill; var isUseTmpFill = false; if (tmpFill !== undefined && tmpFill != null) { var trans = ((tmpFill.transparent != null) && (tmpFill.transparent != 255)) ? tmpFill.transparent : null; if (trans != null) { if (tmpFill.fill === undefined || tmpFill.fill == null) { isUseTmpFill = true; shape.spPr.Fill = shape.brush; } } } oThis.WriteRecord2(0, shape.nvSpPr, oThis.WriteUniNvPr); oThis.WriteRecord1(1, shape.spPr, oThis.WriteSpPr); oThis.WriteRecord2(2, shape.style, oThis.WriteShapeStyle); oThis.WriteRecord2(3, shape.txBody, oThis.WriteTxBody); if (isUseTmpFill) { shape.spPr.Fill = tmpFill; } shape.spPr.WriteXfrm = null; oThis.EndRecord(); }; this.WriteImage = function (image) { oThis.StartRecord(2); oThis.WriteRecord1(0, image.nvPicPr, this.WriteUniNvPr); image.spPr.WriteXfrm = image.spPr.xfrm; if (image.spPr.geometry === undefined || image.spPr.geometry == null) { image.spPr.geometry = CreateGeometry("rect"); } oThis.WriteRecord1(1, image.blipFill, oThis.WriteUniFill); oThis.WriteRecord1(2, image.spPr, oThis.WriteSpPr); oThis.WriteRecord2(3, image.style, oThis.WriteShapeStyle); image.spPr.WriteXfrm = null; oThis.EndRecord(); }; this.WriteTable = function (grObj) { oThis.StartRecord(5); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord1(0, grObj.nvGraphicFramePr, oThis.WriteUniNvPr); if (grObj.spPr.xfrm && grObj.spPr.xfrm.isNotNull()) { oThis.WriteRecord2(1, grObj.spPr.xfrm, oThis.WriteXfrm); } oThis.WriteRecord2(2, grObj.graphicObject, oThis.WriteTable2); oThis.EndRecord(); }; this.WriteChart = function (grObj) { oThis.StartRecord(5); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); if (grObj.spPr.xfrm && grObj.spPr.xfrm.isNotNull()) { oThis.WriteRecord2(1, grObj.spPr.xfrm, oThis.WriteXfrm); } oThis.WriteRecord2(3, grObj, oThis.WriteChart2); oThis.EndRecord(); }; this.WriteChart2 = function (grObj) { var _memory = new CMemory(true); _memory.ImData = oThis.ImData; _memory.data = oThis.data; _memory.len = oThis.len; _memory.pos = oThis.pos; oThis.UseContinueWriter = true; var oBinaryChartWriter = new BinaryChartWriter(_memory); oBinaryChartWriter.WriteChartContent(grObj); oThis.ImData = _memory.ImData; oThis.data = _memory.data; oThis.len = _memory.len; oThis.pos = _memory.pos; oThis.UseContinueWriter = false; _memory.ImData = null; _memory.data = null; }; this.WriteTable2 = function (table) { var obj = new Object(); obj.props = table.Pr; obj.look = table.TableLook; obj.style = table.styleIndex; oThis.WriteRecord1(0, obj, oThis.WriteTableProps); var grid = table.TableGrid; var _len = grid.length; oThis.StartRecord(1); oThis.WriteULong(_len); for (var i = 0; i < _len; i++) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, (grid[i] * 36000) >> 0); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } oThis.EndRecord(); oThis.StartRecord(2); var rows_c = table.Content.length; oThis.WriteULong(rows_c); var _grid = oThis.GenerateTableWriteGrid(table); for (var i = 0; i < rows_c; i++) { oThis.StartRecord(0); oThis.WriteTableRow(table.Content[i], _grid.Rows[i]); oThis.EndRecord(); } oThis.EndRecord(); }; this.GenerateTableWriteGrid = function (table) { var TableGrid = new Object(); var _rows = table.Content; var _cols = table.TableGrid; var _cols_count = _cols.length; var _rows_count = _rows.length; TableGrid.Rows = new Array(_rows_count); for (var i = 0; i < _rows_count; i++) { TableGrid.Rows[i] = new Object(); TableGrid.Rows[i].Cells = new Array(); var _index = 0; var _cells_len = _rows[i].Content.length; for (var j = 0; j < _cells_len; j++) { var _cell = _rows[i].Content[j]; var _cell_info = new Object(); _cell_info.Cell = _cell; _cell_info.row_span = 1; _cell_info.grid_span = (_cell.Pr.GridSpan === undefined || _cell.Pr.GridSpan == null) ? 1 : _cell.Pr.GridSpan; _cell_info.hMerge = false; _cell_info.vMerge = false; _cell_info.isEmpty = false; if (_cell.Pr.VMerge == vmerge_Continue) { _cell_info.vMerge = true; } TableGrid.Rows[i].Cells.push(_cell_info); if (_cell_info.grid_span > 1) { for (var t = _cell_info.grid_span - 1; t > 0; t--) { var _cell_info_empty = new Object(); _cell_info_empty.isEmpty = true; _cell_info_empty.vMerge = _cell_info.vMerge; TableGrid.Rows[i].Cells.push(_cell_info_empty); } } } } for (var i = 0; i < _cols_count; i++) { var _index = 0; while (_index < _rows_count) { var _count = 1; for (var j = _index + 1; j < _rows_count; j++) { if (TableGrid.Rows[j].Cells[i].vMerge !== true) { break; }++_count; } TableGrid.Rows[_index].Cells[i].row_span = _count; _index += _count + 1; } } return TableGrid; }; this.WriteEmptyTableCell = function (_info) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool1(3, true); if (true == _info.vMerge) { oThis._WriteBool1(4, true); } oThis.WriteUChar(g_nodeAttributeEnd); oThis.StartRecord(1); oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); oThis.StartRecord(2); oThis.WriteULong(1); oThis.StartRecord(0); oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); oThis.EndRecord(); oThis.EndRecord(); oThis.EndRecord(); }; this.WriteTableRow = function (row, row_info) { oThis.WriteUChar(g_nodeAttributeStart); if (row.Pr.Height !== undefined && row.Pr.Height != null) { oThis._WriteInt1(0, (row.Pr.Height.Value * 36000) >> 0); } oThis.WriteUChar(g_nodeAttributeEnd); oThis.StartRecord(0); var _len = row_info.Cells.length; oThis.WriteULong(_len); for (var i = 0; i < _len; i++) { oThis.StartRecord(1); var _info = row_info.Cells[i]; if (_info.isEmpty) { oThis.WriteEmptyTableCell(_info); } else { oThis.WriteUChar(g_nodeAttributeStart); if (_info.vMerge === false && _info.row_span > 1) { oThis._WriteInt1(1, _info.row_span); } if (_info.hMerge === false && _info.grid_span > 1) { oThis._WriteInt1(2, _info.grid_span); } if (_info.hMerge === true) { oThis._WriteBool1(3, true); } if (_info.vMerge === true) { oThis._WriteBool1(4, true); } oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteTableCell(_info.Cell); } oThis.EndRecord(); } oThis.EndRecord(); }; this.WriteTableCell = function (cell) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); var _marg = cell.Pr.TableCellMar; if (_marg !== undefined && null != _marg && null != _marg.Left && null != _marg.Top && null != _marg.Right && null != _marg.Bottom) { oThis._WriteInt1(0, (_marg.Left.W * 36000) >> 0); oThis._WriteInt1(1, (_marg.Top.W * 36000) >> 0); oThis._WriteInt1(2, (_marg.Right.W * 36000) >> 0); oThis._WriteInt1(3, (_marg.Bottom.W * 36000) >> 0); } oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord3(0, cell.Pr.TableCellBorders.Left, oThis.WriteTableCellBorder); oThis.WriteRecord3(1, cell.Pr.TableCellBorders.Top, oThis.WriteTableCellBorder); oThis.WriteRecord3(2, cell.Pr.TableCellBorders.Right, oThis.WriteTableCellBorder); oThis.WriteRecord3(3, cell.Pr.TableCellBorders.Bottom, oThis.WriteTableCellBorder); var shd = cell.Pr.Shd; if (shd !== undefined && shd != null) { oThis.WriteRecord2(6, shd.unifill, oThis.WriteUniFill); } oThis.EndRecord(); oThis.StartRecord(1); oThis.WriteRecordArray(2, 0, cell.Content.Content, oThis.WriteParagraph); oThis.EndRecord(); }; this.WriteTableProps = function (obj) { oThis.WriteUChar(g_nodeAttributeStart); if (obj.style != -1) { oThis._WriteString1(0, oThis.tableStylesGuides[obj.style]); } oThis._WriteBool1(2, obj.look.m_bFirst_Row); oThis._WriteBool1(3, obj.look.m_bFirst_Col); oThis._WriteBool1(4, obj.look.m_bLast_Row); oThis._WriteBool1(5, obj.look.m_bLast_Col); oThis._WriteBool1(6, obj.look.m_bBand_Hor); oThis._WriteBool1(7, obj.look.m_bBand_Ver); oThis.WriteUChar(g_nodeAttributeEnd); var shd = obj.props.Shd; if (shd !== undefined && shd != null) { if (shd.unifill !== undefined && shd.unifill != null) { if (shd.unifill.fill !== undefined && shd.unifill.fill != null) { oThis.WriteRecord1(0, shd.unifill, oThis.WriteUniFill); } } } }; this.WriteGroupShape = function (group) { oThis.StartRecord(4); group.spPr.WriteXfrm = group.spPr.xfrm; var _old_ph = group.nvGrpSpPr.nvPr.ph; group.nvGrpSpPr.nvPr.ph = null; oThis.WriteRecord1(0, group.nvGrpSpPr, oThis.WriteUniNvPr); group.nvGrpSpPr.nvPr.ph = _old_ph; oThis.WriteRecord1(1, group.spPr, oThis.WriteGrpSpPr); group.spPr.WriteXfrm = null; var spTree = group.spTree; var _len = spTree.length; if (0 != _len) { oThis.StartRecord(2); oThis.WriteULong(_len); for (var i = 0; i < _len; i++) { oThis.StartRecord(0); if (spTree[i] instanceof CShape) { oThis.WriteShape(spTree[i]); } else { if (spTree[i] instanceof CImageShape) { oThis.WriteImage(spTree[i]); } else { if (spTree[i] instanceof CGroupShape) { oThis.WriteGroupShape(spTree[i]); } else { if (spTree[i] instanceof CGraphicFrame && spTree[i].graphicObject instanceof CTable) { oThis.WriteTable(spTree[i]); } else { if (typeof CChartAsGroup != "undefined" && spTree[i] instanceof CChartAsGroup) { oThis.WriteChart(spTree[i]); } } } } } oThis.EndRecord(0); } oThis.EndRecord(); } oThis.EndRecord(); }; this.WriteGrpSpPr = function (grpSpPr) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit2(0, grpSpPr.bwMode); oThis.WriteUChar(g_nodeAttributeEnd); if (grpSpPr.WriteXfrm && grpSpPr.WriteXfrm.isNotNull()) { oThis.WriteRecord2(0, grpSpPr.WriteXfrm, oThis.WriteXfrm); } oThis.WriteRecord1(1, grpSpPr.Fill, oThis.WriteUniFill); }; this.WriteSpPr = function (spPr) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteLimit2(0, spPr.bwMode); oThis.WriteUChar(g_nodeAttributeEnd); var _fill = spPr.Fill; var bIsExistFill = false; if (_fill !== undefined && _fill != null && _fill.fill !== undefined && _fill.fill != null) { bIsExistFill = true; } var bIsExistLn = false; if (spPr.ln !== undefined && spPr.ln != null) { _fill = spPr.ln.Fill; if (_fill !== undefined && _fill != null && _fill.fill !== undefined && _fill.fill != null) { bIsExistLn = true; } } if (spPr.WriteXfrm && spPr.WriteXfrm.isNotNull()) { oThis.WriteRecord2(0, spPr.WriteXfrm, oThis.WriteXfrm); } oThis.WriteRecord2(1, spPr.geometry, oThis.WriteGeometry); if (spPr.geometry === undefined || spPr.geometry == null) { if (bIsExistFill || bIsExistLn) { oThis.StartRecord(1); oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, "rect"); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); oThis.EndRecord(); } } oThis.WriteRecord1(2, spPr.Fill, oThis.WriteUniFill); oThis.WriteRecord2(3, spPr.ln, oThis.WriteLn); }; this.WriteXfrm = function (xfrm) { if (oThis.IsWordWriter === true) { return oThis.WriteXfrmRot(xfrm); } oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt4(0, xfrm.offX, c_dScalePPTXSizes); oThis._WriteInt4(1, xfrm.offY, c_dScalePPTXSizes); oThis._WriteInt4(2, xfrm.extX, c_dScalePPTXSizes); oThis._WriteInt4(3, xfrm.extY, c_dScalePPTXSizes); oThis._WriteInt4(4, xfrm.chOffX, c_dScalePPTXSizes); oThis._WriteInt4(5, xfrm.chOffY, c_dScalePPTXSizes); oThis._WriteInt4(6, xfrm.chExtX, c_dScalePPTXSizes); oThis._WriteInt4(7, xfrm.chExtY, c_dScalePPTXSizes); oThis._WriteBool2(8, xfrm.flipH); oThis._WriteBool2(9, xfrm.flipV); oThis._WriteInt4(10, xfrm.rot, 180 * 60000 / Math.PI); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteXfrmRot = function (xfrm) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt4(0, xfrm.offX, c_dScalePPTXSizes); oThis._WriteInt4(1, xfrm.offY, c_dScalePPTXSizes); oThis._WriteInt4(2, xfrm.extX, c_dScalePPTXSizes); oThis._WriteInt4(3, xfrm.extY, c_dScalePPTXSizes); oThis._WriteInt4(4, xfrm.chOffX, c_dScalePPTXSizes); oThis._WriteInt4(5, xfrm.chOffY, c_dScalePPTXSizes); oThis._WriteInt4(6, xfrm.chExtX, c_dScalePPTXSizes); oThis._WriteInt4(7, xfrm.chExtY, c_dScalePPTXSizes); oThis._WriteBool2(8, xfrm.flipH); oThis._WriteBool2(9, xfrm.flipV); if (xfrm.rot != null) { var nCheckInvert = 0; if (true == xfrm.flipH) { nCheckInvert += 1; } if (true == xfrm.flipV) { nCheckInvert += 1; } var _rot = (xfrm.rot * 180 * 60000 / Math.PI) >> 0; var _n360 = 360 * 60000; if (_rot > _n360) { var _nDel = (_rot / _n360) >> 0; _rot = _rot - _nDel * _n360; } else { if (_rot < 0) { var _nDel = (-_rot / _n360) >> 0; _nDel += 1; _rot = _rot + _nDel * _n360; } } if (nCheckInvert == 1) { _rot = _n360 - _rot; } oThis._WriteInt1(10, _rot); } oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteUniNvPr = function (nv) { oThis.WriteRecord1(0, nv.cNvPr, oThis.Write_cNvPr); oThis.WriteRecord1(2, nv.nvPr, oThis.Write_nvPr); }; this.Write_cNvPr = function (cNvPr) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteInt1(0, cNvPr.id); oThis._WriteString1(1, cNvPr.name); oThis.WriteUChar(g_nodeAttributeEnd); }; this.Write_nvPr = function (nvPr) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool2(0, nvPr.isPhoto); oThis._WriteBool2(1, nvPr.userDrawn); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord2(0, nvPr.ph, oThis.Write_ph); }; this.Write_ph = function (ph) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteBool2(0, ph.hasCustomPrompt); oThis._WriteString2(1, ph.idx); oThis._WriteLimit2(2, ph.orient); oThis._WriteLimit2(3, ph.sz); oThis._WriteLimit2(4, ph.type); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WriteGeometry = function (geom) { if (undefined === geom || null == geom) { return; } if (geom.preset != null && geom.preset != null) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, geom.preset); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteAdj(geom.gdLst, geom.avLst, 0); oThis.EndRecord(); } else { oThis.StartRecord(2); oThis.WriteAdj(geom.gdLst, geom.avLst, 0); oThis.WriteGuides(geom.gdLstInfo, 1); oThis.WriteAh(geom.ahXYLstInfo, geom.ahPolarLstInfo, 2); oThis.WriteCnx(geom.cnxLstInfo, 3); oThis.WritePathLst(geom.pathLst, 4); oThis.WriteRecord2(5, geom.rectS, oThis.WriteTextRect); oThis.EndRecord(); } }; this.WriteAdj = function (gdLst, avLst, rec_num) { var _len = 0; for (var i in avLst) { ++_len; } if (0 == _len) { return; } oThis.StartRecord(rec_num); oThis.WriteULong(_len); for (var i in avLst) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, i); oThis._WriteInt1(1, 15); oThis._WriteString1(2, "" + (gdLst[i] >> 0)); oThis.WriteUChar(g_nodeAttributeEnd); oThis.EndRecord(); } oThis.EndRecord(); }; this.WriteGuides = function (gdLst, rec_num) { var _len = gdLst.length; if (0 == rec_num) { return; } this.StartRecord(rec_num); this.WriteULong(_len); for (var i = 0; i < _len; i++) { this.StartRecord(1); var _gd = gdLst[i]; this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, _gd.name); this._WriteInt1(1, _gd.formula); if (_gd.x !== undefined) { this._WriteString1(2, _gd.x); } if (_gd.y !== undefined) { this._WriteString1(3, _gd.y); } if (_gd.z !== undefined) { this._WriteString1(4, _gd.z); } this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); } this.EndRecord(); }; this.WriteAh = function (ahLstXY, ahLstPolar, rec_num) { var _len = 0; for (var i in ahLstXY) { ++_len; } for (var i in ahLstPolar) { ++_len; } if (0 == rec_num) { return; } this.StartRecord(rec_num); this.WriteULong(_len); for (var i in ahLstXY) { this.StartRecord(1); var _ah = ahLstXY[i]; this.StartRecord(2); this.WriteUChar(g_nodeAttributeStart); this._WriteString2(0, _ah.posX); this._WriteString2(1, _ah.posY); this._WriteString2(2, _ah.gdRefX); this._WriteString2(3, _ah.gdRefY); this._WriteString2(4, _ah.maxX); this._WriteString2(5, _ah.maxY); this._WriteString2(6, _ah.minX); this._WriteString2(7, _ah.minY); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); this.EndRecord(); } for (var i in ahLstPolar) { this.StartRecord(1); var _ah = ahLstPolar[i]; this.StartRecord(2); this.WriteUChar(g_nodeAttributeStart); this._WriteString2(0, _ah.posX); this._WriteString2(1, _ah.posY); this._WriteString2(2, _ah.gdRefAng); this._WriteString2(3, _ah.gdRefR); this._WriteString2(4, _ah.maxAng); this._WriteString2(5, _ah.maxR); this._WriteString2(6, _ah.minAng); this._WriteString2(7, _ah.minR); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); this.EndRecord(); } this.EndRecord(); }; this.WriteCnx = function (cnxLst, rec_num) { var _len = 0; for (var i in cnxLst) { ++_len; } if (0 == rec_num) { return; } this.StartRecord(rec_num); this.WriteULong(_len); for (var i in cnxLst) { this.StartRecord(1); var _gd = cnxLst[i]; this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, _gd.x); this._WriteString1(1, _gd.y); this._WriteString1(2, _gd.ang); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); } this.EndRecord(); }; this.WriteTextRect = function (rect) { oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString2(0, rect.l); oThis._WriteString2(1, rect.t); oThis._WriteString2(2, rect.r); oThis._WriteString2(3, rect.b); oThis.WriteUChar(g_nodeAttributeEnd); }; this.WritePathLst = function (pathLst, rec_num) { var _len = pathLst.length; if (0 == _len) { return; } this.StartRecord(rec_num); this.WriteULong(_len); for (var i = 0; i < _len; i++) { this.StartRecord(1); var _path = pathLst[i]; this.WriteUChar(g_nodeAttributeStart); this._WriteBool2(0, _path.extrusionOk); if (_path.fill != null && _path.fill !== undefined) { this._WriteLimit1(1, (_path.fill == "none") ? 4 : 5); } this._WriteInt2(2, _path.pathH); this._WriteBool2(3, _path.stroke); this._WriteInt2(4, _path.pathW); this.WriteUChar(g_nodeAttributeEnd); var _comms = _path.ArrPathCommandInfo; var _count = _comms.length; if (0 != _count) { this.StartRecord(0); this.WriteULong(_count); for (var j = 0; j < _count; j++) { this.StartRecord(0); var cmd = _comms[j]; switch (cmd.id) { case moveTo: this.StartRecord(1); this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, "" + cmd.X); this._WriteString1(1, "" + cmd.Y); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); break; case lineTo: this.StartRecord(2); this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, "" + cmd.X); this._WriteString1(1, "" + cmd.Y); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); break; case bezier3: this.StartRecord(6); this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, "" + cmd.X0); this._WriteString1(1, "" + cmd.Y0); this._WriteString1(2, "" + cmd.X1); this._WriteString1(3, "" + cmd.Y1); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); break; case bezier4: this.StartRecord(4); this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, "" + cmd.X0); this._WriteString1(1, "" + cmd.Y0); this._WriteString1(2, "" + cmd.X1); this._WriteString1(3, "" + cmd.Y1); this._WriteString1(4, "" + cmd.X2); this._WriteString1(5, "" + cmd.Y2); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); break; case arcTo: this.StartRecord(5); this.WriteUChar(g_nodeAttributeStart); this._WriteString1(0, "" + cmd.wR); this._WriteString1(1, "" + cmd.hR); this._WriteString1(2, "" + cmd.stAng); this._WriteString1(3, "" + cmd.swAng); this.WriteUChar(g_nodeAttributeEnd); this.EndRecord(); break; case close: this.StartRecord(3); this.EndRecord(); break; } this.EndRecord(); } this.EndRecord(); } this.EndRecord(); } this.EndRecord(); }; this.WriteTableStyle = function (num, tableStyle) { oThis.StartRecord(1); oThis.WriteUChar(g_nodeAttributeStart); oThis._WriteString1(0, oThis.tableStylesGuides[num]); var __name = tableStyle.Name; __name = __name.replace(/&/g, "_"); __name = __name.replace(/>/g, "_"); __name = __name.replace(/</g, "_"); __name = __name.replace(/"/g, "_"); __name = __name.replace(/'/g, "_"); oThis._WriteString2(1, __name); oThis.WriteUChar(g_nodeAttributeEnd); if (undefined !== tableStyle.TablePr.Shd && null != tableStyle.TablePr.Shd) { oThis.StartRecord(0); if (tableStyle.TablePr.Shd.unifill != null && tableStyle.TablePr.Shd.unifill !== undefined) { oThis.StartRecord(0); oThis.WriteRecord2(0, tableStyle.TablePr.Shd.unifill, oThis.WriteUniFill); oThis.EndRecord(); } if (tableStyle.TablePr.Shd.fillRef != null && tableStyle.TablePr.Shd.fillRef !== undefined) { oThis.WriteRecord2(1, tableStyle.TablePr.Shd.fillRef, oThis.WriteStyleRef); } oThis.EndRecord(); } if (tableStyle.TableWholeTable) { oThis.StartRecord(1); oThis.WriteTableStylePartWH(tableStyle.TableWholeTable, tableStyle.TablePr); oThis.EndRecord(); } oThis.WriteRecord2(2, tableStyle.TableBand1Horz, oThis.WriteTableStylePart); oThis.WriteRecord2(3, tableStyle.TableBand2Horz, oThis.WriteTableStylePart); oThis.WriteRecord2(4, tableStyle.TableBand1Vert, oThis.WriteTableStylePart); oThis.WriteRecord2(5, tableStyle.TableBand2Vert, oThis.WriteTableStylePart); oThis.WriteRecord2(6, tableStyle.TableLastCol, oThis.WriteTableStylePart); oThis.WriteRecord2(7, tableStyle.TableFirstCol, oThis.WriteTableStylePart); oThis.WriteRecord2(8, tableStyle.TableFirstRow, oThis.WriteTableStylePart); oThis.WriteRecord2(9, tableStyle.TableLastRow, oThis.WriteTableStylePart); oThis.WriteRecord2(10, tableStyle.TableBRCell, oThis.WriteTableStylePart); oThis.WriteRecord2(11, tableStyle.TableBLCell, oThis.WriteTableStylePart); oThis.WriteRecord2(12, tableStyle.TableTRCell, oThis.WriteTableStylePart); oThis.WriteRecord2(13, tableStyle.TableTLCell, oThis.WriteTableStylePart); oThis.EndRecord(); }; this.WriteTableStylePart = function (_part) { var bIsFontRef = false; if (_part.TextPr.fontRef !== undefined && _part.TextPr.fontRef != null) { bIsFontRef = true; } var bIsFill = false; if (_part.TextPr.unifill !== undefined && _part.TextPr.unifill != null) { bIsFill = true; } if (bIsFontRef || bIsFill) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord2(0, _part.TextPr.fontRef, oThis.WriteFontRef); if (bIsFill && _part.TextPr.unifill.fill !== undefined && _part.TextPr.unifill.fill != null && _part.TextPr.unifill.fill.type == FILL_TYPE_SOLID) { oThis.WriteRecord2(1, _part.TextPr.unifill.fill.color, oThis.WriteUniColor); } oThis.EndRecord(); } oThis.StartRecord(1); oThis.StartRecord(0); oThis.WriteRecord3(0, _part.TableCellPr.TableCellBorders.Left, oThis.WriteTableCellBorderLineStyle); oThis.WriteRecord3(1, _part.TableCellPr.TableCellBorders.Right, oThis.WriteTableCellBorderLineStyle); oThis.WriteRecord3(2, _part.TableCellPr.TableCellBorders.Top, oThis.WriteTableCellBorderLineStyle); oThis.WriteRecord3(3, _part.TableCellPr.TableCellBorders.Bottom, oThis.WriteTableCellBorderLineStyle); oThis.WriteRecord3(4, _part.TableCellPr.TableCellBorders.InsideH, oThis.WriteTableCellBorderLineStyle); oThis.WriteRecord3(5, _part.TableCellPr.TableCellBorders.InsideV, oThis.WriteTableCellBorderLineStyle); oThis.EndRecord(); var _Shd = _part.TableCellPr.Shd; if (undefined !== _Shd && null != _Shd) { oThis.WriteRecord2(1, _Shd.fillRef, oThis.WriteStyleRef); if (_Shd.unifill !== undefined && _Shd.unifill != null) { oThis.StartRecord(2); oThis.WriteRecord2(0, _Shd.unifill, oThis.WriteUniFill); oThis.EndRecord(); } } oThis.EndRecord(); }; this.WriteTableStylePartWH = function (_part, tablePr) { var bIsFontRef = false; if (_part.TextPr.fontRef !== undefined && _part.TextPr.fontRef != null) { bIsFontRef = true; } var bIsFill = false; if (_part.TextPr.unifill !== undefined && _part.TextPr.unifill != null) { bIsFill = true; } if (bIsFontRef || bIsFill) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); oThis.WriteRecord2(0, _part.TextPr.fontRef, oThis.WriteFontRef); if (bIsFill && _part.TextPr.unifill.fill !== undefined && _part.TextPr.unifill.fill != null && _part.TextPr.unifill.fill.type == FILL_TYPE_SOLID) { oThis.WriteRecord2(1, _part.TextPr.unifill.fill.color, oThis.WriteUniColor); } oThis.EndRecord(); } oThis.StartRecord(1); oThis.StartRecord(0); var bIsRet = false; bIsRet = oThis.WriteRecord3(0, _part.TableCellPr.TableCellBorders.Left, oThis.WriteTableCellBorderLineStyle); if (!bIsRet) { oThis.WriteTableCellBorderLineStyle2(0, tablePr.TableBorders.Left); } bIsRet = oThis.WriteRecord3(1, _part.TableCellPr.TableCellBorders.Right, oThis.WriteTableCellBorderLineStyle); if (!bIsRet) { oThis.WriteTableCellBorderLineStyle2(1, tablePr.TableBorders.Right); } bIsRet = oThis.WriteRecord3(2, _part.TableCellPr.TableCellBorders.Top, oThis.WriteTableCellBorderLineStyle); if (!bIsRet) { oThis.WriteTableCellBorderLineStyle2(2, tablePr.TableBorders.Top); } bIsRet = oThis.WriteRecord3(3, _part.TableCellPr.TableCellBorders.Bottom, oThis.WriteTableCellBorderLineStyle); if (!bIsRet) { oThis.WriteTableCellBorderLineStyle2(3, tablePr.TableBorders.Bottom); } oThis.WriteTableCellBorderLineStyle2(4, _part.TablePr.TableBorders.InsideH); oThis.WriteTableCellBorderLineStyle2(5, _part.TablePr.TableBorders.InsideV); oThis.EndRecord(); var _Shd = _part.TableCellPr.Shd; if (undefined !== _Shd && null != _Shd) { oThis.WriteRecord2(1, _Shd.fillRef, oThis.WriteStyleRef); if (_Shd.unifill !== undefined && _Shd.unifill != null) { oThis.StartRecord(2); oThis.WriteRecord2(0, _Shd.unifill, oThis.WriteUniFill); oThis.EndRecord(); } } oThis.EndRecord(); }; this.WriteTableCellBorder = function (_border) { if (_border.Value == border_None) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); var _unifill = new CUniFill(); _unifill.fill = new CNoFill(); oThis.WriteRecord2(0, _unifill, oThis.WriteUniFill); oThis.EndRecord(); return; } var bIsFill = false; var bIsSize = false; if ((_border.unifill !== undefined && _border.unifill != null) || _border.Color instanceof CDocumentColor) { bIsFill = true; } if (_border.Size !== undefined && _border.Size != null) { bIsSize = true; } if (bIsFill || bIsSize) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); if (bIsSize) { oThis._WriteInt2(3, (_border.Size * 36000) >> 0); } oThis.WriteUChar(g_nodeAttributeEnd); if (!_border.unifill && _border.Color instanceof CDocumentColor) { var _unifill = new CUniFill(); _unifill.fill = new CSolidFill(); _unifill.fill.color.color = new CRGBColor(); _unifill.fill.color.color.RGBA.R = _border.Color.r; _unifill.fill.color.color.RGBA.G = _border.Color.g; _unifill.fill.color.color.RGBA.B = _border.Color.b; oThis.WriteRecord2(0, _unifill, oThis.WriteUniFill); } oThis.WriteRecord2(0, _border.unifill, oThis.WriteUniFill); oThis.EndRecord(); } }; this.WriteTableCellBorderLineStyle2 = function (rec_type, _border) { if (!_border) { oThis.StartRecord(rec_type); oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); var _unifill = new CUniFill(); _unifill.fill = new CNoFill(); oThis.WriteRecord2(0, _unifill, oThis.WriteUniFill); oThis.EndRecord(); oThis.EndRecord(); return; } else { oThis.WriteRecord3(rec_type, _border, oThis.WriteTableCellBorderLineStyle); } }; this.WriteTableCellBorderLineStyle = function (_border) { if (_border.Value == border_None) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); oThis.WriteUChar(g_nodeAttributeEnd); var _unifill = new CUniFill(); _unifill.fill = new CNoFill(); oThis.WriteRecord2(0, _unifill, oThis.WriteUniFill); oThis.EndRecord(); return; } var bIsFill = false; var bIsSize = false; var bIsLnRef = false; if ((_border.unifill !== undefined && _border.unifill != null) || _border.Color instanceof CDocumentColor) { bIsFill = true; } if (_border.Size !== undefined && _border.Size != null) { bIsSize = true; } if (bIsFill && bIsSize) { oThis.StartRecord(0); oThis.WriteUChar(g_nodeAttributeStart); if (bIsSize) { oThis._WriteInt2(3, (_border.Size * 36000) >> 0); } oThis.WriteUChar(g_nodeAttributeEnd); if (!_border.unifill && _border.Color instanceof CDocumentColor) { var _unifill = new CUniFill(); _unifill.fill = new CSolidFill(); _unifill.fill.color.color = new CRGBColor(); _unifill.fill.color.color.RGBA.R = _border.Color.r; _unifill.fill.color.color.RGBA.G = _border.Color.g; _unifill.fill.color.color.RGBA.B = _border.Color.b; oThis.WriteRecord2(0, _unifill, oThis.WriteUniFill); } oThis.WriteRecord2(0, _border.unifill, oThis.WriteUniFill); oThis.EndRecord(); } oThis.WriteRecord2(1, _border.lnRef, oThis.WriteStyleRef); }; }
devsarr/ONLYOFFICE-OnlineEditors
OfficeWeb/sdk/Common/Shapes/SerializeWriter.js
JavaScript
agpl-3.0
112,112
Meteor.publish('card-vocoder-vocoders',function(simulatorId){ return Flint.collection('vocoders').find({simulatorId:simulatorId}); });
infinitedg/flint
packages/card-vocoder/publish.js
JavaScript
agpl-3.0
136
import React from "react"; import basicComponent from "core/basicComponent"; import Radium from "radium"; import ReactAplayer from "react-aplayer"; import mergeAdvanced from "object-merge-advanced"; class audioPlayer extends basicComponent { constructor(props) { super(props); if (!this.isRestored) { this.state = { ...this.state, audios: [] }; } this.myRef = React.createRef(); } onInit = ap => { this.ap = ap; }; play = () => this.ap.play(); pause = () => this.ap.pause(); seek = timePos => this.ap.seek(timePos); addAudio(audioProps) { this.setState(prevState => { const prevAudios = prevState.audios; const nextAudios = prevAudios.concat([audioProps]); const nextState = mergeAdvanced(prevState, { audios: nextAudios }); return nextState; }); } thisComponent = () => { const state = this.getState(); const styles = this.getStyles(); return ( <ReactAplayer ref={this.myRef} theme="#F57F17" lrcType={3} audio={state.audios || []} onInit={this.onInit} style={styles} {...this.getEvents()} /> ); }; } export default Radium(audioPlayer);
project-jste/framework
src/JS/components/audioPlayer.js
JavaScript
agpl-3.0
1,207
import { expect, fixture, fixtureCleanup, fixtureSync } from '@open-wc/testing'; import sinon from 'sinon'; import volumesProvider from '../../../../src/BookNavigator/volumes/volumes-provider'; const brOptions = { "options": { "enableMultipleBooks": true, "multipleBooksList": { "by_subprefix": { "/details/SubBookTest": { "url_path": "/details/SubBookTest", "file_subprefix": "book1/GPORFP", "orig_sort": 1, "title": "book1/GPORFP.pdf", "file_source": "/book1/GPORFP_jp2.zip" }, "/details/SubBookTest/subdir/book2/brewster_kahle_internet_archive": { "url_path": "/details/SubBookTest/subdir/book2/brewster_kahle_internet_archive", "file_subprefix": "subdir/book2/brewster_kahle_internet_archive", "orig_sort": 2, "title": "subdir/book2/brewster_kahle_internet_archive.pdf", "file_source": "/subdir/book2/brewster_kahle_internet_archive_jp2.zip" }, "/details/SubBookTest/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume": { "url_path": "/details/SubBookTest/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume", "file_subprefix": "subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume", "orig_sort": 3, "title": "subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume.pdf", "file_source": "/subdir/subsubdir/book3/Rfp008011ResponseInternetArchive-without-resume_jp2.zip" } } } } }; afterEach(() => { sinon.restore(); fixtureCleanup(); }); describe('Volumes Provider', () => { it('constructor', () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const files = brOptions.options.multipleBooksList.by_subprefix; const volumeCount = Object.keys(files).length; expect(provider.onProviderChange).to.equal(onProviderChange); expect(provider.id).to.equal('volumes'); expect(provider.icon).to.exist; expect(fixtureSync(provider.icon).tagName).to.equal('svg'); expect(provider.label).to.equal(`Viewable files (${volumeCount})`); expect(provider.viewableFiles).to.exist; expect(provider.viewableFiles.length).to.equal(3); expect(provider.component.hostUrl).to.exist; expect(provider.component.hostUrl).to.equal(baseHost); expect(provider.component).to.exist; }); it('sorting cycles - render sort actionButton', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); expect(provider.sortOrderBy).to.equal("default"); provider.sortVolumes("title_asc"); expect(provider.sortOrderBy).to.equal("title_asc"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by asc-icon"); provider.sortVolumes("title_desc"); expect(provider.sortOrderBy).to.equal("title_desc"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by desc-icon"); provider.sortVolumes("default"); expect(provider.sortOrderBy).to.equal("default"); expect(fixtureSync(provider.sortButton).outerHTML).includes("sort-by neutral-icon"); }); it('sort volumes in initial order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]).sort((a, b) => a.orig_sort - b.orig_sort); const origSortTitles = files.map(item => item.title); provider.sortVolumes("default"); expect(provider.sortOrderBy).to.equal("default"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...origSortTitles]); }); it('sort volumes in ascending title order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]); const ascendingTitles = files.map(item => item.title).sort((a, b) => a.localeCompare(b)); provider.sortVolumes("title_asc"); expect(provider.sortOrderBy).to.equal("title_asc"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...ascendingTitles]); }); it('sort volumes in descending title order', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); provider.isSortAscending = false; const parsedFiles = brOptions.options.multipleBooksList.by_subprefix; const files = Object.keys(parsedFiles).map(item => parsedFiles[item]); const descendingTitles = files.map(item => item.title).sort((a, b) => b.localeCompare(a)); provider.sortVolumes("title_desc"); expect(provider.sortOrderBy).to.equals("title_desc"); expect(provider.actionButton).to.exist; const providerFileTitles = provider.viewableFiles.map(item => item.title); // use `.eql` for "lose equality" in order to deeply compare values. expect(providerFileTitles).to.eql([...descendingTitles]); }); describe('Sorting icons', () => { it('has 3 icons', async () => { const onProviderChange = sinon.fake(); const baseHost = "https://archive.org"; const provider = new volumesProvider({ baseHost, bookreader: brOptions, onProviderChange }); provider.sortOrderBy = 'default'; const origSortButton = await fixture(provider.sortButton); expect(origSortButton.classList.contains('neutral-icon')).to.be.true; provider.sortOrderBy = 'title_asc'; const ascButton = await fixture(provider.sortButton); expect(ascButton.classList.contains('asc-icon')).to.be.true; provider.sortOrderBy = 'title_desc'; const descButton = await fixture(provider.sortButton); expect(descButton.classList.contains('desc-icon')).to.be.true; }); }); });
internetarchive/bookreader
tests/karma/BookNavigator/volumes/volumes-provider.test.js
JavaScript
agpl-3.0
6,945
describe('Service: can', function () { var api beforeEach(angular.mock.inject(function (can) { api = can })) describe('.can()', function () { it('returns true when the resource includes a method', function () { var project = { '_links': { repositories: { update: 'PUT' } } } expect(api.can('update-repositories', project)).toBeTruthy() }) it('returns false when resource excludes method', function () { var project = { '_links': { repositories: {} } } expect(api.can('update-repositories', project)).toBeFalsy() }) it('returns false otherwise', function () { expect(api.can('update-repositories', {})).toBeFalsy() }) }) })
harrowio/harrow
frontend/test/spec/service/can_test.js
JavaScript
agpl-3.0
779
/* * Copyright 2015 Westfälische Hochschule * * This file is part of Poodle. * * Poodle 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. * * Poodle 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 Poodle. If not, see <http://www.gnu.org/licenses/>. */ /* * This code is mostly responsible for creating the * diagrams with the Google Charts API. * * The server sends us the statistics as a 2 dimensional JSON array. * This way we can directly use it with Google's dataTable.addRows() * function. All diagrams are created from this table. * * Column 0: completion status (partly, not at all...) * Column 1: Difficulty * Column 2: Fun * Column 3: Time * * The difficulty, fun and completion status diagrams are Column Charts, * the time diagrams is a Histogram. * * https://developers.google.com/chart/ * https://developers.google.com/chart/interactive/docs/gallery/columnchart * https://developers.google.com/chart/interactive/docs/gallery/histogram */ $(document).ready(function() { /* global exercise */ /* global messages */ "use strict"; /* Minimum amount of data we need to create a diagram. * If we have less than this, the diagram is not rendered and * the tab is disabled. */ var MIN_DATA_COUNT = 2; // global options for all diagrams var OPTIONS_ALL = { backgroundColor: "transparent", legend: { position: "none" }, hAxis: { titleTextStyle: { bold: true, italic: false } }, vAxis: { titleTextStyle: { bold: true, italic: false }, title: messages.count, minValue: 0 } }; var $chartsTabs = $("#chartsTabs"); function loadChartData() { $.ajax({ url: window.location.pathname + "/chartData", type: "GET", success: onChartDataLoaded }); } function onChartDataLoaded(data) { // create dataTable var dataTable = new google.visualization.DataTable(); dataTable.addColumn("string", messages.completed); dataTable.addColumn("number", messages.difficulty); dataTable.addColumn("number", messages.fun); dataTable.addColumn("number", messages.time); dataTable.addRows(data); /* Create all charts. * We are doing this _before_ creating the tabs on purpose, * since the API is not able to render into a hidden * div i.e. inactice tab. * * Every draw function returns whether the diagram was created or * not (MIN_DATA_COUNT). If not, we disable the tab on this index. */ var disabledTabs = []; if (!drawDifficultyChart(dataTable)) disabledTabs.push(0); if (!drawTimeChart(dataTable)) disabledTabs.push(1); if (!drawFunChart(dataTable)) disabledTabs.push(2); if (!drawCompletedChart(dataTable)) disabledTabs.push(3); if ($("#textList > li").length === 0) disabledTabs.push(4); var tabCount = $chartsTabs.find("#tabList > li").length; // all tabs disabled, hide them and abort if (disabledTabs.length === tabCount) { $chartsTabs.hide(); return; } // get index of the first tab that is not disabled var activeTab = 0; for (var i = 0; i < tabCount; i++) { if ($.inArray(i, disabledTabs) === -1) { activeTab = i; break; } } // generate tabs $chartsTabs.tabs({ disabled: disabledTabs, active: activeTab }); } function drawDifficultyChart(dataTable) { var $difficultyChart =$("#difficultyChart"); var avgDifficulty = $difficultyChart.data("avg"); var difficultyOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.difficultyTitle.format(avgDifficulty) } }); var counts = new google.visualization.DataTable(); // this column must be of type string. Otherwise not all values are displayed on the x axis. counts.addColumn("string", messages.difficulty); counts.addColumn("number", messages.count); var dataCount = 0; for (var difficulty = 1; difficulty <= 10; difficulty++) { var count = dataTable.getFilteredRows([{column: 1, value: difficulty}]).length; counts.addRow([difficulty.toString(), count]); dataCount += count; } if (dataCount < MIN_DATA_COUNT) return false; var chart = new google.visualization.ColumnChart($difficultyChart.get(0)); chart.draw(counts, difficultyOptions); return true; } function drawTimeChart(dataTable) { var $timeChart = $("#timeChart"); var avgTime = $timeChart.data("avg"); var view = new google.visualization.DataView(dataTable); view.setRows(view.getFilteredRows( [{ column: 3, // only columns with time >= 1 minValue: 1 }]) ); view.setColumns([3]); // only time column if (view.getNumberOfRows() < MIN_DATA_COUNT) return false; var timeOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.timeTitle.format(avgTime) } }); var chart = new google.visualization.Histogram($timeChart.get(0)); chart.draw(view, timeOptions); return true; } function drawFunChart(dataTable) { var $funChart = $("#funChart"); var avgFun = $funChart.data("avg"); var funOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.funTitle.format(avgFun) } }); var counts = new google.visualization.DataTable(); // this column must be of type string. Otherwise not all values are displayed on the x axis. counts.addColumn("string", messages.fun); counts.addColumn("number", messages.count); var dataCount = 0; for (var fun = 1; fun <= 10; fun++) { var count = dataTable.getFilteredRows([{column: 2, value: fun}]).length; counts.addRow([fun.toString(), count]); dataCount += count; } if (dataCount < MIN_DATA_COUNT) return false; var chart = new google.visualization.ColumnChart($funChart.get(0)); chart.draw(counts, funOptions); return true; } function drawCompletedChart(dataTable) { var counts = new google.visualization.DataTable(); counts.addColumn("string", messages.completed); counts.addColumn("number", messages.count); var dataCount = 0; /* messages.completedStatus contains the Java enum values (which are also * in the dataTable) as the keys and the localized description as the values. * Iterate over the keys and add a row for each. */ var completedStatus = messages.completedStatus; for (var s in completedStatus) { var count = dataTable.getFilteredRows([{column: 0, value: s}]).length; counts.addRow([completedStatus[s], count]); dataCount += count; } if (dataCount < MIN_DATA_COUNT) return false; var completedOptions = $.extend(true, {}, OPTIONS_ALL, { hAxis: { title: messages.completed } }); var chart = new google.visualization.ColumnChart(document.getElementById("completedChart")); chart.draw(counts, completedOptions); return true; } // confirm exercise deletion $("#deleteForm").submit(function() { return exercise.confirmDelete(); }); /* * Load diagram, if statistics exist. * (#chartsTabs doesn't exist if the statistics are empty). */ if ($chartsTabs.length > 0) { google.load( "visualization", "1.0", { callback: loadChartData, packages: ["corechart"] } ); } // initialize DataTables for feedback table $("#feedbackTable").DataTable({ "order": [[ 1, "desc" ]] // date descending }); });
whs-poodle/poodle
src/main/resources/static/js/instructor/exercise.js
JavaScript
agpl-3.0
7,646
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'link', 'cs', { acccessKey: 'Přístupový klíč', advanced: 'Rozšířené', advisoryContentType: 'Pomocný typ obsahu', advisoryTitle: 'Pomocný titulek', anchor: { toolbar: 'Záložka', menu: 'Vlastnosti záložky', title: 'Vlastnosti záložky', name: 'Název záložky', errorName: 'Zadejte prosím název záložky', remove: 'Odstranit záložku' }, anchorId: 'Podle Id objektu', anchorName: 'Podle jména kotvy', charset: 'Přiřazená znaková sada', cssClasses: 'Třída stylu', download: 'Force Download', // MISSING displayText: 'Zobrazit text', emailAddress: 'E-mailová adresa', emailBody: 'Tělo zprávy', emailSubject: 'Předmět zprávy', id: 'Id', info: 'Informace o odkazu', langCode: 'Kód jazyka', langDir: 'Směr jazyka', langDirLTR: 'Zleva doprava (LTR)', langDirRTL: 'Zprava doleva (RTL)', menu: 'Změnit odkaz', name: 'Jméno', noAnchors: '(Ve stránce není definována žádná kotva!)', noEmail: 'Zadejte prosím e-mailovou adresu', noUrl: 'Zadejte prosím URL odkazu', other: '<jiný>', popupDependent: 'Závislost (Netscape)', popupFeatures: 'Vlastnosti vyskakovacího okna', popupFullScreen: 'Celá obrazovka (IE)', popupLeft: 'Levý okraj', popupLocationBar: 'Panel umístění', popupMenuBar: 'Panel nabídky', popupResizable: 'Umožňující měnit velikost', popupScrollBars: 'Posuvníky', popupStatusBar: 'Stavový řádek', popupToolbar: 'Panel nástrojů', popupTop: 'Horní okraj', rel: 'Vztah', selectAnchor: 'Vybrat kotvu', styles: 'Styl', tabIndex: 'Pořadí prvku', target: 'Cíl', targetFrame: '<rámec>', targetFrameName: 'Název cílového rámu', targetPopup: '<vyskakovací okno>', targetPopupName: 'Název vyskakovacího okna', title: 'Odkaz', toAnchor: 'Kotva v této stránce', toEmail: 'E-mail', toUrl: 'URL', toolbar: 'Odkaz', type: 'Typ odkazu', unlink: 'Odstranit odkaz', upload: 'Odeslat' } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/link/lang/cs.js
JavaScript
agpl-3.0
2,156
/* ListJS 1.1.1 (www.listjs.com) License (MIT) Copyright (c) 2012 Jonny Strömberg <[email protected]> http://jonnystromberg.com */ ;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module._resolving && !module.exports) { var mod = {}; mod.exports = {}; mod.client = mod.component = true; module._resolving = true; module.call(this, mod.exports, require.relative(resolved), mod); delete module._resolving; module.exports = mod.exports; } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("component-classes/index.js", function(exports, require, module){ /** * Module dependencies. */ var index = require('indexof'); /** * Whitespace regexp. */ var re = /\s+/; /** * toString reference. */ var toString = Object.prototype.toString; /** * Wrap `el` in a `ClassList`. * * @param {Element} el * @return {ClassList} * @api public */ module.exports = function(el){ return new ClassList(el); }; /** * Initialize a new ClassList for `el`. * * @param {Element} el * @api private */ function ClassList(el) { if (!el) throw new Error('A DOM element reference is required'); this.el = el; this.list = el.classList; } /** * Add class `name` if not already present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.add = function(name){ // classList if (this.list) { this.list.add(name); return this; } // fallback var arr = this.array(); var i = index(arr, name); if (!~i) arr.push(name); this.el.className = arr.join(' '); return this; }; /** * Remove class `name` when present, or * pass a regular expression to remove * any which match. * * @param {String|RegExp} name * @return {ClassList} * @api public */ ClassList.prototype.remove = function(name){ if ('[object RegExp]' == toString.call(name)) { return this.removeMatching(name); } // classList if (this.list) { this.list.remove(name); return this; } // fallback var arr = this.array(); var i = index(arr, name); if (~i) arr.splice(i, 1); this.el.className = arr.join(' '); return this; }; /** * Remove all classes matching `re`. * * @param {RegExp} re * @return {ClassList} * @api private */ ClassList.prototype.removeMatching = function(re){ var arr = this.array(); for (var i = 0; i < arr.length; i++) { if (re.test(arr[i])) { this.remove(arr[i]); } } return this; }; /** * Toggle class `name`, can force state via `force`. * * For browsers that support classList, but do not support `force` yet, * the mistake will be detected and corrected. * * @param {String} name * @param {Boolean} force * @return {ClassList} * @api public */ ClassList.prototype.toggle = function(name, force){ // classList if (this.list) { if ("undefined" !== typeof force) { if (force !== this.list.toggle(name, force)) { this.list.toggle(name); // toggle again to correct } } else { this.list.toggle(name); } return this; } // fallback if ("undefined" !== typeof force) { if (!force) { this.remove(name); } else { this.add(name); } } else { if (this.has(name)) { this.remove(name); } else { this.add(name); } } return this; }; /** * Return an array of classes. * * @return {Array} * @api public */ ClassList.prototype.array = function(){ var str = this.el.className.replace(/^\s+|\s+$/g, ''); var arr = str.split(re); if ('' === arr[0]) arr.shift(); return arr; }; /** * Check if class `name` is present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.has = ClassList.prototype.contains = function(name){ return this.list ? this.list.contains(name) : !! ~index(this.array(), name); }; }); require.register("segmentio-extend/index.js", function(exports, require, module){ module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }); require.register("component-indexof/index.js", function(exports, require, module){ module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }); require.register("component-event/index.js", function(exports, require, module){ var bind = window.addEventListener ? 'addEventListener' : 'attachEvent', unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent', prefix = bind !== 'addEventListener' ? 'on' : ''; /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ el[bind](prefix + type, fn, capture || false); return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ el[unbind](prefix + type, fn, capture || false); return fn; }; }); require.register("javve-to-array/index.js", function(exports, require, module){ /** * Convert an array-like object into an `Array`. * If `collection` is already an `Array`, then will return a clone of `collection`. * * @param {Array | Mixed} collection An `Array` or array-like object to convert e.g. `arguments` or `NodeList` * @return {Array} Naive conversion of `collection` to a new `Array`. * @api public */ module.exports = function toArray(collection) { if (typeof collection === 'undefined') return [] if (collection === null) return [null] if (collection === window) return [window] if (typeof collection === 'string') return [collection] if (collection instanceof Array) return collection if (typeof collection.length != 'number') return [collection] if (typeof collection === 'function') return [collection] var arr = [] for (var i = 0; i < collection.length; i++) { if (Object.prototype.hasOwnProperty.call(collection, i) || i in collection) { arr.push(collection[i]) } } if (!arr.length) return [] return arr } }); require.register("javve-events/index.js", function(exports, require, module){ var events = require('event'), toArray = require('to-array'); /** * Bind `el` event `type` to `fn`. * * @param {Element} el, NodeList, HTMLCollection or Array * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.bind = function(el, type, fn, capture){ el = toArray(el); for ( var i = 0; i < el.length; i++ ) { events.bind(el[i], type, fn, capture); } }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el, NodeList, HTMLCollection or Array * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.unbind = function(el, type, fn, capture){ el = toArray(el); for ( var i = 0; i < el.length; i++ ) { events.unbind(el[i], type, fn, capture); } }; }); require.register("javve-get-by-class/index.js", function(exports, require, module){ /** * Find all elements with class `className` inside `container`. * Use `single = true` to increase performance in older browsers * when only one element is needed. * * @param {String} className * @param {Element} container * @param {Boolean} single * @api public */ module.exports = (function() { if (document.getElementsByClassName) { return function(container, className, single) { if (single) { return container.getElementsByClassName(className)[0]; } else { return container.getElementsByClassName(className); } }; } else if (document.querySelector) { return function(container, className, single) { className = '.' + className; if (single) { return container.querySelector(className); } else { return container.querySelectorAll(className); } }; } else { return function(container, className, single) { var classElements = [], tag = '*'; if (container == null) { container = document; } var els = container.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)"); for (var i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { if (single) { return els[i]; } else { classElements[j] = els[i]; j++; } } } return classElements; }; } })(); }); require.register("javve-get-attribute/index.js", function(exports, require, module){ /** * Return the value for `attr` at `element`. * * @param {Element} el * @param {String} attr * @api public */ module.exports = function(el, attr) { var result = (el.getAttribute && el.getAttribute(attr)) || null; if( !result ) { var attrs = el.attributes; var length = attrs.length; for(var i = 0; i < length; i++) { if (attr[i] !== undefined) { if(attr[i].nodeName === attr) { result = attr[i].nodeValue; } } } } return result; } }); require.register("javve-natural-sort/index.js", function(exports, require, module){ /* * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license * Author: Jim Palmer (based on chunking idea from Dave Koelle) */ module.exports = function(a, b, options) { var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi, sre = /(^[ ]*|[ ]*$)/g, dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, hre = /^0x[0-9a-f]+$/i, ore = /^0/, options = options || {}, i = function(s) { return options.insensitive && (''+s).toLowerCase() || ''+s }, // convert all to strings strip whitespace x = i(a).replace(sre, '') || '', y = i(b).replace(sre, '') || '', // chunk/tokenize xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), // numeric, hex or date detection xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)), yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null, oFxNcL, oFyNcL, mult = options.desc ? -1 : 1; // first try and sort Hex codes or Dates if (yD) if ( xD < yD ) return -1 * mult; else if ( xD > yD ) return 1 * mult; // natural sorting through split numeric strings and default strings for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { // find floats not starting with '0', string or 0 if not defined (Clint Priest) oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' else if (typeof oFxNcL !== typeof oFyNcL) { oFxNcL += ''; oFyNcL += ''; } if (oFxNcL < oFyNcL) return -1 * mult; if (oFxNcL > oFyNcL) return 1 * mult; } return 0; }; /* var defaultSort = getSortFunction(); module.exports = function(a, b, options) { if (arguments.length == 1) { options = a; return getSortFunction(options); } else { return defaultSort(a,b); } } */ }); require.register("javve-to-string/index.js", function(exports, require, module){ module.exports = function(s) { s = (s === undefined) ? "" : s; s = (s === null) ? "" : s; s = s.toString(); return s; }; }); require.register("component-type/index.js", function(exports, require, module){ /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object Error]': return 'error'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val !== val) return 'nan'; if (val && val.nodeType === 1) return 'element'; return typeof val.valueOf(); }; }); require.register("list.js/index.js", function(exports, require, module){ /* ListJS with beta 1.0.0 By Jonny Strömberg (www.jonnystromberg.com, www.listjs.com) */ (function( window, undefined ) { "use strict"; var document = window.document, getByClass = require('get-by-class'), extend = require('extend'), indexOf = require('indexof'); var List = function(id, options, values) { var self = this, init, Item = require('./src/item')(self), addAsync = require('./src/add-async')(self), parse = require('./src/parse')(self); init = { start: function() { self.listClass = "list"; self.searchClass = "search"; self.sortClass = "sort"; self.page = 200; self.i = 1; self.items = []; self.visibleItems = []; self.matchingItems = []; self.searched = false; self.filtered = false; self.handlers = { 'updated': [] }; self.plugins = {}; self.helpers = { getByClass: getByClass, extend: extend, indexOf: indexOf }; extend(self, options); self.listContainer = (typeof(id) === 'string') ? document.getElementById(id) : id; if (!self.listContainer) { return; } self.list = getByClass(self.listContainer, self.listClass, true); self.templater = require('./src/templater')(self); self.search = require('./src/search')(self); self.filter = require('./src/filter')(self); self.sort = require('./src/sort')(self); this.items(); self.update(); this.plugins(); }, items: function() { parse(self.list); if (values !== undefined) { self.add(values); } }, plugins: function() { for (var i = 0; i < self.plugins.length; i++) { var plugin = self.plugins[i]; self[plugin.name] = plugin; plugin.init(self); } } }; /* * Add object to list */ this.add = function(values, callback) { if (callback) { addAsync(values, callback); return; } var added = [], notCreate = false; if (values[0] === undefined){ values = [values]; } for (var i = 0, il = values.length; i < il; i++) { var item = null; if (values[i] instanceof Item) { item = values[i]; item.reload(); } else { notCreate = (self.items.length > self.page) ? true : false; item = new Item(values[i], undefined, notCreate); } self.items.push(item); added.push(item); } self.update(); return added; }; this.show = function(i, page) { this.i = i; this.page = page; self.update(); return self; }; /* Removes object from list. * Loops through the list and removes objects where * property "valuename" === value */ this.remove = function(valueName, value, options) { var found = 0; for (var i = 0, il = self.items.length; i < il; i++) { if (self.items[i].values()[valueName] == value) { self.templater.remove(self.items[i], options); self.items.splice(i,1); il--; i--; found++; } } self.update(); return found; }; /* Gets the objects in the list which * property "valueName" === value */ this.get = function(valueName, value) { var matchedItems = []; for (var i = 0, il = self.items.length; i < il; i++) { var item = self.items[i]; if (item.values()[valueName] == value) { matchedItems.push(item); } } return matchedItems; }; /* * Get size of the list */ this.size = function() { return self.items.length; }; /* * Removes all items from the list */ this.clear = function() { self.templater.clear(); self.items = []; return self; }; this.on = function(event, callback) { self.handlers[event].push(callback); return self; }; this.off = function(event, callback) { var e = self.handlers[event]; var index = indexOf(e, callback); if (index > -1) { e.splice(index, 1); } return self; }; this.trigger = function(event) { var i = self.handlers[event].length; while(i--) { self.handlers[event][i](self); } return self; }; this.reset = { filter: function() { var is = self.items, il = is.length; while (il--) { is[il].filtered = false; } return self; }, search: function() { var is = self.items, il = is.length; while (il--) { is[il].found = false; } return self; } }; this.update = function() { var is = self.items, il = is.length; self.visibleItems = []; self.matchingItems = []; self.templater.clear(); for (var i = 0; i < il; i++) { if (is[i].matching() && ((self.matchingItems.length+1) >= self.i && self.visibleItems.length < self.page)) { is[i].show(); self.visibleItems.push(is[i]); self.matchingItems.push(is[i]); } else if (is[i].matching()) { self.matchingItems.push(is[i]); is[i].hide(); } else { is[i].hide(); } } self.trigger('updated'); return self; }; init.start(); }; module.exports = List; })(window); }); require.register("list.js/src/search.js", function(exports, require, module){ var events = require('events'), getByClass = require('get-by-class'), toString = require('to-string'); module.exports = function(list) { var item, text, columns, searchString, customSearch; var prepare = { resetList: function() { list.i = 1; list.templater.clear(); customSearch = undefined; }, setOptions: function(args) { if (args.length == 2 && args[1] instanceof Array) { columns = args[1]; } else if (args.length == 2 && typeof(args[1]) == "function") { customSearch = args[1]; } else if (args.length == 3) { columns = args[1]; customSearch = args[2]; } }, setColumns: function() { columns = (columns === undefined) ? prepare.toArray(list.items[0].values()) : columns; }, setSearchString: function(s) { s = toString(s).toLowerCase(); s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // Escape regular expression characters searchString = s; }, toArray: function(values) { var tmpColumn = []; for (var name in values) { tmpColumn.push(name); } return tmpColumn; } }; var search = { list: function() { for (var k = 0, kl = list.items.length; k < kl; k++) { search.item(list.items[k]); } }, item: function(item) { item.found = false; for (var j = 0, jl = columns.length; j < jl; j++) { if (search.values(item.values(), columns[j])) { item.found = true; return; } } }, values: function(values, column) { if (values.hasOwnProperty(column)) { text = toString(values[column]).toLowerCase(); if ((searchString !== "") && (text.search(searchString) > -1)) { return true; } } return false; }, reset: function() { list.reset.search(); list.searched = false; } }; var searchMethod = function(str) { list.trigger('searchStart'); prepare.resetList(); prepare.setSearchString(str); prepare.setOptions(arguments); // str, cols|searchFunction, searchFunction prepare.setColumns(); if (searchString === "" ) { search.reset(); } else { list.searched = true; if (customSearch) { customSearch(searchString, columns); } else { search.list(); } } list.update(); list.trigger('searchComplete'); return list.visibleItems; }; list.handlers.searchStart = list.handlers.searchStart || []; list.handlers.searchComplete = list.handlers.searchComplete || []; events.bind(getByClass(list.listContainer, list.searchClass), 'keyup', function(e) { var target = e.target || e.srcElement; // IE have srcElement searchMethod(target.value); }); list.helpers.toString = toString; return searchMethod; }; }); require.register("list.js/src/sort.js", function(exports, require, module){ var naturalSort = require('natural-sort'), classes = require('classes'), events = require('events'), getByClass = require('get-by-class'), getAttribute = require('get-attribute'); module.exports = function(list) { list.sortFunction = list.sortFunction || function(itemA, itemB, options) { options.desc = options.order == "desc" ? true : false; // Natural sort uses this format return naturalSort(itemA.values()[options.valueName], itemB.values()[options.valueName], options); }; var buttons = { els: undefined, clear: function() { for (var i = 0, il = buttons.els.length; i < il; i++) { classes(buttons.els[i]).remove('asc'); classes(buttons.els[i]).remove('desc'); } }, getOrder: function(btn) { var predefinedOrder = getAttribute(btn, 'data-order'); if (predefinedOrder == "asc" || predefinedOrder == "desc") { return predefinedOrder; } else if (classes(btn).has('desc')) { return "asc"; } else if (classes(btn).has('asc')) { return "desc"; } else { return "asc"; } }, getInSensitive: function(btn, options) { var insensitive = getAttribute(btn, 'data-insensitive'); if (insensitive === "true") { options.insensitive = true; } else { options.insensitive = false; } }, setOrder: function(options) { for (var i = 0, il = buttons.els.length; i < il; i++) { var btn = buttons.els[i]; if (getAttribute(btn, 'data-sort') !== options.valueName) { continue; } var predefinedOrder = getAttribute(btn, 'data-order'); if (predefinedOrder == "asc" || predefinedOrder == "desc") { if (predefinedOrder == options.order) { classes(btn).add(options.order); } } else { classes(btn).add(options.order); } } } }; var sort = function() { list.trigger('sortStart'); options = {}; var target = arguments[0].currentTarget || arguments[0].srcElement || undefined; if (target) { options.valueName = getAttribute(target, 'data-sort'); buttons.getInSensitive(target, options); options.order = buttons.getOrder(target); } else { options = arguments[1] || options; options.valueName = arguments[0]; options.order = options.order || "asc"; options.insensitive = (typeof options.insensitive == "undefined") ? true : options.insensitive; } buttons.clear(); buttons.setOrder(options); options.sortFunction = options.sortFunction || list.sortFunction; list.items.sort(function(a, b) { return options.sortFunction(a, b, options); }); list.update(); list.trigger('sortComplete'); }; // Add handlers list.handlers.sortStart = list.handlers.sortStart || []; list.handlers.sortComplete = list.handlers.sortComplete || []; buttons.els = getByClass(list.listContainer, list.sortClass); events.bind(buttons.els, 'click', sort); list.on('searchStart', buttons.clear); list.on('filterStart', buttons.clear); // Helpers list.helpers.classes = classes; list.helpers.naturalSort = naturalSort; list.helpers.events = events; list.helpers.getAttribute = getAttribute; return sort; }; }); require.register("list.js/src/item.js", function(exports, require, module){ module.exports = function(list) { return function(initValues, element, notCreate) { var item = this; this._values = {}; this.found = false; // Show if list.searched == true and this.found == true this.filtered = false;// Show if list.filtered == true and this.filtered == true var init = function(initValues, element, notCreate) { if (element === undefined) { if (notCreate) { item.values(initValues, notCreate); } else { item.values(initValues); } } else { item.elm = element; var values = list.templater.get(item, initValues); item.values(values); } }; this.values = function(newValues, notCreate) { if (newValues !== undefined) { for(var name in newValues) { item._values[name] = newValues[name]; } if (notCreate !== true) { list.templater.set(item, item.values()); } } else { return item._values; } }; this.show = function() { list.templater.show(item); }; this.hide = function() { list.templater.hide(item); }; this.matching = function() { return ( (list.filtered && list.searched && item.found && item.filtered) || (list.filtered && !list.searched && item.filtered) || (!list.filtered && list.searched && item.found) || (!list.filtered && !list.searched) ); }; this.visible = function() { return (item.elm.parentNode == list.list) ? true : false; }; init(initValues, element, notCreate); }; }; }); require.register("list.js/src/templater.js", function(exports, require, module){ var getByClass = require('get-by-class'); var Templater = function(list) { var itemSource = getItemSource(list.item), templater = this; function getItemSource(item) { if (item === undefined) { var nodes = list.list.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { return nodes[i]; } } return null; } else if (item.indexOf("<") !== -1) { // Try create html element of list, do not work for tables!! var div = document.createElement('div'); div.innerHTML = item; return div.firstChild; } else { return document.getElementById(list.item); } } /* Get values from element */ this.get = function(item, valueNames) { templater.create(item); var values = {}; for(var i = 0, il = valueNames.length; i < il; i++) { var elm = getByClass(item.elm, valueNames[i], true); values[valueNames[i]] = elm ? elm.innerHTML : ""; } return values; }; /* Sets values at element */ this.set = function(item, values) { if (!templater.create(item)) { for(var v in values) { if (values.hasOwnProperty(v)) { // TODO speed up if possible var elm = getByClass(item.elm, v, true); if (elm) { /* src attribute for image tag & text for other tags */ if (elm.tagName === "IMG" && values[v] !== "") { elm.src = values[v]; } else { elm.innerHTML = values[v]; } } } } } }; this.create = function(item) { if (item.elm !== undefined) { return false; } /* If item source does not exists, use the first item in list as source for new items */ var newItem = itemSource.cloneNode(true); newItem.removeAttribute('id'); item.elm = newItem; templater.set(item, item.values()); return true; }; this.remove = function(item) { list.list.removeChild(item.elm); }; this.show = function(item) { templater.create(item); list.list.appendChild(item.elm); }; this.hide = function(item) { if (item.elm !== undefined && item.elm.parentNode === list.list) { list.list.removeChild(item.elm); } }; this.clear = function() { /* .innerHTML = ''; fucks up IE */ if (list.list.hasChildNodes()) { while (list.list.childNodes.length >= 1) { list.list.removeChild(list.list.firstChild); } } }; }; module.exports = function(list) { return new Templater(list); }; }); require.register("list.js/src/filter.js", function(exports, require, module){ module.exports = function(list) { // Add handlers list.handlers.filterStart = list.handlers.filterStart || []; list.handlers.filterComplete = list.handlers.filterComplete || []; return function(filterFunction) { list.trigger('filterStart'); list.i = 1; // Reset paging list.reset.filter(); if (filterFunction === undefined) { list.filtered = false; } else { list.filtered = true; var is = list.items; for (var i = 0, il = is.length; i < il; i++) { var item = is[i]; if (filterFunction(item)) { item.filtered = true; } else { item.filtered = false; } } } list.update(); list.trigger('filterComplete'); return list.visibleItems; }; }; }); require.register("list.js/src/add-async.js", function(exports, require, module){ module.exports = function(list) { return function(values, callback, items) { var valuesToAdd = values.splice(0, 100); items = items || []; items = items.concat(list.add(valuesToAdd)); if (values.length > 0) { setTimeout(function() { addAsync(values, callback, items); }, 10); } else { list.update(); callback(items); } }; }; }); require.register("list.js/src/parse.js", function(exports, require, module){ module.exports = function(list) { var Item = require('./item')(list); var getChildren = function(parent) { var nodes = parent.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { items.push(nodes[i]); } } return items; }; var parse = function(itemElements, valueNames) { for (var i = 0, il = itemElements.length; i < il; i++) { list.items.push(new Item(valueNames, itemElements[i])); } }; var parseAsync = function(itemElements, valueNames) { var itemsToIndex = itemElements.splice(0, 100); // TODO: If < 100 items, what happens in IE etc? parse(itemsToIndex, valueNames); if (itemElements.length > 0) { setTimeout(function() { init.items.indexAsync(itemElements, valueNames); }, 10); } else { list.update(); // TODO: Add indexed callback } }; return function() { var itemsToIndex = getChildren(list.list), valueNames = list.valueNames; if (list.indexAsync) { parseAsync(itemsToIndex, valueNames); } else { parse(itemsToIndex, valueNames); } }; }; }); require.alias("component-classes/index.js", "list.js/deps/classes/index.js"); require.alias("component-classes/index.js", "classes/index.js"); require.alias("component-indexof/index.js", "component-classes/deps/indexof/index.js"); require.alias("segmentio-extend/index.js", "list.js/deps/extend/index.js"); require.alias("segmentio-extend/index.js", "extend/index.js"); require.alias("component-indexof/index.js", "list.js/deps/indexof/index.js"); require.alias("component-indexof/index.js", "indexof/index.js"); require.alias("javve-events/index.js", "list.js/deps/events/index.js"); require.alias("javve-events/index.js", "events/index.js"); require.alias("component-event/index.js", "javve-events/deps/event/index.js"); require.alias("javve-to-array/index.js", "javve-events/deps/to-array/index.js"); require.alias("javve-get-by-class/index.js", "list.js/deps/get-by-class/index.js"); require.alias("javve-get-by-class/index.js", "get-by-class/index.js"); require.alias("javve-get-attribute/index.js", "list.js/deps/get-attribute/index.js"); require.alias("javve-get-attribute/index.js", "get-attribute/index.js"); require.alias("javve-natural-sort/index.js", "list.js/deps/natural-sort/index.js"); require.alias("javve-natural-sort/index.js", "natural-sort/index.js"); require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); require.alias("javve-to-string/index.js", "to-string/index.js"); require.alias("javve-to-string/index.js", "javve-to-string/index.js"); require.alias("component-type/index.js", "list.js/deps/type/index.js"); require.alias("component-type/index.js", "type/index.js"); if (typeof exports == "object") { module.exports = require("list.js"); } else if (typeof define == "function" && define.amd) { define(function(){ return require("list.js"); }); } else { this["List"] = require("list.js"); }})();
studentenportal/web
apps/front/static/js/list.js
JavaScript
agpl-3.0
40,148
app.controller('LeadStatusEditCtrl', ['$scope', 'Auth', 'Leadstatus', function ($scope, Auth, Leadstatus) { $("ul.page-sidebar-menu li").removeClass("active"); $("#id_LeadStatus").addClass("active"); $scope.isSignedIn = false; $scope.immediateFailed = false; $scope.nbLoads = 0; $scope.isLoading = false; $scope.isSelectedAll = false; $scope.nbrSelected = 0; $scope.selectStatus = function (status) { status.isSelected = !status.isSelected; if (status.isSelected) $scope.nbrSelected++; else $scope.nbrSelected--; }; $scope.$watch('isSelectedAll', function (newValue, oldValue) { if (newValue) $scope.nbrSelected = $scope.leadstatuses.length; else $scope.nbrSelected = 0; angular.forEach($scope.leadstatuses, function (value, key) { $scope.leadstatuses[key].isSelected = newValue; }); }); $scope.deleteSelected = function () { angular.forEach($scope.leadstatuses, function (value, index) { if (value.isSelected) { $scope.deletleadstatus(value); } }); }; $scope.inProcess = function (varBool, message) { if (varBool) { $scope.nbLoads += 1; if ($scope.nbLoads == 1) { $scope.isLoading = true; } ; } else { $scope.nbLoads -= 1; if ($scope.nbLoads == 0) { $scope.isLoading = false; } ; } ; }; $scope.apply = function () { if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') { $scope.$apply(); } return false; }; // What to do after authentication $scope.runTheProcess = function () { Leadstatus.list($scope, {}); ga('send', 'pageview', '/admin/lead_status'); }; // We need to call this to refresh token when user credentials are invalid $scope.refreshToken = function () { Auth.refreshToken(); }; $scope.addLeadsStatusModal = function () { $("#addLeadsStatusModal").modal('show') }; $scope.saveLeadStatus = function (lead) { var params = { 'status': lead.status }; Leadstatus.insert($scope, params); $('#addLeadsStatusModal').modal('hide'); $scope.lead.status = ''; }; $scope.editleadstatus = function (leadStatus) { $scope.leadstat = $scope.leadstat || {}; $scope.leadstat.status = leadStatus.status; $scope.leadstat.id = leadStatus.id; $('#EditLeadStatus').modal('show'); }; $scope.updateLeadstatus = function (stat) { var params = { 'id': $scope.leadstat.id, 'status': stat.status }; Leadstatus.update($scope, params) $('#EditLeadStatus').modal('hide'); }; //HKA 22.12.2013 Delete Lead status $scope.deletleadstatus = function (leadstat) { var params = {'entityKey': leadstat.entityKey}; Leadstatus.delete($scope, params); }; $scope.listleadstatus = function () { Leadstatus.list($scope, {}); }; Auth.init($scope); }]);
ioGrow/iogrowCRM
static/app/scripts/controllers/admin/LeadStatusEditController.js
JavaScript
agpl-3.0
3,220
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import SPELLS from 'common/SPELLS'; import { formatThousands } from 'common/format'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; import Statistic from 'parser/ui/Statistic'; import BoringSpellValueText from 'parser/ui/BoringSpellValueText'; import ItemDamageDone from 'parser/ui/ItemDamageDone'; import DemoPets from '../pets/DemoPets'; const BONUS_DAMAGE_PER_PET = 0.04; const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement const debug = false; /* Sacrificed Souls: Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned. */ class SacrificedSouls extends Analyzer { get totalBonusDamage() { return this._shadowBoltDamage + this._demonboltDamage; } static dependencies = { demoPets: DemoPets, }; _shadowBoltDamage = 0; _demonboltDamage = 0; _queue = []; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage); } // essentially same snapshotting mechanic as in Destruction's Eradication handleCast(event) { const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET; this._queue.push({ timestamp: event.timestamp, spellId: event.ability.guid, targetID: event.targetID, targetInstance: event.targetInstance, bonus, }); debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue))); } handleDamage(event) { // filter out old casts if there are any this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME)); const castIndex = this._queue .findIndex(cast => cast.targetID === event.targetID && cast.targetInstance === event.targetInstance && cast.spellId === event.ability.guid); if (castIndex === -1) { debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event); return; } debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex]))); const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus); this._queue.splice(castIndex, 1); if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) { this._shadowBoltDamage += bonusDamage; } else { this._demonboltDamage += bonusDamage; } } statistic() { const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id); return ( <Statistic category={STATISTIC_CATEGORY.TALENTS} size="flexible" tooltip={( <> {formatThousands(this.totalBonusDamage)} bonus damage<br /> Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br /> Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)}) {hasPS && ( <> <br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong. </> )} </> )} > <BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}> <ItemDamageDone amount={this.totalBonusDamage} /> </BoringSpellValueText> </Statistic> ); } } export default SacrificedSouls;
yajinni/WoWAnalyzer
analysis/warlockdemonology/src/modules/talents/SacrificedSouls.js
JavaScript
agpl-3.0
4,211
import * as Actions from './actions' import * as Controls from './controls' import Editor from './editor' import Panel from './panel' export {Actions} export {Editor} export {Panel} export {Controls}
ChuckDaniels87/pydio-core
core/src/plugins/meta.exif/res/js/index.js
JavaScript
agpl-3.0
201
////////////////////////////////////////////////////////////// // File of helper functions for primitives and world. var helpers = {}; (function() { var format = function(formatStr, args, functionName) { var throwFormatError = function() { functionName = functionName || '#<function>'; var matches = formatStr.match(new RegExp('~[sSaA]', 'g')); var expectedNumberOfArgs = matches == null ? 0 : matches.length; var errorStrBuffer = [functionName + ': format string requires ' + expectedNumberOfArgs + ' arguments, but given ' + args.length + '; arguments were:', types.toWrittenString(formatStr)]; for (var i = 0; i < args.length; i++) { errorStrBuffer.push( types.toWrittenString(args[i]) ); } raise( types.incompleteExn(types.exnFailContract, errorStrBuffer.join(' '), []) ); } var pattern = new RegExp("~[sSaAn%~]", "g"); var buffer = args.slice(0);; function f(s) { if (s == "~~") { return "~"; } else if (s == '~n' || s == '~%') { return "\n"; } else if (s == '~s' || s == "~S") { if (buffer.length == 0) { throwFormatError(); } return types.toWrittenString(buffer.shift()); } else if (s == '~a' || s == "~A") { if (buffer.length == 0) { throwFormatError(); } return types.toDisplayedString(buffer.shift()); } else { throw types.internalError('format: string.replace matched invalid regexp', false); } } var result = formatStr.replace(pattern, f); if (buffer.length > 0) { throwFormatError(); } return result; }; // forEachK: CPS( array CPS(array -> void) (error -> void) -> void ) // Iterates through an array and applies f to each element using CPS // If an error is thrown, it catches the error and calls f_error on it var forEachK = function(a, f, f_error, k) { var forEachHelp = function(i) { if( i >= a.length ) { if (k) { k(); } return; } try { f(a[i], function() { forEachHelp(i+1); }); } catch (e) { f_error(e); } }; forEachHelp(0); }; // reportError: (or exception string) -> void // Reports an error to the user, either at the console // if the console exists, or as alerts otherwise. var reportError = function(e) { var reporter; if (typeof(console) != 'undefined' && typeof(console.log) != 'undefined') { reporter = (function(x) { console.log(x); }); } else { reporter = (function(x) { alert(x); }); } if (typeof e == 'string') { reporter(e); } else if ( types.isSchemeError(e) ) { if ( types.isExn(e.val) ) { reporter( ''+types.exnMessage(e.val) ); } else { reporter(e.val); } } else if (e.message) { reporter(e.message); } else { reporter(e.toString()); } // if (plt.Kernel.lastLoc) { // var loc = plt.Kernel.lastLoc; // if (typeof(loc) === 'string') { // reporter("Error was raised around " + loc); // } else if (typeof(loc) !== 'undefined' && // typeof(loc.line) !== 'undefined') { // reporter("Error was raised around: " // + plt.Kernel.locToString(loc)); // } // } }; var raise = function(v) { throw types.schemeError(v); }; var procArityContains = function(n) { return function(proc) { var singleCase = function(aCase) { if ( aCase instanceof types.ContinuationClosureValue ) { return true; } return (aCase.numParams == n || (aCase.isRest && aCase.numParams <= n)); }; var cases = []; if ( proc instanceof types.ContinuationClosureValue || proc instanceof types.ClosureValue || proc instanceof types.PrimProc ) { return singleCase(proc); } else if (proc instanceof types.CasePrimitive) { cases = proc.cases; } else if (proc instanceof types.CaseLambdaValue) { cases = proc.closures; } for (var i = 0; i < cases.length; i++) { if ( singleCase(cases[i]) ) return true; } return false; } }; var throwUncoloredCheckError = function(aState, details, pos, args){ var errorFormatStr; if (args && args.length > 1) { var errorFormatStrBuffer = ['~a: expects type ~a as ~a arguments, but given: ~s; other arguments were:']; for (var i = 0; i < args.length; i++) { if ( i != pos-1 ) { errorFormatStrBuffer.push( types.toWrittenString(args[i]) ); } } errorFormatStr = errorFormatStrBuffer.join(' '); raise( types.incompleteExn(types.exnFailContract, helpers.format(errorFormatStr, [details.functionName, details.typeName, details.ordinalPosition, details.actualValue]), []) ); } else { errorFormatStr = "~a: expects argument of type ~a, but given: ~s"; raise( types.incompleteExn(types.exnFailContract, helpers.format(errorFormatStr, [details.functionName, details.typeName , details.actualValue]), [])); } }; var throwColoredCheckError = function(aState, details, pos, args){ var positionStack = state.captureCurrentContinuationMarks(aState).ref('moby-application-position-key'); var locationList = positionStack[positionStack.length - 1]; //locations -> array var getArgColoredParts = function(locations) { var coloredParts = []; var locs = locations; var i; //getting the actual arguments from args var actualArgs = []; for(i = 0; i < args.length; i++) { if((! (state.isState(args[i]))) && (!((args[i].name !== undefined) && args[i].name === ""))) { actualArgs.push(args[i]); } } window.wtf = args[2]; for(i = 0; i < actualArgs.length; i++){ if(! (locs.isEmpty())){ if(i != (pos -1)) { //coloredParts.push(new types.ColoredPart(types.toWrittenString(actualArgs[i])+(i < actualArgs.length -1 ? " " : ""), locs.first()));\ coloredParts.push(new types.ColoredPart(types.toWrittenString(actualArgs[i])+" ", locs.first())); } locs = locs.rest(); } } if(coloredParts.length > 0){ //removing the last space var lastEltText = coloredParts[coloredParts.length-1].text; lastEltText = lastEltText.substring(0, lastEltText.length - 1); coloredParts[coloredParts.length - 1] = new types.ColoredPart(lastEltText, coloredParts[coloredParts.length-1].location); } return coloredParts; } // listRef for locationList. var getLocation = function(pos) { var locs = locationList; var i; for(i = 0; i < pos; i++){ locs = locs.rest(); } return locs.first(); } var typeName = details.typeName+''; var fL = typeName.substring(0,1); //first letter of type name if(args) { var argColoredParts = getArgColoredParts(locationList.rest()); if(argColoredParts.length > 0){ raise( types.incompleteExn(types.exnFailContract, new types.Message([ new types.ColoredPart(details.functionName, locationList.first()), ": expects ", ((fL === "a" || fL === "e" || fL === "i" || fL === "o" || fL === "u") ? "an " : "a "), typeName, " as ", details.ordinalPosition, " argument, but given: ", new types.ColoredPart(types.toWrittenString(details.actualValue), getLocation(pos)), "; other arguments were: ", new types.GradientPart(argColoredParts) ]), []) ); } } raise( types.incompleteExn(types.exnFailContract, new types.Message([ new types.ColoredPart(details.functionName, locationList.first()), ": expects ", ((fL === "a" || fL === "e" || fL === "i" || fL === "o" || fL === "u") ? "an " : "a "), typeName, " as ", details.ordinalPosition, " argument, but given: ", new types.ColoredPart(types.toWrittenString(details.actualValue), getLocation(pos)) ]), []) ); }; var throwCheckError = function(aState, details, pos, args) { if(aState instanceof state.State){ //if it's defined and a State, can inspect position stack var positionStack = state.captureCurrentContinuationMarks(aState).ref('moby-application-position-key'); //if the positionStack at the correct position is defined, we can throw a colored error if (positionStack[positionStack.length - 1] !== undefined) { throwColoredCheckError(aState, details, pos, args); } } //otherwise, throw an uncolored error throwUncoloredCheckError(aState, details, pos, args); }; var check = function(aState, x, f, functionName, typeName, position, args) { if ( !f(x) ) { throwCheckError(aState, { functionName: functionName, typeName: typeName, ordinalPosition: helpers.ordinalize(position), actualValue: x }, position, args); } }; var checkVarArity = function(aState, x, f, functionName, typeName, position, args) { //check to ensure last thing is an array if(args.length > 0 && (args[args.length - 1] instanceof Array)) { var flattenedArgs = []; var i; for(i = 0; i < (args.length - 1); i++) { flattenedArgs.push(args[i]); } //the angry variable names are because flattenedArgs = flattenedArgs.concat(args[args.length - 1]) doesn't work var wtf1 = flattenedArgs; var wtf2 = args[args.length -1]; var passOn = wtf1.concat(wtf2); check(aState, x, f, functionName, typeName, position, passOn); } else { check(aState, x, f, functionName, typeName, position, args); } }; var isList = function(x) { var tortoise, hare; tortoise = hare = x; if (hare === types.EMPTY) { return true; } while (true) { if (!(types.isPair(hare))) { return false; } if (types.isPair(tortoise)) { // optimization to get amortized linear time isList. if (tortoise._isList === true) { return true; } tortoise = tortoise.rest(); } hare = hare.rest(); if (types.isPair(hare)) { if (hare._isList) { tortoise._isList = true; return true; } hare = hare.rest(); if (types.isPair(hare) && hare._isList) { tortoise._isList = true; return true; } } if (hare === types.EMPTY) { // optimization to get amortized linear time isList. tortoise._isList = true; return true; } if (tortoise === hare) { return false; } } }; var isListOf = function(x, f) { if (! isList(x)) { return false; } while (types.isPair(x)) { if (! f(x.first())) { return false; } x = x.rest(); } return (x === types.EMPTY); }; var checkListOf = function(aState, lst, f, functionName, typeName, position, args) { if ( !isListOf(lst, f) ) { helpers.throwCheckError(aState, {functionName: functionName, typeName: 'list of ' + typeName, ordinalPosition: helpers.ordinalize(position), actualValue: lst}, position, args); } }; // // remove: array any -> array // // removes the first instance of v in a // // or returns a copy of a if v does not exist // var remove = function(a, v) { // for (var i = 0; i < a.length; i++) { // if (a[i] === v) { // return a.slice(0, i).concat( a.slice(i+1, a.length) ); // } // } // return a.slice(0); // }; // map: array (any -> any) -> array // applies f to each element of a and returns the result // as a new array var map = function(f, a) { var b = new Array(a.length); for (var i = 0; i < a.length; i++) { b[i] = f(a[i]); } return b; }; var schemeListToArray = function(lst) { var result = []; while ( !lst.isEmpty() ) { result.push(lst.first()); lst = lst.rest(); } return result; } // deepListToArray: any -> any // Converts list structure to array structure. var deepListToArray = function(x) { var thing = x; if (thing === types.EMPTY) { return []; } else if (types.isPair(thing)) { var result = []; while (!thing.isEmpty()) { result.push(deepListToArray(thing.first())); thing = thing.rest(); } return result; } else { return x; } } var flattenSchemeListToArray = function(x) { if ( !isList(x) ) { return [x]; } var ret = []; while ( !x.isEmpty() ) { ret = ret.concat( flattenSchemeListToArray(x.first()) ); x = x.rest(); } return ret; }; // assocListToHash: (listof (list X Y)) -> (hashof X Y) var assocListToHash = function(lst) { var result = {}; while ( !lst.isEmpty() ) { var key = lst.first().first(); var val = lst.first().rest().first(); result[key] = val; lst = lst.rest(); } return result; }; var ordinalize = function(n) { // special case for 11th: if ( n % 100 == 11 ) { return n + 'th'; } var res = n; switch( n % 10 ) { case 1: res += 'st'; break; case 2: res += 'nd'; break; case 3: res += 'rd'; break; default: res += 'th'; break; } return res; } var wrapJsObject = function(x) { if (x === undefined) { return types.jsObject('undefined', x); } else if (x === null) { return types.jsObject('null', x); } else if (typeof(x) == 'function') { return types.jsObject('function', x); } else if ( x instanceof Array ) { return types.jsObject('array', x); } else if ( typeof(x) == 'string' ) { return types.jsObject("'" + x.toString() + "'", x); } else { return types.jsObject(x.toString(), x); } }; var getKeyCodeName = function(e) { var code = e.charCode || e.keyCode; var keyname; switch(code) { case 8: keyname = "\b"; break; case 16: keyname = "shift"; break; case 17: keyname = "control"; break; case 19: keyname = "pause"; break; case 27: keyname = "escape"; break; case 33: keyname = "prior"; break; case 34: keyname = "next"; break; case 35: keyname = "end"; break; case 36: keyname = "home"; break; case 37: keyname = "left"; break; case 38: keyname = "up"; break; case 39: keyname = "right"; break; case 40: keyname = "down"; break; case 42: keyname = "print"; break; case 45: keyname = "insert"; break; case 46: keyname = String.fromCharCode(127); break; case 144: keyname = "numlock"; break; case 145: keyname = "scroll"; break; default: if (code >= 112 && code <= 123){ // fn keys keyname = "f" + (code - 111); } else { keyname = ""; } break; } return keyname; }; // maybeCallAfterAttach: dom-node -> void // walk the tree rooted at aNode, and call afterAttach if the element has // such a method. var maybeCallAfterAttach = function(aNode) { var stack = [aNode]; while (stack.length !== 0) { var nextNode = stack.pop(); if (nextNode.afterAttach) { nextNode.afterAttach(nextNode); } if (nextNode.hasChildNodes && nextNode.hasChildNodes()) { var children = nextNode.childNodes; for (var i = 0; i < children.length; i++) { stack.push(children[i]); } } } }; // makeLocationDom: location -> dom // Dom type that has special support in the editor through the print hook. // The print hook is expected to look at the printing of dom values with // this particular structure. In the context of WeScheme, the environment // will rewrite these to be clickable links. var makeLocationDom = function(aLocation) { var locationSpan = document.createElement("span"); var idSpan = document.createElement("span"); var offsetSpan = document.createElement("span"); var lineSpan = document.createElement("span"); var columnSpan = document.createElement("span"); var spanSpan = document.createElement("span"); locationSpan['className'] = 'location-reference'; idSpan['className'] = 'location-id'; offsetSpan['className'] = 'location-offset'; lineSpan['className'] = 'location-line'; columnSpan['className'] = 'location-column'; spanSpan['className'] = 'location-span'; idSpan.appendChild(document.createTextNode(aLocation.id + '')); offsetSpan.appendChild(document.createTextNode(aLocation.offset + '')); lineSpan.appendChild(document.createTextNode(aLocation.line + '')); columnSpan.appendChild(document.createTextNode(aLocation.column + '')); spanSpan.appendChild(document.createTextNode(aLocation.span + '')); locationSpan.appendChild(idSpan); locationSpan.appendChild(offsetSpan); locationSpan.appendChild(lineSpan); locationSpan.appendChild(columnSpan); locationSpan.appendChild(spanSpan); return locationSpan; }; var isLocationDom = function(thing) { return (thing && (thing.nodeType === Node.TEXT_NODE || thing.nodeType === Node.ELEMENT_NODE) && thing['className'] === 'location-reference'); }; //////////////////////////////////////////////// helpers.format = format; helpers.forEachK = forEachK; helpers.reportError = reportError; helpers.raise = raise; helpers.procArityContains = procArityContains; helpers.throwCheckError = throwCheckError; helpers.isList = isList; helpers.isListOf = isListOf; helpers.check = check; helpers.checkVarArity = checkVarArity; helpers.checkListOf = checkListOf; // helpers.remove = remove; helpers.map = map; helpers.schemeListToArray = schemeListToArray; helpers.deepListToArray = deepListToArray; helpers.flattenSchemeListToArray = flattenSchemeListToArray; helpers.assocListToHash = assocListToHash; helpers.ordinalize = ordinalize; helpers.wrapJsObject = wrapJsObject; helpers.getKeyCodeName = getKeyCodeName; helpers.maybeCallAfterAttach = maybeCallAfterAttach; helpers.makeLocationDom = makeLocationDom; helpers.isLocationDom = isLocationDom; })(); /////////////////////////////////////////////////////////////////
bootstrapworld/wescheme-js
src/runtime/helpers.js
JavaScript
lgpl-2.1
17,782
/* Lasso range library Name: Lasso Description: Lightweight, crossbrowser javascript library for creating and modifying ranges. Used by the GhostEdit editor. Licence: Dual licensed under MIT and LGPL licenses. Browser Support: Internet Explorer 6+, Mozilla Firefox 3.5+, Google Chrome, Apple Safari 3+, Opera 10.50+, Any other browser that supports DOMranges or TextRanges Author: Nico Burns <[email protected]> Website: http://ghosted.it/lasso Version: 1.5.0 Release Date: --- Changelog: Changes to the node selection functions. Change to deleteContents() for TextRange browsers (ie) Added clearSelection(); Available methods: Native range: setFromNative(nativerange) getNative() Selection: setToSelection() select() clearSelection() Modify range: reset() setStartToRangeStart(lasso object | range) setStartToRangeEnd(lasso object | range) setEndToRangeStart(lasso object | range) setStartToRangeEnd(lasso object | range) Modify content: deleteContents() pasteText(string) Get content: getText() extractText() getHTML() extractHTML() Node/element: selectNode(node) selectNodeContents(node) [only works on block elements in ie8] setCaretToStart(elem | elemid) setCaretToEnd(elem | elemid) Range information: isCollapsed() compareEndPoints() getStartNode() getEndNode() getParentNode() getStartElement() getEndElement() Save & restore: saveToDOM() restoreFromDOM() isSavedRange() removeDOMmarkers() bookmarkify() [ie <= 8 only] unbookmarkify() [ie <= 8 only] other: clone() inspect() Example usage: 1. Set the caret to the end of an element with ID 'testelem': lasso().setCaretToEnd('testelem').select(); 2. Get the currently selected text lasso().setToSelection().getText(); */ window.lasso = function() { //define local range object to be returned at end var r = { saved: null, endpoint: null, startpoint: null, bookmark: null, textrange: false, domrange: false, isLassoObject: true }, lasso = window.lasso, console = window.console || {}; console.log = console.log || function () {}; r.init = r.reset = r.create = function () { if(document.createRange) { r.textrange = false; r.saved = document.createRange(); } else if (document.selection) { r.textrange = true; r.saved = document.body.createTextRange(); } r.bookmark = false; r.domrange = !r.textrange; return r; }; r.setToEmpty = function () { if (r.domrange) { r.saved = document.createRange(); } else if (r.textrange) { r.saved = document.body.createTextRange(); } return r; }; /* Native Range Functions */ r.setFromNative = function (nativerange) { r.saved = nativerange; return r; }; r.getNative = function () { return r.saved; }; /* Selection Functions */ r.setToSelection = function () { var s; if(r.domrange) { s = window.getSelection(); if(s.rangeCount > 0) { r.saved = s.getRangeAt(0).cloneRange(); } } else if (r.textrange) { r.saved = document.selection.createRange(); } return r; }; r.select = function () { if (r.domrange) { var s = window.getSelection(); if (s.rangeCount > 0) s.removeAllRanges(); s.addRange(r.saved); } else if (r.textrange) { r.saved.select(); } return r; }; r.clearSelection = function () { if (r.domrange) { var s = window.getSelection(); if (s.rangeCount > 0) s.removeAllRanges(); } else if (r.textrange) { document.selection.empty(); } return r; }; /* Modify Range Functions */ r.collapseToStart = function () { r.saved.collapse(true); return r; }; r.collapseToEnd = function () { r.saved.collapse(false); return r; }; r.setStartToRangeStart = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.startContainer, range.startOffset); } else if (r.textrange) { r.saved.setEndPoint("StartToStart", range); } return r; }; r.setStartToRangeEnd = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("StartToEnd", range); } return r; }; r.setEndToRangeStart = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("EndToStart", range); } return r; }; r.setEndToRangeEnd = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setEnd(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("EndToEnd", range); } return r; }; /* Modify Content Functions */ r.deleteContents = function () { if (r.domrange) { r.saved.deleteContents(); } else if (r.textrange) { /* TextRange deleting seems quite buggy - these *should* work, but text = "" has been most successful so far try { r.saved.pasteHTML(""); } catch (e) { r.saved.execCommand("delete"); }*/ r.saved.text = ""; } return r; }; r.pasteText = function (text, collapse) { if(typeof collapse === "undefined") collapse = true; r.deleteContents(); if (r.domrange) { var txt = document.createTextNode(text); r.saved.insertNode(txt); r.reset().selectNodeContents(txt); } else if (r.textrange) { r.saved.pasteHTML(text); } if (collapse) r.collapseToEnd(); r.select(); return r; }; r.insertNode = function (node, collapse) { var div; if(typeof collapse === "undefined") collapse = true; r.deleteContents(); if (r.domrange) { r.saved.insertNode(node); r.setToEmpty().selectNodeContents(node); } else if (r.textrange) { div = document.createNode("div"); div.appendChild(node); r.saved.pasteHTML(div.innerHTML); } if (collapse) r.collapseToEnd(); //r.select(); return r; }; /* Get Content Functions */ r.getText = function () { if (r.domrange) { return r.saved.toString(); } else if (r.textrange) { return r.saved.text; } }; r.extractText = function () { var text = r.getText(); r.deleteContents(); return text; }; r.getHTML = function () { var tempelem, docfrag; if (r.domrange) { docfrag = r.saved.cloneContents(); tempelem = document.createElement("div"); tempelem.appendChild(docfrag); return tempelem.innerHTML; } else if (r.textrange) { return r.saved.htmlText; } }; r.extractHTML = function () { var html = r.getHTML(); r.deleteContents(); return html; }; /* Node/Element Functions */ r.actualSelectNode = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNode(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); } return r; }; r.selectNode = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); } return r; }; //Only works on block elements in ie8 r.selectNodeContents = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); var r1, r2; if (r.domrange) { r.saved.selectNodeContents(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); r1 = lasso().setCaretToStart(elem).getNative(); r2 = lasso().setCaretToEnd(elem).getNative(); r.saved.setEndPoint("StartToStart", r1); r.saved.setEndPoint("EndToStart", r2); } return r; }; r.setCaretToStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true); } else if (r.textrange) { /*elem.innerHTML = "<span id=\"range_marker\">&#x200b;</span>" + elem.innerHTML; r.selectNode('range_marker');//.deleteContents(); // For some reason .deleteContents() sometimes deletes too much document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker'));*/ r.saved.moveToElementText(elem); r.saved.collapse(true); } return r; }; r.setCaretToBlockStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true); } else if (r.textrange) { r.saved.moveToElementText(elem); r.saved.collapse(false); r.saved.move("character", -(elem.innerText.length + 1)); } return r; }; r.selectInlineStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true).select(); } else if (r.textrange) { elem.innerHTML = "a" + elem.innerHTML; // The 'a' is arbitrary, any single character will work r.saved.moveToElementText(elem); r.saved.collapse(false); r.saved.move("character", -(elem.innerText.length + 1)); r.saved.moveEnd("character", 1); r.saved.select(); r.saved.text = ""; } return r; }; r.setCaretToEnd = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(false); } else if (r.textrange) { /*elem.innerHTML = elem.innerHTML + "<span id=\"range_marker\">&#x200b;</span>"; r.selectNode('range_marker');//.deleteContents(); document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker'));*/ r.saved.moveToElementText(elem); r.saved.collapse(false); } return r; }; /* Range Information Functions */ r.isCollapsed = function () { if (r.domrange) { return r.saved.collapsed; } else if (r.textrange) { //return r.saved.compareEndPoints("StartToEnd", r.saved) === 0 ? true : false; return r.saved.isEqual(r.clone().collapseToStart().saved); } }; r.compareEndPoints = function (how, range) { var R; if (range && range.saved) range = range.getNative(); if (r.domrange) { // Note that EndToStart and StartToEnd are reversed (to make compatible with ie order) R = window.Range; var howlookup = {"StartToStart": R.START_TO_START, "StartToEnd": R.END_TO_START, "EndToStart": R.START_TO_END, "EndToEnd": R.END_TO_END}; how = howlookup[how]; return r.saved.compareBoundaryPoints(how, range); } else if (r.textrange) { return r.saved.compareEndPoints(how, range); } }; r.isEqualTo = function (range) { if (range && range.saved) range = range.getNative(); if (r.compareEndPoints("StartToStart", range) !== 0) return false; if (r.compareEndPoints("EndToEnd", range) !== 0) return false; return true; }; r.getStartNode = function () { if (r.domrange) { return r.saved.startContainer; } else if (r.textrange) { var range = r.saved.duplicate(); range.collapse(true); return range.parentElement(); } }; r.getEndNode = function () { if (r.domrange) { return r.saved.endContainer; } else if (r.textrange) { var range = r.saved.duplicate(); range.collapse(false); return range.parentElement(); } }; r.getParentNode = function () { if (r.domrange) { return r.saved.commonAncestorContainer; } else if (r.textrange) { return r.saved.parentElement(); } }; r.getStartElement = function () { return r.util.getParentElement( r.getStartNode() ); }; r.getEndElement = function () { return r.util.getParentElement( r.getEndNode() ); }; r.getParentElement = function () { if (r.domrange) { return r.util.getParentElement( r.saved.commonAncestorContainer); } else if (r.textrange) { return r.saved.parentElement(); } }; /* Clone Function */ r.clone = function () { var r2 = lasso(); if(r.domrange) { r2.saved = r.saved.cloneRange(); } else if (r.textrange) { r2.saved = r.saved.duplicate(); } r2.bookmark = r.cloneBookmark(); return r2; }; /* Save and Restore Functions (save to DOM) */ r.saveToDOM = function (id) { var start, end, smark, emark, collapsed; if (!id) id = "lasso"; r.removeDOMmarkers(id); collapsed = r.isCollapsed(); start = r.clone().collapseToStart().getNative(); if (!collapsed) end = r.clone().collapseToEnd().getNative(); if (r.domrange) { smark = document.createElement("span"); smark.innerHTML = "&#x200b"; smark.id = id + "_range_start"; start.insertNode(smark); if (!collapsed) { emark = document.createElement("span"); emark.innerHTML = "&#x200b"; emark.id = id + "_range_end"; end.insertNode(emark); } } else if (r.textrange) { start.pasteHTML("<span id=\"" + id + "_range_start\">&#x200b;</span>"); if (!collapsed) { end.pasteHTML("<span id=\"" + id + "_range_end\">&#x200b;</span>"); } } // Restore in case selection is lost by changing DOM above r = r.restoreFromDOM(id, false) || r.reset(); return r; }; r.restoreFromDOM = function (id, removemarkers) { var start, end, smark, emark; if (!id || id === "" || id === true || id === false) id = "lasso"; if (id === true) removemarkers = true; smark = document.getElementById(id + "_range_start"); emark = document.getElementById(id + "_range_end"); if (!smark) return false; start = lasso().actualSelectNode(smark).collapseToEnd(); if (removemarkers !== false) smark.parentNode.removeChild(smark); if (emark) { end= lasso().actualSelectNode(emark).collapseToStart(); if (removemarkers !== false) emark.parentNode.removeChild(emark); } else { end = start; } r = lasso().setStartToRangeStart(start).setEndToRangeEnd(end); return r; }; r.isSavedRange = function (id) { if (!id) id = "lasso"; return (document.getElementById(id + "_range_start")) ? true : false; }; r.removeDOMmarkers = function (id) { var smark, emark; if (!id) id = "lasso"; smark = document.getElementById(id + "_range_start"); emark = document.getElementById(id + "_range_end"); if (smark) smark.parentNode.removeChild(smark); if (emark) emark.parentNode.removeChild(emark); }; /* More save and restore functions (save reference from root node) */ r.bookmarkify = function (rootnode) { if (r.domrange) { var node, startnodeoffsets, endnodeoffsets, b = {}; if (!rootnode || !rootnode.nodeType) return r; // Save start and end offset to bookmark b.startoffset = r.saved.startOffset; b.endoffset = r.saved.endOffset; // Get start node offset path relative to rootnode startnodeoffsets = []; node = r.saved.startContainer; while (node !== rootnode) { startnodeoffsets.unshift(r.util.getNodeOffset(node)); node = node.parentNode; if (node === null) return r; } // Get end node offset path relative to rootnode endnodeoffsets = []; node = r.saved.endContainer; while (node !== rootnode) { endnodeoffsets.unshift(r.util.getNodeOffset(node)); node = node.parentNode; if (node === null) return r; } // Save paths to bookmark b.startnodeoffsets = startnodeoffsets.join("-"); b.endnodeoffsets = endnodeoffsets.join("-"); // Save rootnode to bookmark (used to show that bookmark exists) b.rootnode = rootnode; r.bookmark = b; } else if (r.textrange) { r.bookmark = r.saved.getBookmark(); } return r; }; r.unbookmarkify = function (rootnode) { var bookmark = r.bookmark; if (r.domrange) { var node, offset, startnodeoffsets, endnodeoffsets, startcontainer, endcontainer; if (!bookmark.rootnode || !rootnode) return r.setToEmpty(); node = rootnode; startnodeoffsets = bookmark.startnodeoffsets.split("-"); while (startnodeoffsets.length > 0) { offset = startnodeoffsets.shift(); if (!node.childNodes || !node.childNodes[offset]) return r.setToEmpty(); node = node.childNodes[offset]; } startcontainer = node; node = rootnode; endnodeoffsets = bookmark.endnodeoffsets.split("-"); while (endnodeoffsets.length > 0) { offset = endnodeoffsets.shift(); if (!node.childNodes || !node.childNodes[offset]) return r.setToEmpty(); node = node.childNodes[offset]; } endcontainer = node; r.setToEmpty(); r.saved.setStart(startcontainer, bookmark.startoffset); r.saved.setEnd(endcontainer, bookmark.endoffset); } else if (r.textrange) { if (r.bookmark) { r.reset().saved.moveToBookmark(bookmark); r.bookmarkify(); } } return r; }; r.clearBookmark = function () { r.bookmark = false; return r; }; r.cloneBookmark = function (bookmark) { if (!bookmark) bookmark = r.bookmark; if (r.domrange) { return !bookmark ? false : { "rootnode": bookmark.rootnode, "startnodeoffsets": bookmark.startnodeoffsets, "endnodeoffsets": bookmark.endnodeoffsets, "startoffset": bookmark.startoffset, "endoffset": bookmark.endoffset }; } else if (r.textrange) { if (!bookmark) return false; var r2 = lasso().getNative(); return r2.moveToBookmark(bookmark) ? r2.getBookmark() : false; } }; /* Inspection and debugging functions */ r.inspect = function (logid) { console.log({ logid: logid ? logid : "", startelement: r.getStartElement(), startnode: r.getStartNode(), endelement: r.getEndElement(), endnode: r.getEndNode(), text: r.getText(), html: r.getHTML(), parent: r.getParentNode() }); }; /* Utility, 'non-public' functions, used by other functions */ r.util = { //Used only for next two functions (getStartElement and getEndElement) getParentElement: function (node) { if (node.nodeType !== 1) { while (node.nodeType !== 1) { node = node.parentNode; if (node === null) return null; } } return node; }, getNodeOffset: function (node) { if (!node || !node.parentNode) return; var offset = 0; while (node.parentNode.childNodes[offset] !== node) { offset += 1; } return offset; } }; r.init(); return r; }; (function(window, undefined) { // Create ghostedit object and global variables var _ghostedit = { version: "1.0pre", enabledplugins: [], ready: false, active: false, isEditing: true, blockElemId: 0, editorchrome: null, debug: false }; // Empty object for references to any elements which need to be globally accesable to be stored on _ghostedit.el = {}; // Empty api object for plugins and init functions to add to _ghostedit.api = {}; // Empty object for plugins to be stored in _ghostedit.plugins = {}; // Add the ghostedit object to the global namespace window.ghostedit = _ghostedit; })(window); (function(window, undefined) { window.ghostedit.init = function (source, options) { if (typeof source === "string") source = document.getElementById(source); var i, handler, ghostedit = window.ghostedit, rootnode, uilayer, htmlelem; // Set up user options ghostedit.options = {}; ghostedit.options = options || {}; // Check for debug option (but only enable if log module exists) if (ghostedit.options.debug) { ghostedit.debug = true; } // Detect whether we need to add extra br's to work around firefox's bugs (also used for webkit and opera) ghostedit.browserEngine = ghostedit.util.detectEngines(); ghostedit.useMozBr = (ghostedit.browserEngine.gecko !== 0 || ghostedit.browserEngine.webkit !== 0 || ghostedit.browserEngine.opera !== 0); //Hide div containing original content source.style.display = 'none'; ghostedit.el.source = source; // Create contextual ui layer uilayer = document.createElement("div"); uilayer.id = "ghostedit_uilayer"; uilayer.className = "ghostedit_uilayer"; uilayer.innerHTML = "<span style='position: absolute; display: none;left: 0; top: 0;line-height: 0'>ie bug fix</span>"; source.parentNode.insertBefore(uilayer, source); ghostedit.el.uilayer = uilayer; // Run init events for core modules ghostedit.history.init(); ghostedit.inout.init(); ghostedit.clipboard.init(); // Enable plugins ghostedit.options.plugins = ghostedit.options.plugins || []; ghostedit.options.plugins.unshift("container", "textblock"); if (ghostedit.options.plugins) { for (i = 0; i < ghostedit.options.plugins.length; i++) { ghostedit.api.plugin.enable(ghostedit.options.plugins[i]); } } // Send init event to plugins (and core modules) ghostedit.event.trigger("init"); // Import initial content rootnode = ghostedit.inout.importHTML(source); source.parentNode.insertBefore(rootnode, source); ghostedit.el.rootnode = rootnode; // Focus the editor handler = rootnode.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].focus(rootnode); // Make sure that FF uses tags not CSS, and doesn't show resize handles on images try{document.execCommand("styleWithCSS", false, false);} catch(err){}//makes FF use tags for contenteditable try{document.execCommand("enableObjectResizing", false, false);} catch(err){}//stops resize handles being resizeable in FF // Save selection & setup undo ghostedit.selection.save(); ghostedit.history.reset(); ghostedit.history.saveUndoState(); // Attach event handlers to html element htmlelem = document.getElementsByTagName("html")[0]; ghostedit.util.addEvent(htmlelem, "dragenter", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "dragleave", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "dragover", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "drop", ghostedit.util.cancelEvent); // Attach handlers to rootnode ghostedit.util.addEvent(rootnode, "click", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "mouseup", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "keyup", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "keydown", function (event) {ghostedit.event.keydown(this, event); }); ghostedit.util.addEvent(rootnode, "keypress", function (event) {ghostedit.event.keypress(this, event); }); ghostedit.util.addEvent(rootnode, "dragenter", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "dragleave", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "dragover", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "drop", ghostedit.util.cancelEvent); // Focus rootnode rootnode.focus(); ghostedit.plugins.container.focus(rootnode); ghostedit.ready = true; ghostedit.event.trigger("init:after"); }; })(window); (function (window, undefined) { var _plugins = {}, ghostedit = window.ghostedit; _plugins.register = function(name, object) { if (ghostedit.plugins[name]) return false; ghostedit.plugins[name] = object; return true; }; _plugins.enable = function (name) { if (!ghostedit.plugins[name]) return false; if (ghostedit.enabledplugins[name]) _plugins.disable(name); var plugin = ghostedit.plugins[name]; if (typeof(plugin.enable) === "function") { plugin.enable(); } ghostedit.enabledplugins[name] = true; }; _plugins.disable = function (name) { if (!ghostedit.enabledplugins[name] || !ghostedit.plugins[name]) return false; var plugin = ghostedit.plugins[name]; if (typeof(plugin.disable) === "function") { plugin.disable(); } ghostedit.enabledplugins[name] = false; }; window.ghostedit.api.plugin = _plugins; })(window); (function (window, undefined) { var _util = {}; _util.trim = function (string) { return string.replace(/^\s+/, "").replace(/\s+$/, ""); }; // This will call a function using a reference with predefined arguments. //SECOND ARGUMENT = CONTEXT (this) - should usually be false _util.preparefunction = function (func, context /*, 0..n args */) { var args = Array.prototype.slice.call(arguments, 2); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(context ? context : this, allArguments); }; }; _util.isFunction = function (variable) { if (!variable) return false; if (typeof variable !== "function") return false; return true; }; _util.cloneObject = function (obj) { var copy, len, i, attr; // Handle the 3 simple types, and null or undefined if (null === obj || "object" !== typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (i = 0, len = obj.length; i < len; ++i) { copy[i] = _util.cloneObject(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = _util.cloneObject(obj[attr]); } return copy; } }; _util.addClass = function (elem, c) { elem.className = _util.trim(elem.className) + " " + c; }; _util.removeClass = function (elem, c) { var r = new RegExp(c,"g"); elem.className = _util.trim(elem.className.replace(r, "")); }; _util.cancelEvent = function (e) { if (e && e.preventDefault) { e.stopPropagation(); // DOM style (return false doesn't always work in FF) e.preventDefault(); } else if (e) { e.returnValue = false; } return false; // false = IE style }; _util.cancelAllEvents = function (e) { if (e && e.preventDefault) { e.stopPropagation(); // DOM style (return false doesn't always work in FF) e.preventDefault(); } else if (window.event) { window.event.cancelBubble = true; //IE cancel bubble; } return false; // false = IE style }; _util.preventDefault = function (e) { // Standards based browsers if (e && e.preventDefault) { e.preventDefault(); } // ie <= 8 return false; }; _util.preventBubble = function (e) { // Standards based browsers if (e && e.stopPropagation) { e.stopPropagation(); } // ie <= 8 if (window.event) window.event.cancelBubble = true; }; _util.addEvent = function (elem, eventType, handle) { if (elem.addEventListener !== undefined) { elem.addEventListener(eventType, handle, false); } else { elem.attachEvent("on" + eventType, handle); } }; _util.removeEvent = function (elem, eventType, handle) { if (elem.removeEventListener !== undefined) { elem.removeEventListener(eventType, handle, false); } else { elem.detachEvent("on" + eventType, handle); } }; _util.ajax = function (URL, method, params, sHandle, dataType) { var time, connector, xhr; if (!URL || !method) return false; // Get XHR object xhr = false; if(window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject)) { xhr = new window.XMLHttpRequest(); } else { try { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xhr = new window.ActiveXObject("MSXML2.XMLHTTP"); } catch (e2) {} } } if (!xhr) return false; // Prepare variables method = method.toUpperCase(); time = new Date().getTime(); URL = URL.replace(/(\?)+$/, ""); connector = (URL.indexOf('?') === -1) ? "?" : "&"; //connector = (URL.indexOf('?') === URL.length - 1) ? "" : "&"; // Open ajax Request if (method === "GET") { xhr.open(method, URL + connector + time + "&" + params, true); } else { xhr.open(method, URL + connector + time, true); } // Define function to handle response xhr.onreadystatechange = function () { var responseData; if(xhr.readyState === 4) { if(xhr.status === 200) { responseData = (dataType === "xml") ? xhr.responseXML : xhr.responseText; if (sHandle !== null){ sHandle(true, responseData); } return true; } else{ if (sHandle !== null){ sHandle(false, responseData); } return false; } } }; // Set HTTP headers xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //xhr.setRequestHeader("Content-length", params.length); //xhr.setRequestHeader("Connection", "close"); // Send ajax request if (method === "POST" && params !== null) { xhr.send(params); } else { xhr.send(); } }; _util.detectEngines = function() { //rendering engines var engine = {ie: 0, gecko: 0, webkit: 0, khtml: 0, opera: 0, ver: null}; // Detect rendering engines/browsers var ua = navigator.userAgent; if (window.opera){ engine.ver = window.opera.version(); engine.opera = parseFloat(engine.ver); } else if (/AppleWebKit\/(\S+)/.test(ua)){ engine.ver = RegExp.$1; engine.webkit = parseFloat(engine.ver); } else if (/KHTML\/(\S+)/.test(ua) || /Konqueror\/([^;]+)/.test(ua)){ engine.ver = RegExp.$1; engine.khtml = parseFloat(engine.ver); } else if (/rv:([^\)]+)\) Gecko\/\d{8}/.test(ua)){ engine.ver = RegExp.$1; engine.gecko = parseFloat(engine.ver); } else if (/MSIE ([^;]+)/.test(ua)){ engine.ver = RegExp.$1; engine.ie = parseFloat(engine.ver); } //return it return engine; }; window.ghostedit.util = _util; })(window); (function(window, undefined) { var _event = { listeners: [], listenerid: 0, eventtypes: [], cancelKeypress: false //allows onkeypress event to be cancelled from onkeydown event. }, ghostedit = window.ghostedit; // Used to capture non-repeating keyboard event (also, non-printing keys don't fire onkeypress in most browsers) _event.keydown = function (elem, e) { var keycode, ghostblock, handler, handled; ghostedit.selection.save(false); e = !(e && e.istest) && window.event ? window.event : e; keycode = e.keyCode !== null ? e.keyCode : e.charCode; _event.trigger("input:keydown", {"event": e, "keycode": keycode}); // Global shortcuts switch(keycode) { case 8: //backspace case 46: // delete key _event.cancelKeypress = false; if(ghostedit.selection.savedRange.isCollapsed() === false) { ghostedit.history.saveUndoState(); ghostedit.selection.deleteContents( (keycode === 8) ? "collapsetostart" : "collapsetoend" ); ghostedit.history.saveUndoState(); _event.cancelKeypress = true;//otherwise opera fires default backspace event onkeyPRESS (not onkeyDOWN) return ghostedit.util.cancelEvent ( e ); } break; case 83: //ctrl-s if (e.ctrlKey){ ghostedit.api.save(); return ghostedit.util.cancelEvent ( e ); } break; case 66: //ctrl-b if (e.ctrlKey) { ghostedit.plugins.textblock.format.bold (); return ghostedit.util.cancelEvent ( e ); } break; case 73: //ctrl-i if (e.ctrlKey && !e.shiftKey) { ghostedit.plugins.textblock.format.italic (); return ghostedit.util.cancelEvent ( e ); } break; case 85: //ctrl-u if (e.ctrlKey) { ghostedit.plugins.textblock.format.underline (); return ghostedit.util.cancelEvent ( e ); } break; case 90: //ctrl-z if (e.ctrlKey) { ghostedit.history.undo (); return ghostedit.util.cancelEvent ( e ); } break; case 89: //ctrl-y if (e.ctrlKey) { ghostedit.history.redo (); return ghostedit.util.cancelEvent ( e ); } break; } // If not handled by one of above, pass to plugin keydown handlers ghostblock = ghostedit.selection.getContainingGhostBlock(); while (true) { // If plugin for the GhostBlock containing the selection has an 'event.keydown' function, call it handler = ghostblock.getAttribute("data-ghostedit-handler"); if (ghostedit.plugins[handler] && ghostedit.plugins[handler].event && ghostedit.plugins[handler].event.keydown) { handled = ghostedit.plugins[handler].event.keydown(ghostblock, keycode, e); if (handled === true) break; } // If above GhostBlock doesn't handle the keypress, send event to it's parent ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } ghostedit.selection.save(); return true; }; _event.keypress = function (elem, e) { var keycode, ghostblock, handler, handled, currentDocLen, savedDocLen; ghostedit.selection.save(); currentDocLen = ghostedit.el.rootnode.innerHTML.length; savedDocLen = ghostedit.history.undoData[ghostedit.history.undoPoint] !== undefined ? ghostedit.history.undoData[ghostedit.history.undoPoint].content.string.length : 0; //if (currentDocLen - savedDocLen >= 20 || savedDocLen - currentDocLen >= 20) ghostedit.history.saveUndoState(); e = !(e && e.istest) && window.event ? window.event : e; keycode = e.keyCode !== null ? e.keyCode : e.charCode; _event.trigger("input:keydown", {"event": e, "keycode": keycode}); if (ghostedit.selection.saved.type !== "none" && !ghostedit.selection.savedRange.isCollapsed() && !e.ctrlKey) { ghostedit.selection.deleteContents("collapsetostart"); } // Global keyevents switch(keycode) { case 8: //cancel backspace event in opera if cancelKeypress = true if (_event.cancelKeypress === true) { _event.cancelKeypress = false; return ghostedit.util.cancelEvent ( e ); } break; case 13: // Enter (don't allow default action for enter to happen) ghostedit.util.cancelEvent ( e ); break; } // If not handled by one of above, pass to plugin keypress handlers ghostblock = ghostedit.selection.getContainingGhostBlock(); while (true) { // If plugin for the GhostBlock containing the selection has an 'event.keypress' function, call it handler = ghostblock.getAttribute("data-ghostedit-handler"); if (ghostedit.plugins[handler] && ghostedit.plugins[handler].event && ghostedit.plugins[handler].event.keypress) { handled = ghostedit.plugins[handler].event.keypress(ghostblock, keycode, e); if (handled === true) break; } // If above GhostBlock doesn't handle the keypress, send event to it's parent ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } ghostedit.selection.save(); return true; }; _event.addListener = function (event, callback, revokekey) { var listeners, eventtypes, isnewevent, i; if (typeof(callback) !== "function") return false; // Check if array for that event needs to be created listeners = _event.listeners; if (!listeners[event] || typeof(listeners[event]) !== "object" || !(listeners[event] instanceof Array)) { listeners[event] = []; } // Add event to list of events eventtypes = _event.eventtypes; isnewevent = true; for (i = 0; i < eventtypes.length; i++) { if (eventtypes[i] === event) { isnewevent = false; break; } } if (isnewevent) eventtypes.push(event); _event.listenerid++; listeners[event].push({"id": _event.listenerid, "callback": callback, "revokekey": revokekey}); return _event.listenerid; }; _event.removeListener = function (event, listenerid) { var listeners = _event.listeners, i, newlist = []; if(!listeners[event]) return; for (i = 0; i < listeners[event].length; i++) { if (listeners[event].id !== listenerid) { newlist.push(listeners[event][i]); } } listeners[event] = newlist; }; _event.removeAllListeners = function (revokekey) { var listeners, eventtypes, event, i, j, newlist = []; if(!revokekey) return; listeners = _event.listeners; eventtypes = _event.eventtypes; for (i = 0; i < eventtypes.length; i++) { event = eventtypes[i]; for (j = 0; j < listeners[event].length; j++) { if(!listeners[event][j].revokekey || listeners[event][j].revokekey !== revokekey) { newlist.push(listeners[event][j]); } } listeners[event] = ghostedit.util.cloneObject(newlist); newlist = []; } }; _event.trigger = function (event, params) { var listeners = _event.listeners, i; if (params === undefined) params = {}; if (!listeners[event] || typeof(listeners[event]) !== "object" || !(listeners[event] instanceof Array)) return; if (ghostedit.debug) { window.console.log(event); window.console.log(params); } for (i = 0; i < listeners[event].length; i++) { listeners[event][i].callback.call(this, params); } }; _event.sendBackwards = function (eventtype, source, params) { var target = false, tracker, result, direction; if (!params) params = {}; if (!ghostedit.dom.isGhostBlock(source)) return false; tracker = source; //tracks currently tried targets while(true) { if ((target = ghostedit.dom.getPreviousSiblingGhostBlock(tracker))) { direction = "ahead"; } else if ((target = ghostedit.dom.getParentGhostBlock(tracker))) { direction = "top"; } result = _event.send (eventtype, target, direction, params); if (!result) return false; else if (result.handled === true) return true; tracker = target; } }; _event.sendForwards = function (eventtype, source, params) { var target = false, tracker, result, direction; if (!params) params = {}; if (!ghostedit.dom.isGhostBlock(source)) return false; tracker = source; //tracks currently tried targets while(true) { if ((target = ghostedit.dom.getNextSiblingGhostBlock(tracker))) { direction = "behind"; } else if ((target = ghostedit.dom.getParentGhostBlock(tracker))) { direction = "bottom"; } result = _event.send (eventtype, target, direction, params); if (!result) return false; else if (result.handled === true) return true; tracker = target; } }; _event.send = function (eventtype, target, fromdirection, params) { var handler, handled; if (!target) return false; // = no previous/next GhostBlock handler = target.getAttribute("data-ghostedit-handler"); if (!ghostedit.plugins[handler] || !ghostedit.plugins[handler].dom || !ghostedit.plugins[handler].dom.deleteevent) { return {"handled": false}; // = no handler for this elemtype } handled = ghostedit.plugins[handler].dom.deleteevent (target, fromdirection, params); return {"handled": handled}; }; window.ghostedit.event = _event; })(window); (function(window, undefined) { var _dom = {}; _dom.getNodeOffset = function (node) { var offset, nodelist; if (!node || !node.parentNode) return; offset = 0; nodelist = node.parentNode.childNodes; while (nodelist[offset] !== node) { offset += 1; } return offset; }; _dom.extractContent = function (node) { var frag = document.createDocumentFragment(), child; while ( (child = node.firstChild) ) { frag.appendChild(child); } return frag; }; _dom.cloneContent = function (node) { var child, i, frag = document.createDocumentFragment(); for (i = 0; i < node.childNodes.length; i++) { child = node.childNodes[i]; frag.appendChild(child.cloneNode(true)); } return frag; }; _dom.parse = function (node, rules) { var parsednode = false, nodes, parsedchild, i, j, value, text, tagname, tagrules, attribute, style; if (!node || !rules || !node.nodeType) return false; rules.textnode = rules.textnode || {}; rules.tags = rules.tags || {}; // Handle textnodes if (node.nodeType === 3) { text = (rules.textnode.clean) ? node.nodeValue.replace(/[\n\r\t]/g,"") : node.nodeValue; return (text.length > 0) ? document.createTextNode(text) : false; } // Handle not-element case (textnodes already handled) if (node.nodeType !== 1) return false; // Get rules for tag, if none default to content only tagname = node.tagName.toLowerCase(); tagrules = {"contentsonly": true}; if (rules.tags[tagname]) { tagrules = rules.tags[tagname]; if (typeof tagrules.template === "string") tagrules = tagrules.template; if (typeof tagrules === "string" && rules.templates[tagrules]) tagrules = rules.templates[tagrules]; if (typeof tagrules === "string") return false; } // If "contentsonly" flag set, create document fragment, else create element of same type as node parsednode = tagrules.contentsonly ? document.createDocumentFragment() : document.createElement(node.tagName.toLowerCase()); // Unless "ignorechildren" flag set, recurse on children if (!tagrules.ignorechildren) { nodes = node.childNodes; for (i = 0; i < nodes.length; i++) { parsedchild = _dom.parse(nodes[i], rules); if (parsedchild) { parsednode.appendChild(parsedchild); } } } // Return here if contents only (no need to copy attributes if no node to copy to) if (tagrules.contentsonly) return (parsednode.childNodes.length > 0) ? parsednode : false; // If attributes specified, copy specified attributes if (tagrules.attributes) { for (i = 0; i < tagrules.attributes.length; i++) { attribute = tagrules.attributes[i]; // Handle simple (no rules) case if (typeof attribute === "string") attribute = {"name": attribute}; // Get value of attribute on source node if (typeof attribute.name !== "string") break; value = attribute.value || (attribute.name === "class") ? node.className : node.getAttribute(attribute.name); if (value === undefined) break; attribute.copy = true; // If allowedvalues are specified, check if value is correct if (attribute.allowedvalues) { attribute.copy = false; for (j = 0; j < attribute.allowedvalues.length; j++) { if (attribute.allowedvalues[i] === value){ attribute.copy = true; break; } } } // If all checks passed, set attribute on new node if (attribute.copy) { if (attribute.name === "class") { parsednode.className = value; } else { parsednode.setAttribute(attribute.name, value); } } } } // If styles specified, copy specified attributes if (tagrules.styles) { for (i = 0; i < tagrules.styles.length; i++) { style = tagrules.styles[i]; // Handle simple (no rules) case if (typeof style === "string") style = {"name": style}; // Get value of style on source node if (typeof style.name !== "string") break; if (style.name === "float") style.name = (node.style.cssFloat) ? "cssFloat" : "styleFloat"; value = style.value || node.style[style.name]; if (value === undefined) break; style.copy = true; // If allowedvalues are specified, check if value is correct if (style.allowedvalues) { style.copy = false; for (j = 0; j < style.allowedvalues.length; j++) { if (style.allowedvalues[j] === value) { style.copy = true; break; } } } // If all checks passed, set style on new node if (style.copy) parsednode.style[style.name] = value; } } return parsednode; }; _dom./*compareNodes = function (node1, node2) { var node; // If node1 is a documentFragment, wrap in an element if (n1.nodeType === 11) { node = document.createElement("div"); node.appendChild(nodeOrFrag); node1 = node; } // If node2 is a documentFragment, wrap in an element if (n2.nodeType === 11) { node = document.createElement("div"); node.appendChild(nodeOrFrag); node2 = node; } function getNextNode (nodelist, current) { } nodes1 = node1.getElementsByTagName(*); },*/ isGhostBlock = function (node) { if (!node || !node.nodeType || node.nodeType !== 1) return false; var ghosttype = node.getAttribute("data-ghostedit-elemtype"); return (ghosttype !== undefined && ghosttype !== false && ghosttype !== null) ? true : false; }; _dom.isChildGhostBlock = function (elem, parent) { var i; if (!elem || !parent || !parent.childNodes) return false; if (elem.nodeType !== 1) return false; if (elem.getAttribute("data-ghostedit-elemtype") === undefined) return false; if (elem.getAttribute("data-ghostedit-elemtype") === false) return false; if (elem.getAttribute("data-ghostedit-elemtype") === null) return false; var childblocks = parent.childNodes; for(i = 0; i < childblocks.length; i += 1) { if (elem === childblocks[i]) { return true; } } return false; }; _dom.isGhostToplevel = function (node) { return (node && node.getAttribute("data-ghostedit-isrootnode") === true) ? true : false; }; _dom.getParentGhostBlock = function (node) { if (!node) return false; do { node = node.parentNode; if (node === null) return false; } while (!_dom.isGhostBlock(node)); return node; }; _dom.getFirstChildGhostBlock = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse forwards through DOM until first GhostBlock is found. children = node.childNodes; for (i = 0; i < children.length; i += 1) { if (_dom.isGhostBlock(children[i])) { return children[i]; } } return false; }; _dom.getLastChildGhostBlock = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse backwards through DOM until previous GhostBlock is found. children = node.childNodes; for (i = children.length -1; i >= 0; i -= 1) { if (_dom.isGhostBlock(children[i])) { return children[i]; } } return false; }; _dom.getPreviousSiblingGhostBlock = function (node) { var parent, offset, siblings; if (!node || !node.parentNode) return false; // Otherwise, recurse backwards through DOM until previous GhostBlock is found. parent = node.parentNode; offset = _dom.getNodeOffset (node) - 1; siblings = parent.childNodes; do { if (_dom.isGhostBlock(siblings[offset]) === true) { return siblings[offset]; } offset -= 1; } while (offset >= 0); return false; }; _dom.getNextSiblingGhostBlock = function (node) { var parent, offset, siblings; if (!node || !node.parentNode) return false; // Otherwise, recurse forwards through DOM until next GhostBlock is found. parent = node.parentNode; offset = _dom.getNodeOffset (node) + 1; siblings = parent.childNodes; do { if (_dom.isGhostBlock(siblings[offset]) === true) { return siblings[offset]; } offset += 1; } while (offset < siblings.length); return false; }; _dom.getParentElement = function (node) { if (node.nodeType !== 1) { while (node.nodeType !== 1) { node = node.parentNode; if (node === null) return null; } } return node; }; _dom.isDescendant = function (parent, child) { var node = child.parentNode; while (node !== null) { if (node === parent) { return true; } node = node.parentNode; } return false; }; _dom.getFirstChildElement = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse forwards through DOM until next element is found. children = node.childNodes; for (i = 0; i < children.length; i += 1) { if (children[i].nodeType === 1) { return children[i]; } } return false; }; _dom.getCertainParent = function (condition, elem) { var args = [].slice.call(arguments); args.shift(); if (!condition.apply(this, args)) { while (!condition.apply(this, args)) { elem = elem.parentNode; args[0] = elem; if (elem === null) return false; } } return elem; }; window.ghostedit.dom = _dom; })(window); (function(window, undefined) { var _selection = { savedRange: null, nodepath: [], saved: {type: "none", data: null}, archived: {type: "none", data: null} }, ghostedit = window.ghostedit, lasso = window.lasso; _selection.save = function (updateui) { var sel; if (updateui !== false) updateui = true; sel = lasso().setToSelection(); if (!_selection.isInEditdiv(sel.getStartNode())) { _selection.saved.type = "none"; return false; } else { //Save current selection to range _selection.saved.type = "textblock"; _selection.saved.data = sel;//.bookmarkify(ghostedit.el.rootnode); // Save to legacy variable _selection.savedRange = _selection.saved.data; ghostedit.event.trigger("selection:change"); _selection.updatePathInfo(); if (updateui) ghostedit.event.trigger("ui:update"); return true; } }; _selection.set = function (type, data, updateui) { if (updateui !== false) updateui = true; if (typeof type !== "string") return; // Update selection variables _selection.saved.type = type; _selection.saved.data = data; // Save to legacy variable _selection.savedRange = _selection.saved.data; // Update path information _selection.updatePathInfo(); // Send events ghostedit.event.trigger("selection:change"); if (updateui) ghostedit.event.trigger("ui:update"); return true; }; _selection.restore = function (type, data, mustbevalid) { if (!type || typeof type !== "string") type = _selection.saved.type; if (!data) data = _selection.saved.data; // if type is none, but cant be, get archived selection if (type === "none" && mustbevalid) { type = _selection.archived.type; data = _selection.archived.data; } // If type is none, clear selection if (type === "none") { _selection.clear(); return true; } // Else, call restore function from appropriate plugin if (ghostedit.plugins[type] && ghostedit.plugins[type].selection.restore) { if (ghostedit.plugins[type].selection.restore(data)) { return true; } else { _selection.clear(); return false; } } }; _selection.restoreValid = function (type, data) { return _selection.restore(type, data, true); }; _selection.deleteContents = function (collapse) { if (collapse !== "collapsetostart" && collapse !== "collapsetoend") collapse = false; var handler, handled, ghostblock; ghostblock = _selection.getContainingGhostBlock(); while (true) { handler = ghostblock.getAttribute("data-ghostedit-handler"); handled = ghostedit.plugins[handler].selection.deleteContents(ghostblock, collapse); if (handled === true) break; ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } switch (collapse) { case "collapsetostart": lasso().setToSelection().collapseToStart().select(); break; case "collapsetoend": lasso().setToSelection().collapseToEnd().select(); break; } _selection.save(); }; _selection.isSameAs = function (sel) { if (!sel || !sel.type) return false; if (sel.type !== _selection.saved.type) return false; if (sel.type === "none") return true; // Else, call compare function from appropriate plugin if (ghostedit.plugins[sel.type] && ghostedit.plugins[sel.type].selection.compare) { return ghostedit.plugins[sel.type].selection.compare (sel.data, _selection.saved.data); } return false; }; _selection.clear = function () { lasso().clearSelection(); _selection.saved = {"type": "none", "data": null}; }; _selection.isInEditdiv = function (elem) { if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { if (elem === null) return false; elem = elem.parentNode; if (elem === null) return false; } } return true; }; _selection.updatePathInfo = function (elem) { if (!elem) elem = _selection.saved.data; if (!elem.nodeType) elem = elem.getParentNode(); // If nodepath is same as before, don't bother calculating it again // below code DOES NOT equal above statement. (dom node can have moved) //if (elem === _selection.nodepath[0]) return true; _selection.nodepath = []; if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { if (elem === null) return null; if (elem.nodeType === 1) _selection.nodepath.push(elem); elem = elem.parentNode; if (elem === null) return false; } } // Make sure rootnode is also included in path if (elem && elem.getAttribute("data-ghostedit-isrootnode") === "true") { _selection.nodepath.push(elem); } }; _selection.getContainingGhostBlock = function () { var node = _selection.saved.data; if (!node.nodeType) node = node.getParentNode(); if (!node) return false; while (!ghostedit.dom.isGhostBlock(node)) { node = node.parentNode; if (node === null) return false; } return node; }; window.ghostedit.selection = _selection; })(window); (function(window, undefined) { var _inout = {}, ghostedit = window.ghostedit; _inout.init = function () { // Set initial variables _inout.reset(); // Add listener to check whether the selection has changed since the last undo save ghostedit.event.addListener("selection:change", function () { ghostedit.history.selectionchanged = true; }); // Export undo and redo function to the api ghostedit.api.importHTML = function (source) { return _inout.importHTML(source); }; ghostedit.api.exportHTML = function () { return _inout.exportHTML(); }; }; _inout.reset = function () { _inout.importhandlers = []; }; _inout.importHTML = function (sourcenode) { var /*tagname, handler, result*/ rootnode; if (!sourcenode || sourcenode.childNodes.length < 1) return false; /*var tagname = sourcenode.tagName.toLowerCase(); if (handler = _inout.importhandlers[tagname]) { result = ghostedit.plugins[handler].inout.importHTML(insertedelem, elem) if (result) insertedelem = result; }*/ // Call container import, and set resulting domnode's contenteditable to true rootnode = ghostedit.plugins.container.inout.importHTML(sourcenode); rootnode.className = "ghostedit_rootnode"; rootnode.setAttribute("data-ghostedit-isrootnode", "true"); rootnode.contentEditable = 'true'; // Trigger 'import:after' event ghostedit.event.trigger("import:after", {"rootnode": rootnode}); // Return rootnode container return rootnode; }; _inout.exportHTML = function () { var finalexport, editwrap = ghostedit.el.rootnode; ghostedit.event.trigger("export:before"); //Preparation - contenteditable = false editwrap.contentEditable = false; finalexport = ghostedit.plugins.container.inout.exportHTML(editwrap, false); //Tidy up - contenteditable = true editwrap.contentEditable = true; ghostedit.event.trigger("export:after"); return finalexport; //{snippet: snippet, full: finalCode}; }; _inout.openPreview = function () { window.open(ghostedit.options.previewurl); }; _inout.registerimporthandler = function (importhandler/*, tagnames of elements that can be handled*/) { var i, args, tag; if (typeof importhandler !== "function") return false; if (arguments.length < 2) return false; args = Array.prototype.slice.call(arguments); args.shift(); // Loop through arguments for (i = 0; i < args.length; i++) { tag = args[i]; _inout.importhandlers[tag] = importhandler; } }; window.ghostedit.inout = _inout; })(window); (function(window, undefined) { var _history = {}, ghostedit = window.ghostedit; _history.init = function () { // Set initial variables _history.reset(); // Add listener to check whether the selection has changed since the last undo save ghostedit.event.addListener("selection:change", function () { _history.selectionchanged = true; }); // Export undo and redo function to the api ghostedit.api.undo = function () { return _history.undo(); }; ghostedit.api.redo = function () { return _history.redo(); }; }; _history.reset = function () { _history.undoData = [];//new Array(_history.undolevels); /*_history.undolevels = 4000,*/ _history.undoPoint = 0; _history.selectionchanged = true; }; _history.saveUndoState = function (force) { var undoPoint, undoData, contentchanged, selectionchanged, currentstate, undostate, editwrap = ghostedit.el.rootnode; if (force !== true) force = false; ghostedit.event.trigger("history:save:before"); // Localise undo variables undoPoint = _history.undoPoint; undoData = _history.undoData; // Get latest undopoint into a variable undostate = undoData[undoPoint]; if (!undostate) force = true; // Start capturing current editor state currentstate = { id: "", selection: { "type": ghostedit.selection.saved.type, //"data": ghostedit.selection.saved.type === "textblock" ? ghostedit.selection.saved.data.clone() : ghostedit.selection.saved.data "data": ghostedit.selection.saved.data }, content: { "string": editwrap.innerHTML } }; // Calcuate whether the selection or content have changed if (!force) { contentchanged = (undostate.content.string !== currentstate.content.string) ? true : false; selectionchanged = !(ghostedit.selection.isSameAs(undostate.selection)); } if (force || selectionchanged || contentchanged) { // Clone editor content as documentFragment currentstate.content.dom = ghostedit.dom.extractContent(editwrap.cloneNode(true)); if (force || contentchanged) { // Remove existing redo data if (undoPoint > 0) _history.undoData.splice(0, undoPoint); // Save new data and set undoPoint to point at it _history.undoData.unshift(currentstate); _history.undoPoint = 0; } else { _history.undoData[undoPoint] = currentstate; } } ghostedit.event.trigger("history:save:after"); }; _history.restoreUndoPoint = function (undopoint) { var undoData = _history.undoData, undostate = undoData[undopoint]; if (!undostate || undostate.content.string.length < 1) return false; ghostedit.event.trigger("history:restore:before"); ghostedit.el.rootnode.innerHTML = ""; ghostedit.el.rootnode.appendChild(ghostedit.dom.cloneContent(undostate.content.dom)); ghostedit.selection.restore (undostate.selection.type, undostate.selection.data); //ghostedit.selection.save(); ghostedit.event.trigger("history:restore:after"); }; _history.undo = function () { var undoPoint = _history.undoPoint, undoData = _history.undoData, editwrap = ghostedit.el.rootnode; if (undoData[undoPoint+1] === undefined || undoData[undoPoint+1].content.string.length <= 0) return; // if (undoPoint < _history.undolevels - 1) return; //unlimited undo levels ghostedit.event.trigger("history:undo:before"); // If there are unsaved changes, save current content and revert to last saved undopoint (was 0, but now 1 because current state saved in 0) if (undoData[undoPoint].content.string !== editwrap.innerHTML) { _history.saveUndoState(); undoPoint = 1; } // Else, current state already saved, revert to previous saved one (undoPoint + 1) else { if (undoPoint === 0) { _history.saveUndoState(); } undoPoint = _history.undoPoint; undoPoint += 1; } _history.restoreUndoPoint(undoPoint); _history.undoPoint = undoPoint; _history.undoData = undoData; ghostedit.event.trigger("history:undo:after"); }; _history.redo = function () { var undoPoint = _history.undoPoint, undoData = _history.undoData, editwrap = ghostedit.el.rootnode; if (undoPoint > 0 && undoData[undoPoint-1] !== undefined && undoData[undoPoint-1].content.string.length > 0) { ghostedit.event.trigger("history:redo:before"); // The user has made changes since the last undo/redo, throw away redo data and save undo state if (undoData[undoPoint].content.string !== editwrap.innerHTML) { _history.saveUndoState(true); } // Last action was an undo/redo, move one point forwards if possible else { undoPoint-=1; _history.restoreUndoPoint(undoPoint); _history.undoPoint = undoPoint; _history.undoData = undoData; } ghostedit.event.trigger("history:redo:after"); } }; window.ghostedit.history = _history; })(window); (function (window, undefined) { var _clipboard = {}, _paste, _cut, lasso = window.lasso, ghostedit = window.ghostedit, console = window.console || {}; console.log = console.log || function () {}; _clipboard.init = function () { _clipboard.paste.init(); _clipboard.cut.init(); }; _paste = { savedcontent: null, savedundodata: null, savedundopoint: null, beforerangedata: "", afterrangedata: "", waitlength: 0, postpastetidylist: [] }; _paste.init = function () { ghostedit.event.addListener("init:after", function () { ghostedit.util.addEvent(ghostedit.el.rootnode, "paste", function(event) { _paste.handle(event); }); }, "clipboard"); }; _paste.handle = function (e) {//elem no longer used? // Save editor state, and save undo data in case paste functions mess up undo stack ghostedit.history.saveUndoState(); _paste.savedundodata = ghostedit.history.undoData; _paste.savedundopoint = ghostedit.history.undoPoint; _paste.triedpasteimage = false; // If webkit - get data from clipboard, put into rootnode, cleanup, then cancel event if (e.clipboardData && e.clipboardData.getData) { if (/image/.test(e.clipboardData.types)) { _paste.triedpasteimage = true; } if (/text\/html/.test(e.clipboardData.types)) { ghostedit.el.rootnode.innerHTML = e.clipboardData.getData('text/html'); } else if (/text\/plain/.test(e.clipboardData.types) || ghostedit.browserEngine.opera) { ghostedit.el.rootnode.innerHTML = e.clipboardData.getData('text/plain').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); } else { ghostedit.el.rootnode.innerHTML = ""; } _paste.waitfordata(); return ghostedit.util.cancelEvent(e); } //Else - empty rootnode and allow browser to paste content into it, then cleanup else { ghostedit.el.rootnode.innerHTML = ""; _paste.waitfordata(); return true; } }; _paste.waitfordata = function () { var elem = ghostedit.el.rootnode; if (elem.childNodes && elem.childNodes.length > 0) { _paste.process(); } else { setTimeout(_paste.waitfordata, 20); } }; _paste.process = function () { var pastenode, collapsed, hasmerged, handler, target, result, source, position; // Extract pasted content into a new element pastenode = document.createElement("div"); pastenode = ghostedit.plugins.container.inout.importHTML(ghostedit.el.rootnode); console.log ("processed content"); console.log (pastenode.cloneNode(true)); // Restore undo data, and restore editor content ghostedit.history.undoData = _paste.savedundodata; ghostedit.history.undoPoint = _paste.savedundopoint; ghostedit.history.restoreUndoPoint(ghostedit.history.undoPoint); ghostedit.selection.save(); // Delete selection contents if selection is non-collapsed ghostedit.selection.deleteContents(); ghostedit.selection.save(); // If no content was pasted, return source = ghostedit.dom.getFirstChildGhostBlock(pastenode); if (!source) return; // Save selection to DOM if(ghostedit.selection.saved.data.isCollapsed()){ ghostedit.selection.saved.data.saveToDOM("ghostedit_paste_start"); } else { ghostedit.selection.saved.data.clone().collapseToStart().saveToDOM("ghostedit_paste_start"); ghostedit.selection.saved.data.clone().collapseToEnd().saveToDOM("ghostedit_paste_end"); } // Call handler on first pasted node target = function () { return ghostedit.selection.saved.data.getStartNode(); }; position = {"isfirst": true, "islast": (ghostedit.dom.getLastChildGhostBlock(pastenode) === source) ? true : false}; target = _paste.callHandler (target, source, position); /*ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } ghostedit.selection.saved.data.select().inspect(); return;/* */ // Call handler on last pasted node source = ghostedit.dom.getLastChildGhostBlock(pastenode); if (source) { target = function () { return ghostedit.selection.saved.data.getEndNode(); }; position = {"isfirst": false, "islast": true}; _paste.callHandler (target, source, position); } /*ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } ghostedit.selection.saved.data.select().inspect(); return;/* */ // Loop through and call handler on remaining nodes target = function () { return ghostedit.selection.saved.data.getParentNode(); }; position = {"isfirst": false, "islast": false}; while ((source = ghostedit.dom.getFirstChildGhostBlock(pastenode))) { _paste.callHandler (target, source, position); } // Restore the selection (collapsed to the end) ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", true).select(); if (ghostedit.selection.saved.data.isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_end", true).select(); } ghostedit.selection.save(); // Save undo state ghostedit.history.undoData = _paste.savedundodata; ghostedit.history.undoPoint = _paste.savedundopoint; ghostedit.history.saveUndoState(); if (_paste.triedpasteimage) { ghostedit.event.trigger("ui:message", {message: "You cannot paste images into the editor, please use the add image button instead", time: 2, color: "warn"}); } ghostedit.event.trigger("clipboard:paste:after"); }; _paste.callHandler = function (targetF, source, position) { var target, handler, result; // Restore the selection from DOM markers ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } // Get the target target = targetF(); if (!ghostedit.dom.isGhostBlock(target)) target = ghostedit.dom.getParentGhostBlock(target); // Recursively call handler of target and it's parents while (true) { if (!target) break; // Get handler plugin for specified target handler = target.getAttribute("data-ghostedit-handler"); if (!ghostedit.plugins[handler] || !ghostedit.plugins[handler].paste) break; console.log("Call handler: (" + (position.isfirst?"first":position.islast?"last":"normal") + ")" + handler); console.log(target.cloneNode(true)); console.log(source.cloneNode(true)); // Call handler function for target result = ghostedit.plugins[handler].paste.handle (target, source, position); console.log("result: " + result); // If handler function returns true, then source is handled: remove it and return false to indicate not to continue if (result) { source.parentNode.removeChild(source); break; } // Else, restore the selection from DOM markers ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } // Get the the parent GhostBlock as the next target to try target = ghostedit.dom.getParentGhostBlock(target); } }; _cut = { savedcontent: null, savedundodata: null, savedundopoint: null }; _cut.init = function () { ghostedit.event.addListener("init:after", function () { ghostedit.util.addEvent(ghostedit.el.rootnode, "cut", function(event) { _cut.handle(event); }); }, "clipboard"); }; _cut.handle = function () { // Save editor state, and save undo data in case paste functions mess up undo stack ghostedit.history.saveUndoState(); _cut.savedundodata = ghostedit.history.undoData; _cut.savedundopoint = ghostedit.history.undoPoint; //Else - empty rootnode and allow browser to paste content into it, then cleanup setTimeout(_cut.cleanup, 20); return true; }; _cut.cleanup = function () { // Restore undo data, and restore editor content ghostedit.history.undoData = _cut.savedundodata; ghostedit.history.undoPoint = _cut.savedundopoint; ghostedit.history.restoreUndoPoint(ghostedit.history.undoPoint); ghostedit.selection.save(); // Delete selection contents if selection is non-collapsed ghostedit.selection.deleteContents(); ghostedit.selection.save(); ghostedit.history.saveUndoState(); }; _clipboard.paste = _paste; _clipboard.cut = _cut; window.ghostedit.clipboard = _clipboard; })(window); (function (window, undefined) { var _textblock = {}, lasso = window.lasso, ghostedit = window.ghostedit, console = window.console || {}; console.log = console.log || function () {}; _textblock.enable = function () { _textblock.format.init(); ghostedit.inout.registerimporthandler (_textblock.inout.importHTML, "p", "h1", "h2", "h3", "h4", "h5", "h6"); ghostedit.inout.registerimporthandler (_textblock.inout.importHTML, "#textnode", "b", "strong", "i", "em", "u", "strike", "span"); // Bookmarkify (serialize) the selection, and save the bookmark to the lasso object ghostedit.event.addListener("history:save:after", function () { if (ghostedit.selection.saved.type === "textblock") { ghostedit.selection.saved.data.bookmarkify(ghostedit.el.rootnode); } }); // Clone range object after undo save to avoid accidentally modifying the saved range objects ghostedit.event.addListener("history:save:after", function () { if (ghostedit.selection.saved.type === "textblock") { ghostedit.selection.saved.data = ghostedit.selection.saved.data.clone(); } }); ghostedit.api.insert = ghostedit.api.insert || {}; ghostedit.api.insert.character = function (character) { return _textblock.insert.character(character); }; ghostedit.api.insert.br = function () {return _textblock.insert.br; }; return true; }; _textblock.event = { keydown: function (target, keycode, event) { switch (keycode) { case 8: // backspace return _textblock.event.backspace(target, event); case 46: //delete return _textblock.event.deletekey (target, event); } }, keypress: function (target, keycode, event) { // Enter key if (keycode === 13) return _textblock.event.enterkey (target, event); }, backspace: function (block, e) { if (_textblock.selection.isAtStartOfTextBlock() !== true) { //Caret not at start of textblock: return true to indicate handled return true; } else { //var block = ghostedit.selection.getContainingGhostBlock(); var params = { "merge": { "contenttype": "inlinehtml", "sourcecontent": block.innerHTML, callback: ghostedit.util.preparefunction(function (node) { var parent = node.parentNode; var handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, node);}, false, block) } }; ghostedit.event.sendBackwards("delete", block, params ); ghostedit.event.cancelKeypress = true; ghostedit.util.cancelEvent ( e ); return true; } }, deletekey: function (block, e) { //var block = ghostedit.selection.getContainingGhostBlock(); if (_textblock.selection.isAtEndOfTextBlock() !== true) { //Caret not at end of textblock: return true to indicate handled return true; } else { ghostedit.event.sendForwards("delete", block); //_textblock.remove(_textblock.selection.getStartTextBlockNode()); ghostedit.event.cancelKeypress = true; ghostedit.util.cancelEvent ( e ); return true; } }, enterkey: function (elem, e) { ghostedit.history.saveUndoState(); if (e.shiftKey) { _textblock.insert.br(); _textblock.mozBrs.tidy (elem); } else { _textblock.split(elem); } ghostedit.history.saveUndoState(); ghostedit.util.cancelEvent ( e ); return true; } }; _textblock.dom = { deleteevent: function (target, sourcedirection, params){ var parent, handler, block; switch (sourcedirection) { case "ahead": ghostedit.history.saveUndoState(); if (!_textblock.isEmpty(target)) { target.innerHTML += "<span id='ghostedit_selection_marker'>&#x200b;</span>"; if (params.merge && params.merge.sourcecontent && (params.merge.contenttype === "inlinehtml" || params.merge.contenttype === "text")) { target.innerHTML += params.merge.sourcecontent; } _textblock.mozBrs.tidy(target); params.merge.callback(); //params.sourceblock.parentNode.removeChild(params.sourceblock); lasso().selectNode("ghostedit_selection_marker").select();//.deleteContents(); document.getElementById("ghostedit_selection_marker").parentNode.removeChild(document.getElementById("ghostedit_selection_marker")); ghostedit.selection.save(); } else { parent = ghostedit.dom.getParentGhostBlock(target); handler = parent.getAttribute("data-ghostedit-handler"); //alert(target.id); ghostedit.plugins[handler].dom.removechild(parent, target); } ghostedit.history.saveUndoState(); return true; case "behind": block = ghostedit.selection.getContainingGhostBlock(); params = { "merge": { "contenttype": "inlinehtml", "sourcecontent": target.innerHTML, "callback": ghostedit.util.preparefunction(function (node) { var parent = node.parentNode, handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, node); }, false, target) } }; ghostedit.event.sendBackwards("delete", target, params); //---------------------------------- //_textblock.remove(_textblock.selection.getStartTextBlockNode()); //ghostedit.event.cancelKeypress = true; //return ghostedit.util.cancelEvent ( e ); return true; } } }; _textblock.selection = { compare: function (r1, r2) { if (!r1 || !r1.isEqualTo) return false; return r1.isEqualTo(r2); }, restore: function (savedrange) { if (!savedrange || !savedrange.unbookmarkify) return false; savedrange.unbookmarkify(ghostedit.el.rootnode); savedrange.select(); return true; }, deleteContents: function (textblockelem) { var startofblock, endofblock, selrange; // Temporary selection range to avoid changing actual saved range selrange = ghostedit.selection.savedRange.clone(); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(textblockelem); endofblock = lasso().setCaretToEnd(textblockelem); // If selrange starts before block, move start of selrange to start of block if (selrange.compareEndPoints("StartToStart", startofblock) === -1) { selrange.setStartToRangeStart(startofblock); } // If selrange end after block, move end of selrange to end of block if (selrange.compareEndPoints("EndToEnd", endofblock) === 1) { //alert(textblockelem.id); selrange.setEndToRangeEnd(endofblock); } selrange.deleteContents(); return true; }, getTextBlockNode: function (elem) { if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-elemtype") !== "textblock") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-elemtype") !== "textblock") { elem = elem.parentNode; if (elem === null) return false; } } return elem; }, getStartTextBlockNode: function () { return _textblock.selection.getTextBlockNode( ghostedit.selection.savedRange.getStartNode() ); }, getEndTextBlockNode: function () { return _textblock.selection.getTextBlockNode( ghostedit.selection.savedRange.getEndNode() ); }, //Assumes selection saved manually isAtStartOfTextBlock: function (point) { var caretIsAtStart = false, range, selrange, i, isequal, firstnode, textblocknode, wholenode, tempnode, useselection; // Check if 'point' parameter was passed and is a lasso object, otherwise get selection useselection = false; if (!point || !point.isLassoObject) { if (ghostedit.selection.saved.type !== "textblock") return false; point = ghostedit.selection.saved.data; useselection = true; } if(document.createRange) { range = point; if(range.isCollapsed() && range.getNative().startOffset === 0) { caretIsAtStart = true; tempnode = ghostedit.selection.savedRange.getStartNode(); } if (!tempnode) return caretIsAtStart; // If tempnode not right at start while (tempnode.nodeType !== 1 || tempnode.getAttribute("data-ghostedit-elemtype") !== "textblock") { if (tempnode !== tempnode.parentNode.childNodes[0]) { isequal = false; if((tempnode.parentNode.childNodes[0].nodeType === 3 && tempnode.parentNode.childNodes[0].length === 0) || (tempnode.parentNode.childNodes[0].nodeType === 1 && tempnode.parentNode.childNodes[0].className === "moz_dirty")) { //Deals with empty text nodes at start of textblock elem for(i = 1; i < tempnode.parentNode.childNodes.length; i += 1) { firstnode = tempnode.parentNode.childNodes[0]; if (tempnode === tempnode.parentNode.childNodes[i]) { isequal = true; break; } else if(!(firstnode.nodeType === 3 && firstnode.length === 0) && !(firstnode.nodeType === 1 && firstnode.className === "moz_dirty")) { break; } } } if(isequal !== true) { caretIsAtStart = false; break; } } tempnode = tempnode.parentNode; } } else if (document.selection) { // Bookmarkify range, so DOM modification doesn't break it selrange = point.clone().bookmarkify(); textblocknode = _textblock.selection.getStartTextBlockNode(); // Get range representing the whole TextBlock contents wholenode = lasso().selectNodeContents( textblocknode ); // Unbookmarkify the range, so it can be used in comparisons again selrange.unbookmarkify(); // Compare html of wholenode with html of node starting from selected point, if eqaul then selection is at the start of the textblock if (wholenode.getHTML() === wholenode.setStartToRangeStart(selrange).getHTML()) { caretIsAtStart = true; } if (useselection) { ghostedit.selection.savedRange = selrange.select(); } } return caretIsAtStart; }, //Assumes selection saved manually isAtEndOfTextBlock: function () { var caretIsAtEnd = false, selrange, range, rangefrag, elemfrag, textblocknode, endpoint; if (!ghostedit.selection.savedRange.isCollapsed()) return false; textblocknode = _textblock.selection.getEndTextBlockNode(); if(document.createRange) { rangefrag = document.createElement("div"); rangefrag.appendChild( ghostedit.selection.savedRange.getNative().cloneContents() ); range = ghostedit.selection.savedRange.getNative(); range.setEnd(textblocknode, textblocknode.childNodes.length); elemfrag = document.createElement("div"); rangefrag.appendChild( range.cloneContents() ); _textblock.mozBrs.clear(rangefrag); _textblock.mozBrs.clear(elemfrag); if(rangefrag.innerHTML === elemfrag.innerHTML) { caretIsAtEnd = true; } } else if (document.selection) { // Bookmarkify range, so DOM modification doesn't break it selrange = ghostedit.selection.savedRange.clone().bookmarkify(); // Get range representing the end of the TextBlock textblocknode.innerHTML += "<span id=\"range_marker\">&#x200b;</span>"; endpoint = lasso().selectNode('range_marker');//.deleteContents(); document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker')); // Unbookmarkify the range, so it can be used in comparisons again selrange.unbookmarkify(); // Compare endpoint to selected point, if equal then selection is at the end of the textblock if (selrange.compareEndPoints("EndToEnd", endpoint) === 0) { caretIsAtEnd = true; } ghostedit.selection.savedRange = selrange.select(); } return caretIsAtEnd; }, extendtoword: function (range, onlyfrommiddle) { var wordstart, wordend; range = range.clone().getNative(); if (document.createRange) { wordstart = _textblock.selection.findwordstart (range.startContainer, range.startOffset); wordend = _textblock.selection.findwordend (range.endContainer, range.endOffset); //If only one end has moved (or neither), then it's not from the middle if (onlyfrommiddle) { if (range.startContainer === wordstart.node && range.startOffset === wordstart.offset) return lasso().setFromNative(range); if (range.endContainer === wordend.node && range.endOffset === wordend.offset) return lasso().setFromNative(range); } range.setStart(wordstart.node, wordstart.offset); range.setEnd(wordend.node, wordend.offset); } else { range.expand("word"); if (range.htmlText.split().reverse()[0] === " ") { range.moveEnd("character", -1); } } return lasso().setFromNative(range); }, findwordstart: function (node, offset) { var leftnodecontent, stroffset, totalstroffset, prevnode, wordendregex = /\s|[\!\?\.\,\:\;\"]/; if (!node || !node.nodeType) return false; // Handle text node if (node.nodeType === 3) { leftnodecontent = node.nodeValue.substring(0, offset); stroffset = leftnodecontent.search(wordendregex); //If there is a space or punctuation mark left of position in current textNode if(stroffset !== -1) { totalstroffset = stroffset + 1; while ((stroffset = leftnodecontent.substring(totalstroffset).search(wordendregex)) !== -1) { totalstroffset += stroffset + 1; } return { node: node, offset: totalstroffset }; } } // Handle Element else if (node.nodeType === 1) { if (offset > 0) { return _textblock.selection.findwordstart(node.childNodes[offset - 1], node.childNodes[offset - 1].length); } } // If no wordend match found in current node and node is a ghostedit_textblock: return current position if (_textblock.isTextBlock(node)){ return {"node": node, "offset": offset}; } // If node is a NOT ghostedit_textblock: check previous node prevnode = node.previousSibling; if (prevnode) { if (prevnode.nodeType === 3) { return _textblock.selection.findwordstart(prevnode, prevnode.nodeValue.length); } else if (prevnode.nodeType === 1) { return _textblock.selection.findwordstart(prevnode, prevnode.childNodes.length); } } // If node is a NOT ghostedit_textblock and no previousSibling: move up tree else { return _textblock.selection.findwordstart(node.parentNode, ghostedit.dom.getNodeOffset(node)); } }, findwordend: function (node, offset) { var rightnodecontent, stroffset, totalstroffset, nextnode, wordendregex = /\s|[\!\?\.\,\:\;\"]/; if (!node || !node.nodeType) return false; // Handle text node if (node.nodeType === 3) { rightnodecontent = node.nodeValue.substring(offset); stroffset = rightnodecontent.search(wordendregex); //If there is a space or punctuation mark left of position in current textNode if (stroffset !== -1) { totalstroffset = offset + stroffset; return { node: node, offset: totalstroffset }; } } // Handle Element else if (node.nodeType === 1) { if (offset < node.childNodes.length) { return _textblock.selection.findwordend(node.childNodes[offset], 0); } } // If no wordend match found in current node and node is a ghostedit_textblock: return current position if (_textblock.isTextBlock(node)){ return {"node": node, "offset": offset}; } // If node is a NOT ghostedit_textblock: check next node nextnode = node.nextSibling; if (nextnode) { return _textblock.selection.findwordend(nextnode, 0); } // If node is a NOT ghostedit_textblock and no nextSibling: move up tree else { return _textblock.selection.findwordend(node.parentNode, ghostedit.dom.getNodeOffset(node) + 1); } } }; _textblock.inout = { handledtags: { "h1": "block", "h2": "block", "h3": "block", "h4": "block", "h5": "block", "h6": "block", "p": "block", "b": "child", "i": "child", "u": "child", "strong": "child", "em": "child", "strike": "child", "br": "child", "a": "contents", "span": "contents" }, parserules: { "textnode": { "clean": true }, "tags": { "h1": "textblock", "h2": "textblock", "h3": "textblock", "h4": "textblock", "h5": "textblock", "h6": "textblock", "p": "textblock", "b": {}, "i": {}, "u": {}, "strong": {}, "em": {}, "strike": {}, "br": { "attributes": [ {"name": "class", "allowedvalues": [ "moz_dirty" ]} ] } }, "templates": { "textblock": { "attributes": [ "class" ], "styles": [ {"name": "textAlign", "allowedvalues": ["left", "right", "center", "justified"] }, {"name": "clear", "allowedvalues": ["left", "right"] } ] } } }, importHTML: function (source) { var newTextBlock, tagname, node, childcount, prevnode, nodetype, parsednode; nodetype = _textblock.inout.isHandleableNode(source); switch (nodetype) { case "block": // Create TextBlock tagname = source.tagName.toLowerCase(); newTextBlock = ghostedit.dom.parse(source, _textblock.inout.parserules); ghostedit.blockElemId += 1; newTextBlock.id = 'ghostedit_textblock_' + ghostedit.blockElemId; // Set GhostEdit handler attributes newTextBlock.setAttribute("data-ghostedit-iselem", "true"); newTextBlock.setAttribute("data-ghostedit-elemtype", "textblock"); newTextBlock.setAttribute("data-ghostedit-handler", "textblock"); // Add event handlers newTextBlock.ondragenter = function(){return false;}; newTextBlock.ondragleave = function(){return false;}; newTextBlock.ondragover = function(){return false;}; newTextBlock.ondrop = function(e){ var elem, elemid; // This function does basic image paragraph changing dnd elemid = e.dataTransfer.getData("Text") || e.srcElement.id; //alert(elemid); TODO drag drop elem = document.getElementById(elemid); elem.parentNode.insertBefore(elem,this); ghostedit.image.focus(elem); }; newTextBlock.onresizestart = function(e) {return ghostedit.util.cancelEvent(e);}; _textblock.mozBrs.tidy (newTextBlock); return newTextBlock; case "child": case "contents": case "text": newTextBlock = _textblock.create("p"); newTextBlock.setAttribute("data-ghostedit-importinfo", "wasinline"); childcount = 0; node = source; do { parsednode = ghostedit.dom.parse(node, _textblock.inout.parserules); if (parsednode) { childcount += 1; newTextBlock.appendChild(parsednode); prevnode = node; node = node.nextSibling; if (childcount > 1) prevnode.parentNode.removeChild(prevnode); } } while (_textblock.inout.isHandleableNode(node) && _textblock.inout.isHandleableNode(node) !== "block"); _textblock.mozBrs.tidy (newTextBlock); return (childcount > 0) ? newTextBlock : false; } return false; }, exportHTML: function (target) { if (!target || !ghostedit.dom.isGhostBlock(target) || target.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; var finalCode = "", stylecode = "", elem; elem = target; _textblock.mozBrs.clear(elem); //if(elem.tagName.toLowerCase() == "p") paracount++; finalCode += "<" + elem.tagName.toLowerCase(); // Extract styles if (elem.style.textAlign !== "") { stylecode += "text-align:" + elem.style.textAlign + ";"; } if (elem.style.clear !== "") stylecode += "clear:" + elem.style.clear + ";"; if (stylecode.length > 0) finalCode += " style='" + stylecode + "'"; // Extract class if (elem.className.length > 0 && !/ghostedit/.test(elem.className)) finalCode += " class='" + elem.className + "'"; finalCode += ">"; // Copy content and end tag finalCode += elem.innerHTML; finalCode += "</" + elem.tagName.toLowerCase() + ">"; _textblock.mozBrs.tidy(elem); return {content: finalCode}; }, isHandleableNode: function (node) { var nodetag; if (!node || !node.nodeType) return false; // Handle textnode case if (node.nodeType === 3) return (node.nodeValue.replace(/[\n\r\t]/g,"").length > 0) ? "text" : false; // Handle not-element case (textnodes already handled) if (node.nodeType !== 1) return false; // Handle textblock case if(node.getAttribute("data-ghostedit-elemtype") === "textblock") return "block"; // Handle other GhostBlock case (don't process other plugins' stuff) if (ghostedit.dom.isGhostBlock(node)) return false; // Else get tagname, and check handleable tag list nodetag = node.tagName.toLowerCase(); if (_textblock.inout.handledtags[nodetag]) { return _textblock.inout.handledtags[nodetag]; } // Else return false return false; } }; _textblock.paste = { handle: function (target, source, position) { if (!ghostedit.dom.isGhostBlock(target) || !ghostedit.dom.isGhostBlock(source)) return; console.log(position); // If source is first pasted element, and was inline content, or is of same type as target, then merge contents into target node if (position.isfirst) { return _textblock.paste.handleFirst(target, source, position); } if (position.islast) { return _textblock.paste.handleLast(target, source, position); } _textblock.paste.split(target); return false; /*if (!position.islast || !(source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) && _textblock.isEmpty(blocks.block2)) { parent = ghostedit.dom.getParentGhostBlock(blocks.block2); handler = parent.getAttribute("data-ghostedit-handler"); marker = document.createElement("span"); marker.id = "ghostedit_paste_end_range_start"; marker.innerHTML = "&#x200b;"; lasso().removeDOMmarkers("ghostedit_paste_end"); ghostedit.plugins[handler].dom.addchild(parent, "after", blocks.block2, marker); ghostedit.plugins[handler].dom.removechild(parent, blocks.block2); return false; }*/ /*PART OF SPLIT FUNCTION lasso().removeDOMmarkers("ghostedit_paste_end"); blocks.block2.innerHTML = "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>" + blocks.block2.innerHTML; _textblock.mozBrs.tidy(blocks.block2);*/ // If source is last pasted element, and was inline content, or is of same type as target, then prepend contents to second node /*if (position.islast && (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName)) { //DEV console.log("paste (last):"); //DEV console.log(blocks.block2); blocks.block2.innerHTML = source.innerHTML + blocks.block2.innerHTML; blocks.block2 = _textblock.format.setTagType({"textblock": blocks.block2, "tagname": source.tagName.toLowerCase()}); return true; }*/ //DEV console.log(blocks.block1.parentNode.cloneNode(true)); }, handleFirst: function (target, source, position) { // No longer needed because is subset of 'p' check: source.getAttribute("data-ghostedit-importinfo") === "wasinline" if (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) { console.log("paste (first):"); _textblock.mozBrs.clear(source); lasso().removeDOMmarkers("ghostedit_paste_start"); source.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t1'>&#x200b;</span>"; if (document.createRange) { ghostedit.selection.saved.data.collapseToStart().getNative().insertNode( ghostedit.dom.extractContent(source) ); } else { ghostedit.selection.saved.data.collapseToStart().getNative().pasteHTML(source.innerHTML); } return true; } else { return false; } }, handleLast: function (target, source, position) { if (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) { console.log("paste (last):"); // If selection is collapsed, then create a new paragraph before merging contents if (ghostedit.selection.saved.data.isCollapsed()) { _textblock.paste.split(target); ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } } _textblock.mozBrs.clear(source); lasso().removeDOMmarkers("ghostedit_paste_end"); source.innerHTML += "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>"; if (document.createRange) { ghostedit.selection.saved.data.collapseToEnd().getNative().insertNode( ghostedit.dom.extractContent(source) ); } else { ghostedit.selection.saved.data.collapseToEnd().getNative().pasteHTML(source.innerHTML); } return true; } else { return false; } }, split: function (target, range) { var blocks, handlestartmarker = false; range = range || ghostedit.selection.saved.data; range = range.clone().collapseToStart(); // Check whether target contains a start marker if (ghostedit.dom.isDescendant(target, document.getElementById("ghostedit_paste_start_range_start"))) { handlestartmarker = true; } if (handlestartmarker) { lasso().removeDOMmarkers("ghostedit_paste_start");//Must be before split or marker is duplicated } blocks = _textblock.split(target, range); if (handlestartmarker) { blocks.block1.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t2'>&#x200b;</span>"; _textblock.mozBrs.tidy(blocks.block1); } // Tidy up end marker lasso().removeDOMmarkers("ghostedit_paste_end"); blocks.block2.innerHTML = "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>" + blocks.block2.innerHTML; _textblock.mozBrs.tidy(blocks.block2); return blocks; } }; _textblock.isTextBlock = function (textblock) { if (!ghostedit.dom.isGhostBlock(textblock)) return false; if (textblock.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; return true; }; _textblock.isEmpty = function (textblock) { var textcontent, imgs, brs, i; // If the node contains textual content then it's not empty //if (ghostedit.util.strip_tags(textblockelem.innerHTML).length > 1) return false; textcontent = textblock.innerText || textblock.textContent; if (textcontent && textcontent.length > 1) return false; // If the node contains no textual content and no <br> or <img> tags then it is empty brs = textblock.getElementsByTagName("br"); imgs = textblock.getElementsByTagName("img"); if (brs.length === 0 && imgs.length === 0) return true; // Otherwise check for non MozDirty <br>'s for(i = 0; i < brs.length; i += 1) { if(brs[i].MozDirty === undefined && !/moz_dirty/.test(brs[i].className)) return false; } // If none are found then it's empty return true; }; _textblock.isFirst = function (textblockelem) { var rootnode, i; rootnode = ghostedit.el.rootnode; for(i = 0; i < rootnode.getElementsByTagName("*").length; i += 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { if(rootnode.getElementsByTagName("*")[i] === textblockelem) { return true; } else { return false; } } } }; _textblock.isLast = function (textblockelem) { var rootnode, i; rootnode = ghostedit.el.rootnode; for(i = rootnode.getElementsByTagName("*").length - 1; i > 0; i -= 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { if(rootnode.getElementsByTagName("*")[i] === textblockelem) { return true; } else { return false; } } } }; _textblock.count = function () { var rootnode, childCount, i; rootnode = ghostedit.el.rootnode; childCount = 0; for(i = 0; i < rootnode.getElementsByTagName("*").length; i += 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { childCount += 1; } } return childCount; }; _textblock.create = function (elemtype, content, id) { var newElem; // If explicit id not passed, get next blockElemId if (!id) { ghostedit.blockElemId += 1; id = 'ghostedit_textblock_' + ghostedit.blockElemId; } // If no content sent, set to default content of "" ---"Edit Here!" content = (content && ((content.length && content.length > 0) || content.nodeType)) ? content : "";//"Edit Here!"; // Create element, and assign id and content newElem = document.createElement(elemtype); newElem.id = id; if (content.nodeType) { content = ghostedit.dom.parse(content, {"textnode": { "clean": true }, "tags": { "b": {}, "i": {}, "u": {}, "strong": {}, "em": {}, "strike": {}, "br": {} } }); if (content) newElem.appendChild(content); } else { newElem.innerHTML = content; } // Set GhostEdit handler attributes newElem.setAttribute("data-ghostedit-iselem", "true"); newElem.setAttribute("data-ghostedit-elemtype", "textblock"); newElem.setAttribute("data-ghostedit-handler", "textblock"); // Add event handlers newElem.ondragenter = function(){return false;}; newElem.ondragleave = function(){return false;}; newElem.ondragover = function(){return false;}; newElem.ondrop = function(e){ var elem, elemid; // This function does basic image paragraph changing dnd elemid = e.dataTransfer.getData("Text") || e.srcElement.id; //alert(elemid); TODO drag drop elem = document.getElementById(elemid); elem.parentNode.insertBefore(elem,this); ghostedit.image.focus(elem); }; newElem.onresizestart = function(e) {return ghostedit.util.cancelEvent(e);}; // Tidy MozBr's in new element _textblock.mozBrs.tidy(newElem); return newElem; }; _textblock.remove = function (textblockelem) { var savedElemContent, rootnode, focuselem, i, thisone, textblockelems; ghostedit.selection.save(); ghostedit.history.saveUndoState(); // If textblock elem still contains content, save to variable for appending to previous textblock elem savedElemContent = ""; savedElemContent = textblockelem.innerHTML; // Cycle through textblock elements backwards to select the one before the current one to focus rootnode = ghostedit.el.rootnode; textblockelems = rootnode.getElementsByTagName("*"); thisone = false; for(i = textblockelems.length - 1; i >= 0; i -= 1) { if (thisone === true && textblockelems[i].getAttribute("data-ghostedit-elemtype") === "textblock") { focuselem = textblockelems[i]; break; } else if (textblockelems[i] === textblockelem) { thisone = true; } } // If focuselem is empty, delete it instead (intuitive behaviour) if (_textblock.isEmpty(focuselem)) { rootnode.removeChild(focuselem); lasso().setCaretToStart(textblockelem).select(); ghostedit.selection.save(); ghostedit.history.saveUndoState(); return; } // Remove textblock elem rootnode.removeChild(textblockelem); // Set caret to end of focuselem lasso().setCaretToEnd(focuselem).select(); ghostedit.selection.save(); // Add saved content focuselem.innerHTML += "<span id='ghostedit_marker'>&#x200b;</span>" + savedElemContent; // Sort out MozBr's (one at very end of elements, that's it) _textblock.mozBrs.tidy(focuselem); // Place caret in correct place lasso().selectNode('ghostedit_marker').deleteContents().select(); if (document.getElementById('ghostedit_marker')) { document.getElementById('ghostedit_marker').parentNode.removeChild(document.getElementById('ghostedit_marker')); } ghostedit.selection.save(); ghostedit.history.saveUndoState(); }; _textblock.focus = function (target) { if (!target || target.nodeType !== 1 || target.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; lasso().setCaretToEnd(target).select(); ghostedit.selection.save(); return true; }; _textblock.merge = function (block1, block2, collapse) { var block1type, block2type, parent, handler; // If collapse === false don't merge if (collapse === false) return block1; // If blocks are same node, return that node if (block1 === block2) return block1; block1type = block1.getAttribute("data-ghostedit-elemtype"); block2type = block2.getAttribute("data-ghostedit-elemtype"); // If one of the blocks isn't a textblock, return false if (block1type !== "textblock" || block2type !== "textblock") return false; // Otherwise, append block2content to block1 and delete block2 block1.innerHTML += "<span id='ghostedit_marker'>&#x200b;</span>" + block2.innerHTML; parent = block2.parentNode; handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, block2); _textblock.mozBrs.tidy(block1); lasso().selectNode("ghostedit_marker").select();//.deleteContents(); document.getElementById("ghostedit_marker").parentNode.removeChild(document.getElementById("ghostedit_marker")); return block1; }; _textblock.split = function (elem, splitpoint) { var wheretoinsert, atstart, atend, elemtype, savedElemContent, range, result, newTextBlock, parent, handler, useselection; useselection = false; if (!splitpoint || !splitpoint.isLassoObject) { ghostedit.selection.save(); if (ghostedit.selection.saved.type !== "textblock") return false; splitpoint = ghostedit.selection.saved.data; useselection = true; } splitpoint = splitpoint.clone().collapseToStart(); atstart = (_textblock.selection.isAtStartOfTextBlock() === true) ? true : false; atend = (_textblock.selection.isAtEndOfTextBlock() === true) ? true : false; wheretoinsert = (atstart && !atend) ? "before" : "after"; elemtype = (wheretoinsert === "before" || atend) ? "p" : _textblock.selection.getStartTextBlockNode().tagName; //console.log("atstart - " + atstart+ "\natend - " + atend + "\nwhere - " + wheretoinsert); // Tidy MozBr's in original element _textblock.mozBrs.tidy(elem); // Save and the delete the content after the caret from the original element if(!atstart && !atend) {//wheretoinsert === "after") { if (document.createRange) { range = lasso().selectNodeContents( elem ).setStartToRangeStart(splitpoint); // Odd bug (at least in chrome) where savedRange is already to the end. savedElemContent = range.getHTML(); range.deleteContents(); } else if (document.selection) { // Bookmark lines allow innerHTML to be modified as long as it is put back to how it was /*savedrange = ghostedit.selection.savedRange.getNative().getBookmark(); range = lasso().selectNodeContents( elem ); ghostedit.selection.savedRange.getNative().moveToBookmark(savedrange); range.getNative().setEndPoint("StartToEnd", ghostedit.selection.savedRange.getNative());*/ range = lasso().selectNode(elem); range.setStartToRangeEnd(splitpoint); savedElemContent = range.getHTML(); range.getNative().text = ""; } } else { savedElemContent = ""; } /*result = _textblock.insert(elem, elemtype, false, wheretoinsert, savedElemContent); */ // Create new element for inserting newTextBlock = _textblock.create(elemtype, savedElemContent); if (!newTextBlock) return false; // Ask (ghost) parent to insert new element into page parent = ghostedit.dom.getParentGhostBlock(elem); handler = parent.getAttribute("data-ghostedit-handler"); result = ghostedit.plugins[handler].dom.addchild (parent, wheretoinsert, elem, newTextBlock, {"contentlength": savedElemContent.length}); if (!result) return false; /* IF !result, replace saved and deleted content after cursor */ // Workaround for ie (6?) bug which doesn't allow an empty element to be selected newTextBlock.innerHTML = "dummy"; lasso().selectNode(newTextBlock).select(); newTextBlock.innerHTML = savedElemContent; // Tidy MozBrs (previous code section often) removes all MozBrs) _textblock.mozBrs.tidy(newTextBlock); // Set caret to start of new element if(wheretoinsert === "before") { range = lasso().setCaretToBlockStart(elem); } else { range = lasso().setCaretToBlockStart(newTextBlock); } // If using selection, set caret to range position if (useselection) { range.select(); ghostedit.selection.save(); } // block1 = first in dom; block2 = second in dom return { "block1": wheretoinsert === "before" ? newTextBlock : elem, "block2": wheretoinsert === "before" ? elem :newTextBlock, "caretposition": range }; }; _textblock.mozBrs = { checkifcontains: function (node) { var elements, i; elements = node.getElementsByTagName("br"); for(i = 0; i < elements.length; i += 1) { if(elements[i].MozDirty !== undefined) return true; } return false; }, insert: function (elem) { var brNode; brNode = document.createElement("br"); brNode.setAttribute("_moz_dirty", ""); brNode.className = "moz_dirty"; elem.appendChild(brNode); }, clear: function (node) { var elements, i; elements = node.getElementsByTagName("br"); for(i = 0; i < elements.length; i += 1) { if(elements[i].MozDirty !== undefined || /moz_dirty/.test(elements[i].className)) { elements[i].parentNode.removeChild(elements[i]); i--; //One less element in live list, so decrease iterator } } }, tidy: function (elem) { _textblock.mozBrs.clear(elem); if(ghostedit.useMozBr) { _textblock.mozBrs.insert(elem); } } }; _textblock.insert = { character: function (character) { if(ghostedit.selection.saved.type === "textblock") { ghostedit.selection.restore(); ghostedit.selection.savedRange.pasteText(character); } }, br: function () { //var isEmpty = false; var s, newBr, r; if (window.getSelection) { s = window.getSelection(); s.getRangeAt(0).collapse(false); newBr = document.createElement("br"); newBr.id = "newBr"; s.getRangeAt(0).insertNode(newBr); s.getRangeAt(0).selectNode(newBr.parentNode); //alert(newBr.nextSibling); r = document.createRange(); r.setStartAfter(newBr); r.setEndAfter(newBr); s.removeAllRanges(); s.addRange(r); document.getElementById("newBr").removeAttribute("id"); } else if (document.selection) { r = document.selection.createRange(); r.collapse(false); r.pasteHTML("<br id='newBr' />"); r.moveToElementText(document.getElementById("newBr")); r.collapse(false); r.select(); document.getElementById("newBr").removeAttribute("id"); } } }; _textblock.format = { init: function () { ghostedit.api.format = ghostedit.api.format || {}; ghostedit.api.format.setStyle = function (tagname, newclass) { _textblock.format.formatSelected(_textblock.format.setTagType, {"tagname": tagname,"newclass": newclass}); }; ghostedit.api.format.alignText = function (alignDirection) { if (!/left|right|center|justify/.test(alignDirection)) return false; _textblock.format.formatSelected(_textblock.format.alignText, {"alignDirection": alignDirection}); }; ghostedit.api.format.bold = function () { _textblock.format.formatSelected(_textblock.format.bold); }; ghostedit.api.format.italic = function () { _textblock.format.formatSelected(_textblock.format.italic); }; ghostedit.api.format.underline = function () { _textblock.format.formatSelected(_textblock.format.underline); }; ghostedit.api.format.strikethrough = function () { _textblock.format.formatSelected(_textblock.format.strikethrough); }; ghostedit.api.format.textColor = function (color) { _textblock.format.formatSelected(_textblock.format.textColor, {"color": color}); }; }, useCommand: function (commandType, param) { //var i, nodes, node, selrange, startofblock, endofblock; //if (typeof param == "undefined") { param = null; } //if (ghostedit.selection.saved.type !== "text") return false; //ghostedit.history.saveUndoState(); document.execCommand(commandType, false, param); //ghostedit.selection.save(); //ghostedit.history.saveUndoState(); }, getNextNode: function (node) { if (node.firstChild) return node.firstChild; while (node) { if (node.nextSibling) return node.nextSibling; node = node.parentNode; } }, getNodesInRange: function (range) { var start = range.getStartNode(), end = range.getEndNode(), commonAncestor = range.getParentNode(), nodes = [], node; // walk parent nodes from start to common ancestor for (node = start.parentNode; node; node = node.parentNode) { nodes.push(node); if (node === commonAncestor) break; } nodes.reverse(); // walk children and siblings from start until end is found for (node = start; node; node = _textblock.format.getNextNode(node)) { nodes.push(node); if (node === end) break; } return nodes; }, useCommandOnWord: function (command) { var range, marker; if (ghostedit.selection.savedRange.isCollapsed() && _textblock.selection.getStartTextBlockNode()) { range = ghostedit.selection.savedRange.clone(); if (document.createRange) { marker = document.createElement("span"); marker.id = "ghostedit_marker"; range.getNative().insertNode(marker); } if (!document.createRange && document.selection) { range.getNative().pasteHTML("<span id='ghostedit_marker'>z</span>"); } range.selectNode("ghostedit_marker"); range = _textblock.selection.extendtoword(range, true); range.select(); } /* Placing cursor inside empty <b> doesn't work in ie <=8 (might work in 6/7) if (range.isCollapsed() && document.selection) { if (document.selection) { range.getNative().pasteHTML("<b><span id='ghostedit_marker'>&#x200b;</span></b>"); alert(lasso().selectNodeContents("ghostedit_marker").getHTML());//.select().deleteContents(); //document.getElementById("ghostedit_newnode").innerHTML = ""; //document.getElementById("ghostedit_newnode").id = ""; } } else {*/ _textblock.format.useCommand(command); if (document.getElementById("ghostedit_marker")) { lasso().selectNode("ghostedit_marker").select(); document.getElementById("ghostedit_marker").parentNode.removeChild(document.getElementById("ghostedit_marker")); } ghostedit.selection.save(); }, bold: function () { _textblock.format.useCommand("bold"); }, italic: function () { _textblock.format.useCommand("italic"); }, underline: function () { _textblock.format.useCommand("underline"); }, strikethrough: function () { _textblock.format.useCommand("strikethrough"); }, textColor: function (color) { _textblock.format.useCommand("foreColor",color); }, formatSelected: function (formatFunc, params) { var elem, startpara, endpara, oldelem, doend, i, descendantblocks; ghostedit.selection.save(); ghostedit.history.saveUndoState(); startpara = _textblock.selection.getStartTextBlockNode(); endpara = _textblock.selection.getEndTextBlockNode(); if (startpara && endpara) { elem = startpara; doend = false; do { if (elem === ghostedit.el.rootnode || elem === null) break; if (_textblock.isTextBlock(elem)) { if (elem === endpara) doend = true; elem = _textblock.format.formatTextBlock(elem, ghostedit.selection.saved.data.clone(), formatFunc, params); if (doend) break; elem = elem.nextSibling ? elem.nextSibling : elem.parentNode; continue; } else if (ghostedit.dom.isDescendant(elem, endpara)) { elem = ghostedit.dom.getFirstChildElement(elem); continue; } else { oldelem = elem; //necessary because setTagType kills list item (and if no list item, then no nextSibling) elem = elem.nextSibling ? elem.nextSibling : elem.parentNode; descendantblocks = oldelem.getElementsByTagName("*"); for(i = 0; i < descendantblocks.length; i += 1) { if (_textblock.isTextBlock(descendantblocks[i])) { _textblock.format.formatTextBlock(descendantblocks[i], ghostedit.selection.saved.data.clone(), formatFunc, params); } } } } while (true); ghostedit.selection.save(); ghostedit.history.saveUndoState(); } ghostedit.history.saveUndoState(); }, formatTextBlock: function (textblock, range, formatFunc, params) { var startofblock, endofblock, newelem; if (!params) params = {}; params.textblock = textblock; // Clone range to avoid reference errors range = range.clone(); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(textblock); endofblock = lasso().setCaretToEnd(textblock); // If range doesn't intersect textblock return false //console.log(range.compareEndPoints("EndToStart", startofblock)); //console.log(range.compareEndPoints("StartToEnd", endofblock)); if (range.compareEndPoints("EndToStart", startofblock) === -1 || range.compareEndPoints("StartToEnd", endofblock) === 1) return false; // If range starts before block, move start of selrange to start of block if (range.compareEndPoints("StartToStart", startofblock) === -1) range.setStartToRangeStart(startofblock); // If range end after block, move end of selrange to end of block if (range.compareEndPoints("EndToEnd", endofblock) === 1) range.setEndToRangeEnd(endofblock); ghostedit.selection.saved.data.clone().saveToDOM("ghostedit_format"); //if(textblock.id === "ghostedit_textblock_4") return; range.select(); newelem = formatFunc(params); lasso().restoreFromDOM("ghostedit_format").select(); ghostedit.selection.save(); return newelem && newelem.nodeType !== undefined ? newelem : textblock; }, alignText: function(params) { var elem = lasso().setToSelection().getParentElement(); while (!ghostedit.dom.isGhostBlock(elem)) { elem = elem.parentNode; if (elem === null) return false; } if (!_textblock.isTextBlock(elem)) return false; elem.style.textAlign = params.alignDirection; }, // .tagName is readonly -> need to remove element and add new one setTagType: function (params) { var target, tagtype, newclass, parent, targetid, newTextBlock; target = params.textblock; tagtype = params.tagname; newclass = params.newclass; // Retrieve target node //target = target || ghostedit.selection.nodepath[0]; if (!_textblock.isTextBlock(target)) return false; // Save id of target targetid = 'ghostedit_textblock_' + target.id.replace("ghostedit_textblock_",""); // Create replacement element, and copy over attributes/html newTextBlock = _textblock.create(tagtype); newTextBlock.appendChild(ghostedit.dom.extractContent(target)); _textblock.mozBrs.tidy(newTextBlock); newTextBlock.setAttribute("style", target.getAttribute("style")); if (newclass !== undefined) newTextBlock.className = newclass; // Use naive DOM manipulation because just doing an in place swap parent = target.parentNode; target.id = ""; parent.insertBefore(newTextBlock, target); parent.removeChild(target); // Set id of new TextBlock newTextBlock.id = targetid; return newTextBlock; } }; ghostedit.api.plugin.register("textblock", _textblock); })(window); (function (window, undefined) { var _container = {}, lasso = window.lasso, ghostedit = window.ghostedit; _container.enable = function () { return true; }; _container.dom = { addchild: function (target, wheretoinsert, anchorelem, newElem) { if (wheretoinsert === "before") { target.insertBefore(newElem, anchorelem); } else { if (anchorelem.nextSibling !== null) { target.insertBefore(newElem, anchorelem.nextSibling); } else { target.appendChild(newElem); } } return true; }, removechild: function (target, child) { if (!target || !child) return false; target.removeChild(child); return true; } // Not currently needed, but comments left for easier future implementation /*deleteevent: function (target, sourcedirection, params) { switch (sourcedirection) { case "ahead": // Backspace was pressed at the start of the element after the container break; case "behind": // Delete was pressed at the end of the element before the container break; case "top": // Backspace was pressed at the start of the first child GhostBlock of the container break; case "bottom": // Delete was pressed at the end of the last child GhostBlock the container break; } return false; }*/ }; _container.selection = { deleteContents: function (container, collapse) { var i, firstchildblock, lastchildblock, startofblock, endofblock, atverystart = false, atveryend = false, startblock, endblock, cblock, startcblock, endcblock, childblocks, dodelete, selrange, handler; // Temporary selection range to avoid changing actual saved range if(ghostedit.selection.saved.type !== "textblock") return false; selrange = ghostedit.selection.saved.data; // Get first and last child ghostblock childblocks = container.childNodes; firstchildblock = ghostedit.dom.getFirstChildGhostBlock(container); lastchildblock = ghostedit.dom.getLastChildGhostBlock(container); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(firstchildblock); endofblock = lasso().setCaretToEnd(lastchildblock); // If selrange starts before or at block, set startblock to the first child ghostblock if (selrange.compareEndPoints("StartToStart", startofblock) !== 1) { atverystart = true; startblock = firstchildblock; } // Otherwise, set child ghostblock containing the start of the selection else { startblock = selrange.getStartNode(); if (!ghostedit.dom.isGhostBlock(startblock)) startblock = ghostedit.dom.getParentGhostBlock(startblock); } // If selrange ends after or at block, set endblock to the last child ghostblock if (selrange.compareEndPoints("EndToEnd", endofblock) !== -1) { atveryend = true; endblock = lastchildblock; } // Otherwise, set child ghostblock containing the end of the selection else { endblock = selrange.getEndNode(); if (!ghostedit.dom.isGhostBlock(endblock)) endblock = ghostedit.dom.getParentGhostBlock(endblock); } startcblock = startblock; while(!ghostedit.dom.isChildGhostBlock(startcblock, container)) startcblock = ghostedit.dom.getParentGhostBlock(startcblock); endcblock = endblock; while(!ghostedit.dom.isChildGhostBlock(endcblock, container)) endcblock = ghostedit.dom.getParentGhostBlock(endcblock); //alert(startblock.id + endblock.id); /*//Handle selectall case if (isatverystart && isatveryend) { dodelete = false; firsttextblocktype = textblockelems[i].tagName.toLowerCase(); for(i = 0; i < childblocks.length; i += 1) { if (childblocks[i].getAttribute("data-ghostedit-elemtype") !== undefined && childblocks[i].getAttribute("data-ghostedit-elemtype") !== false) { firstchildblock = childblocks[i]; break; } } lasso().setCaretToStart(firstchildblock).select(); return true; }*/ //ghostedit.textblock.selection.deleteContents(lastchildblock); //alert("start - " + startblock.id + "\nend - " + endblock.id); // Cycle through SELECTED child ghostblocks and call delete method dodelete = false; for(i = 0; i < childblocks.length; i += 1) { cblock = childblocks[i]; if ( !ghostedit.dom.isGhostBlock(cblock) ) continue; handler = cblock.getAttribute("data-ghostedit-handler"); if (cblock.id === startcblock.id) { ghostedit.plugins[handler].selection.deleteContents( cblock ); dodelete = true; continue; } else if (cblock.id === endcblock.id) { ghostedit.plugins[handler].selection.deleteContents( cblock ); dodelete = false; break; } if (dodelete) { container.removeChild(childblocks[i]); i--; } } // If the first and last elements in the selection are the same type, then merge if(startcblock.getAttribute("data-ghostedit-elemtype") === endcblock.getAttribute("data-ghostedit-elemtype")) { lasso().setToSelection().saveToDOM("ghostedit_container_deleteselection"); ghostedit.plugins[startcblock.getAttribute("data-ghostedit-elemtype")].merge(startcblock, endcblock, collapse); lasso().restoreFromDOM("ghostedit_container_deleteselection").select(); //if (!ghostedit.dom.getParentGhostBlock(endcblock)) lasso().setToSelection().collapseToStart().select(); //^^tests whether endcblock is still in the document, i.e. whether a merge took place } // If container has no children left, create empty <p> element if (!ghostedit.dom.getFirstChildGhostBlock(container)) { container.appendChild(ghostedit.plugins.textblock.create("p")); } // Place caret where the selection was //lasso().setCaretToStart(endelem).select(); return true; } }; _container.inout = { importHTML: function (sourcenode) { var container, result, i, elemcount, elem, tagname; if (!sourcenode || sourcenode.childNodes.length < 1) return false; container = _container.create(); // For each source child node, check if appropriate import handler exists, if so then call it on the node for (i = 0; i < sourcenode.childNodes.length; i += 1) { elem = sourcenode.childNodes[i]; if (elem.nodeType !== 1 && elem.nodeType !== 3) continue; tagname = (elem.nodeType === 3) ? "#textnode" : elem.tagName.toLowerCase(); /*if (handler = ghostedit.inout.importhandlers[tagname]) { result = ghostedit.plugins[handler].inout.importHTML(elem) if (result && ghostedit.dom.isGhostBlock(result)) { container.appendChild(result); } }*/ if (ghostedit.inout.importhandlers[tagname]) { result = ghostedit.inout.importhandlers[tagname].call(this, elem); if (result && ghostedit.dom.isGhostBlock(result)) { container.appendChild(result); } } else if (elem.childNodes.length > 0) { elemcount = elem.childNodes.length; elem.parentNode.insertBefore(ghostedit.dom.extractContent(elem), elem); elem.parentNode.removeChild(elem); i -= 1; } } // Check any GhostBlock children have been added, else add empty paragraph if (!ghostedit.dom.getFirstChildGhostBlock(container)) { container.appendChild(ghostedit.plugins.textblock.create("p")); } return container; }, exportHTML: function (target/*, includeself*/) { // Shouldn't be used without first using export prepare functions if (!target || !ghostedit.dom.isGhostBlock(target) || target.getAttribute("data-ghostedit-elemtype") !== "container") return false; var i = 0, elem, blockreturn, finalCode = "", blockcount = 0, snippet, handler; //if (target.getAttribute("data-ghostedit-isrootnode") === true) isrootnode = true; // Allows for inclusion of enclosing <div> if wanted in future, may also want to retreieve properties //if (includeself === true) finalCode =+ "<div>"; for (i = 0; i < target.childNodes.length; i += 1) { elem = ghostedit.dom.isGhostBlock( target.childNodes[i] ) ? target.childNodes[i] : false; if (!elem) continue; handler = elem.getAttribute("data-ghostedit-handler"); if (!handler || !ghostedit.plugins[handler]) continue; blockreturn = ghostedit.plugins[handler].inout.exportHTML(elem); if (blockreturn) { finalCode += blockreturn.content; blockcount++; } //Create snippet from first 3 paragraphs if (blockcount <= 3){ snippet = finalCode; } } return {content: finalCode, snippet: snippet}; } }; _container.paste = { handle: function (target, source, position) { var sel, anchor, newnode, dummy; if (!ghostedit.dom.isGhostBlock(target) || !ghostedit.dom.isGhostBlock(source)) return false; //if (position.isfirst || position.islast) return false; sel = ghostedit.selection.saved.data; anchor = sel.clone().collapseToStart().getParentElement(); sel.saveToDOM("ghostedit_paste_start"); if (anchor === target) { /* Just use range marker as dummy elem dummy = document.createElement("span"); dummy.innerHTML = "&#x200b"; dummy.id = "ghostedit_paste_dummy"; sel.clone().collapseToStart().insertNode(dummy);*/ dummy = document.getElementById("ghostedit_paste_start_range_start"); anchor = ghostedit.dom.getPreviousSiblingGhostBlock(dummy) || dummy; } while (anchor.parentNode !== target) { anchor = anchor.parentNode; if (anchor === null || !anchor.parentNode) return true; } newnode = source.cloneNode(true); /*if (position.islast) { sel.removeDOMmarkers("ghostedit_paste"); newnode.innerHTML = "<span id='ghostedit_paste_range_end'>&#x200b;</span>" + newnode.innerHTML; } else { document.getElementById("ghostedit_paste_range_start").parentNode.removeChild(document.getElementById("ghostedit_paste_range_start")); }*/ lasso().removeDOMmarkers("ghostedit_paste_start"); newnode.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t3'>&#x200b;</span>"; _container.dom.addchild(target, "after", anchor, newnode); if (dummy && dummy.parentNode) dummy.parentNode.removeChild(dummy); return true; } }; // TODO remove this function is favour of dom.isChildGhostBlock _container.isChildGhostBlock = function (elem, childblocks) { var i; if (!elem) return false; if (elem.nodeType !== 1) return false; if (elem.getAttribute("data-ghostedit-elemtype") === undefined) return false; if (elem.getAttribute("data-ghostedit-elemtype") === false) return false; if (elem.getAttribute("data-ghostedit-elemtype") === null) return false; for(i = 0; i < childblocks.length; i += 1) { if (elem === childblocks[i]) { return true; } } return false; }; _container.create = function () { var newElem; // Create element, and assign id and content newElem = document.createElement("div"); ghostedit.blockElemId += 1; newElem.id = "ghostedit_container_" + ghostedit.blockElemId; // Set GhostEdit handler attributes newElem.setAttribute("data-ghostedit-iselem", "true"); newElem.setAttribute("data-ghostedit-elemtype", "container"); newElem.setAttribute("data-ghostedit-handler", "container"); return newElem; }; _container.focus = function (target) { var firstchild, handler; if (!target || target.nodeType !== 1 || target.getAttribute("data-ghostedit-elemtype") !== "container") return false; // Get first child of container firstchild = ghostedit.dom.getFirstChildGhostBlock (target); if (!firstchild) return false; handler = firstchild.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].focus(firstchild); return true; }; ghostedit.api.plugin.register("container", _container); })(window);
nicoburns/ghostedit
dist/ghostedit-core-1.0.0-pre.js
JavaScript
lgpl-2.1
128,789
/* * Give a file path uuid, or full path, render a html for the file display. * * ../unit/u-rvp.js will be the test file. */ var fs = require('fs'); var path = require('path'); var handlebars = require('handlebars'); var folder_module = require("../aws/folder-v5.js"); var vpt = require("./video-player-tpl.js"); var tpl = require("../myutils/tpl.js"); var p = console.log; // Constants var Html_template = path.join(__dirname, "video.html"); /* * */ function render_video_page_pu(path_uuid, callback){ folder_module.retrieve_file_meta_pu(path_uuid, function(err, meta){ var s3key = meta.storage.key; var vid_src = path.join('/ss/', s3key); console.log('console.log vid src: ', vid_src); var video_html = vpt.render_video_element(meta); var context = { video_element : video_html, }; tpl.render_template(Html_template, context, callback); //callback(null, video_html); }); } var get_file = require("../aws/get-file.js"); /* * Given video file full path, give an html render of the video player. */ function render_video_page(video_full_path, callback){ get_file.get_1st_file_obj_with_auxpath_by_path(video_full_path, function(err, file){ if(err) return callback(err); var meta = file.get_meta(); render_video_meta_to_web_page(meta, callback); }); } function render_video_meta_to_web_page(meta, callback){ var video_html = vpt.render_video_element(meta); var context = { video_element : video_html, }; tpl.render_template(Html_template, context, callback); } module.exports.render_video_meta_to_web_page = render_video_meta_to_web_page; module.exports.render_video_page_pu = render_video_page_pu; module.exports.render_video_page = render_video_page; //todo function render_html (context, callback) { tpl.render_template(Html_template, context, callback); //return fs.readFile(Html_template, 'utf-8', function(err, str){ // if(err) return callback(err); // p(str.slice(0, 300)); // callback(null,null); //}); }; // -- checkings -- // function c_render_html(){ render_html({}, function(err, what){ p(err, what); process.exit(); }); } /* * to give video element <video...> </video> */ function c_v_element(fpath){ fpath = fpath || {}; } if(require.main === module){ //p(Html_template); c_render_html(); }
goodagood/gg
plain/video/render-video-player.js
JavaScript
lgpl-2.1
2,470
/** * EditorUpload.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Handles image uploads, updates undo stack and patches over various internal functions. * * @private * @class tinymce.EditorUpload */ define("tinymce/EditorUpload", [ "tinymce/util/Arr", "tinymce/file/Uploader", "tinymce/file/ImageScanner", "tinymce/file/BlobCache" ], function(Arr, Uploader, ImageScanner, BlobCache) { return function(editor) { var blobCache = new BlobCache(); // Replaces strings without regexps to avoid FF regexp to big issue function replaceString(content, search, replace) { var index = 0; do { index = content.indexOf(search, index); if (index !== -1) { content = content.substring(0, index) + replace + content.substr(index + search.length); index += replace.length - search.length + 1; } } while (index !== -1); return content; } function replaceImageUrl(content, targetUrl, replacementUrl) { content = replaceString(content, 'src="' + targetUrl + '"', 'src="' + replacementUrl + '"'); content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"'); return content; } function replaceUrlInUndoStack(targetUrl, replacementUrl) { Arr.each(editor.undoManager.data, function(level) { level.content = replaceImageUrl(level.content, targetUrl, replacementUrl); }); } function uploadImages(callback) { var uploader = new Uploader({ url: editor.settings.images_upload_url, basePath: editor.settings.images_upload_base_path, credentials: editor.settings.images_upload_credentials, handler: editor.settings.images_upload_handler }); function imageInfosToBlobInfos(imageInfos) { return Arr.map(imageInfos, function(imageInfo) { return imageInfo.blobInfo; }); } return scanForImages().then(imageInfosToBlobInfos).then(uploader.upload).then(function(result) { result = Arr.map(result, function(uploadInfo) { var image; image = editor.dom.select('img[src="' + uploadInfo.blobInfo.blobUri() + '"]')[0]; if (image) { replaceUrlInUndoStack(image.src, uploadInfo.url); editor.$(image).attr({ src: uploadInfo.url, 'data-mce-src': editor.convertURL(uploadInfo.url, 'src') }); } return { element: image, status: uploadInfo.status }; }); if (callback) { callback(result); } return result; }, function() { // Silent // TODO: Maybe execute some failure callback here? }); } function scanForImages() { return ImageScanner.findAll(editor.getBody(), blobCache).then(function(result) { Arr.each(result, function(resultItem) { replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri()); resultItem.image.src = resultItem.blobInfo.blobUri(); }); return result; }); } function destroy() { blobCache.destroy(); } function replaceBlobWithBase64(content) { return content.replace(/src="(blob:[^"]+)"/g, function(match, blobUri) { var blobInfo = blobCache.getByUri(blobUri); if (!blobInfo) { blobInfo = Arr.reduce(editor.editorManager.editors, function(result, editor) { return result || editor.editorUpload.blobCache.getByUri(blobUri); }, null); } if (blobInfo) { return 'src="data:' + blobInfo.blob().type + ';base64,' + blobInfo.base64() + '"'; } return match[0]; }); } editor.on('setContent paste', scanForImages); editor.on('RawSaveContent', function(e) { e.content = replaceBlobWithBase64(e.content); }); editor.on('getContent', function(e) { if (e.source_view || e.format == 'raw') { return; } e.content = replaceBlobWithBase64(e.content); }); return { blobCache: blobCache, uploadImages: uploadImages, scanForImages: scanForImages, destroy: destroy }; }; });
VioletLife/tinymce
js/tinymce/classes/EditorUpload.js
JavaScript
lgpl-2.1
4,051
var searchData= [ ['fan2para',['Fan2Para',['../classrisa_1_1cuda_1_1_fan2_para.html',1,'risa::cuda']]], ['filter',['Filter',['../classrisa_1_1cuda_1_1_filter.html',1,'risa::cuda']]] ];
HZDR-FWDF/RISA
docs/search/classes_4.js
JavaScript
lgpl-3.0
189
'use strict'; /** * Module dependencies. */ var passport = require('passport'), url = require('url'), config = require('../../config'), GitHubStrategy = require('passport-github').Strategy; module.exports = function() { // Use github strategy passport.use(new GitHubStrategy({ clientID: config.github.clientID, clientSecret: config.github.clientSecret, callbackURL: config.github.callbackURL, passReqToCallback: true }, function(req, accessToken, refreshToken, profile, done) { req.session.gitToken = accessToken; process.nextTick(function () { return done(null, profile); }); } )); };
ClearcodeHQ/angular-collective
config/strategies/github/github.js
JavaScript
lgpl-3.0
663
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import _ from 'underscore'; import Backbone from 'backbone'; export default Backbone.Model.extend({ defaults: function () { return { page: 1, maxResultsReached: false, query: {}, facets: [] }; }, nextPage: function () { var page = this.get('page'); this.set({ page: page + 1 }); }, clearQuery: function (query) { var q = {}; Object.keys(query).forEach(function (key) { if (query[key]) { q[key] = query[key]; } }); return q; }, _areQueriesEqual: function (a, b) { var equal = Object.keys(a).length === Object.keys(b).length; Object.keys(a).forEach(function (key) { equal = equal && a[key] === b[key]; }); return equal; }, updateFilter: function (obj, options) { var oldQuery = this.get('query'), query = _.extend({}, oldQuery, obj), opts = _.defaults(options || {}, { force: false }); query = this.clearQuery(query); if (opts.force || !this._areQueriesEqual(oldQuery, query)) { this.setQuery(query); } }, setQuery: function (query) { this.set({ query: query }, { silent: true }); this.set({ changed: true }); this.trigger('change:query'); } });
joansmith/sonarqube
server/sonar-web/src/main/js/components/navigator/models/state.js
JavaScript
lgpl-3.0
2,070
var sys = require('sys'), child_process = require('child_process'), vm = require('vm'), http = require('http'), querystring = require('querystring'), Persistence = require('./persistence/persistence'), request = require('request'), xml2jsParser = require('xml2js').parseString; function msToString(ms) { var str = ""; if (ms > 3600000) { var hours = Math.floor(ms/3600000); str += hours + " hours, "; ms = ms - (hours*3600000); } if (ms > 60000) { var minutes = Math.floor(ms/60000); str += minutes + " minutes, "; ms = ms - (minutes*60000); } str += Math.floor(ms/1000) + " seconds"; return str; } function addBehaviors(bot, properties) { var persistence = new Persistence(properties); var userEval = 1; // Rate to mix in yahoo answers with stored responses // 0.75 = 75% Yahoo answers, 25% stored responses var mix = 0.5; bot.addMessageListener("logger", function(nick, message) { // Check to see if this is from a nick we shouldn't log if (properties.logger.ignoreNicks.filter(function (x) { return nick.indexOf(x) > -1; }).length > 0) { return true; } if (! (/^!/).test(message)) { persistence.saveMessage(nick, message); } return true; }); var yahooAnswer = function(message) { var url = 'http://answers.yahoo.com/AnswersService/V1/questionSearch?appid=' + properties.yahooId + "&query=" + querystring.escape(message) + "&type=resolved&output=json"; sys.log("Calling " + url); request(url, function(error, response, body) { try { var yahooResponse = JSON.parse(body); if (yahooResponse.all.count > 0) { var bestAnswer = yahooResponse.all.questions[0].ChosenAnswer; bestAnswer = bestAnswer.substring(0, 400); bot.say(bestAnswer); } else { persistence.getRandom(bot); } } catch (err) { sys.log(err); persistence.getRandom(bot); } }); }; bot.addMessageListener("listen for name", function (nick, message) { var re = new RegExp(properties.bot.nick); if (re.test(message)) { if (Math.random() < mix && properties.yahooId) { sys.log("mix = " + mix + ", serving from yahoo answers"); yahooAnswer(message.replace(re, '')); } else { sys.log("mix = " + mix + ", serving from mysql"); persistence.getRandom(bot); } return false; } else { return true; } }); bot.addCommandListener("!do [nick]", /!do ([0-9A-Za-z_\-]*)/, "random quote", function(doNick) { persistence.getQuote(doNick, bot); }); bot.addCommandListener("!msg [#]", /!msg ([0-9]*)/, "message recall", function(id) { persistence.getMessage(id, bot); }); bot.addCommandListener("!about [regex pattern]", /!about (.*)/, "random message with phrase", function(pattern) { persistence.matchMessage(pattern, bot); }); bot.addCommandListener("!uds", /!uds/, "random message about uds", function() { persistence.matchMessage('uds', bot); }); bot.addCommandListener("!aevans", /!aevans/, "so, message from aevans", function() { persistence.matchMessageForNick('aevans', '^so(\\s|,)', bot); }); bot.addCommandListener("!leaders [start index]", /!leaders\s*(\d*)/, "top users by message count", function(index) { persistence.leaders(index, bot); }); bot.addCommandListener("!playback start end", /!playback (\d+ \d+)/, "playback a series of messages", function(range) { var match = range.match(/(\d+) (\d+)/); if (match) { var start = match[1]; var end = match[2]; if (end - start >= 10) { bot.say("playback limited to 10 messages"); } else if (start >= end) { bot.say("start must be less than end"); } else { for (var i = start; i <= end; i++) { persistence.getMessage(i, bot); } } } }); bot.addCommandListener("!stats nick", /!stats (.*)/, "stats about a user", function(nick) { persistence.userStats(nick, bot); }); bot.addCommandListener("!alarm <time> -m <message>", /!alarm (.* -m .*)/, "set an alarm, valid time examples: 5s, 5m, 5h, 10:00, 14:30, 2:30pm", function(timeString, nick) { var matchInterval = timeString.match(/(\d+)([h|m|s]) -m (.*)/); var matchTime = timeString.match(/(\d{1,2}):(\d{2})(am|pm){0,1} -m (.*)/); if (matchInterval) { var timeNumber = matchInterval[1]; var timeUnit = matchInterval[2]; var sleepTime = timeNumber; if (timeUnit === 'h') { sleepTime = sleepTime * 60 * 60 * 1000; } else if (timeUnit === 'm') { sleepTime = sleepTime * 60 * 1000; } else if (timeUnit === 's') { sleepTime = sleepTime * 1000; } if (sleepTime < 2147483647) { bot.say("Alarm will go off in " + msToString(sleepTime)); setTimeout(function() { bot.say(nick + ': ' + matchInterval[3]); }, sleepTime); } else { bot.say("Delay exceeds maximum timeout, see: http://stackoverflow.com/questions/3468607/why-does-settimeout-break-for-large-millisecond-delay-values"); } } else if (matchTime) { var hour = parseInt(matchTime[1]); var minute = matchTime[2]; if (matchTime[3] === 'pm' && hour != 12) { hour = hour + 12; } else if (matchTime[3] === 'am' && hour === 12) { hour = 0; } var now = new Date(); var sleepTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0, 0) - now; if (sleepTime < 0) { sleepTime += 86400000; } bot.say("Alarm will go off in " + msToString(sleepTime)); setTimeout(function() { bot.say(nick + ': ' + matchTime[4]); }, sleepTime); } else { bot.say("Unknown time format!"); } }); bot.addCommandListener("!uname", /!uname/, "information about host", function() { child_process.exec('uname -a', function(error, stdout, stderr) { bot.say(stdout); }); }); bot.addCommandListener("!version", /!version/, "report node version", function() { bot.say("Node version = " + process.version); }); bot.addCommandListener("!help <cmd>", /!help(.*)/, "command help", function(cmd) { if (cmd) { bot.helpCommand(cmd); } else { bot.listCommands(); } }); bot.addCommandListener("!quote [symbol]", /!quote (.*)/, "get a stock quote", function(symbol) { var url = 'https://api.iextrading.com/1.0/stock/' + symbol + '/batch?types=quote'; request(url, function(error, response, body) { if (error) { console.log(error); } var result = JSON.parse(body); if (! error && result.quote && result.quote.latestPrice) { var mktCap = result.quote.marketCap; var mktCapString = ""; if (mktCap > 1000000000) { mktCapString = "$" + ((mktCap/1000000000).toFixed(2)) + "B"; } else if (mktCap > 1000000) { mktCapString = "$" + ((mktCap/1000000).toFixed(2)) + "M"; } var changePrefix = (result.quote.change > 0) ? '+' : ''; bot.say(result.quote.companyName + ' ... ' + '$' + String(result.quote.latestPrice) + ' ' + changePrefix + String(result.quote.change) + ' ' + changePrefix + String((result.quote.changePercent * 100).toFixed(2)) + '% ' + mktCapString); } else { bot.say("Unable to get a quote for " + symbol); } }); }); bot.addMessageListener("toggle", function(nick, message) { var check = message.match(/!toggle (.*)/); if (check) { var name = check[1]; var result = bot.toggleMessageListener(name); if (result) { bot.say("Message listener " + name + " is active"); } else { bot.say("Message listener " + name + " is inactive"); } return false; } return true; }); bot.addMessageListener("eval", function(nick, message) { var check = message.match(/!add (.*)/); if (check) { var msg = check[1]; var mlName = "user eval " + userEval++; bot.addMessageListener(mlName, function(nick, message) { var sandbox = { output: null, nick: nick, message: message }; vm.runInNewContext(msg, sandbox); if (sandbox.output) { bot.say(sandbox.output); return false; } return true; }); bot.say("Added message listener: " + mlName); return false; } return true; }); bot.addCommandListener("!define [phrase]", /!define (.*)/, "urban definition of a word or phrase", function(msg) { var data = ""; var request = require('request'); request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) { if (!error && response.statusCode == 200) { var urbanresult = JSON.parse(body); bot.say(urbanresult.list[0].definition); } }) }); bot.addCommandListener("!example [phrase]", /!example (.*)/, "Use of urban definition of a word or phrase in a sentence", function(msg) { var data = ""; var request = require('request'); request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) { if (!error && response.statusCode == 200) { var urbanresult = JSON.parse(body); bot.say(urbanresult.list[0].example); } }) }); bot.addCommandListener("!showerthought", /!showerthought/, "Return a reddit shower thought", function(msg) { var data = ""; var request = require('request'); request("http://www.reddit.com/r/showerthoughts/.json", function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body) // Print the results var showerthought = JSON.parse(body); // There are many returned in the json. Get a count var showercount=showerthought.data.children.length var randomthought=Math.floor((Math.random() * showercount) + 1); console.log("Found " + showercount + " shower thoughts. Randomly returning number " + randomthought); bot.say(showerthought.data.children[randomthought].data.title); } }) }); bot.addCommandListener("!firstworldproblems", /!firstworldproblems/, "Return a reddit first world problem", function(msg) { var data = ""; var request = require('request'); request("http://www.reddit.com/r/firstworldproblems/.json", function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body) // Print the results var firstworldproblem = JSON.parse(body); // There are many returned in the json. Get a count var problemcount=firstworldproblem.data.children.length var randomproblem=Math.floor((Math.random() * problemcount) + 1); console.log("Found " + problemcount + " shower thoughts. Randomly returning number " + randomproblem); bot.say(firstworldproblem.data.children[randomproblem].data.title); } }) }); } module.exports = addBehaviors;
mmattozzi/botboy
behaviors.js
JavaScript
lgpl-3.0
12,397
/** * Copyright (C) 2015 Swift Navigation Inc. * Contact: Joshua Gross <[email protected]> * This source is subject to the license found in the file 'LICENSE' which must * be distributed together with this source. All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ var fs = require('fs'); var path = require('path'); var assert = require('assert'); var Readable = require('stream').Readable; var dispatch = require(path.resolve(__dirname, '../sbp/')).dispatch; var MsgPosLlh = require(path.resolve(__dirname, '../sbp/navigation')).MsgPosLlh; var MsgVelEcef = require(path.resolve(__dirname, '../sbp/navigation')).MsgVelEcef; var framedMessage = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x14, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; var corruptedMessageTooShort = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x12, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; var corruptedMessageTooLong = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x16, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; var corruptedMessageExtraPreamble = [0x55, 0x55, 0x02, 0x02, 0xcc, 0x04, 0x14, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; describe('dispatcher', function () { it('should read stream of bytes and dispatch callback for single framed message', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should read stream of bytes and dispatch callback for two framed message', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 2) { assert.equal(validMessages, 2); done(); } }); }); it('should read stream of bytes and dispatch callback for two framed message, with garbage in between', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage)); rs.push(new Buffer([0x54, 0x53, 0x00, 0x01])); rs.push(new Buffer(framedMessage)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 2) { assert.equal(validMessages, 2); done(); } }); }); it('should read stream of bytes and dispatch callback for three framed messages, with garbage before first message and last', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage.slice(2))); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage.slice(1))); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage.slice(3))); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage.slice(4))); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 3) { assert.equal(validMessages, 3); done(); } }); }); it('should read stream of bytes and dispatch callback for one valid message, ignore corrupt message', function (done) { var rs = new Readable(); rs.push(new Buffer(corruptedMessageTooShort)); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(corruptedMessageTooLong)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should read stream of bytes and dispatch callback for one valid message, ignore corrupt preamble', function (done) { var rs = new Readable(); rs.push(new Buffer(corruptedMessageExtraPreamble)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should whitelist messages properly - no whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgLlhPayload); rs.push(msgVelEcefPayload); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 2) { assert.equal(validMessages, 2); done(); } }); }); it('should whitelist messages properly - array whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgVelEcefPayload); rs.push(msgLlhPayload); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, [MsgPosLlh.prototype.msg_type], function (err, framedMessage) { assert.equal(framedMessage.msg_type, MsgPosLlh.prototype.msg_type); if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should whitelist messages properly - mask whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgVelEcefPayload); rs.push(msgLlhPayload); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, ~MsgVelEcef.prototype.msg_type, function (err, framedMessage) { assert.equal(framedMessage.msg_type, MsgPosLlh.prototype.msg_type); if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should whitelist messages properly - function whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgVelEcefPayload); rs.push(msgLlhPayload); rs.push(null); var callbacks = 0; var validMessages = 0; var whitelist = function (msgType) { return msgType === MsgVelEcef.prototype.msg_type; }; dispatch(rs, whitelist, function (err, framedMessage) { assert.equal(framedMessage.msg_type, MsgVelEcef.prototype.msg_type); if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); });
swift-nav/libsbp
javascript/tests/test_dispatch.js
JavaScript
lgpl-3.0
8,674
angular.module('dnsControllers', ['dnsServices', 'dnsModels']) .controller('dnsCtrl', function($scope, $location, socket, Hosts, Zone) { $scope.dns = { zone : Zone.get(), hosts : Hosts.list() }; socket.on('new:host', function (host) { var found = false; if ($scope.dns.hosts.records) { for (var i = 0 ; i < $scope.dns.hosts.records.length ; ++i) { if ($scope.dns.hosts.records[i].name === host.name) { found = true; $scope.dns.hosts.records[i].record = host.record; break; } } } if (!found) { if (!$scope.dns.hosts.records) $scope.dns.hosts.records = []; $scope.dns.hosts.records.push(host); } }); socket.on('delete:host', function (host) { if ($scope.dns.hosts.records) { for (var i = 0 ; i < $scope.dns.hosts.records.length ; ++i) { if ($scope.dns.hosts.records[i].name === host.name) { $scope.dns.hosts.records.splice(i, 1); break; } } } }); }) ;
binRick/thc.digital
dnsServer/public/js/controllers/dns-controller.js
JavaScript
unlicense
1,158
const fs = require("fs"); const assert = require("assert"); const testMngr = require("test/testManager"); const FormData = require("form-data"); describe("Document No Auth", function () { let client; before(async function () { if (!testMngr.app.config.document) { this.skip(); } client = testMngr.client("bob"); }); after(async () => {}); it("should get a 401 when getting all documents", async () => { try { let tickets = await client.get("v1/document"); assert(tickets); } catch (error) { console.log("error ", error); assert.equal(error.response.status, 401); assert.equal(error.response.data, "Unauthorized"); } }); }); describe("Document", function () { let client; before(async function () { if (!testMngr.app.config.document) { this.skip(); } client = testMngr.client("alice"); await client.login(); }); after(async () => {}); it("should upload a document", async () => { const formData = new FormData(); formData.append("name", "IMG_20180316_153034.jpg"); formData.append("file_type", "image/jpeg"); formData.append( "photo", fs.createReadStream(__dirname + "/testDocument.js") ); await client.upload("v1/document", formData); const formData2 = new FormData(); formData2.append("name", "IMG_20180316_153035.jpg"); formData2.append("file_type", "image/jpeg"); formData2.append( "photo", fs.createReadStream(__dirname + "/testDocument.js") ); await client.upload("v1/document", formData2); //assert(document); }); it("should upload a specific document", async () => { const formData = new FormData(); formData.append("name", "IMG_20180316_153034.jpg"); formData.append("file_type", "image/jpeg"); formData.append( "photo", fs.createReadStream(__dirname + "/testDocument.js") ); const type = "profile_picture"; await client.upload(`v1/document/${type}`, formData); const picture = await client.get(`v1/document/${type}`); assert.equal(picture.type, type); assert(picture.content); }); it("should return an error when no file is present", async () => { const formData = new FormData(); formData.append("name", "IMG_20180316_153034.jpg"); formData.append("file_type", "image/jpeg"); try { await client.upload("v1/document", formData); assert(false); } catch (error) { assert.equal(error.response.status, 400); } }); });
FredericHeem/starhackit
server/src/plugins/document/testDocument.js
JavaScript
unlicense
2,513
import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import { Navigation } from 'react-router'; import recipeActions from 'actions/recipe'; import recipeStore from 'stores/recipe'; import SapCalculator from 'components/sapCalculator'; import FormSaveRecipe from 'components/formSaveRecipe'; import Imageable from 'components/imageable'; import ImageableEdit from 'components/imageableEdit'; export default React.createClass( { statics: { willTransitionTo: function ( transition, params ) { recipeActions.getRecipeById( params.id ); } }, mixins: [ Navigation, Reflux.connect( recipeStore, 'recipe' ) ], render() { document.title = 'Soapee - Edit'; return ( <div id="recipe-edit"> <SapCalculator recipe={ this.state.recipe } /> { _.get(this.state, 'recipe.recipe.images.length' ) > 0 && <div className="row"> <div className="col-md-12"> <legend>Delete Photos?</legend> <ImageableEdit images={ this.state.recipe.recipe.images } /> </div> </div> } { this.state.recipe.countWeights() > 0 && <div className="row"> <FormSaveRecipe recipe={ this.state.recipe } buttonCancel={ true } buttonCaptionSave={ this.saveCaption() } buttonDisabledSave={ this.state.saving } onSave={ this.saveRecipe } onSaveAs={ this.saveAsRecipe } onCancel={ this.goBackToView } /> </div> } </div> ); }, startImageUploadHookFn( fnToStartUploads ) { this.startUploads = fnToStartUploads; }, saveCaption() { return this.state.saving ? 'Saving Recipe' : 'Save Recipe'; }, saveRecipe() { return this.doSaveAction( recipeActions.updateRecipe ); }, saveAsRecipe() { return this.doSaveAction( recipeActions.createRecipe ); }, doSaveAction( action ) { this.setState( { saving: true } ); recipeStore.calculate(); return action( this.state.recipe ) .then( this.toRecipeView.bind( this ) ) .finally(() => this.setState({ saving: false })); function uploadImages() { this.startUploads( this.state.recipe.getModelValue( 'id' ) ); } }, printRecipe() { this.replaceWith( 'printRecipe', { id: this.state.recipe.getModelValue( 'id' ) } ); }, goBackToView() { this.toRecipeView( this.state.recipe.recipe ); }, toRecipeView(recipe) { this.transitionTo( 'recipe', { id: recipe.id} ); } } );
nazar/soapee-ui
src/app/views/recipeEdit.js
JavaScript
unlicense
3,163
var AppGlobal = { exposePrivateVariablesForTesting: true }; var testableObject = function (exposePrivateVariablesForTesting) { var _privateVar = "can't see this"; var _publicVar = "we see this fine"; function _privateFunction() { console.log("Executed Private"); } function _exposedFunction() { console.log("Exposed Function"); } var returnValue = { ExposedFunction: _exposedFunction, ExposedVariable: _publicVar }; if (exposePrivateVariablesForTesting) { $.extend(returnValue, { PrivateVar: _privateVar, PrivateFunction: _privateFunction }); } return returnValue; }(AppGlobal.exposePrivateVariablesForTesting); testableObject.ExposedFunction(); console.log(testableObject.ExposedVariable); testableObject.PrivateFunction(); console.log(testableObject.PrivateVar);
Grax32/JurassicPlayground
JurassicPlayground/Scripts/RevealingModuleVariant.js
JavaScript
unlicense
898
import when from 'when'; import { post } from 'utils/http'; import baseUrl from 'utils/baseUrl'; export function requestPasswordReset( email ) { return when( post( baseUrl( 'auth/reset_password' ), { params: { email } } ) ); } export function verifyResetPasswordToken( token, password) { return when( post( baseUrl( 'auth/verify_reset_password_token' ), { params: { token, password } } ) ); }
FrontSmith/FSFramework
client/src/app/resources/resets.js
JavaScript
unlicense
540
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('gftApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope // place here mocked dependencies }); })); it('should attach a list of awesomeThings to the scope', function () { expect(MainCtrl.awesomeThings.length).toBe(3); }); });
murilobeltrame/gft
ui/test/spec/controllers/main.js
JavaScript
unlicense
545
(function(synth, lang, langIndex) { var voice = synth.getVoices().filter(voice => voice.lang === lang)[langIndex], text = window.getSelection().toString(); function speak(text, voice) { var utterance = new SpeechSynthesisUtterance(text); utterance.voice = voice; utterance.lang = lang; utterance.rate = .4; synth.speak(utterance); } speak(text, voice); })(window.speechSynthesis, 'pt-PT', 0);
pansay/tts_bookmarklets
read_selection_in_pt_PT.js
JavaScript
unlicense
461
(function (parent, $, element) { function loadEvents() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); return [ { title: 'Appointment 1', start: new Date(y, m, d, 10), end: new Date(y, m, d, 11), allDay: false, editable: true, startEditable: true, durationEditable: true, plantpot: 'coffeetable' }, { title: 'Appointment 2', start: new Date(y, m, d, 11, 30), end: new Date(y, m, d, 12), allDay: false } ]; } function onEventClick(event) { alert(event.plantpot); alert($(element).fullCalendar('clientEvents').length); } function render() { $(document).ready(function() { $(element).fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, events: loadEvents(), eventClick: onEventClick }); }); } parent.schedule = { load: render }; })(window, $, '#calendar'); window.schedule.load();
lowds/scheduler
src/Scheduler.UI/js/schedule.js
JavaScript
apache-2.0
1,409
#!/usr/bin/env node /** * Copyright IBM Corp. 2019, 2019 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable no-console */ 'use strict'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', (error) => { console.error(error); }); var chalk = require('chalk'); var currentNodeVersion = process.versions.node; var semver = currentNodeVersion.split('.'); var major = semver[0]; if (major < 14) { console.error( chalk.red( `You are running Node ${currentNodeVersion}.\n` + `carbon-upgrade requires Node 14 or higher, please update your ` + `version of Node.` ) ); process.exit(1); } var main = require('../src/cli'); main(process).catch((error) => { console.error(error); process.exit(1); });
carbon-design-system/carbon-components
packages/upgrade/bin/carbon-upgrade.js
JavaScript
apache-2.0
1,034
var studio_locale = {lc:{"ar":function(n){ if (n === 0) { return 'zero'; } if (n == 1) { return 'one'; } if (n == 2) { return 'two'; } if ((n % 100) >= 3 && (n % 100) <= 10 && n == Math.floor(n)) { return 'few'; } if ((n % 100) >= 11 && (n % 100) <= 99 && n == Math.floor(n)) { return 'many'; } return 'other'; },"en":function(n){return n===1?"one":"other"},"bg":function(n){return n===1?"one":"other"},"bn":function(n){return n===1?"one":"other"},"ca":function(n){return n===1?"one":"other"},"cs":function(n){ if (n == 1) { return 'one'; } if (n == 2 || n == 3 || n == 4) { return 'few'; } return 'other'; },"da":function(n){return n===1?"one":"other"},"de":function(n){return n===1?"one":"other"},"el":function(n){return n===1?"one":"other"},"es":function(n){return n===1?"one":"other"},"et":function(n){return n===1?"one":"other"},"eu":function(n){return n===1?"one":"other"},"fa":function(n){return "other"},"fi":function(n){return n===1?"one":"other"},"fil":function(n){return n===0||n==1?"one":"other"},"fr":function(n){return Math.floor(n)===0||Math.floor(n)==1?"one":"other"},"ga":function(n){return n==1?"one":(n==2?"two":"other")},"gl":function(n){return n===1?"one":"other"},"he":function(n){return n===1?"one":"other"},"hi":function(n){return n===0||n==1?"one":"other"},"hr":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"hu":function(n){return "other"},"id":function(n){return "other"},"is":function(n){ return ((n%10) === 1 && (n%100) !== 11) ? 'one' : 'other'; },"it":function(n){return n===1?"one":"other"},"ja":function(n){return "other"},"ko":function(n){return "other"},"lt":function(n){ if ((n % 10) == 1 && ((n % 100) < 11 || (n % 100) > 19)) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 9 && ((n % 100) < 11 || (n % 100) > 19) && n == Math.floor(n)) { return 'few'; } return 'other'; },"lv":function(n){ if (n === 0) { return 'zero'; } if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } return 'other'; },"mk":function(n){return (n%10)==1&&n!=11?"one":"other"},"mr":function(n){return n===1?"one":"other"},"ms":function(n){return "other"},"mt":function(n){ if (n == 1) { return 'one'; } if (n === 0 || ((n % 100) >= 2 && (n % 100) <= 4 && n == Math.floor(n))) { return 'few'; } if ((n % 100) >= 11 && (n % 100) <= 19 && n == Math.floor(n)) { return 'many'; } return 'other'; },"nl":function(n){return n===1?"one":"other"},"no":function(n){return n===1?"one":"other"},"pl":function(n){ if (n == 1) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || n != 1 && (n % 10) == 1 || ((n % 10) >= 5 && (n % 10) <= 9 || (n % 100) >= 12 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"pt":function(n){return n===1?"one":"other"},"ro":function(n){ if (n == 1) { return 'one'; } if (n === 0 || n != 1 && (n % 100) >= 1 && (n % 100) <= 19 && n == Math.floor(n)) { return 'few'; } return 'other'; },"ru":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"sk":function(n){ if (n == 1) { return 'one'; } if (n == 2 || n == 3 || n == 4) { return 'few'; } return 'other'; },"sl":function(n){ if ((n % 100) == 1) { return 'one'; } if ((n % 100) == 2) { return 'two'; } if ((n % 100) == 3 || (n % 100) == 4) { return 'few'; } return 'other'; },"sq":function(n){return n===1?"one":"other"},"sr":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"sv":function(n){return n===1?"one":"other"},"ta":function(n){return n===1?"one":"other"},"th":function(n){return "other"},"tr":function(n){return n===1?"one":"other"},"uk":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"ur":function(n){return n===1?"one":"other"},"vi":function(n){return "other"},"zh":function(n){return "other"}}, c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")}, n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)}, v:function(d,k){studio_locale.c(d,k);return d[k]}, p:function(d,k,o,l,p){studio_locale.c(d,k);return d[k] in p?p[d[k]]:(k=studio_locale.lc[l](d[k]-o),k in p?p[k]:p.other)}, s:function(d,k,p){studio_locale.c(d,k);return d[k] in p?p[d[k]]:p.other}}; (window.blockly = window.blockly || {}).studio_locale = { "actor":function(d){return "herec"}, "addItems1":function(d){return "přidat 1 položku typu"}, "addItems2":function(d){return "přidat 2 položky typu"}, "addItems3":function(d){return "přidat 3 položky typu"}, "addItems5":function(d){return "přidat 5 položek typu"}, "addItems10":function(d){return "přidat 10 položek typu"}, "addItemsRandom":function(d){return "přidat náhodné položky typu"}, "addItemsTooltip":function(d){return "Přidat položky na scénu."}, "alienInvasion":function(d){return "Mimozemská invaze!"}, "backgroundBlack":function(d){return "černý"}, "backgroundCave":function(d){return "jeskyně"}, "backgroundCloudy":function(d){return "zataženo"}, "backgroundHardcourt":function(d){return "tvrdé hřiště"}, "backgroundNight":function(d){return "noc"}, "backgroundUnderwater":function(d){return "pod vodou"}, "backgroundCity":function(d){return "město"}, "backgroundDesert":function(d){return "poušť"}, "backgroundRainbow":function(d){return "duha"}, "backgroundSoccer":function(d){return "fotbal"}, "backgroundSpace":function(d){return "vesmír"}, "backgroundTennis":function(d){return "tenis"}, "backgroundWinter":function(d){return "zima"}, "catActions":function(d){return "Akce"}, "catControl":function(d){return "Smyčky"}, "catEvents":function(d){return "Události"}, "catLogic":function(d){return "Logika"}, "catMath":function(d){return "Matematika"}, "catProcedures":function(d){return "Funkce"}, "catText":function(d){return "text"}, "catVariables":function(d){return "Proměnné"}, "changeScoreTooltip":function(d){return "Přidat nebo odebrat bod ze skóre."}, "changeScoreTooltipK1":function(d){return "Přidat bod."}, "continue":function(d){return "Pokračovat"}, "decrementPlayerScore":function(d){return "Odebrat bod"}, "defaultSayText":function(d){return "Piš zde"}, "dropletBlock_changeScore_description":function(d){return "Přidat nebo odebrat bod ze skóre."}, "dropletBlock_penColour_description":function(d){return "Sets the color of the line drawn behind the turtle as it moves"}, "dropletBlock_penColour_param0":function(d){return "color"}, "dropletBlock_setBackground_description":function(d){return "Nastavit obrázek pozadí"}, "dropletBlock_setSpriteEmotion_description":function(d){return "Nastaví náladu herce"}, "dropletBlock_setSpritePosition_description":function(d){return "Okamžitě přesune herce na zadané místo."}, "dropletBlock_setSpriteSpeed_description":function(d){return "Nastaví rychlost herce"}, "dropletBlock_setSprite_description":function(d){return "Nastaví obrázek herce"}, "dropletBlock_throw_description":function(d){return "Hodí střelu od zadaného herce."}, "dropletBlock_vanish_description":function(d){return "Herec zmizí."}, "emotion":function(d){return "nálada"}, "finalLevel":function(d){return "Dobrá práce! Vyřešil si poslední hádanku."}, "for":function(d){return "pro"}, "hello":function(d){return "ahoj"}, "helloWorld":function(d){return "Ahoj světe!"}, "incrementPlayerScore":function(d){return "Bod"}, "itemBlueFireball":function(d){return "modrá ohnivá koule"}, "itemPurpleFireball":function(d){return "fialová ohnivá koule"}, "itemRedFireball":function(d){return "červená ohnivá koule"}, "itemYellowHearts":function(d){return "žlutá srdce"}, "itemPurpleHearts":function(d){return "fialová srdce"}, "itemRedHearts":function(d){return "červená srdce"}, "itemRandom":function(d){return "náhodně"}, "itemAnna":function(d){return "hák"}, "itemElsa":function(d){return "jiskra"}, "itemHiro":function(d){return "mikroboti"}, "itemBaymax":function(d){return "raketa"}, "itemRapunzel":function(d){return "pánev"}, "itemCherry":function(d){return "třešeň"}, "itemIce":function(d){return "led"}, "itemDuck":function(d){return "kachna"}, "makeProjectileDisappear":function(d){return "zmizet"}, "makeProjectileBounce":function(d){return "odrazit"}, "makeProjectileBlueFireball":function(d){return "udělej modrou ohnivou kouli"}, "makeProjectilePurpleFireball":function(d){return "udělej fialovou ohnivou kouli"}, "makeProjectileRedFireball":function(d){return "udělej červenou ohnivou kouli"}, "makeProjectileYellowHearts":function(d){return "udělej žlutá srdce"}, "makeProjectilePurpleHearts":function(d){return "udělej fialová srdce"}, "makeProjectileRedHearts":function(d){return "udělej červená srdce"}, "makeProjectileTooltip":function(d){return "Nechat střelu narazit a zmizet nebo odrazit."}, "makeYourOwn":function(d){return "Vytvořit si vlastní hru v Hravé laboratoři"}, "moveDirectionDown":function(d){return "dolů"}, "moveDirectionLeft":function(d){return "vlevo"}, "moveDirectionRight":function(d){return "vpravo"}, "moveDirectionUp":function(d){return "nahoru"}, "moveDirectionRandom":function(d){return "náhodně"}, "moveDistance25":function(d){return "25 pixelů"}, "moveDistance50":function(d){return "50 pixelů"}, "moveDistance100":function(d){return "100 pixelů"}, "moveDistance200":function(d){return "200 pixelů"}, "moveDistance400":function(d){return "400 pixelů"}, "moveDistancePixels":function(d){return "pixely"}, "moveDistanceRandom":function(d){return "náhodné pixely"}, "moveDistanceTooltip":function(d){return "Přemístit herce určenou vzdálenost ve specifickém směru."}, "moveSprite":function(d){return "pohyb"}, "moveSpriteN":function(d){return "pohnout hercem "+studio_locale.v(d,"spriteIndex")}, "toXY":function(d){return "do x,y"}, "moveDown":function(d){return "pohyb dolů"}, "moveDownTooltip":function(d){return "pohnout hercem dolů."}, "moveLeft":function(d){return "pohnout vlevo"}, "moveLeftTooltip":function(d){return "pohnout hercem vlevo."}, "moveRight":function(d){return "pohnout vpravo"}, "moveRightTooltip":function(d){return "pohnout hercem vpravo."}, "moveUp":function(d){return "pohnout nahoru"}, "moveUpTooltip":function(d){return "pohnout hercem nahoru."}, "moveTooltip":function(d){return "pohnout hercem."}, "nextLevel":function(d){return "Dobrá práce! Dokončil jsi tuto hádanku."}, "no":function(d){return "Ne"}, "numBlocksNeeded":function(d){return "Tato hádanka může být vyřešena pomocí %1 bloků."}, "onEventTooltip":function(d){return "Spustit kód v reakci na konkrétní událost."}, "ouchExclamation":function(d){return "Au!"}, "playSoundCrunch":function(d){return "přehrát zvuk křupání"}, "playSoundGoal1":function(d){return "přehrát zvuk cíl 1"}, "playSoundGoal2":function(d){return "přehrát zvuk cíl 2"}, "playSoundHit":function(d){return "přehrát zvuk zásah"}, "playSoundLosePoint":function(d){return "přehrát zvuk ztráta bodu"}, "playSoundLosePoint2":function(d){return "přehrát zvuk ztráta bodu 2"}, "playSoundRetro":function(d){return "přehrát zvuk \"retro\""}, "playSoundRubber":function(d){return "přehrát zvuk guma"}, "playSoundSlap":function(d){return "přehrát zvuk plácnutí"}, "playSoundTooltip":function(d){return "Přehraj vybraný zvuk."}, "playSoundWinPoint":function(d){return "přehrát zvuk získaný bod"}, "playSoundWinPoint2":function(d){return "přehrát zvuk získaný bod 2"}, "playSoundWood":function(d){return "přehrát zvuk dřevo"}, "positionOutTopLeft":function(d){return "na pozici nad horní levou pozicí"}, "positionOutTopRight":function(d){return "na pozici nad horní pravou pozicí"}, "positionTopOutLeft":function(d){return "na horní vnější levou pozici"}, "positionTopLeft":function(d){return "na horní levou pozici"}, "positionTopCenter":function(d){return "na horní středovou pozici"}, "positionTopRight":function(d){return "na horní pravou pozici"}, "positionTopOutRight":function(d){return "na horní vnější pravou pozici"}, "positionMiddleLeft":function(d){return "na střední levou pozici"}, "positionMiddleCenter":function(d){return "na prostřední středovou pozici"}, "positionMiddleRight":function(d){return "na prostřední pravou pozici"}, "positionBottomOutLeft":function(d){return "na spodní vnější levou pozici"}, "positionBottomLeft":function(d){return "na spodní levou pozici"}, "positionBottomCenter":function(d){return "na spodní středovou pozici"}, "positionBottomRight":function(d){return "na spodní pravou pozici"}, "positionBottomOutRight":function(d){return "na spodní vnější pravou pozici"}, "positionOutBottomLeft":function(d){return "na pozici pod spodní levou pozicí"}, "positionOutBottomRight":function(d){return "na pozici pod spodní pravou pozicí"}, "positionRandom":function(d){return "na náhodnou pozici"}, "projectileBlueFireball":function(d){return "modrá ohnivá koule"}, "projectilePurpleFireball":function(d){return "fialová ohnivá koule"}, "projectileRedFireball":function(d){return "červená ohnivá koule"}, "projectileYellowHearts":function(d){return "žlutá srdce"}, "projectilePurpleHearts":function(d){return "fialová srdce"}, "projectileRedHearts":function(d){return "červená srdce"}, "projectileRandom":function(d){return "náhodně"}, "projectileAnna":function(d){return "hák"}, "projectileElsa":function(d){return "jiskra"}, "projectileHiro":function(d){return "mikroboti"}, "projectileBaymax":function(d){return "raketa"}, "projectileRapunzel":function(d){return "pánev"}, "projectileCherry":function(d){return "třešeň"}, "projectileIce":function(d){return "led"}, "projectileDuck":function(d){return "kachna"}, "reinfFeedbackMsg":function(d){return "Můžeš stisknout tlačítko \"Pokračovat v hraní\" pro návrat do hraní tvé historie."}, "repeatForever":function(d){return "opakujte navždy"}, "repeatDo":function(d){return "dělej"}, "repeatForeverTooltip":function(d){return "Provést akce v tomto bloku opakovaně dokud je spuštěn příběh."}, "saySprite":function(d){return "řekni"}, "saySpriteN":function(d){return "herec "+studio_locale.v(d,"spriteIndex")+" říká"}, "saySpriteTooltip":function(d){return "Zobrazit komiksovou bublinu s přidruženým textem od zvoleného herece."}, "saySpriteChoices_0":function(d){return "Ahoj."}, "saySpriteChoices_1":function(d){return "Ahoj všichni."}, "saySpriteChoices_2":function(d){return "Jak se máš?"}, "saySpriteChoices_3":function(d){return "Dobré ráno"}, "saySpriteChoices_4":function(d){return "Dobré odpoledne"}, "saySpriteChoices_5":function(d){return "Dobrou noc"}, "saySpriteChoices_6":function(d){return "Dobrý večer"}, "saySpriteChoices_7":function(d){return "Co je nového?"}, "saySpriteChoices_8":function(d){return "Co?"}, "saySpriteChoices_9":function(d){return "Kde?"}, "saySpriteChoices_10":function(d){return "Kdy?"}, "saySpriteChoices_11":function(d){return "Dobře."}, "saySpriteChoices_12":function(d){return "Skvělé!"}, "saySpriteChoices_13":function(d){return "Dobře."}, "saySpriteChoices_14":function(d){return "Není to zlé."}, "saySpriteChoices_15":function(d){return "Hodně štěstí."}, "saySpriteChoices_16":function(d){return "Ano"}, "saySpriteChoices_17":function(d){return "Ne"}, "saySpriteChoices_18":function(d){return "Dobře"}, "saySpriteChoices_19":function(d){return "Pěkný hod!"}, "saySpriteChoices_20":function(d){return "Hezký den."}, "saySpriteChoices_21":function(d){return "Ahoj."}, "saySpriteChoices_22":function(d){return "Hned jsem zpátky."}, "saySpriteChoices_23":function(d){return "Zítra ahoj!"}, "saySpriteChoices_24":function(d){return "Zatím se měj!"}, "saySpriteChoices_25":function(d){return "Opatruj se!"}, "saySpriteChoices_26":function(d){return "Užijte si!"}, "saySpriteChoices_27":function(d){return "Musím jít."}, "saySpriteChoices_28":function(d){return "Chcete být přátelé?"}, "saySpriteChoices_29":function(d){return "Skvělá práce!"}, "saySpriteChoices_30":function(d){return "Pane jo!"}, "saySpriteChoices_31":function(d){return "Jaj!"}, "saySpriteChoices_32":function(d){return "Těší mě."}, "saySpriteChoices_33":function(d){return "Dobře!"}, "saySpriteChoices_34":function(d){return "Děkuji"}, "saySpriteChoices_35":function(d){return "Ne, děkuji"}, "saySpriteChoices_36":function(d){return "Aaaaaah!"}, "saySpriteChoices_37":function(d){return "Nevadí"}, "saySpriteChoices_38":function(d){return "Dnes"}, "saySpriteChoices_39":function(d){return "Zítra"}, "saySpriteChoices_40":function(d){return "Včera"}, "saySpriteChoices_41":function(d){return "Našel jsem tě!"}, "saySpriteChoices_42":function(d){return "Našel si mě!"}, "saySpriteChoices_43":function(d){return "10, 9, 8, 7, 6, 5, 4, 3, 2, 1!"}, "saySpriteChoices_44":function(d){return "Jsi skvělý!"}, "saySpriteChoices_45":function(d){return "Jsi vtipný!"}, "saySpriteChoices_46":function(d){return "Jsi pošetilý! "}, "saySpriteChoices_47":function(d){return "Jsi dobrý přítel!"}, "saySpriteChoices_48":function(d){return "Dávej pozor!"}, "saySpriteChoices_49":function(d){return "Kachna!"}, "saySpriteChoices_50":function(d){return "Mám tě!"}, "saySpriteChoices_51":function(d){return "Au!"}, "saySpriteChoices_52":function(d){return "Promiň!"}, "saySpriteChoices_53":function(d){return "Opatrně!"}, "saySpriteChoices_54":function(d){return "Uau!"}, "saySpriteChoices_55":function(d){return "Ups!"}, "saySpriteChoices_56":function(d){return "Skoro si mě dostal!"}, "saySpriteChoices_57":function(d){return "Dobrý pokus!"}, "saySpriteChoices_58":function(d){return "Nemůžeš mě chytit!"}, "scoreText":function(d){return "Body: "+studio_locale.v(d,"playerScore")}, "setBackground":function(d){return "nastavit pozadí"}, "setBackgroundRandom":function(d){return "nastavit náhodné pozadí"}, "setBackgroundBlack":function(d){return "nastavit černé pozadí"}, "setBackgroundCave":function(d){return "nastavit pozadí jeskyně"}, "setBackgroundCloudy":function(d){return "nastavit pozadí mraky"}, "setBackgroundHardcourt":function(d){return "nastavit pozadí tvrdé hřiště"}, "setBackgroundNight":function(d){return "nastavit pozadí noc"}, "setBackgroundUnderwater":function(d){return "nastavit pozadí pod vodou"}, "setBackgroundCity":function(d){return "nastavit pozadí město"}, "setBackgroundDesert":function(d){return "nastavit pozadí poušť"}, "setBackgroundRainbow":function(d){return "nastavit pozadí duha"}, "setBackgroundSoccer":function(d){return "nastavit pozadí fotbal"}, "setBackgroundSpace":function(d){return "nastavit pozadí vesmír"}, "setBackgroundTennis":function(d){return "nastavit pozadí tenis"}, "setBackgroundWinter":function(d){return "nastavit pozadí zima"}, "setBackgroundLeafy":function(d){return "nastavit listnaté pozadí"}, "setBackgroundGrassy":function(d){return "nastavit travnaté pozadí"}, "setBackgroundFlower":function(d){return "nastavit květinové pozadí"}, "setBackgroundTile":function(d){return "nastavit dlaždicové pozadí"}, "setBackgroundIcy":function(d){return "nastavit ledové pozadí"}, "setBackgroundSnowy":function(d){return "nastavit zasněžené pozadí"}, "setBackgroundTooltip":function(d){return "Nastavit obrázek pozadí"}, "setEnemySpeed":function(d){return "nastavit rychlost protivníka"}, "setPlayerSpeed":function(d){return "nastavit rychlost hráče"}, "setScoreText":function(d){return "nastavit body"}, "setScoreTextTooltip":function(d){return "Nastaví text, který se má zobrazit v oblasti pro výsledek."}, "setSpriteEmotionAngry":function(d){return "na nahněvanou náladu"}, "setSpriteEmotionHappy":function(d){return "na šťastnou náladu"}, "setSpriteEmotionNormal":function(d){return "na normální náladu"}, "setSpriteEmotionRandom":function(d){return "na náhodnou náladu"}, "setSpriteEmotionSad":function(d){return "na smutnou náladu"}, "setSpriteEmotionTooltip":function(d){return "Nastaví náladu herce"}, "setSpriteAlien":function(d){return "na obrázek mimozemšťana"}, "setSpriteBat":function(d){return "na obrázek netopýra"}, "setSpriteBird":function(d){return "na obrázek ptáka"}, "setSpriteCat":function(d){return "na obrázek kočky"}, "setSpriteCaveBoy":function(d){return "na obrázek jeskynního chlapece"}, "setSpriteCaveGirl":function(d){return "na obrázek jeskynní dívky"}, "setSpriteDinosaur":function(d){return "na obrázek dinosaura"}, "setSpriteDog":function(d){return "na obrázek psa"}, "setSpriteDragon":function(d){return "na obrázek draka"}, "setSpriteGhost":function(d){return "na obrázek ducha"}, "setSpriteHidden":function(d){return "na skrytý obrázek"}, "setSpriteHideK1":function(d){return "skrýt"}, "setSpriteAnna":function(d){return "na Anin obrázek"}, "setSpriteElsa":function(d){return "na Elsin obrázek"}, "setSpriteHiro":function(d){return "na obrázek Hira"}, "setSpriteBaymax":function(d){return "na obrázek Baymaxe"}, "setSpriteRapunzel":function(d){return "na obrázek Rapunzela"}, "setSpriteKnight":function(d){return "na obrázek rytíře"}, "setSpriteMonster":function(d){return "na obrázek příšery"}, "setSpriteNinja":function(d){return "na obrázek maskovaného ninjy"}, "setSpriteOctopus":function(d){return "na obrázek chobotnice"}, "setSpritePenguin":function(d){return "na obrázek tučňáka"}, "setSpritePirate":function(d){return "na obrázek piráta"}, "setSpritePrincess":function(d){return "na obrázek princezny"}, "setSpriteRandom":function(d){return "na náhodný obrázek"}, "setSpriteRobot":function(d){return "na obrázek robota"}, "setSpriteShowK1":function(d){return "zobrazit"}, "setSpriteSpacebot":function(d){return "na obrázek vesmírného robota"}, "setSpriteSoccerGirl":function(d){return "na obrázek fotbalistky"}, "setSpriteSoccerBoy":function(d){return "na obrázek fotbalisty"}, "setSpriteSquirrel":function(d){return "na obrázek veverky"}, "setSpriteTennisGirl":function(d){return "na obrázek tenistky"}, "setSpriteTennisBoy":function(d){return "na obrázek tenisty"}, "setSpriteUnicorn":function(d){return "na obrázek jednorožce"}, "setSpriteWitch":function(d){return "na obrázek čarodějnice"}, "setSpriteWizard":function(d){return "na obrázek čaroděje"}, "setSpritePositionTooltip":function(d){return "Okamžitě přesune herce na zadané místo."}, "setSpriteK1Tooltip":function(d){return "Zobrazí nebo skryje zadaného herce."}, "setSpriteTooltip":function(d){return "Nastaví obrázek herce"}, "setSpriteSizeRandom":function(d){return "na náhodnou velikost"}, "setSpriteSizeVerySmall":function(d){return "na velmi malou velikost"}, "setSpriteSizeSmall":function(d){return "na malou velikost"}, "setSpriteSizeNormal":function(d){return "na normální velikost"}, "setSpriteSizeLarge":function(d){return "na velkou velikost"}, "setSpriteSizeVeryLarge":function(d){return "na velmi velkou velikost"}, "setSpriteSizeTooltip":function(d){return "Nastaví velikost herce"}, "setSpriteSpeedRandom":function(d){return "na náhodnou rychlost"}, "setSpriteSpeedVerySlow":function(d){return "na velmi pomalou rychlost"}, "setSpriteSpeedSlow":function(d){return "na pomalou rychlost"}, "setSpriteSpeedNormal":function(d){return "na normální rychlost"}, "setSpriteSpeedFast":function(d){return "na rychlou rychlost"}, "setSpriteSpeedVeryFast":function(d){return "na velmi rychlou rychlost"}, "setSpriteSpeedTooltip":function(d){return "Nastaví rychlost herce"}, "setSpriteZombie":function(d){return "na obrázek zombie"}, "shareStudioTwitter":function(d){return "Podívejte se na aplikaci, kterou jsem udělal. Napsal jsem to sám s @codeorg"}, "shareGame":function(d){return "Sdílej svůj příběh:"}, "showCoordinates":function(d){return "Zobrazit souřadnice"}, "showCoordinatesTooltip":function(d){return "zobrazí souřadnice hlavní postavy na obrazovce"}, "showTitleScreen":function(d){return "zobrazit úvodní obrazovku"}, "showTitleScreenTitle":function(d){return "nadpis"}, "showTitleScreenText":function(d){return "text"}, "showTSDefTitle":function(d){return "zde napiš nadpis"}, "showTSDefText":function(d){return "zde napiš text"}, "showTitleScreenTooltip":function(d){return "Zobrazit úvodní obrazovka k přidruženému názvu a textu."}, "size":function(d){return "velikost"}, "setSprite":function(d){return "nastavit"}, "setSpriteN":function(d){return "nastavit herece "+studio_locale.v(d,"spriteIndex")}, "soundCrunch":function(d){return "křupnutí"}, "soundGoal1":function(d){return "cíl 1"}, "soundGoal2":function(d){return "cíl 2"}, "soundHit":function(d){return "zásah"}, "soundLosePoint":function(d){return "ztracený bod"}, "soundLosePoint2":function(d){return "ztracený bod 2"}, "soundRetro":function(d){return "retro"}, "soundRubber":function(d){return "guma"}, "soundSlap":function(d){return "facka"}, "soundWinPoint":function(d){return "vyhraný bod"}, "soundWinPoint2":function(d){return "vyhraný bod 2"}, "soundWood":function(d){return "dřevo"}, "speed":function(d){return "rychlost"}, "startSetValue":function(d){return "start (funkce)"}, "startSetVars":function(d){return "game_vars (nadpis, podnadpis, pozadí, cíl, nebezpečí, hráč)"}, "startSetFuncs":function(d){return "game_funcs (aktualizuj-cíl, aktualizuj-nebezpečí, aktualizuj-hráče, kolize?, na-obrazovce?)"}, "stopSprite":function(d){return "zastavit"}, "stopSpriteN":function(d){return "zastavit herce "+studio_locale.v(d,"spriteIndex")}, "stopTooltip":function(d){return "Zastaví pohyb herce."}, "throwSprite":function(d){return "hoď"}, "throwSpriteN":function(d){return "herec "+studio_locale.v(d,"spriteIndex")+" hodí"}, "throwTooltip":function(d){return "Hodí střelu od zadaného herce."}, "vanish":function(d){return "zmiz"}, "vanishActorN":function(d){return "zmiz herec "+studio_locale.v(d,"spriteIndex")}, "vanishTooltip":function(d){return "Herec zmizí."}, "waitFor":function(d){return "čekat na"}, "waitSeconds":function(d){return "sekund"}, "waitForClick":function(d){return "čekat na kliknutí"}, "waitForRandom":function(d){return "čekat na náhodně"}, "waitForHalfSecond":function(d){return "čekat půl sekundy"}, "waitFor1Second":function(d){return "čekat 1 sekundu"}, "waitFor2Seconds":function(d){return "čekat 2 sekundy"}, "waitFor5Seconds":function(d){return "čekat 5 sekund"}, "waitFor10Seconds":function(d){return "čekat 10 sekund"}, "waitParamsTooltip":function(d){return "Čeká zadaný počet sekund. Použijte nulu pro čekání na kliknutí."}, "waitTooltip":function(d){return "Čeká zadané množství času nebo dokud nedojde ke kliknutí."}, "whenArrowDown":function(d){return "šipka dolů"}, "whenArrowLeft":function(d){return "šipka vlevo"}, "whenArrowRight":function(d){return "šipka vpravo"}, "whenArrowUp":function(d){return "šipka nahoru"}, "whenArrowTooltip":function(d){return "Provést zadané akce po stisknutí klávesy se šipkou."}, "whenDown":function(d){return "když šipka dolů"}, "whenDownTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"dolů\"."}, "whenGameStarts":function(d){return "když se příběh začne"}, "whenGameStartsTooltip":function(d){return "Provést uvedené akce, když příběh začne."}, "whenLeft":function(d){return "když šipka vlevo"}, "whenLeftTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"vlevo\"."}, "whenRight":function(d){return "když šipka vpravo"}, "whenRightTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"vpravo\"."}, "whenSpriteClicked":function(d){return "po kliknutí na herce"}, "whenSpriteClickedN":function(d){return "po kliknutí na herce "+studio_locale.v(d,"spriteIndex")}, "whenSpriteClickedTooltip":function(d){return "Provést uvedené akce po kliknutí na herce."}, "whenSpriteCollidedN":function(d){return "když se herec "+studio_locale.v(d,"spriteIndex")}, "whenSpriteCollidedTooltip":function(d){return "Provést uvedené akce když se herec dotkne jiného herce."}, "whenSpriteCollidedWith":function(d){return "dotkne"}, "whenSpriteCollidedWithAnyActor":function(d){return "dotkne jiného herce"}, "whenSpriteCollidedWithAnyEdge":function(d){return "dotkne okraje"}, "whenSpriteCollidedWithAnyProjectile":function(d){return "dotkne střely"}, "whenSpriteCollidedWithAnything":function(d){return "dotkne čehokoliv"}, "whenSpriteCollidedWithN":function(d){return "dotkne herce "+studio_locale.v(d,"spriteIndex")}, "whenSpriteCollidedWithBlueFireball":function(d){return "dotkne modré ohnivé koule"}, "whenSpriteCollidedWithPurpleFireball":function(d){return "dotkne fialové ohnivé koule"}, "whenSpriteCollidedWithRedFireball":function(d){return "dotkne červené ohnivé koule"}, "whenSpriteCollidedWithYellowHearts":function(d){return "dotkne žlutých srdcí"}, "whenSpriteCollidedWithPurpleHearts":function(d){return "dotkne fialových srdcí"}, "whenSpriteCollidedWithRedHearts":function(d){return "dotkne červených srdcí"}, "whenSpriteCollidedWithBottomEdge":function(d){return "dotkne dolního okraje"}, "whenSpriteCollidedWithLeftEdge":function(d){return "dotkne levého okraje"}, "whenSpriteCollidedWithRightEdge":function(d){return "dotkne pravého okraje"}, "whenSpriteCollidedWithTopEdge":function(d){return "dotkne horního okraje"}, "whenUp":function(d){return "když šipka nahoru"}, "whenUpTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"nahoru\"."}, "yes":function(d){return "Ano"}};
ty-po/code-dot-org
dashboard/public/apps-package/js/cs_cz/studio_locale-bfd0c94141f74417a2ff3e69569591ae.js
JavaScript
apache-2.0
30,817
var gulp = require('gulp'); var g = require('gulp-load-plugins')({lazy: false}); var config = require('../config'); gulp.task('webpack', function () { g.webpack(config.webpack) .pipe(gulp.dest(config.js.dest)); }); gulp.task('webpack-dev', function () { g.webpack(config.webpackDev) .pipe(gulp.dest(config.js.dest)); });
rightcode/gaepack
gulp/tasks/webpack.js
JavaScript
apache-2.0
347
(function(){ id = Ti.App.Properties.getString("tisink", ""); var param, xhr; file = Ti.Filesystem.getFile("examples/label.js"); xhr = Ti.Network.createHTTPClient(); xhr.open("POST", "http://tisink.nodester.com/"); xhr.setRequestHeader("content-type", "application/json"); param = { data: "" + file.read(), file: "label.js", id: id }; xhr.send(JSON.stringify(param)); })(); //TISINK---------------- // create label view data object var data = [ {title:'Basic', hasChild:true, test:'../examples/label_basic.js'} ]; // add android specific tests if (Ti.Platform.name == 'android') { data.push({title:'Auto Link', hasChild:true, test:'../examples/label_linkify.js'}); } // create table view var tableview = Ti.UI.createTableView({ data:data }); // create table view event listener tableview.addEventListener('click', function(e) { if (e.rowData.test) { var win = Ti.UI.createWindow({ url:e.rowData.test, title:e.rowData.title }); Ti.UI.currentTab.open(win,{animated:true}); } }); // add table view to the window Ti.UI.currentWindow.add(tableview);
steerapi/KichenSinkLive
build/mobileweb/examples/label.js
JavaScript
apache-2.0
1,095
// "use strict"; var AppDispatcher = require('../dispatcher/AppDispatcher'); var StationEquipmentAlarmConstants = require('../constants/StationEquipmentAlarmConstants'); var StationEquipmentAlarmsWebApiUtils = require('../webapiutils/StationEquipmentAlarmsWebApiUtils') var Station = require('../domain/Station'); var StationEquipmentAlarmActionCreators = { loadDefectData: function(station){ console.assert(station instanceof Station); AppDispatcher.dispatch({ action: StationEquipmentAlarmConstants.ActionTypes.GET_EQUIPMENT_ALARMS, payload: station }); StationEquipmentAlarmsWebApiUtils.getEquipmentAlarms(station); } }; module.exports = StationEquipmentAlarmActionCreators;
DForshner/ReactFluxDashboardProto
ReactFluxDashboardProto.Web/Scripts/App/actions/StationEquipmentAlarmActionCreators.js
JavaScript
apache-2.0
733
var expect = require('chai').expect describe('Pane', function () { describe('# Show pane', function () { it('should show a lateral pane when requested (click on data feature)', function () { const pane = require('../src/pane') expect(pane.show).to.be.a('function') pane.show() expect(document.getElementById('pane')).not.to.be.null }) }) describe('# Close pane', function () { it('should empty lateral pane when requested (click on map or click on close button)', function () { const pane = require('../src/pane') expect(pane.close).to.be.a('function') pane.close() expect(document.getElementById('pane').hasChildNodes()).to.be.false }) }) describe('# Show feature in pane', function () { const pane = require('../src/pane') const parcelFeature = require('./fixtures').getGoogleMapsParcelFeature() it('should have a hero header section with an image button', function () { pane.show(parcelFeature) var sectionsHeroHeader = document.getElementById('pane').getElementsByClassName('section-hero-header') expect(sectionsHeroHeader).to.not.be.null expect(sectionsHeroHeader.length).to.be.equal(1, '1 and only 1 section hero header') var sectionHeroHeader = sectionsHeroHeader[0] expect(sectionHeroHeader.getElementsByTagName('button')).to.not.be.null expect(sectionHeroHeader.getElementsByTagName('button').length).to.be.least(1, 'Almost a button in section-hero-header') var imageButton = sectionHeroHeader.getElementsByTagName('button')[0] expect(imageButton.getElementsByTagName('img')).to.not.be.null expect(imageButton.getElementsByTagName('img').length).to.be.least(1, 'Almost an image in the button of section-hero-header') }) it('and with a description in the hero header section', function () { pane.show(parcelFeature) var sectionHeroHeader = document.getElementById('pane').getElementsByClassName('section-hero-header')[0] expect(sectionHeroHeader.getElementsByClassName('section-hero-header-description')).to.not.be.null expect(sectionHeroHeader.getElementsByClassName('section-hero-header-description').length).to.be.least(1, 'Almost a description in section-hero-header') var description = sectionHeroHeader.getElementsByClassName('section-hero-header-description')[0] expect(description.getElementsByClassName('section-hero-header-title')).to.not.be.null expect(description.getElementsByClassName('section-hero-header-title').length).to.be.least(1, 'Almost a title in section-hero-header') expect(description.getElementsByTagName('h1').length).to.be.least(1, 'Almost a title in section-hero-header') expect(description.getElementsByTagName('h1')[0].textContent).to.be.equal(parcelFeature.properties.nationalCadastralReference, 'Title with the national cadastral reference of the selected parcel') expect(description.getElementsByClassName('section-hero-header-container')).to.not.be.null expect(description.getElementsByClassName('section-hero-header-description-container').length).to.be.least(1, 'Almost a description container in section-hero-header') }) it('should have an action section', function () { pane.show(parcelFeature) var sectionsAction = document.getElementById('pane').getElementsByClassName('section-action') expect(sectionsAction).to.not.be.null expect(sectionsAction.length).to.be.equal(1, '1 and only 1 action section') var sectionAction = sectionsAction[0] var buttons = sectionAction.getElementsByTagName('button') expect(buttons).to.not.be.null expect(buttons.length).to.be.equal(4, 'Four action buttons in the action section') }) }) })
ilice/OSCWeb
test/pane.test.js
JavaScript
apache-2.0
3,763
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP export default { 'People Finder': 'Localizador de Pessoas', 'Groups Finder': 'Localizador de Grupos', 'Locations Finder': 'Localizador de Locais', 'People': 'Pessoas', 'Groups': 'Grupos', 'Locations': 'Locais', 'Organization': 'Organização', 'Details': 'Detalhes', 'Owners': 'Proprietários', 'Search': 'Buscar', 'No matching people': 'Nenhuma pessoa encontrada', 'No matching groups': 'Nenhum grupo encontrado', 'No matching locations': 'Nenhuma localização encontrada', 'People matching': 'Pessoas correspondentes {search}', 'Groups matching': 'Grupos correspondentes {search}', 'Locations matching': 'Locais correspondentes {search}', 'Refine search to find more': 'Refinar a pesquisa para encontrar mais.', };
grommet/grommet-people-finder
src/messages/pt-BR.js
JavaScript
apache-2.0
822
module.exports = LocalTransport; function LocalTransport(incoming, options) { options = options || {}; this.name = "local"; this.outgoing = function(destination, message, sender, callback) { setImmediate(incoming(destination, message, callback)); //to make function async, just like other transports? //incoming(destination, message, callback) } }
RemcoTukker/eve-nodejs-remco
services/localTransport.js
JavaScript
apache-2.0
364
export const GET = 'GET'; export const PUT = 'PUT'; export const POST = 'POST'; export const DELETE = 'DELETE';
adioss/MyWebAppBootstrap
src/main/resources/static/js/apis/ApiConstants.js
JavaScript
apache-2.0
111
/* ------ IOS ------ */ if(OS_IOS){ // NappSlideMenu var NappSlideMenu = require('dk.napp.slidemenu'); var drawerIphone = NappSlideMenu.createSlideMenuWindow({ centerWindow: $.navWindow, leftWindow: Alloy.createController('menu').getView(), leftLedge: 50 }); // Configure navigation and init app Alloy.Globals.nav.setIphoneDrawer(drawerIphone); Alloy.Globals.nav.setParentWindow($.firstWindow); Alloy.Globals.nav.openCenter('Feed', 'feed', false); Alloy.Globals.nav.init(); function openMenu(){ drawerIphone.toggleLeftView(); } } /* ------ ANDROID ------ */ else if(OS_ANDROID){ // Ti.DrawerLayout var TiDrawerLayout = require('com.tripvi.drawerlayout'); var drawer = TiDrawerLayout.createDrawer({ leftView: Alloy.createController('menu').getView(), leftDrawerWidth: "280dp", width: Ti.UI.FILL, height: Ti.UI.FILL }); // Configure navigation and init app Alloy.Globals.nav.setAppName('My App Name'); Alloy.Globals.nav.setAndroidDrawer(drawer); Alloy.Globals.nav.setParentWindow($.index); Alloy.Globals.nav.openCenter('Feed', 'feed', false); Alloy.Globals.nav.init(); }
netoramalho/ti.slidemenu
app/controllers/index.js
JavaScript
apache-2.0
1,119
module.exports = function (process, manifest, actionCallback) { var program = require('commander'); program .version(manifest.version) .option('-v, --verbose', 'Enable verbose output') .command('*') .action(function (args) { actionCallback(process, args); }); program.parse(process.argv); };
blegros/TestBoxCLI
lib/cli.js
JavaScript
apache-2.0
357
define(['socket.io'], function() { var socket = io.connect('//' + window.document.location.host); return socket; })
pinittome/pinitto.me
public/js/socket.js
JavaScript
apache-2.0
124
/* * Copyright (C) 2013 salesforce.com, 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. */ ({ /** * Set up the actions by creating a storage, building the hierarchy, and resetting the buffer for the test. */ setUp: function(cmp) { // // Initialize storage here, in JS to avoid issues with instantiating the component multiple // times. // $A.storageService.initStorage("actions", false, false, 100000, 50, 0, true, true, 1); cmp.helper.buildHierarchy(cmp); var ready = false; $A.test.callServerAction($A.test.getAction(cmp, "c.execute", { "commands" : "RESET" }, function() { ready = true; })); $A.test.addWaitFor(true, function() { return ready; }); }, /** * Get a lock name that will not conflict. * * FIXME: there should be a $A.test.getUniqueId() */ getSafeLock: function(cmp, name) { if (!cmp._lock_names) { cmp._lock_names = {}; cmp._lock_base = ""+new Date().getTime(); } if (!cmp._lock_names[name]) { cmp._lock_names[name] = $A.test.getTestName()+"."+cmp._lock_base+"."+name; } return cmp._lock_names[name]; }, /** * Convert an array of command arrays into a simple string. * * This allows us to ensure locks are unique, and check the command string. */ buildCommands: function(cmp, commands) { var i; var commands_out = ""; var name; var parent = cmp; for (i = 0; i < commands.length; i++) { var command_list = commands[i]; var command = command_list[0]; if (command === "WAIT") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "WAIT "+name+";"; } else if (command === "RESUME") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "RESUME "+name+";"; } else if (command === "APPEND") { commands_out += "APPEND "+command_list[1]+";"; } else if (command === "COPY") { commands_out += "COPY;"; } else if (command === "READ") { commands_out += "READ;"; } else { throw new Error("Unknown command "+command+" in "+command_list); } } return commands_out; }, sendAction: function(cmp, path, commands, label, options) { var i; var commands_out = ""; var name; var parent = cmp; for (i = 0; i < commands.length; i++) { var command_list = commands[i]; var command = command_list[0]; if (command === "WAIT") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "WAIT "+name+";"; } else if (command === "RESUME") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "RESUME "+name+";"; } else if (command === "APPEND") { commands_out += "APPEND "+command_list[1]+";"; } else if (command === "COPY") { commands_out += "COPY;"; } else if (command === "READ") { commands_out += "READ;"; } } cmp.runAction(path, parent, commands_out, label, options); }, /** * Wait for a line to appear at a specific location. */ addWaitForLog : function(cmp, index, content, cb, partialMatch) { var actual; $A.test.addWaitForWithFailureMessage(false, function() { actual = cmp.get("v.log")?cmp.get("v.log")[index]:undefined; return actual === undefined; }, "Never received log message '" + content + "' at index " + index, function() { if(partialMatch === true) { $A.test.assertTrue(actual.contains(content), "mismatch on log entry "+index); } else { $A.test.assertEquals(content, actual, "mismatch on log entry "+index); } if (cb) { cb(); } } ); }, /** * Wait for a log entry that will fall in a range due to race conditions. */ addWaitForLogRace : function(cmp, index1, index2, content, partialMatch) { var actual; $A.test.addWaitForWithFailureMessage(true, function() { actual = cmp.get("v.log")?cmp.get("v.log")[index2]:undefined; return actual !== undefined; }, "Never received log message '" + content + "' between index " + index1 + " and " + index2, function() { var i; var logs = cmp.get("v.log"); var acc = ''; for (i = index1; i <= index2; i++) { if(partialMatch === true) { if(logs[i].indexOf(content) >= 0) { return; } } else { if (logs[i] === content) { return; } } acc = acc + '\n' + logs[i]; } $A.test.fail("mismatch in log range "+index1+','+index2+ ': did not find '+content+' in:'+acc); } ); }, /** * Wait for a set of log entries that will fall (in order) in a range due to race conditions. * * Unlike wait for log race above, this requires a set of log lines to be in order, but allows then to have * races with other groups of lines. This is useful when you have several sets of actions in paralel, but * want to ensure that a given set is executed in order. */ addWaitForLogRaceOrdered : function(cmp, index1, index2, contentSet, partialMatch) { var actual; $A.test.addWaitForWithFailureMessage(true, function() { actual = cmp.get("v.log")?cmp.get("v.log")[index2]:undefined; return actual !== undefined; }, "Never received log message '" + contentSet + "' between index " + index1 + " and " + index2, function() { var i, j; var logs = cmp.get("v.log"); var acc = ''; for (i = index1, j=0; j < contentSet.length && i <= index2; i++) { if(partialMatch === true) { if(logs[i].indexOf(contentSet[j]) >= 0) { j++; } } else { if (logs[i] === contentSet[j]) { j++; } } acc = acc + '\n' + logs[i]; } if (j === contentSet.length) { return; } $A.test.fail("mismatch in log range "+index1+','+index2+ ': did not find '+contentSet+' in:'+acc); } ); }, /** * Test that we can enqueue and execute client actions. * * Guarantees: * * client action MUST not run immediately. * * client action MAY run after a timeout. * * client action MUST run before render. */ testEnqueueClientAction : { test : [ function(cmp) { //Action is enqueued but not executed var action = cmp.get("c.client"); // FIXME: Ensure that the component is not rendered until after the client action runs. $A.enqueueAction(action); // logging here should always beat enqueueing. cmp.helper.log(cmp, cmp, "log1"); this.addWaitForLog(cmp, 0, "log1"); // the only guarantee is that the client actions should // execute before the render occurs In this case, we should get exactly one rerender. // FIXME: goliver actions-rewrite // Don't know how to check for this. this.addWaitForLog(cmp, 1, "client"); } ] }, /** * Test that we can have more than one foreground actions run in parallel on server. * * max 4 foreground actions can be run in parallel. here we enqueue 4 foreground actions. ask first 3 to wait on * server till 4th arrives, then release them all. * * if enqueue 4 foreground action without releasing any of them, we will run out of available XHR when we want to * enqueue another, no error/warning message on anywhere though, we just put actions in the deferred queue. * * This is dangerous, so we have to ensure that we don't create races. To avoid races, we explicitely chain * our actions using resume and wait. Be careful of deadlocks. */ testMultipleForegroundInFlight : { labels: ["flapper"], test : [ function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "fore1" ], [ "RESUME", "fore1.chain" ], [ "WAIT", "fore1" ], [ "COPY" ] ], "fore1"); }, function(cmp) { this.sendAction(cmp, [], [ [ "WAIT", "fore1.chain"], [ "APPEND", "fore2" ], [ "RESUME", "fore2.chain" ], [ "WAIT", "fore2" ], [ "COPY" ] ], "fore2"); }, function(cmp) { this.sendAction(cmp, [], [ [ "WAIT", "fore2.chain"], [ "APPEND", "fore3" ], [ "RESUME", "fore3.chain" ], [ "WAIT", "fore3" ], [ "COPY" ] ], "fore3"); }, function(cmp) { this.sendAction(cmp, [], [ [ "WAIT", "fore3.chain"], [ "APPEND", "fore4" ], [ "READ" ], [ "APPEND", "fore4.after" ], [ "RESUME", "fore1" ], [ "RESUME", "fore2" ], [ "RESUME", "fore3" ] ], "fore4"); }, function(cmp) { this.addWaitForLogRace(cmp, 0, 3, "fore1: SUCCESS fore4.after"); this.addWaitForLogRace(cmp, 0, 3, "fore2: SUCCESS fore4.after"); this.addWaitForLogRace(cmp, 0, 3, "fore3: SUCCESS fore4.after"); this.addWaitForLogRace(cmp, 0, 3, "fore4: SUCCESS fore1,fore2,fore3,fore4"); } ] }, /** * Test to ensure that caboose actions are not executed until another foreground action is sent. * * Guarantees: * * Caboose action will not be sent until a server side foreground action is enqueued. * * allAboardCallback will be called before the action is sent, but after the foreground action is enqueued * * This test emulates the log+flush pattern that can be used with a combination of caboose actions and allAboard * callbacks. This pattern lets the user queue a caboose action and use allAboardCallback to set a param (in this * case fake log data) to be attached to the action right before the XHR is sent to the server. */ testCabooseActionsWithAllAboardCallback : { test : [ function(cmp) { var that = this; this.sendAction(cmp, [], [ [ "APPEND", "back1" ], [ "READ" ] ], "back1", [ "background" ]); this.sendAction(cmp, [], [ [ "APPEND", "caboose1" ], [ "READ" ] ], "caboose1", [ "caboose", "allaboard" ]); // verify only background action ran this.addWaitForLog(cmp, 0, "back1: SUCCESS back1"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "back2" ], [ "READ" ] ], "back2", [ "background" ]); this.addWaitForLog(cmp, 1, "back2: SUCCESS back2"); }, function(cmp) { // Client actions also should not trigger the caboose. $A.enqueueAction(cmp.get("c.client")); this.addWaitForLog(cmp, 2, "client"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "fore1" ], [ "READ" ] ], "fore1"); // new foreground action should flush out all pending caboose actions this.addWaitForLog(cmp, 3, "caboose1[AllAboard]: NEW"); this.addWaitForLogRace(cmp, 4, 5, "caboose1: SUCCESS caboose1"); this.addWaitForLogRace(cmp, 4, 5, "fore1: SUCCESS fore1"); } ] }, /** * run storable action ('c.execute', param:'WAIT;READ') couple times, make sure we read response from storage * also check storage is updated when new response come from server (we did it by bgAction1/2/etc). * NOTE: from storage point of view, only action def and parameter matters, foreground or background are the same */ testStorableRefresh : { test : [ function(cmp) { //enqueue foreground action(a), ask it to wait on server, till another action (bgAction1) release it. //a is storable, its return 'initial' is stored var that = this; // prime storage this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "prime", [ "storable" ]); this.sendAction(cmp, [], [ [ "APPEND", "initial" ], [ "RESUME", "prime" ] ], "back", [ "background" ]); this.addWaitForLogRace(cmp, 0, 1, "prime: SUCCESS initial"); this.addWaitForLogRace(cmp, 0, 1, "back: SUCCESS "); }, function(cmp) { //fire foreground action(a), because we already have its response('initial') stored, it will just get that. //we also fire background action(bgAction2), it update a's return with a new value, //it will update stored response for a. this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "refresh", [ "storable" ]); this.addWaitForLog(cmp, 2, "refresh[stored]: SUCCESS initial"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "round two" ], [ "RESUME", "prime" ] ], "back", [ "background" ]); this.addWaitForLogRace(cmp, 3, 4, "back: SUCCESS "); this.addWaitForLogRace(cmp, 3, 4, "refresh: SUCCESS round two"); }, function(cmp) { //fire background action(a), it will read response from storage, which is updated by bgAction2 above //fire foreground action, it update response in storage }, function(cmp) { //enqueue foreground action(a) again to double check update from foreAction1 is indeed in storage. //enqueue background action bgAction3 to release a from server, //also update the storage with new response 'theEnd' } ] }, /** * Make sure that we send only one of two duplicate actions enqueued. * * Test this by putting a single value on the buffer, then reading and clearing in both actions. If they * both go to the server, they will have different values. */ testDeDupeStorable : { test : [ function(cmp) { // The storable actions should be 'de-duped', and only one should go to the server. // This is shown by the fact that they will both get the 'initial' that is saved in a buffer. this.sendAction(cmp, [], [ [ "APPEND", "initial" ] ], "setup", [ "background" ]); this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "prime1", [ "storable" ]); this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "prime2", [ "storable" ]); this.addWaitForLog(cmp, 0, "setup: SUCCESS "); }, function(cmp) { this.sendAction(cmp, [], [ [ "RESUME", "prime" ] ], "release", [ "background" ]); this.addWaitForLogRace(cmp, 1, 3, "release: SUCCESS "); this.addWaitForLogRace(cmp, 1, 3, "prime1: SUCCESS initial"); this.addWaitForLogRace(cmp, 1, 3, "prime2: SUCCESS initial"); } ] }, /** * enqueue two actions, a1(foreground), a2(background) with same action def and param, they run in parallel * make sure they read response from storage first, then update the storage with their responses. * * Note a1&a2 are not both foreground/background, a2 won't become a dupe of a1 */ testParallelStorable : { test : [ function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "initial" ] ], "setup"); this.addWaitForLog(cmp, 0, "setup: SUCCESS "); }, function(cmp) { this.sendAction(cmp, [], [ [ "READ" ] ], "prime", [ "storable" ]); this.addWaitForLog(cmp, 1, "prime: SUCCESS initial"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "second" ] ], "setup2"); this.addWaitForLog(cmp, 2, "setup2: SUCCESS "); }, function(cmp) { this.sendAction(cmp, [], [ [ "READ" ] ], "retrieve-fore", [ "storable" ]); this.sendAction(cmp, [], [ [ "READ" ] ], "retrieve-back", [ "storable", "background" ]); // both callbacks with stored value executed. These should be executed _before_ any refreshes go out. this.addWaitForLogRace(cmp, 3, 4, "retrieve-fore[stored]: SUCCESS initial"); this.addWaitForLogRace(cmp, 3, 4, "retrieve-back[stored]: SUCCESS initial"); //last param=true:we only check partial match this.addWaitForLogRace(cmp, 5, 6, "retrieve-fore: SUCCESS ", true); this.addWaitForLogRace(cmp, 5, 6, "retrieve-back: SUCCESS ", true); } ] }, /** * Check that an abortable action is aborted prior to send. */ testAbortAbortablePriorToSend : { test : [ function(cmp) { $A.test.blockForegroundRequests(); this.sendAction(cmp, [ "child1" ], [ [ "APPEND", "value" ], [ "READ" ] ], "aborted", [ "abortable" ]); // return to top so that the action gets queued up. }, function(cmp) { cmp.helper.deleteChild(cmp, "child1"); }, function(cmp) { $A.test.releaseForegroundRequests(); this.addWaitForLog(cmp, 0, "aborted: ABORTED undefined"); } ] }, /** * Check that an abortable action is aborted after send. */ testAbortAbortableAfterSend : { test : [ function(cmp) { this.sendAction(cmp, [ "child1" ], [ [ "WAIT", "release" ], [ "APPEND", "value" ], [ "READ" ] ], "aborted", [ "abortable" ]); // make sure we sent the action. $A.test.addWaitFor(false, function() { return $A.test.isActionQueued(); }) }, function(cmp) { var old = cmp.find("child1"); cmp.helper.deleteChild(cmp, "child1"); // Make sure that the component is gone before we release. $A.test.addWaitFor(false, function() { return old.isValid(); }) }, function(cmp) { this.sendAction(cmp, [ ], [ [ "RESUME", "release" ] ], "release"); this.addWaitForLogRace(cmp, 0, 1, "aborted: ABORTED value"); this.addWaitForLogRace(cmp, 0, 1, "release: SUCCESS "); } ] }, /** * Check that a non-abortable action is not aborted prior to send. */ testAbortNonAbortableNotPriorToSend : { test : [ function(cmp) { $A.test.blockForegroundRequests(); this.sendAction(cmp, [ "child1" ], [ [ "APPEND", "value" ], [ "READ" ] ], "aborted"); // return to top so that the action gets queued up. }, function(cmp) { cmp.helper.deleteChild(cmp, "child1"); }, function(cmp) { $A.test.releaseForegroundRequests(); this.addWaitForLog(cmp, 0, "aborted: ABORTED value"); } ] }, /** * Check that an abortable action is aborted prior to send. */ testAbortNonAbortableAfterSend : { test : [ function(cmp) { this.sendAction(cmp, [ "child1" ], [ [ "WAIT", "release" ], [ "APPEND", "value" ], [ "READ" ] ], "aborted", [ "abortable" ]); }, function(cmp) { var old = cmp.find("child1"); cmp.helper.deleteChild(cmp, "child1"); // Make sure that the component is gone before we release. $A.test.addWaitFor(false, function() { return old.isValid(); }); }, function(cmp) { this.sendAction(cmp, [ ], [ [ "RESUME", "release" ] ], "release"); this.addWaitForLogRace(cmp, 0, 1, "aborted: ABORTED value"); this.addWaitForLogRace(cmp, 0, 1, "release: SUCCESS "); } ] }, /////////////////////////////////////////////////////////////////////// // runActions /////////////////////////////////////////////////////////////////////// testSimpleRunActions : { test : [ function(cmp) { var helper = cmp.helper; $A.clientService.runActions([ helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "a" ], ["READ"] ]), "first") ], this, function() { cmp.helper.log(cmp, cmp, "group1"); }); }, function(cmp) { var helper = cmp.helper; $A.clientService.runActions([ helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "b1" ], ["READ"] ]), "second"), helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "b2" ], ["READ"] ]), "second") ], this, function() { cmp.helper.log(cmp, cmp, "group2"); }); }, function(cmp) { var helper = cmp.helper; $A.clientService.runActions([ helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "c1" ], ["READ"] ]), "third"), helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "c2" ], ["READ"] ]), "third") ], this, function() { cmp.helper.log(cmp, cmp, "group3"); }); }, function(cmp) { this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "first: SUCCESS a", "group1" ] ); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "second: SUCCESS b1", "group2" ]); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "second: SUCCESS b2", "group2" ]); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "third: SUCCESS c1", "group3" ]); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "third: SUCCESS c2", "group3" ]); }] } })
badlogicmanpreet/aura
aura-components/src/test/components/clientServiceTest/enqueueAction/enqueueActionTest.js
JavaScript
apache-2.0
25,099
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Lévy distribution median. * * @module @stdlib/stats/base/dists/levy/median * * @example * var median = require( '@stdlib/stats/base/dists/levy/median' ); * * var y = median( 0.0, 1.0 ); * // returns ~2.198 * * y = median( 4.0, 2.0 ); * // returns ~8.396 */ // MODULES // var median = require( './median.js' ); // EXPORTS // module.exports = median;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/levy/median/lib/index.js
JavaScript
apache-2.0
994
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * A service for maintaining form-related metadata and linking that data to * corresponding controllers and templates. */ angular.module('form').provider('formService', function formServiceProvider() { /** * Reference to the provider itself. * * @type formServiceProvider */ var provider = this; /** * Map of all registered field type definitions by name. * * @type Object.<String, FieldType> */ this.fieldTypes = { /** * Text field type. * * @see {@link Field.Type.TEXT} * @type FieldType */ 'TEXT' : { module : 'form', controller : 'textFieldController', templateUrl : 'app/form/templates/textField.html' }, /** * Email address field type. * * @see {@link Field.Type.EMAIL} * @type FieldType */ 'EMAIL' : { templateUrl : 'app/form/templates/emailField.html' }, /** * Numeric field type. * * @see {@link Field.Type.NUMERIC} * @type FieldType */ 'NUMERIC' : { module : 'form', controller : 'numberFieldController', templateUrl : 'app/form/templates/numberField.html' }, /** * Boolean field type. * * @see {@link Field.Type.BOOLEAN} * @type FieldType */ 'BOOLEAN' : { module : 'form', controller : 'checkboxFieldController', templateUrl : 'app/form/templates/checkboxField.html' }, /** * Username field type. Identical in principle to a text field, but may * have different semantics. * * @see {@link Field.Type.USERNAME} * @type FieldType */ 'USERNAME' : { templateUrl : 'app/form/templates/textField.html' }, /** * Password field type. Similar to a text field, but the contents of * the field are masked. * * @see {@link Field.Type.PASSWORD} * @type FieldType */ 'PASSWORD' : { module : 'form', controller : 'passwordFieldController', templateUrl : 'app/form/templates/passwordField.html' }, /** * Enumerated field type. The user is presented a finite list of values * to choose from. * * @see {@link Field.Type.ENUM} * @type FieldType */ 'ENUM' : { module : 'form', controller : 'selectFieldController', templateUrl : 'app/form/templates/selectField.html' }, /** * Multiline field type. The user may enter multiple lines of text. * * @see {@link Field.Type.MULTILINE} * @type FieldType */ 'MULTILINE' : { templateUrl : 'app/form/templates/textAreaField.html' }, /** * Field type which allows selection of languages. The languages * displayed are the set of languages supported by the Guacamole web * application. Legal values are valid language IDs, as dictated by * the filenames of Guacamole's available translations. * * @see {@link Field.Type.LANGUAGE} * @type FieldType */ 'LANGUAGE' : { module : 'form', controller : 'languageFieldController', templateUrl : 'app/form/templates/languageField.html' }, /** * Field type which allows selection of time zones. * * @see {@link Field.Type.TIMEZONE} * @type FieldType */ 'TIMEZONE' : { module : 'form', controller : 'timeZoneFieldController', templateUrl : 'app/form/templates/timeZoneField.html' }, /** * Field type which allows selection of individual dates. * * @see {@link Field.Type.DATE} * @type FieldType */ 'DATE' : { module : 'form', controller : 'dateFieldController', templateUrl : 'app/form/templates/dateField.html' }, /** * Field type which allows selection of times of day. * * @see {@link Field.Type.TIME} * @type FieldType */ 'TIME' : { module : 'form', controller : 'timeFieldController', templateUrl : 'app/form/templates/timeField.html' }, /** * Field type which allows selection of color schemes accepted by the * Guacamole server terminal emulator and protocols which leverage it. * * @see {@link Field.Type.TERMINAL_COLOR_SCHEME} * @type FieldType */ 'TERMINAL_COLOR_SCHEME' : { module : 'form', controller : 'terminalColorSchemeFieldController', templateUrl : 'app/form/templates/terminalColorSchemeField.html' } }; /** * Registers a new field type under the given name. * * @param {String} fieldTypeName * The name which uniquely identifies the field type being registered. * * @param {FieldType} fieldType * The field type definition to associate with the given name. */ this.registerFieldType = function registerFieldType(fieldTypeName, fieldType) { // Store field type provider.fieldTypes[fieldTypeName] = fieldType; }; // Factory method required by provider this.$get = ['$injector', function formServiceFactory($injector) { // Required services var $compile = $injector.get('$compile'); var $q = $injector.get('$q'); var $templateRequest = $injector.get('$templateRequest'); var service = {}; service.fieldTypes = provider.fieldTypes; /** * Compiles and links the field associated with the given name to the given * scope, producing a distinct and independent DOM Element which functions * as an instance of that field. The scope object provided must include at * least the following properties: * * namespace: * A String which defines the unique namespace associated the * translation strings used by the form using a field of this type. * * fieldId: * A String value which is reasonably likely to be unique and may * be used to associate the main element of the field with its * label. * * field: * The Field object that is being rendered, representing a field of * this type. * * model: * The current String value of the field, if any. * * disabled: * A boolean value which is true if the field should be disabled. * If false or undefined, the field should be enabled. * * @param {Element} fieldContainer * The DOM Element whose contents should be replaced with the * compiled field template. * * @param {String} fieldTypeName * The name of the field type defining the nature of the element to be * created. * * @param {Object} scope * The scope to which the new element will be linked. * * @return {Promise.<Element>} * A Promise which resolves to the compiled Element. If an error occurs * while retrieving the field type, this Promise will be rejected. */ service.insertFieldElement = function insertFieldElement(fieldContainer, fieldTypeName, scope) { // Ensure field type is defined var fieldType = provider.fieldTypes[fieldTypeName]; if (!fieldType) return $q.reject(); var templateRequest; // Use raw HTML template if provided if (fieldType.template) { var deferredTemplate = $q.defer(); deferredTemplate.resolve(fieldType.template); templateRequest = deferredTemplate.promise; } // If no raw HTML template is provided, retrieve template from URL else if (fieldType.templateUrl) templateRequest = $templateRequest(fieldType.templateUrl); // Otherwise, use empty template else { var emptyTemplate= $q.defer(); emptyTemplate.resolve(''); templateRequest = emptyTemplate.promise; } // Defer compilation of template pending successful retrieval var compiledTemplate = $q.defer(); // Resolve with compiled HTML upon success templateRequest.then(function templateRetrieved(html) { // Insert template into DOM fieldContainer.innerHTML = html; // Populate scope using defined controller if (fieldType.module && fieldType.controller) { var $controller = angular.injector(['ng', fieldType.module]).get('$controller'); $controller(fieldType.controller, { '$scope' : scope, '$element' : angular.element(fieldContainer.childNodes) }); } // Compile DOM with populated scope compiledTemplate.resolve($compile(fieldContainer.childNodes)(scope)); }) // Reject on failure ['catch'](function templateError() { compiledTemplate.reject(); }); // Return promise which resolves to the compiled template return compiledTemplate.promise; }; return service; }]; });
jmuehlner/incubator-guacamole-client
guacamole/src/main/webapp/app/form/services/formService.js
JavaScript
apache-2.0
10,923
var less, tree; if (typeof environment === "object" && ({}).toString.call(environment) === "[object Environment]") { // Rhino // Details on how to detect Rhino: https://github.com/ringo/ringojs/issues/88 if (typeof(window) === 'undefined') { less = {} } else { less = window.less = {} } tree = less.tree = {}; less.mode = 'rhino'; } else if (typeof(window) === 'undefined') { // Node.js less = exports, tree = require('./tree'); less.mode = 'node'; } else { // Browser if (typeof(window.less) === 'undefined') { window.less = {} } less = window.less, tree = window.less.tree = {}; less.mode = 'browser'; } // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `current` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // // less.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk temp, // temporarily holds a chunk's state, for backtracking memo, // temporarily holds `i`, when backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // index of current chunk, in `input` parser; var that = this; // This function is called after all files // have been imported through `@import`. var finish = function () {}; var imports = this.imports = { paths: env && env.paths || [], // Search paths, when importing queue: [], // Files which haven't been imported yet files: {}, // Holds the imported parse trees contents: {}, // Holds the imported file contents mime: env && env.mime, // MIME type of .less files error: null, // Error in parsing/evaluating an import push: function (path, callback) { var that = this; this.queue.push(path); // // Import a file asynchronously // less.Parser.importer(path, this.paths, function (e, root, contents) { that.queue.splice(that.queue.indexOf(path), 1); // Remove the path from the queue var imported = path in that.files; that.files[path] = root; // Store the root that.contents[path] = contents; if (e && !that.error) { that.error = e } callback(e, root, imported); if (that.queue.length === 0) { finish() } // Call `finish` if we're done importing }, env); } }; function save() { temp = chunks[j], memo = i, current = i } function restore() { chunks[j] = temp, i = memo, current = i } function sync() { if (i > current) { chunks[j] = chunks[j].slice(i - current); current = i; } } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var match, args, length, c, index, endIndex, k, mem; // // Non-terminal // if (tok instanceof Function) { return tok.call(parser.parsers); // // Terminal // // Either match a single character in the input, // or match a regexp in the current chunk (chunk[j]). // } else if (typeof(tok) === 'string') { match = input.charAt(i) === tok ? tok : null; length = 1; sync (); } else { sync (); if (match = tok.exec(chunks[j])) { length = match[0].length; } else { return null; } } // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. // if (match) { mem = i += length; endIndex = i + chunks[j].length - length; while (i < endIndex) { c = input.charCodeAt(i); if (! (c === 32 || c === 10 || c === 9)) { break } i++; } chunks[j] = chunks[j].slice(length + (i - mem)); current = i; if (chunks[j].length === 0 && j < chunks.length - 1) { j++ } if(typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } } function expect(arg, msg) { var result = $(arg); if (! result) { error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" : "unexpected token")); } else { return result; } } function error(msg, type) { throw { index: i, type: type || 'Syntax', message: msg }; } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { if (tok.test(chunks[j])) { return true; } else { return false; } } } function basename(pathname) { if (less.mode === 'node') { return require('path').basename(pathname); } else { return pathname.match(/[^\/]+$/)[0]; } } function getInput(e, env) { if (e.filename && env.filename && (e.filename !== env.filename)) { return parser.imports.contents[basename(e.filename)]; } else { return input; } } function getLocation(index, input) { for (var n = index, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } return { line: typeof(index) === 'number' ? (input.slice(0, index).match(/\n/g) || "").length : null, column: column }; } function LessError(e, env) { var input = getInput(e, env), loc = getLocation(e.index, input), line = loc.line, col = loc.column, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = e.call && (getLocation(e.call, input).line + 1); this.callExtract = lines[getLocation(e.call, input).line]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, // the lower the number, the less nodes it will create in the tree. // This could matter for debugging, or if you want to access // the individual nodes in the tree. this.optimization = ('optimization' in this.env) ? this.env.optimization : 1; this.env.filename = this.env.filename || null; // // The Parser // return parser = { imports: imports, // // Parse an input string into an abstract syntax tree, // call `callback` when done. // parse: function (str, callback) { var root, start, end, zone, line, lines, buff = [], c, error = null; i = j = current = furthest = 0; input = str.replace(/\r\n/g, '\n'); // Split the input into chunks. chunks = (function (chunks) { var j = 0, skip = /[^"'`\{\}\/\(\)\\]+/g, comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`\\\r\n]|\\.)*)`/g, level = 0, match, chunk = chunks[0], inParam; for (var i = 0, c, cc; i < input.length; i++) { skip.lastIndex = i; if (match = skip.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); } } c = input.charAt(i); comment.lastIndex = string.lastIndex = i; if (match = string.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); c = input.charAt(i); } } if (!inParam && c === '/') { cc = input.charAt(i + 1); if (cc === '/' || cc === '*') { if (match = comment.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); c = input.charAt(i); } } } } switch (c) { case '{': if (! inParam) { level ++; chunk.push(c); break } case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break } case '(': if (! inParam) { inParam = true; chunk.push(c); break } case ')': if ( inParam) { inParam = false; chunk.push(c); break } default: chunk.push(c); } } if (level > 0) { error = new(LessError)({ index: i, type: 'Parse', message: "missing closing `}`", filename: env.filename }, env); } return chunks.map(function (c) { return c.join('') });; })([[]]); if (error) { return callback(error); } // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { root = new(tree.Ruleset)([], $(this.parsers.primary)); root.root = true; } catch (e) { return callback(new(LessError)(e, env)); } root.toCSS = (function (evaluate) { var line, lines, column; return function (options, variables) { var frames = [], importError; options = options || {}; // // Allows setting variables with a hash, so: // // `{ color: new(tree.Color)('#f01') }` will become: // // new(tree.Rule)('@color', // new(tree.Value)([ // new(tree.Expression)([ // new(tree.Color)('#f01') // ]) // ]) // ) // if (typeof(variables) === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (! (value instanceof tree.Value)) { if (! (value instanceof tree.Expression)) { value = new(tree.Expression)([value]); } value = new(tree.Value)([value]); } return new(tree.Rule)('@' + k, value, false, 0); }); frames = [new(tree.Ruleset)(null, variables)]; } try { var css = evaluate.call(this, { frames: frames }) .toCSS([], { compress: options.compress || false }); } catch (e) { throw new(LessError)(e, env); } if ((importError = parser.imports.error)) { // Check if there was an error during importing if (importError instanceof LessError) throw importError; else throw new(LessError)(importError, env); } if (options.yuicompress && less.mode === 'node') { return require('./cssmin').compressor.cssmin(css); } else if (options.compress) { return css.replace(/(\s)+/g, "$1"); } else { return css; } }; })(root.eval); // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occured. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. if (i < input.length - 1) { i = furthest; lines = input.split('\n'); line = (input.slice(0, i).match(/\n/g) || "").length + 1; for (var n = i, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } error = { type: "Parse", message: "Syntax Error on line " + line, index: i, filename: env.filename, line: line, column: column, extract: [ lines[line - 2], lines[line - 1], lines[line] ] }; } if (this.imports.queue.length > 0) { finish = function () { callback(error, root) }; } else { callback(error, root); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // Here's some LESS code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Rule ("color", Value ([Expression [Color #fff]])) // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var node, root = []; while ((node = $(this.mixin.definition) || $(this.rule) || $(this.ruleset) || $(this.mixin.call) || $(this.comment) || $(this.directive)) || $(/^[\s\n]+/)) { node && root.push(node); } return root; }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') return; if (input.charAt(i + 1) === '/') { return new(tree.Comment)($(/^\/\/.*/), true); } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) { return new(tree.Comment)(comment); } }, // // Entities are tokens which can be found inside an Expression // entities: { // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++, e = true } // Escaped strings if (input.charAt(j) !== '"' && input.charAt(j) !== "'") return; e && $('~'); if (str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/)) { return new(tree.Quoted)(str[0], str[1] || str[2], e); } }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k; if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) { if (tree.colors.hasOwnProperty(k)) { // detect named color return new(tree.Color)(tree.colors[k].slice(1)); } else { return new(tree.Keyword)(k); } } }, // // A function call // // rgb(255, 0, 255) // // We also try to catch IE's `alpha()`, but let the `alpha` parser // deal with the details. // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, args, index = i; if (! (name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(chunks[j]))) return; name = name[1].toLowerCase(); if (name === 'url') { return null } else { i += name.length } if (name === 'alpha') { return $(this.alpha) } $('('); // Parse the '(' and consume whitespace. args = $(this.entities.arguments); if (! $(')')) return; if (name) { return new(tree.Call)(name, args, index, env.filename) } }, arguments: function () { var args = [], arg; while (arg = $(this.entities.assignment) || $(this.expression)) { args.push(arg); if (! $(',')) { break } } return args; }, literal: function () { return $(this.entities.dimension) || $(this.entities.color) || $(this.entities.quoted); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; if ((key = $(/^\w+(?=\s?=)/i)) && $('=') && (value = $(this.entity))) { return new(tree.Assignment)(key, value); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value; if (input.charAt(i) !== 'u' || !$(/^url\(/)) return; value = $(this.entities.quoted) || $(this.entities.variable) || $(this.entities.dataURI) || $(/^[-\w%@$\/.&=:;#+?~]+/) || ""; expect(')'); return new(tree.URL)((value.value || value.data || value instanceof tree.Variable) ? value : new(tree.Anonymous)(value), imports.paths); }, dataURI: function () { var obj; if ($(/^data:/)) { obj = {}; obj.mime = $(/^[^\/]+\/[^,;)]+/) || ''; obj.charset = $(/^;\s*charset=[^,;)]+/) || ''; obj.base64 = $(/^;\s*base64/) || ''; obj.data = $(/^,\s*[^)]+/); if (obj.data) { return obj } } }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.filename); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (input.charAt(i) === '#' && (rgb = $(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { var value, c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; if (value = $(/^(-?\d*\.?\d+)(px|%|em|rem|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/)) { return new(tree.Dimension)(value[1], value[2]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++, e = true } // Escaped strings if (input.charAt(j) !== '`') { return } e && $('~'); if (str = $(/^`([^`]*)`/)) { return new(tree.JavaScript)(str[1], i, e); } } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { return name[1] } }, // // A font size/line-height shorthand // // small/12px // // We need to peek first, or we'll match on keywords and dimensions // shorthand: function () { var a, b; if (! peek(/^[@\w.%-]+\/[@\w.-]+/)) return; if ((a = $(this.entity)) && $('/') && (b = $(this.entity))) { return new(tree.Shorthand)(a, b); } }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function () { var elements = [], e, c, args, index = i, s = input.charAt(i), important = false; if (s !== '.' && s !== '#') { return } while (e = $(/^[#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/)) { elements.push(new(tree.Element)(c, e, i)); c = $('>'); } $('(') && (args = $(this.entities.arguments)) && $(')'); if ($(this.important)) { important = true; } if (elements.length > 0 && ($(';') || peek('}'))) { return new(tree.mixin.Call)(elements, args || [], index, env.filename, important); } }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, param, value, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || peek(/^[^{]*(;|})/)) return; save(); if (match = $(/^([#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+)\s*\(/)) { name = match[1]; do { if (input.charAt(i) === '.' && $(/^\.{3}/)) { variadic = true; break; } else if (param = $(this.entities.variable) || $(this.entities.literal) || $(this.entities.keyword)) { // Variable if (param instanceof tree.Variable) { if ($(':')) { value = expect(this.expression, 'expected expression'); params.push({ name: param.name, value: value }); } else if ($(/^\.{3}/)) { params.push({ name: param.name, variadic: true }); variadic = true; break; } else { params.push({ name: param.name }); } } else { params.push({ value: param }); } } else { break; } } while ($(',')) expect(')'); if ($(/^when/)) { // Guard cond = expect(this.conditions, 'expected condition'); } ruleset = $(this.block); if (ruleset) { return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { restore(); } } } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { return $(this.entities.literal) || $(this.entities.variable) || $(this.entities.url) || $(this.entities.call) || $(this.entities.keyword) || $(this.entities.javascript) || $(this.comment); }, // // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. // end: function () { return $(';') || peek('}'); }, // // IE's alpha function // // alpha(opacity=88) // alpha: function () { var value; if (! $(/^\(opacity=/i)) return; if (value = $(/^\d+/) || $(this.entities.variable)) { expect(')'); return new(tree.Alpha)(value); } }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, t, c, v; c = $(this.combinator); e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/) || $('*') || $(this.attribute) || $(/^\([^)@]+\)/); if (! e) { $('(') && (v = $(this.entities.variable)) && $(')') && (e = new(tree.Paren)(v)); } if (e) { return new(tree.Element)(c, e, i) } if (c.value && c.value.charAt(0) === '&') { return new(tree.Element)(c, null, i); } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var match, c = input.charAt(i); if (c === '>' || c === '+' || c === '~') { i++; while (input.charAt(i) === ' ') { i++ } return new(tree.Combinator)(c); } else if (c === '&') { match = '&'; i++; if(input.charAt(i) === ' ') { match = '& '; } while (input.charAt(i) === ' ') { i++ } return new(tree.Combinator)(match); } else if (input.charAt(i - 1) === ' ') { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); } }, // // A CSS Selector // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function () { var sel, e, elements = [], c, match; if ($('(')) { sel = $(this.entity); expect(')'); return new(tree.Selector)([new(tree.Element)('', sel, i)]); } while (e = $(this.element)) { c = input.charAt(i); elements.push(e) if (c === '{' || c === '}' || c === ';' || c === ',') { break } } if (elements.length > 0) { return new(tree.Selector)(elements) } }, tag: function () { return $(/^[a-zA-Z][a-zA-Z-]*[0-9]?/) || $('*'); }, attribute: function () { var attr = '', key, val, op; if (! $('[')) return; if (key = $(/^[a-zA-Z-]+/) || $(this.entities.quoted)) { if ((op = $(/^[|~*$^]?=/)) && (val = $(this.entities.quoted) || $(/^[\w-]+/))) { attr = [key, op, val.toCSS ? val.toCSS() : val].join(''); } else { attr = key } } if (! $(']')) return; if (attr) { return "[" + attr + "]" } }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if ($('{') && (content = $(this.primary)) && $('}')) { return content; } }, // // div, .class, body > p {...} // ruleset: function () { var selectors = [], s, rules, match; save(); while (s = $(this.selector)) { selectors.push(s); $(this.comment); if (! $(',')) { break } $(this.comment); } if (selectors.length > 0 && (rules = $(this.block))) { return new(tree.Ruleset)(selectors, rules, env.strictImports); } else { // Backtrack furthest = i; restore(); } }, rule: function () { var name, value, c = input.charAt(i), important, match; save(); if (c === '.' || c === '#' || c === '&') { return } if (name = $(this.variable) || $(this.property)) { if ((name.charAt(0) != '@') && (match = /^([^@+\/'"*`(;{}-]*);/.exec(chunks[j]))) { i += match[0].length - 1; value = new(tree.Anonymous)(match[1]); } else if (name === "font") { value = $(this.font); } else { value = $(this.value); } important = $(this.important); if (value && $(this.end)) { return new(tree.Rule)(name, value, important, memo); } else { furthest = i; restore(); } } }, // // An @import directive // // @import "lib"; // // Depending on our environemnt, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // "import": function () { var path, features, index = i; var dir = $(/^@import(?:-(once))?\s+/); if (dir && (path = $(this.entities.quoted) || $(this.entities.url))) { features = $(this.mediaFeatures); if ($(';')) { return new(tree.Import)(path, imports, features, (dir[1] === 'once'), index); } } }, mediaFeature: function () { var e, p, nodes = []; do { if (e = $(this.entities.keyword)) { nodes.push(e); } else if ($('(')) { p = $(this.property); e = $(this.entity); if ($(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, i, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { return null; } } else { return null } } } while (e); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var e, features = []; do { if (e = $(this.mediaFeature)) { features.push(e); if (! $(',')) { break } } else if (e = $(this.entities.variable)) { features.push(e); if (! $(',')) { break } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules; if ($(/^@media/)) { features = $(this.mediaFeatures); if (rules = $(this.block)) { return new(tree.Media)(rules, features); } } }, // // A CSS Directive // // @charset "utf-8"; // directive: function () { var name, value, rules, types, e, nodes; if (input.charAt(i) !== '@') return; if (value = $(this['import']) || $(this.media)) { return value; } else if (name = $(/^@page|@keyframes/) || $(/^@(?:-webkit-|-moz-|-o-|-ms-)[a-z0-9-]+/)) { types = ($(/^[^{]+/) || '').trim(); if (rules = $(this.block)) { return new(tree.Directive)(name + " " + types, rules); } } else if (name = $(/^@[-a-z]+/)) { if (name === '@font-face') { if (rules = $(this.block)) { return new(tree.Directive)(name, rules); } } else if ((value = $(this.entity)) && $(';')) { return new(tree.Directive)(name, value); } } }, font: function () { var value = [], expression = [], weight, shorthand, font, e; while (e = $(this.shorthand) || $(this.entity)) { expression.push(e); } value.push(new(tree.Expression)(expression)); if ($(',')) { while (e = $(this.expression)) { value.push(e); if (! $(',')) { break } } } return new(tree.Value)(value); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = [], important; while (e = $(this.expression)) { expressions.push(e); if (! $(',')) { break } } if (expressions.length > 0) { return new(tree.Value)(expressions); } }, important: function () { if (input.charAt(i) === '!') { return $(/^! *important/); } }, sub: function () { var e; if ($('(') && (e = $(this.expression)) && $(')')) { return e; } }, multiplication: function () { var m, a, op, operation; if (m = $(this.operand)) { while (!peek(/^\/\*/) && (op = ($('/') || $('*'))) && (a = $(this.operand))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, addition: function () { var m, a, op, operation; if (m = $(this.multiplication)) { while ((op = $(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && ($('+') || $('-')))) && (a = $(this.multiplication))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, conditions: function () { var a, b, index = i, condition; if (a = $(this.condition)) { while ($(',') && (b = $(this.condition))) { condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var a, b, c, op, index = i, negate = false; if ($(/^not/)) { negate = true } expect('('); if (a = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { if (op = $(/^(?:>=|=<|[<=>])/)) { if (b = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { c = new(tree.Condition)(op, a, b, index, negate); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); } expect(')'); return $(/^and/) ? new(tree.Condition)('and', c, $(this.condition)) : c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var negate, p = input.charAt(i + 1); if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $('-') } var o = $(this.sub) || $(this.entities.dimension) || $(this.entities.color) || $(this.entities.variable) || $(this.entities.call); return negate ? new(tree.Operation)('*', [new(tree.Dimension)(-1), o]) : o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var e, delim, entities = [], d; while (e = $(this.addition) || $(this.entity)) { entities.push(e); } if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name; if (name = $(/^(\*?-?[-a-z_0-9]+)\s*:/)) { return name[1]; } } } }; }; if (less.mode === 'browser' || less.mode === 'rhino') { // // Used by `@import` directives // less.Parser.importer = function (path, paths, callback, env) { if (!/^([a-z]+:)?\//.test(path) && paths.length > 0) { path = paths[0] + path; } // We pass `true` as 3rd argument, to force the reload of the import. // This is so we can get the syntax tree as opposed to just the CSS output, // as we need this to evaluate the current stylesheet. loadStyleSheet({ href: path, title: path, type: env.mime }, function (e) { if (e && typeof(env.errback) === "function") { env.errback.call(null, path, paths, callback, env); } else { callback.apply(null, arguments); } }, true); }; }
qvuilliot/less.js
lib/less/parser.js
JavaScript
apache-2.0
49,427
/** * This looks at static needs parameter in components and waits for the promise to be fullfilled * It is used to make sure server side rendered pages wait for APIs to resolve before * returning res.end() * * As seen in: https://github.com/caljrimmer/isomorphic-redux-app */ export function fetchComponentDataBeforeRender(dispatch, components, params) { const needs = components.reduce((prev, current) => { if (!current) { return prev; } return (current.need || []) .concat((current.WrappedComponent ? current.WrappedComponent.need : []) || []) .concat(prev); }, []); const promises = needs.map(need => dispatch(need(params))); return Promise.all(promises); }
Poniverse/Poniverse.net
app/api/fetchComponentDataBeforeRender.js
JavaScript
apache-2.0
710
/* eslint-disable no-underscore-dangle, no-param-reassign */ import d3 from 'd3'; require('./sequences.css'); // Modified from http://bl.ocks.org/kerryrodden/7090426 function sunburstVis(slice) { const container = d3.select(slice.selector); const render = function () { // vars with shared scope within this function const margin = { top: 10, right: 5, bottom: 10, left: 5 }; const containerWidth = slice.width(); const containerHeight = slice.height(); const breadcrumbHeight = containerHeight * 0.085; const visWidth = containerWidth - margin.left - margin.right; const visHeight = containerHeight - margin.top - margin.bottom - breadcrumbHeight; const radius = Math.min(visWidth, visHeight) / 2; let totalSize; const vis; const arcs; // Dimensions of sunburst. const width = visWidth; const height = visHeight; // Breadcrumb dimensions: width, height, spacing, width of tip/tail. const b = { w: 75, h: 30, s: 3, t: 10, }; // Mapping of step names to colors. const colors = {}; const sequenceDiv = container.append('div:div').attr('class', 'sequence'); const chartDiv = sequenceDiv.append('div:div').attr('clas', 'chart'); const explanationDiv = chartDiv.append('div:div').attr('clas', 'explanation'); const percentageSPAN = explanationDiv.append('span:span').attr('clas', 'percentage'); percentageSPAN.text(''); // Total size of all segments; we set this later, after loading the data. totalSize = 0; vis = container.append('svg:svg') .attr('width', width) .attr('height', height) .append('svg:g') .attr('class', 'container') .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')'); const partition = d3.layout.partition() .size([2 * Math.PI, radius * radius]) .value(function (d) { return d.size; }); arcs = d3.svg.arc() .startAngle(function (d) { return d.x; }) .endAngle(function (d) { return d.x + d.dx; }) .innerRadius(function (d) { return Math.sqrt(d.y); }) .outerRadius(function (d) { return Math.sqrt(d.y + d.dy); }); // Main function to draw and set up the visualization, once we have the data. function createVisualization(json) { // Basic setup of page elements. initializeBreadcrumbTrail(); drawLegend(); d3.select('.togglelegend').on('click', toggleLegend); // Bounding circle underneath the sunburst, to make it easier to detect // when the mouse leaves the parent g. vis.append('svg:circle') .attr('r', radius) .style('opacity', 0); // For efficiency, filter nodes to keep only those large enough to see. const nodes = partition.nodes(json) .filter(function (d) { return (d.dx > 0.005); // 0.005 radians = 0.29 degrees }); const path = vis.data([json]).selectAll('path') .data(nodes) .enter().append('svg:path') .attr('display', function (d) { return d.depth ? null : 'none'; }) .attr('d', arc) .attr('fill-rule', 'evenodd') .style('fill', function (d) { return colors[d.name]; }) .style('opacity', 1) .on('mouseover', mouseover); // Add the mouseleave handler to the bounding circle. d3.select('.container').on('mouseleave', mouseleave); // Get total size of the tree = value of root node from partition. totalSize = path.node().__data__.value; }; // Use d3.text and d3.csv.parseRows so that we do not need to have a header // row, and can receive the csv as an array of arrays. d3.text(slice.csvEndpoint(), function (text) { const csv = d3.csv.parseRows(text); const json = buildHierarchy(csv); createVisualization(json); }); // Fade all but the current sequence, and show it in the breadcrumb trail. function mouseover(d) { const percentage = (100 * d.value / totalSize).toPrecision(3); const percentageString = percentage + '%'; if (percentage < 0.1) { percentageString = '< 0.1%'; } d3.select('.percentage') .text(percentageString); d3.select('.explanation') .style('visibility', ''); const sequenceArray = getAncestors(d); updateBreadcrumbs(sequenceArray, percentageString); // Fade all the segments. d3.selectAll('path') .style('opacity', 0.3); // Then highlight only those that are an ancestor of the current segment. vis.selectAll('path') .filter(function (node) { return (sequenceArray.indexOf(node) >= 0); }) .style('opacity', 1); } // Restore everything to full opacity when moving off the visualization. function mouseleave(d) { // Hide the breadcrumb trail d3.select('.trail') .style('visibility', 'hidden'); // Deactivate all segments during transition. d3.selectAll('path').on('mouseover', null); // Transition each segment to full opacity and then reactivate it. d3.selectAll('path') .transition() .duration(1000) .style('opacity', 1) .each('end', function () { d3.select(this).on('mouseover', mouseover); }); d3.select('.explanation') .style('visibility', 'hidden'); } // Given a node in a partition layout, return an array of all of its ancestor // nodes, highest first, but excluding the root. function getAncestors(node) { const path = []; let current = node; while (current.parent) { path.unshift(current); current = current.parent; } return path; } function initializeBreadcrumbTrail() { // Add the svg area. const trail = d3.select('.sequence').append('svg:svg') .attr('width', width) .attr('height', 50) .attr('class', 'trail'); // Add the label at the end, for the percentage. trail.append('svg:text') .attr('class', 'endlabel') .style('fill', '#000'); } // Generate a string that describes the points of a breadcrumb polygon. function breadcrumbPoints(d, i) { const points = []; points.push('0,0'); points.push(b.w + ',0'); points.push(b.w + b.t + ',' + (b.h / 2)); points.push(b.w + ',' + b.h); points.push('0,' + b.h); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. points.push(b.t + ',' + (b.h / 2)); } return points.join(' '); } // Update the breadcrumb trail to show the current sequence and percentage. function updateBreadcrumbs(nodeArray, percentageString) { // Data join; key function combines name and depth (= position in sequence). const g = d3.select('.trail') .selectAll('g') .data(nodeArray, function (d) { return d.name + d.depth; }); // Add breadcrumb and label for entering nodes. const entering = g.enter().append('svg:g'); entering.append('svg:polygon') .attr('points', breadcrumbPoints) .style('fill', function (d) { return colors[d.name]; }); entering.append('svg:text') .attr('x', (b.w + b.t) / 2) .attr('y', b.h / 2) .attr('dy', '0.35em') .attr('text-anchor', 'middle') .text(function (d) { return d.name; }); // Set position for entering and updating nodes. g.attr('transform', function (d, i) { return 'translate(' + i * (b.w + b.s) + ', 0)'; }); // Remove exiting nodes. g.exit().remove(); // Now move and update the percentage at the end. d3.select('.trail').select('.endlabel') .attr('x', (nodeArray.length + 0.5) * (b.w + b.s)) .attr('y', b.h / 2) .attr('dy', '0.35em') .attr('text-anchor', 'middle') .text(percentageString); // Make the breadcrumb trail visible, if it's hidden. d3.select('.trail') .style('visibility', ''); } function drawLegend() { // Dimensions of legend item: width, height, spacing, radius of rounded rect. const li = { w: 75, h: 30, s: 3, r: 3 }; const legend = d3.select('.legend').append('svg:svg') .attr('width', li.w) .attr('height', d3.keys(colors).length * (li.h + li.s)); const g = legend.selectAll('g') .data(d3.entries(colors)) .enter().append('svg:g') .attr('transform', function (d, i) { return 'translate(0,' + i * (li.h + li.s) + ')'; }); g.append('svg:rect') .attr('rx', li.r) .attr('ry', li.r) .attr('width', li.w) .attr('height', li.h) .style('fill', function (d) { return d.value; }); g.append('svg:text') .attr('x', li.w / 2) .attr('y', li.h / 2) .attr('dy', '0.35em') .attr('text-anchor', 'middle') .text(function (d) { return d.key; }); } function toggleLegend() { const legend = d3.select('.legend'); if (legend.style('visibility') == 'hidden') { legend.style('visibility', ''); } else { legend.style('visibility', 'hidden'); } } // Take a 2-column CSV and transform it into a hierarchical structure suitable // for a partition layout. The first column is a sequence of step names, from // root to leaf, separated by hyphens. The second column is a count of how // often that sequence occurred. function buildHierarchy(csv) { const root = {'name': 'root', 'children': []}; for (const i = 0; i < csv.length; i++) { let sequence = csv[i][0]; let size = +csv[i][1]; if (isNaN(size)) { // e.g. if this is a header row continue; } const parts = sequence.split('-'); let currentNode = root; for (let j = 0; j < parts.length; j++) { let children = currentNode['children']; let nodeName = parts[j]; let childNode; if (j + 1 < parts.length) { // Not yet at the end of the sequence; move down the tree. const foundChild = false; for (let k = 0; k < children.length; k++) { if (children[k]['name'] == nodeName) { childNode = children[k]; foundChild = true; break; } } // If we don't already have a child node for this branch, create it. if (!foundChild) { childNode = {'name': nodeName, 'children': []}; children.push(childNode); } currentNode = childNode; } else { // Reached the end of the sequence; create a leaf node. childNode = {'name': nodeName, 'size': size}; children.push(childNode); } } } return root; }; }; return { render, resize: render, }; } module.exports = sunburstVis;
jeromecn/caravel_viz_full
caravel/assets/visualizations/sequences.js
JavaScript
apache-2.0
11,085
//Funcion para insertar un trozo de codigo HTML function loadXMLDoc(url) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("principal").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET",url,true); xmlhttp.send(); }
CarlosIribarren/Ejemplos-Examples
JavaScript/Nativo/Algunos ejemplos/02 Insertar codigo HTML/funcionJS.js
JavaScript
apache-2.0
535
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ define("joynr/messaging/inprocess/InProcessMessagingSkeleton", [], function() { /** * @name InProcessMessagingSkeleton * @constructor */ function InProcessMessagingSkeleton() { var onReceive; /** * @name InProcessMessagingSkeleton#receiveMessage * @function * * @param {JoynrMessage} joynrMessage * @returns {Object} A+ promise object */ this.receiveMessage = function receiveMessage(joynrMessage) { return onReceive(joynrMessage); }; /** * A setter for the callback function that will receive the incoming messages * * @name InProcessMessagingSkeleton#registerListener * @function * * @param {Function} newOnReceive the function that is called with the incoming JoynrMessage */ this.registerListener = function registerListener(newOnReceive) { onReceive = newOnReceive; }; } return InProcessMessagingSkeleton; });
clive-jevons/joynr
javascript/libjoynr-js/src/main/js/joynr/messaging/inprocess/InProcessMessagingSkeleton.js
JavaScript
apache-2.0
1,684
var http=require('http'); var url = require('url') var httpget = function ( url ) { return new Promise(( resolve,reject)=>{ http.get( url ,function(req,res){ var html=''; req.on('data',function(data){ html+=data; }); req.on('end',function(){ resolve(html); }); req.on('error',function(err){ reject(err); }); }); }) } var httppostsimple = function (posturl,port,postData,username,passwd) { var postDatastr=JSON.stringify(postData); var urlObj = url.parse(posturl) var p = username + ":" + passwd; var b = new Buffer( p ); var cred = b.toString('base64'); var options={ hostname:urlObj.hostname, port:port, path: urlObj.pathname, method:'POST', headers:{ 'Content-Type':'text/plain', 'Content-Length':Buffer.byteLength(postDatastr), 'Authorization': `Basic ${cred}` } } return httppost(options,postDatastr); } var httppost = function (options,postData) { /* var options={ hostname:'www.gongjuji.net', port:80, path:'/', method:'POST', headers:{ //'Content-Type':'application/x-www-form-urlencoded', 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'Content-Length':Buffer.byteLength(postData) } }*/ return new Promise(( resolve,reject)=>{ var buffers = []; var req=http.request(options, function(res) { res.on('data',function(reposebuffer){ buffers.push(reposebuffer); }); res.on('end',function(){ //console.log('No more data in response.********'); var wholeData = Buffer.concat(buffers); var dataStr = wholeData.toString('utf8'); resolve(dataStr) }); res.on('error',function(err){ reject(err); }); }); req.write(postData); req.end(); }) } exports.httpget = httpget; exports.httppost =httppost; exports.httppostsimple = httppostsimple;
17golang/nodejsstudy
httpclient.js
JavaScript
apache-2.0
2,282
import {rnaPlot} from './rnaplot.js'; export function rnaTreemapChart() { var width = 550; var height = 400; function rnaTreemapNode(selection) { // create a background rectangle for each RNA structure selection.each(function(d) { d3.select(this) .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')' }) .append('rect') .classed('structure-background-rect', true) .attr('width', function(d) { return Math.max(0, d.dx); }) .attr('height', function(d) { return Math.max(0, d.dy); }) // draw the actual RNA structure var chart = rnaPlot() .width( Math.max(0, d.dx)) .height( Math.max(0, d.dy)) .labelInterval(0) .rnaEdgePadding(10) .showNucleotideLabels(false); if ('structure' in d) d3.select(this).call(chart) }); } var chart = function(selection) { selection.each(function(data) { console.log('data:', data) // initialize the treemap structure // sample input // { 'name': 'blah', // 'children: [{'structure': '..((..))', // 'sequence': 'ACCGGCC', // 'size': 50}] // } var treemap = d3.layout.treemap() .size([width, height]) .sticky(false) .value(function(d) { return d.size; }); // create a new <g> for each node in the treemap // this may be a little redundant, since we expect the calling // selection to contain their own g elements var gEnter = d3.select(this).append('g'); var treemapGnodes = gEnter.datum(data).selectAll('.treemapNode') .data(treemap.nodes) .enter() .append('g') .attr('class', 'treemapNode') .call(rnaTreemapNode); }); }; chart.width = function(_) { if (!arguments.length) return width; width = _; return chart; } chart.height = function(_) { if (!arguments.length) return height; height = _; return chart; } return chart; } function rnaTreemapGridChart() { var chart = function(selection) { console.log('selection:', selection); selection.each(function(data) { console.log('data:', data); }); } return chart; }
pkerpedjiev/fornac
app/scripts/rnatreemap.js
JavaScript
apache-2.0
2,511
'use strict'; /** * Configuration options for Ember CLI App used to manage broccoli build tree for DataHub web. * Returns a method to import build dependencies and an options * object with configuration attributes * * @param {string} env current build application environment * @returns { options: object } */ module.exports = function(env) { const isTesting = env === 'test'; const isProduction = env === 'production'; return { options: { // Configuration options for ember-auto-import library autoImport: { // Note: restliparams has an outDir of lib, but autoImport looks for dist alias: { restliparams: 'restliparams/lib' }, webpack: { node: { // this will add support for 'require('path')' in browsers // this is needed by minimatch dependency path: true } }, exclude: ['@glimmer/tracking'] }, // Configurations options for ember-ace editor library ace: isTesting ? {} : { modes: ['json', 'graphqlschema', 'text'], workers: ['json', 'graphqlschema', 'text'], exts: ['searchbox'] }, babel: { sourceMaps: env === 'development' ? 'inline' : false, targets: { browsers: ['last 3 versions'] } }, 'ember-cli-babel': { includePolyfill: !isTesting }, storeConfigInMeta: false, SRI: { enabled: false }, fingerprint: { enabled: isProduction }, 'ember-cli-uglify': { enabled: isProduction, // Improve build times by using the Fast Minify Mode // For our internal use case, app load times are not a significant bottleneck currently // https://github.com/mishoo/UglifyJS2#uglify-fast-minify-mode uglify: { compress: false, mangle: true } }, outputPaths: { app: { html: 'index.html', css: { app: '/assets/datahub-web.css' }, js: '/assets/datahub-web.js' }, vendor: { css: '/assets/vendor.css', js: '/assets/vendor.js' } }, svgJar: { sourceDirs: ['public/assets/images/svgs'] }, // Configuration options specifying inclusion of Mirage addon files in the application tree 'mirage-from-addon': { includeAll: true, exclude: [/scenarios\/default/, /config/] } } }; };
mars-lan/WhereHows
datahub-web/configs/ember-cli-build-options.js
JavaScript
apache-2.0
2,560
var Canvas = require('canvas'); function generateCode() { return ('' + Math.random()).substr(3, 6); } function generateImage(req, res, params) { params.color = params.color || 'rgb(0, 0, 0)'; params.background = params.background || 'rgb(255, 255, 255)'; params.width = params.width || 250; params.height = params.height || 150; params.innerWidth = params.width * 0.6; params.fontHeight = params.height * 0.6; params.offset = params.width * 0.08; params.fontWidth = Math.ceil(params.fontHeight / 2); var offset = params.width * 0.4 * Math.random(); var canvas = new Canvas(params.width, params.height); var ctx = canvas.getContext('2d'); ctx.antialias = 'gray'; ctx.fillStyle = params.background; ctx.fillRect(0, 0, params.width, params.height); ctx.fillStyle = params.color; ctx.lineWidth = params.fontHeight / 10; ctx.strokeStyle = params.color; ctx.font = params.fontHeight + 'px sans'; for (var i = 0; i < 2; i++) { ctx.moveTo(offset, Math.random() * params.innerWidth); ctx.bezierCurveTo( params.width * 0.32, Math.random() * params.height, params.width * 0.64, Math.random() * params.height, params.width * 0.92, Math.random() * params.height); ctx.stroke(); } var text = params.text || generateCode(); for (i = 0; i < text.length; i++) { ctx.setTransform(Math.random() * 0.5 + 1, Math.random() * 0.4, Math.random() * 0.4, Math.random() * 0.5 + 1, params.fontWidth * i + offset, params.height * 2 / 3); ctx.fillText(text.charAt(i), 0, 0); } canvas.toBuffer(function(err, buf) { if(req.session) req.session.captcha = text; res.end(buf); }); } module.exports = function(params){ if (params.hasOwnProperty('text')) delete params.text; return function(req, res, next){ generateImage(req, res, params); }; }; module.exports.generateImage = generateImage; module.exports.generateCode = generateCode;
klesh/kaptcha
kaptcha.js
JavaScript
apache-2.0
1,961
(function($, utils, $HELPER){ var $app = window.vgrome; $app.controller('CalendarCtrl', ['$scope', '$compile', 'lang', 'apiProvider', '$controller', function ($scope, $compile, $lang, $apiProvider, $controller) { $.extend(this, $controller('EntityCtrl', {$scope: $scope})); $scope.trans = $lang.translate; window.calendarCtrl = $scope; $scope.mode = 'index'; $scope.focusFields = { events: [], tasks: [] }; $scope.focusObject = 'Calendar'; $scope.focusId = ''; $scope.listViewData = { events: [], tasks: [] }; $scope.listViewHeaderColumns = {}; $scope.enableShowRefList = enableShowRefList = function(originObject, originId) { $scope.listViewData = { events: [], tasks: [] }; $scope.listViewHeaderColumns = { events: userdata.search_config['Events'], tasks: userdata.search_config['Calendar'] }; $apiProvider.findListRef(originObject, originId, 'Calendar', $scope.listViewHeaderColumns, function(result) { utils.log(originObject+':explode ref list('+$scope.focusObject+'):' + $scope.focusId); if(result.success) { _.each(result.records['tasks'], function(record) { var data = {}; _.each($scope.listViewHeaderColumns['tasks'], function(field) { var recordValue = record[field.name]; if($HELPER.inArray(field.name, ['date_start', 'due_date'])) { if(field.name == 'date_start') { recordValue += ' ' + record['time_start']; } else if(field.name == 'due_date') { recordValue += ' ' + record['time_end']; } } data[field.name] = $HELPER.formatValueByField(field, recordValue); if(arrayContains(field.type.name, ['reference', 'owner'])) { data[field.name + '_display'] = record[field.name + '_display']; } }); data['id'] = record.id; $scope.listViewData['tasks'].push(data); }); _.each(result.records['events'], function(record) { var data = {}; _.each($scope.listViewHeaderColumns['events'], function(field) { var recordValue = record[field.name]; if($HELPER.inArray(field.name, ['date_start', 'due_date'])) { if(field.name == 'date_start') { recordValue += ' ' + record['time_start']; } else if(field.name == 'due_date') { recordValue += ' ' + record['time_end']; } } data[field.name] = $HELPER.formatValueByField(field, recordValue); if(arrayContains(field.type.name, ['reference', 'owner'])) { data[field.name + '_display'] = record[field.name + '_display']; } }); data['id'] = record.id; $scope.listViewData['events'].push(data); }); $scope.switchMode('ref-list'); utils.hideLoading(); } else { utils.handleError(result, 'Calendar'); utils.hideLoading(); } }); }; $scope.submitCreate = submitCreate = function() { var templateFields = $scope.focusFields; var post = {}; _.each(templateFields, function(block){ _.each(block.items, function(field){ if(field.uitype.name == 'boolean') { var value = $('.create-section #inp_'+$scope.focusObject+'_'+field.name).prop( "checked" ); value = value ? 1 : 0; } else { var value = $('.create-section #inp_'+$scope.focusObject+'_'+field.name).val(); } if(field.uitype.name == 'datetime' && arrayContains(field.name, ['date_start', 'due_date'])) { if(field.name == 'date_start') { var subData = { time: $('.create-section #inp_'+$scope.focusObject+'_time_start').val() }; } else if(field.name == 'due_date') { var subData = { time: $('.create-section #inp_'+$scope.focusObject+'_time_end').val() }; } value = $HELPER.formatToVTFormat(field, value, subData); } else { value = $HELPER.formatToVTFormat(field, value); } post[field.name] = value; }); }); post['time_start'] = post['date_start'][1]; post['date_start'] = post['date_start'][0]; post['time_end'] = post['due_date'][1]; post['due_date'] = post['due_date'][0]; if($scope.focusObject == 'Calendar') { if(empty(post['activitytype'])) { post['activitytype'] = 'Task'; } if(empty(post['visibility'])) { post['visibility'] = 'Public'; } } else if($scope.focusObject == 'Events') { if(empty(post['activitytype'])) { post['activitytype'] = 'Call'; } if(empty(post['visibility'])) { post['visibility'] = 'Public'; } } //Calculate duration hours and minutes utils.showLoading(); $apiProvider.createObject($scope.focusObject, post, function(result){ if(result.success) { var record = result.record; utils.hideLoading(); $scope.enableShowDetail(record.id); $scope.needToReloadRefList = true; } else { utils.handleError(result, 'Calendar'); utils.hideLoading(); } }); }; $scope.submitEdit = submitEdit = function(){ var templateFields = $scope.focusFields; var post = {}; _.each(templateFields, function(block){ _.each(block.items, function(field){ if(field.uitype.name == 'boolean') { var value = $('.edit-section #inp_'+$scope.focusObject+'_'+field.name).prop( "checked" ); value = value ? 1 : 0; } else { var value = $('.edit-section #inp_'+$scope.focusObject+'_'+field.name).val(); } if(field.uitype.name == 'datetime' && arrayContains(field.name, ['date_start', 'due_date'])) { if(field.name == 'date_start') { var subData = { time: $('.edit-section #inp_'+$scope.focusObject+'_time_start').val() }; } else if(field.name == 'due_date') { var subData = { time: $('.edit-section #inp_'+$scope.focusObject+'_time_end').val() }; } value = $HELPER.formatToVTFormat(field, value, subData); } else { value = $HELPER.formatToVTFormat(field, value); } if(value != '') { post[field.name] = value; } }); }); post['time_start'] = post['date_start'][1]; post['date_start'] = post['date_start'][0]; post['time_end'] = post['due_date'][1]; post['due_date'] = post['due_date'][0]; if($scope.focusObject == 'Calendar') { if(empty(post['activitytype'])) { post['activitytype'] = 'Task'; } if(empty(post['visibility'])) { post['visibility'] = 'Public'; } } else if($scope.focusObject == 'Events') { if(empty(post['activitytype'])) { post['activitytype'] = 'Call'; } if(empty(post['visibility'])) { post['visibility'] = 'Public'; } } if($scope.focusObject == 'Calendar' || $scope.focusObject == 'Events') { if(!empty(window.summaryData) && window.summaryData.type == 'Leads') { post['parent_id'] = summaryData.id; } } utils.showLoading(); $apiProvider.updateObject($scope.focusObject, $scope.focusId, post, function(result){ if(result.success) { var record = result.record; utils.hideLoading(); $scope.enableShowDetail(record.id); } else { utils.handleError(result, $scope.focusObject); utils.hideLoading(); } }); }; $scope.backHistory = backHistory = function () { if(window.summaryData) { $scope.mode = 'ref-list'; if(summaryData && $scope.needToReloadRefList) { utils.showLoading('Reloading data...'); $scope.enableShowRefList(summaryData.type, summaryData.id); $scope.needToReloadRefList = false; } } else { $scope.mode = 'index'; } }; }]); })(jQuery, window.UTILS, window.VTEHelperInstance);
vijay-developer/Chrome-Extension
ui/app/controllers/calendar.js
JavaScript
apache-2.0
10,975
// Copyright 2012 Google Inc. All Rights Reserved. /** * @fileoverview A class representing operations on binary expressions. */ goog.provide('wgxpath.BinaryExpr'); goog.require('wgxpath.DataType'); goog.require('wgxpath.Expr'); goog.require('wgxpath.Node'); /** * Constructor for BinaryExpr. * * @param {!wgxpath.BinaryExpr.Op} op A binary operator. * @param {!wgxpath.Expr} left The left hand side of the expression. * @param {!wgxpath.Expr} right The right hand side of the expression. * @extends {wgxpath.Expr} * @constructor */ wgxpath.BinaryExpr = function(op, left, right) { var opCast = /** @type {!wgxpath.BinaryExpr.Op_} */ (op); wgxpath.Expr.call(this, opCast.dataType_); /** * @private * @type {!wgxpath.BinaryExpr.Op_} */ this.op_ = opCast; /** * @private * @type {!wgxpath.Expr} */ this.left_ = left; /** * @private * @type {!wgxpath.Expr} */ this.right_ = right; this.setNeedContextPosition(left.doesNeedContextPosition() || right.doesNeedContextPosition()); this.setNeedContextNode(left.doesNeedContextNode() || right.doesNeedContextNode()); // Optimize [@id="foo"] and [@name="bar"] if (this.op_ == wgxpath.BinaryExpr.Op.EQUAL) { if (!right.doesNeedContextNode() && !right.doesNeedContextPosition() && right.getDataType() != wgxpath.DataType.NODESET && right.getDataType() != wgxpath.DataType.VOID && left.getQuickAttr()) { this.setQuickAttr({ name: left.getQuickAttr().name, valueExpr: right}); } else if (!left.doesNeedContextNode() && !left.doesNeedContextPosition() && left.getDataType() != wgxpath.DataType.NODESET && left.getDataType() != wgxpath.DataType.VOID && right.getQuickAttr()) { this.setQuickAttr({ name: right.getQuickAttr().name, valueExpr: left}); } } }; goog.inherits(wgxpath.BinaryExpr, wgxpath.Expr); /** * Performs comparison between the left hand side and the right hand side. * * @private * @param {function((string|number|boolean), (string|number|boolean))} * comp A comparison function that takes two parameters. * @param {!wgxpath.Expr} lhs The left hand side of the expression. * @param {!wgxpath.Expr} rhs The right hand side of the expression. * @param {!wgxpath.Context} ctx The context to perform the comparison in. * @param {boolean=} opt_equChk Whether the comparison checks for equality. * @return {boolean} True if comp returns true, false otherwise. */ wgxpath.BinaryExpr.compare_ = function(comp, lhs, rhs, ctx, opt_equChk) { var left = lhs.evaluate(ctx); var right = rhs.evaluate(ctx); var lIter, rIter, lNode, rNode; if (left instanceof wgxpath.NodeSet && right instanceof wgxpath.NodeSet) { lIter = left.iterator(); for (lNode = lIter.next(); lNode; lNode = lIter.next()) { rIter = right.iterator(); for (rNode = rIter.next(); rNode; rNode = rIter.next()) { if (comp(wgxpath.Node.getValueAsString(lNode), wgxpath.Node.getValueAsString(rNode))) { return true; } } } return false; } if ((left instanceof wgxpath.NodeSet) || (right instanceof wgxpath.NodeSet)) { var nodeset, primitive; if ((left instanceof wgxpath.NodeSet)) { nodeset = left, primitive = right; } else { nodeset = right, primitive = left; } var iter = nodeset.iterator(); var type = typeof primitive; for (var node = iter.next(); node; node = iter.next()) { var stringValue; switch (type) { case 'number': stringValue = wgxpath.Node.getValueAsNumber(node); break; case 'boolean': stringValue = wgxpath.Node.getValueAsBool(node); break; case 'string': stringValue = wgxpath.Node.getValueAsString(node); break; default: throw Error('Illegal primitive type for comparison.'); } if (comp(stringValue, /** @type {(string|number|boolean)} */ (primitive))) { return true; } } return false; } if (opt_equChk) { if (typeof left == 'boolean' || typeof right == 'boolean') { return comp(!!left, !!right); } if (typeof left == 'number' || typeof right == 'number') { return comp(+left, +right); } return comp(left, right); } return comp(+left, +right); }; /** * @override * @return {(boolean|number)} The boolean or number result. */ wgxpath.BinaryExpr.prototype.evaluate = function(ctx) { return this.op_.evaluate_(this.left_, this.right_, ctx); }; /** * @override */ wgxpath.BinaryExpr.prototype.toString = function() { var text = 'Binary Expression: ' + this.op_; text += wgxpath.Expr.indent(this.left_); text += wgxpath.Expr.indent(this.right_); return text; }; /** * A binary operator. * * @param {string} opString The operator string. * @param {number} precedence The precedence when evaluated. * @param {!wgxpath.DataType} dataType The dataType to return when evaluated. * @param {function(!wgxpath.Expr, !wgxpath.Expr, !wgxpath.Context)} * evaluate An evaluation function. * @constructor * @private */ wgxpath.BinaryExpr.Op_ = function(opString, precedence, dataType, evaluate) { /** * @private * @type {string} */ this.opString_ = opString; /** * @private * @type {number} */ this.precedence_ = precedence; /** * @private * @type {!wgxpath.DataType} */ this.dataType_ = dataType; /** * @private * @type {function(!wgxpath.Expr, !wgxpath.Expr, !wgxpath.Context)} */ this.evaluate_ = evaluate; }; /** * Returns the precedence for the operator. * * @return {number} The precedence. */ wgxpath.BinaryExpr.Op_.prototype.getPrecedence = function() { return this.precedence_; }; /** * @override */ wgxpath.BinaryExpr.Op_.prototype.toString = function() { return this.opString_; }; /** * A mapping from operator strings to operator objects. * * @private * @type {!Object.<string, !wgxpath.BinaryExpr.Op>} */ wgxpath.BinaryExpr.stringToOpMap_ = {}; /** * Creates a binary operator. * * @param {string} opString The operator string. * @param {number} precedence The precedence when evaluated. * @param {!wgxpath.DataType} dataType The dataType to return when evaluated. * @param {function(!wgxpath.Expr, !wgxpath.Expr, !wgxpath.Context)} * evaluate An evaluation function. * @return {!wgxpath.BinaryExpr.Op} A binary expression operator. * @private */ wgxpath.BinaryExpr.createOp_ = function(opString, precedence, dataType, evaluate) { if (opString in wgxpath.BinaryExpr.stringToOpMap_) { throw new Error('Binary operator already created: ' + opString); } // The upcast and then downcast for the JSCompiler. var op = /** @type {!Object} */ (new wgxpath.BinaryExpr.Op_( opString, precedence, dataType, evaluate)); op = /** @type {!wgxpath.BinaryExpr.Op} */ (op); wgxpath.BinaryExpr.stringToOpMap_[op.toString()] = op; return op; }; /** * Returns the operator with this opString or null if none. * * @param {string} opString The opString. * @return {!wgxpath.BinaryExpr.Op} The operator. */ wgxpath.BinaryExpr.getOp = function(opString) { return wgxpath.BinaryExpr.stringToOpMap_[opString] || null; }; /** * Binary operator enumeration. * * @enum {{getPrecedence: function(): number}} */ wgxpath.BinaryExpr.Op = { DIV: wgxpath.BinaryExpr.createOp_('div', 6, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) / right.asNumber(ctx); }), MOD: wgxpath.BinaryExpr.createOp_('mod', 6, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) % right.asNumber(ctx); }), MULT: wgxpath.BinaryExpr.createOp_('*', 6, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) * right.asNumber(ctx); }), PLUS: wgxpath.BinaryExpr.createOp_('+', 5, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) + right.asNumber(ctx); }), MINUS: wgxpath.BinaryExpr.createOp_('-', 5, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) - right.asNumber(ctx); }), LESSTHAN: wgxpath.BinaryExpr.createOp_('<', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a < b;}, left, right, ctx); }), GREATERTHAN: wgxpath.BinaryExpr.createOp_('>', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a > b;}, left, right, ctx); }), LESSTHAN_EQUAL: wgxpath.BinaryExpr.createOp_( '<=', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a <= b;}, left, right, ctx); }), GREATERTHAN_EQUAL: wgxpath.BinaryExpr.createOp_('>=', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a >= b;}, left, right, ctx); }), EQUAL: wgxpath.BinaryExpr.createOp_('=', 3, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a == b;}, left, right, ctx, true); }), NOT_EQUAL: wgxpath.BinaryExpr.createOp_('!=', 3, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a != b}, left, right, ctx, true); }), AND: wgxpath.BinaryExpr.createOp_('and', 2, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return left.asBool(ctx) && right.asBool(ctx); }), OR: wgxpath.BinaryExpr.createOp_('or', 1, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return left.asBool(ctx) || right.asBool(ctx); }) };
vinay-qa/vinayit-android-server-apk
third_party/js/wgxpath/binaryExpr.js
JavaScript
apache-2.0
10,027
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var path = require('path'), fs = require('fs'), url = require('url'), shell = require('shelljs'); // Map of project_root -> JSON var configCache = {}; var autoPersist = true; /** * 将opts中的属性值以json格式添加到<proj_root>/.xface/config.json中 * config.json包含的属性主要有id, name, lib, dev_type。id和name分别为工程的id和名称, * dev_type用于标识是内部项目开发还是外部开发者使用('internal'表示内部项目开发,不存在或者为空时为外部使用) * @param {String} project_root * @param {Object} opts */ function config(project_root, opts) { var json = config.read(project_root); for (var p in opts) { json[p] = opts[p]; } if (autoPersist) { config.write(project_root, json); } else { configCache[project_root] = JSON.stringify(json); } return json; }; config.setAutoPersist = function(value) { autoPersist = value; }; config.read = function get_config(project_root) { var data = configCache[project_root]; if (data === undefined) { var configPath = path.join(project_root, '.xface', 'config.json'); if (!fs.existsSync(configPath)) { data = '{}'; } else { data = fs.readFileSync(configPath, 'utf-8'); } } configCache[project_root] = data; return JSON.parse(data); }; config.write = function set_config(project_root, json) { var configPath = path.join(project_root, '.xface', 'config.json'); var contents = JSON.stringify(json, null, 4); configCache[project_root] = contents; // Don't write the file for an empty config. if (contents != '{}' || !fs.existsSync(configPath)) { shell.mkdir('-p', path.join(project_root, '.xface')); fs.writeFileSync(configPath, contents, 'utf-8'); } return json; }; config.has_custom_path = function(project_root, platform) { var json = config.read(project_root); if (json.lib && json.lib[platform]) { var uri = url.parse(json.lib[platform].uri); if (!(uri.protocol)) return uri.path; else if (uri.protocol && uri.protocol[1] ==':') return uri.href; } return false; }; /** * 判断指定工程是否为内部开发使用的工程 * @param {String} project_root 工程根路径 */ config.internalDev = function(project_root) { var json = config.read(project_root); return json.dev_type === 'internal'; }; module.exports = config;
polyvi/xface-lib
xface-lib/src/cordova/config.js
JavaScript
apache-2.0
3,336
(function() { const MAX_LINE_CHARS = 4000; const RE_WS = /^\s*$/; this.search_panel = function(search, type, handler) { return ( [ ['div', this['advanced_' + type + '_search'](search), 'class', 'advanced-search-controls'], ['div', ['div', 'class', 'panel-search mono'], 'class', 'panel-search-container', 'handler', handler], ]); }; this.searchbar_content = function(search) { var content = this.filters(search.controls); content[0] = 'div'; content.push('class', 'advanced-panel-search'); return content; }; this._search_input = function(name, type, value, label, is_selected, is_disabled, title) { var input = ['input', 'type', type, 'value', value, 'name', name]; if (is_selected) { input.push('checked', 'checked'); } if (is_disabled) { input.push('disabled', 'disabled'); } if (title) { input.push('title', title); } var ret = ['label', input, label]; if (title) { ret.push('title', title); } return ret; }; this.advanced_search_field = function(search) { return ( ['div', ['table', ['tr', ['td', this.default_filter(search.controls[0])], ['td', ['span', '\u00A0', 'class', 'search-info-badge'], 'width', '1px'], ['td', this.search_control(search.controls[1]), 'width', '1px'], ['td', this.search_control(search.controls[2]), 'width', '1px']], 'class', 'advanced-search-table'], 'class', 'advanced-search']); }; this.advanced_dom_search = function(search) { return ( [ this.advanced_search_field(search), ['div', ['form', this._search_input('dom-search-type', 'radio', DOMSearch.PLAIN_TEXT, ui_strings.S_LABEL_SEARCH_TYPE_TEXT, DOMSearch.PLAIN_TEXT == search.search_type), this._search_input('dom-search-type', 'radio', DOMSearch.REGEXP, ui_strings.S_LABEL_SEARCH_TYPE_REGEXP, DOMSearch.REGEXP == search.search_type), this._search_input('dom-search-type', 'radio', DOMSearch.CSS, ui_strings.S_LABEL_SEARCH_TYPE_CSS, DOMSearch.CSS == search.search_type), this._search_input('dom-search-type', 'radio', DOMSearch.XPATH, ui_strings.S_LABEL_SEARCH_TYPE_XPATH, DOMSearch.XPATH == search.search_type), this._search_input('dom-search-ignore-case', 'checkbox', 'ignore-case', ui_strings.S_LABEL_SEARCH_FLAG_IGNORE_CASE, search.ignore_case, !search.is_token_search), 'handler', 'dom-search-type-changed', ], ], ]); }.bind(this); this.advanced_js_search = function(search) { return ( [ this.advanced_search_field(search), ['div', ['form', this._search_input('js-search-type', 'checkbox', 'reg-exp', ui_strings.S_LABEL_SEARCH_TYPE_REGEXP, TextSearch.REGEXP == search.search_type), this._search_input('js-search-ignore-case', 'checkbox', 'ignore-case', ui_strings.S_LABEL_SEARCH_FLAG_IGNORE_CASE, search.ignore_case), this._search_input('js-search-all-files', 'checkbox', 'search-all-files', ui_strings.S_LABEL_SEARCH_ALL_FILES, search.search_all_files), this._search_input('js-search-injected-scripts', 'checkbox', 'search-injected-scripts', ui_strings.S_LABEL_SEARCH_INJECTED_SCRIPTS, search.search_injected_scripts, !search.search_all_files, ui_strings.S_LABEL_SEARCH_INJECTED_SCRIPTS_TOOLTIP), 'handler', 'js-search-type-changed', ], ], ]); }.bind(this); this.js_search_window = function() { return ['div', 'class', 'js-search-results', 'handler', 'show-script']; }; this.js_search_results = function(results, result_count, max_count) { var ret = this._search_result_init(result_count, max_count); var div = null; for (var rt_id in results) { div = ['div']; div.push(this._search_result_header(rt_id)); div.extend(results[rt_id].map(this.search_result_script, this)); div.push('class', 'js-search-results-runtime'); ret.push(div); if (this._js_search_ctx.count > this._js_search_ctx.max_count) { break; } } return ret; }; this.js_search_result_single_file = function(script, result_count, max_count) { var ret = this._search_result_init(result_count, max_count); ret.push(this.search_result_script(script)); return ret; }; this._search_result_init = function(result_count, max_count) { var ret = ['div']; this._js_search_ctx = {count: 0, max_count: max_count}; if (result_count > max_count) { ret.push(['div', ['div', ui_strings.S_INFO_TOO_MANY_SEARCH_RESULTS .replace('%(COUNT)s', result_count) .replace('%(MAX)s', max_count), 'class', 'info-box'], 'class', 'info-box-container']); } return ret; }; this._search_result_header = function(rt_id) { var runtime = window.runtimes.getRuntime(rt_id); var display_uri = runtime && helpers.shortenURI(runtime.uri); return ['h2', runtime && (runtime.title || display_uri.uri) || '']; }; this._format_line_no = function(line_no) { line_no = String(line_no); var padding = [' ', ' ', ' ', ' ', ' ', ' ']; return (padding[line_no.length] || '') + line_no; }; this.resource_link = function(url, text, line) { var ret = ["span", text, "handler", "open-resource-tab", "data-resource-url", url, "class", "internal-link"]; if (line) { ret.push("data-resource-line-number", String(line)); } return ret; }; this.search_result_script = function(script, show_script_uri) { var ret = ['div']; if (this._js_search_ctx.count < this._js_search_ctx.max_count) { if (typeof show_script_uri != 'boolean' || show_script_uri) { var h3 = ['h3']; if (script.uri) { h3.push(this.resource_link(script.uri, script.uri), ':'); } else if (script.script_type == "inline") { var rt = window.runtimes.getRuntime(script.runtime_id); if (rt && rt.uri) { h3.push(script.script_type + " ("); h3.push(this.resource_link(rt.uri, rt.uri)); h3.push("):"); } } else { h3.push(script.script_type + ":"); } ret.push(h3); } var line = 0, cur_line = 0, script_data = '', script_tmpl = null, cur = null; for (var i = 0; i < script.line_matches.length; i++) { if (this._js_search_ctx.count++ < this._js_search_ctx.max_count) { cur_line = script.line_matches[i]; if (cur_line != line) { line = cur_line; script_data = script.script_data.slice(script.line_arr[line - 1], script.line_arr[line]); script_tmpl = this.highlight_js_source(script_data, null, script.state_arr[line - 1], ['code'], true); if (script_tmpl.length == 2 && RE_WS.test(script_tmpl[1])) { script_tmpl[1] += "\u00a0"; } if (script.line_offsets_length[i] && script.line_offsets[i] + script.line_offsets_length[i] > script.get_line_length(line)) { script_tmpl.push(['span', '…', 'class', 'match-following-line']) } ret.push(['div', ['span', String(line), 'class', 'line-no'], script_tmpl, 'data-line-no', String(line), 'class', 'search-match js-search']); } } } ret.push('class', 'js-search-results-script js-source', 'data-script-id', String(script.script_id)); } return ret; }; }).apply(window.templates || (window.templates = {}));
operasoftware/dragonfly
src/searches/templates.js
JavaScript
apache-2.0
9,442
/* * ../../../..//localization/fr/HelpDialog.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ /************************************************************* * * MathJax/localization/fr/HelpDialog.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("fr", "HelpDialog", { version: "2.7.5", isLoaded: true, strings: { Help: "Aide MathJax", MathJax: "*MathJax* est une biblioth\u00E8que JavaScript qui permet aux auteurs de pages d\u2019inclure des math\u00E9matiques dans leurs pages web. En tant que lecteur, vous n\u2019avez rien besoin de faire pour que cela fonctionne.", Browsers: "*Navigateurs*: MathJax fonctionne avec tous les navigateurs modernes y compris Internet Explorer 6, Firefox 3, Chrome 0.2, Safari 2, Opera 9.6 et leurs versions sup\u00E9rieures ainsi que la plupart des navigateurs pour mobiles et tablettes.", Menu: "*Menu math*: MathJax ajoute un menu contextuel aux \u00E9quations. Cliquez-droit ou Ctrl-cliquez sur n\u2019importe quelle formule math\u00E9matique pour acc\u00E9der au menu.", ShowMath: "*Afficher les maths comme* vous permet d\u2019afficher le balisage source de la formule pour copier-coller (comme MathML ou dans son format d\u2019origine).", Settings: "*Param\u00E8tres* vous donne le contr\u00F4le sur les fonctionnalit\u00E9s de MathJax, comme la taille des math\u00E9matiques, et le m\u00E9canisme utilis\u00E9 pour afficher les \u00E9quations.", Language: "*Langue* vous laisse s\u00E9lectionner la langue utilis\u00E9e par MathJax pour ses menus et ses messages d\u2019avertissement.", Zoom: "*Zoom des maths*: Si vous avez des difficult\u00E9s \u00E0 lire une \u00E9quation, MathJax peut l\u2019agrandir pour vous aider \u00E0 mieux la voir.", Accessibilty: "*Accessibilit\u00E9*: MathJax travaillera automatiquement avec les lecteurs d\u2019\u00E9cran pour rendre les math\u00E9matiques accessibles aux malvoyants.", Fonts: "*Polices*: MathJax utilisera certaines polices math\u00E9matiques si elles sont install\u00E9es sur votre ordinateur\u202F; sinon, il utilisera les polices trouv\u00E9es sur le web. Bien que ce ne soit pas obligatoire, des polices install\u00E9es localement acc\u00E9l\u00E9reront la composition. Nous vous sugg\u00E9rons d\u2019installer les [polices STIX](%1).", CloseDialog: "Fermer la bo\u00EEte de dialogue d\u2019aide" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/fr/HelpDialog.js");
GerHobbelt/MathJax
localization/fr/HelpDialog.js
JavaScript
apache-2.0
3,680
function Vec2(_x, _y) { var self = this; self.x = _x; self.y = _y; self.Distance = function (OtherPoint) { try { return Math.sqrt(Math.pow(OtherPoint.x - self.x, 2) + Math.pow(OtherPoint.y - self.y, 2)); } catch (e) { console.error(e); return false; } } } function getMCC(c, e) { var x; var y; if (e.pageX || e.pageY) { x = e.pageX; y = e.pageY; } else { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } x -= c.offsetLeft + c.clientLeft; y -= c.offsetTop + c.clientTop; return new Vec2(x, y); }
SpencerAlanWatson/Javascript-Expierments
public/js/utilities.js
JavaScript
apache-2.0
751
MotorTemperatures = new Mongo.Collection('MotorTemperatures'); // fields : value, timestamp MotorTemperatures.allow({ insert: function(userid, temp){return true;} //for now }); Meteor.methods({ motorTemperatureInsert: function(temp) { check(temp,Match.Integer); var tempObject = { value: temp, timestamp: Date.now() }; MotorTemperatures.insert(tempObject); } }); if(Meteor.isClient){ Session.set("actualMotorTemp",MotorTemperatures.find({}, {sort: {timestamp: -1}, limit:1}).fetch()[0]); motorTemps = []; Session.set("motorTemps", motorTemps); MotorTemperatures.find().observe({ added: function(temp){ Session.set("actualMotorTemp",temp); var localMotorTemps = Session.get("motorTemps"); localMotorTemps.push({x:temp.timestamp, y:temp.value}); if(localMotorTemps.length > 50){ localMotorTemps.shift(); } Session.set("motorTemps", localMotorTemps); } }); }
yanisIk/TelemetryDashboard
.old app/collections/motorTemperature.js
JavaScript
apache-2.0
973
/*global define*/ define([ '../Core/combine', '../Core/Credit', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/DeveloperError', '../Core/Event', '../Core/freezeObject', '../Core/isArray', '../Core/objectToQuery', '../Core/queryToObject', '../Core/Rectangle', '../Core/WebMercatorTilingScheme', '../ThirdParty/Uri', '../ThirdParty/when', './ImageryProvider' ], function( combine, Credit, defaultValue, defined, defineProperties, DeveloperError, Event, freezeObject, isArray, objectToQuery, queryToObject, Rectangle, WebMercatorTilingScheme, Uri, when, ImageryProvider) { 'use strict'; /** * Provides tiled imagery served by {@link http://www.opengeospatial.org/standards/wmts|WMTS 1.0.0} compliant servers. * This provider supports HTTP KVP-encoded and RESTful GetTile requests, but does not yet support the SOAP encoding. * * @alias WebMapTileServiceImageryProvider * @constructor * * @param {Object} options Object with the following properties: * @param {String} options.url The base URL for the WMTS GetTile operation (for KVP-encoded requests) or the tile-URL template (for RESTful requests). The tile-URL template should contain the following variables: &#123;style&#125;, &#123;TileMatrixSet&#125;, &#123;TileMatrix&#125;, &#123;TileRow&#125;, &#123;TileCol&#125;. The first two are optional if actual values are hardcoded or not required by the server. The &#123;s&#125; keyword may be used to specify subdomains. * @param {String} [options.format='image/jpeg'] The MIME type for images to retrieve from the server. * @param {String} options.layer The layer name for WMTS requests. * @param {String} options.style The style name for WMTS requests. * @param {String} options.tileMatrixSetID The identifier of the TileMatrixSet to use for WMTS requests. * @param {Array} [options.tileMatrixLabels] A list of identifiers in the TileMatrix to use for WMTS requests, one per TileMatrix level. * @param {Number} [options.tileWidth=256] The tile width in pixels. * @param {Number} [options.tileHeight=256] The tile height in pixels. * @param {TilingScheme} [options.tilingScheme] The tiling scheme corresponding to the organization of the tiles in the TileMatrixSet. * @param {Object} [options.proxy] A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL. * @param {Rectangle} [options.rectangle=Rectangle.MAX_VALUE] The rectangle covered by the layer. * @param {Number} [options.minimumLevel=0] The minimum level-of-detail supported by the imagery provider. * @param {Number} [options.maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit. * @param {Ellipsoid} [options.ellipsoid] The ellipsoid. If not specified, the WGS84 ellipsoid is used. * @param {Credit|String} [options.credit] A credit for the data source, which is displayed on the canvas. * @param {String|String[]} [options.subdomains='abc'] The subdomains to use for the <code>{s}</code> placeholder in the URL template. * If this parameter is a single string, each character in the string is a subdomain. If it is * an array, each element in the array is a subdomain. * * * @example * // Example 1. USGS shaded relief tiles (KVP) * var shadedRelief1 = new Cesium.WebMapTileServiceImageryProvider({ * url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS', * layer : 'USGSShadedReliefOnly', * style : 'default', * format : 'image/jpeg', * tileMatrixSetID : 'default028mm', * // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...], * maximumLevel: 19, * credit : new Cesium.Credit('U. S. Geological Survey') * }); * viewer.imageryLayers.addImageryProvider(shadedRelief1); * * @example * // Example 2. USGS shaded relief tiles (RESTful) * var shadedRelief2 = new Cesium.WebMapTileServiceImageryProvider({ * url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS/tile/1.0.0/USGSShadedReliefOnly/{Style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpg', * layer : 'USGSShadedReliefOnly', * style : 'default', * format : 'image/jpeg', * tileMatrixSetID : 'default028mm', * maximumLevel: 19, * credit : new Cesium.Credit('U. S. Geological Survey') * }); * viewer.imageryLayers.addImageryProvider(shadedRelief2); * * @see ArcGisMapServerImageryProvider * @see BingMapsImageryProvider * @see GoogleEarthImageryProvider * @see createOpenStreetMapImageryProvider * @see SingleTileImageryProvider * @see createTileMapServiceImageryProvider * @see WebMapServiceImageryProvider * @see UrlTemplateImageryProvider */ function WebMapTileServiceImageryProvider(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); //>>includeStart('debug', pragmas.debug); if (!defined(options.url)) { throw new DeveloperError('options.url is required.'); } if (!defined(options.layer)) { throw new DeveloperError('options.layer is required.'); } if (!defined(options.style)) { throw new DeveloperError('options.style is required.'); } if (!defined(options.tileMatrixSetID)) { throw new DeveloperError('options.tileMatrixSetID is required.'); } //>>includeEnd('debug'); this._url = options.url; this._layer = options.layer; this._style = options.style; this._tileMatrixSetID = options.tileMatrixSetID; this._tileMatrixLabels = options.tileMatrixLabels; this._format = defaultValue(options.format, 'image/jpeg'); this._proxy = options.proxy; this._tileDiscardPolicy = options.tileDiscardPolicy; this._tilingScheme = defined(options.tilingScheme) ? options.tilingScheme : new WebMercatorTilingScheme({ ellipsoid : options.ellipsoid }); this._tileWidth = defaultValue(options.tileWidth, 256); this._tileHeight = defaultValue(options.tileHeight, 256); this._minimumLevel = defaultValue(options.minimumLevel, 0); this._maximumLevel = options.maximumLevel; this._rectangle = defaultValue(options.rectangle, this._tilingScheme.rectangle); this._readyPromise = when.resolve(true); // Check the number of tiles at the minimum level. If it's more than four, // throw an exception, because starting at the higher minimum // level will cause too many tiles to be downloaded and rendered. var swTile = this._tilingScheme.positionToTileXY(Rectangle.southwest(this._rectangle), this._minimumLevel); var neTile = this._tilingScheme.positionToTileXY(Rectangle.northeast(this._rectangle), this._minimumLevel); var tileCount = (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1); //>>includeStart('debug', pragmas.debug); if (tileCount > 4) { throw new DeveloperError('The imagery provider\'s rectangle and minimumLevel indicate that there are ' + tileCount + ' tiles at the minimum level. Imagery providers with more than four tiles at the minimum level are not supported.'); } //>>includeEnd('debug'); this._errorEvent = new Event(); var credit = options.credit; this._credit = typeof credit === 'string' ? new Credit(credit) : credit; this._subdomains = options.subdomains; if (isArray(this._subdomains)) { this._subdomains = this._subdomains.slice(); } else if (defined(this._subdomains) && this._subdomains.length > 0) { this._subdomains = this._subdomains.split(''); } else { this._subdomains = ['a', 'b', 'c']; } } var defaultParameters = freezeObject({ service : 'WMTS', version : '1.0.0', request : 'GetTile' }); function buildImageUrl(imageryProvider, col, row, level) { var labels = imageryProvider._tileMatrixLabels; var tileMatrix = defined(labels) ? labels[level] : level.toString(); var subdomains = imageryProvider._subdomains; var url; if (imageryProvider._url.indexOf('{') >= 0) { // resolve tile-URL template url = imageryProvider._url .replace('{style}', imageryProvider._style) .replace('{Style}', imageryProvider._style) .replace('{TileMatrixSet}', imageryProvider._tileMatrixSetID) .replace('{TileMatrix}', tileMatrix) .replace('{TileRow}', row.toString()) .replace('{TileCol}', col.toString()) .replace('{s}', subdomains[(col + row + level) % subdomains.length]); } else { // build KVP request var uri = new Uri(imageryProvider._url); var queryOptions = queryToObject(defaultValue(uri.query, '')); queryOptions = combine(defaultParameters, queryOptions); queryOptions.tilematrix = tileMatrix; queryOptions.layer = imageryProvider._layer; queryOptions.style = imageryProvider._style; queryOptions.tilerow = row; queryOptions.tilecol = col; queryOptions.tilematrixset = imageryProvider._tileMatrixSetID; queryOptions.format = imageryProvider._format; uri.query = objectToQuery(queryOptions); url = uri.toString(); } var proxy = imageryProvider._proxy; if (defined(proxy)) { url = proxy.getURL(url); } return url; } defineProperties(WebMapTileServiceImageryProvider.prototype, { /** * Gets the URL of the service hosting the imagery. * @memberof WebMapTileServiceImageryProvider.prototype * @type {String} * @readonly */ url : { get : function() { return this._url; } }, /** * Gets the proxy used by this provider. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Proxy} * @readonly */ proxy : { get : function() { return this._proxy; } }, /** * Gets the width of each tile, in pixels. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Number} * @readonly */ tileWidth : { get : function() { return this._tileWidth; } }, /** * Gets the height of each tile, in pixels. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Number} * @readonly */ tileHeight : { get : function() { return this._tileHeight; } }, /** * Gets the maximum level-of-detail that can be requested. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Number} * @readonly */ maximumLevel : { get : function() { return this._maximumLevel; } }, /** * Gets the minimum level-of-detail that can be requested. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Number} * @readonly */ minimumLevel : { get : function() { return this._minimumLevel; } }, /** * Gets the tiling scheme used by this provider. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {TilingScheme} * @readonly */ tilingScheme : { get : function() { return this._tilingScheme; } }, /** * Gets the rectangle, in radians, of the imagery provided by this instance. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Rectangle} * @readonly */ rectangle : { get : function() { return this._rectangle; } }, /** * Gets the tile discard policy. If not undefined, the discard policy is responsible * for filtering out "missing" tiles via its shouldDiscardImage function. If this function * returns undefined, no tiles are filtered. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {TileDiscardPolicy} * @readonly */ tileDiscardPolicy : { get : function() { return this._tileDiscardPolicy; } }, /** * Gets an event that is raised when the imagery provider encounters an asynchronous error. By subscribing * to the event, you will be notified of the error and can potentially recover from it. Event listeners * are passed an instance of {@link TileProviderError}. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Event} * @readonly */ errorEvent : { get : function() { return this._errorEvent; } }, /** * Gets the mime type of images returned by this imagery provider. * @memberof WebMapTileServiceImageryProvider.prototype * @type {String} * @readonly */ format : { get : function() { return this._format; } }, /** * Gets a value indicating whether or not the provider is ready for use. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Boolean} * @readonly */ ready : { value: true }, /** * Gets a promise that resolves to true when the provider is ready for use. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Promise.<Boolean>} * @readonly */ readyPromise : { get : function() { return this._readyPromise; } }, /** * Gets the credit to display when this imagery provider is active. Typically this is used to credit * the source of the imagery. This function should not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Credit} * @readonly */ credit : { get : function() { return this._credit; } }, /** * Gets a value indicating whether or not the images provided by this imagery provider * include an alpha channel. If this property is false, an alpha channel, if present, will * be ignored. If this property is true, any images without an alpha channel will be treated * as if their alpha is 1.0 everywhere. When this property is false, memory usage * and texture upload time are reduced. * @memberof WebMapTileServiceImageryProvider.prototype * @type {Boolean} * @readonly */ hasAlphaChannel : { get : function() { return true; } } }); /** * Gets the credits to be displayed when a given tile is displayed. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level; * @returns {Credit[]} The credits to be displayed when the tile is displayed. * * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready. */ WebMapTileServiceImageryProvider.prototype.getTileCredits = function(x, y, level) { return undefined; }; /** * Requests the image for a given tile. This function should * not be called before {@link WebMapTileServiceImageryProvider#ready} returns true. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @returns {Promise.<Image|Canvas>|undefined} A promise for the image that will resolve when the image is available, or * undefined if there are too many active requests to the server, and the request * should be retried later. The resolved image may be either an * Image or a Canvas DOM object. * * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready. */ WebMapTileServiceImageryProvider.prototype.requestImage = function(x, y, level) { var url = buildImageUrl(this, x, y, level); return ImageryProvider.loadImage(this, url); }; /** * Picking features is not currently supported by this imagery provider, so this function simply returns * undefined. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @param {Number} longitude The longitude at which to pick features. * @param {Number} latitude The latitude at which to pick features. * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous * picking completes. The resolved value is an array of {@link ImageryLayerFeatureInfo} * instances. The array may be empty if no features are found at the given location. * It may also be undefined if picking is not supported. */ WebMapTileServiceImageryProvider.prototype.pickFeatures = function(x, y, level, longitude, latitude) { return undefined; }; return WebMapTileServiceImageryProvider; });
atrawog/360-flight-explorer
Source/Scene/WebMapTileServiceImageryProvider.js
JavaScript
apache-2.0
19,958
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Elem=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var _ = require('./utils'); var globalObject = _.memoGobalObject(); exports.debug = false; exports.perfs = false; exports.voidElements = ["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "META", "PARAM", "SOURCE", "TRACK", "WBR"]; exports.events = ['wheel', 'scroll', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'click', 'doubleclick', 'drag', 'dragend', 'dragenter', 'dragexit', 'dragleave', 'dragover', 'dragstart', 'drop', 'change', 'input', 'submit', 'focus', 'blur', 'keydown', 'keypress', 'keyup', 'copy', 'cut', 'paste', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup']; // redraw with requestAnimationFrame (https://developer.mozilla.org/fr/docs/Web/API/window.requestAnimationFrame) // perfs measures (http://www.html5rocks.com/en/tutorials/webperformance/usertiming/) var Performances = { mark: function() {}, measure: function() {}, getEntriesByName: function() { return []; }, getEntriesByType: function() { return []; }, clearMarks: function() {}, clearMeasures: function() {} }; // Avoid some issues in non browser environments if (typeof globalObject === 'undefined') { globalObject = { __fake: true }; } // Avoid some issues in older browsers if (typeof globalObject.console === 'undefined') { globalObject.console = { log: function() {}, error: function() {}, table: function() {}, debug: function() {}, trace: function() {} }; } if (typeof globalObject.performance !== 'undefined' && typeof globalObject.performance.mark !== 'undefined' && typeof globalObject.performance.measure !== 'undefined') { Performances = globalObject.performance; } globalObject.requestAnimationFrame = globalObject.requestAnimationFrame || globalObject.mozRequestAnimationFrame || globalObject.webkitRequestAnimationFrame || globalObject.msRequestAnimationFrame || (function() { if (globalObject.console) console.error('[ELEMJS] No requestAnimationFrame, using lame polyfill ...'); return function(callback, element) { globalObject.setTimeout(callback, 1000 / 60); } })(); var ElemMeasureStart = 'ElemMeasureStart'; var ElemMeasureStop = 'ElemMeasureStop'; var ElemMeasure = 'ElemComponentRenderingMeasure'; var names = [ElemMeasure]; exports.markStart = function(name) { if (exports.perfs) { if (name) { Performances.mark(name + '_start'); } else { Performances.mark(ElemMeasureStart); } } }; exports.markStop = function(name) { if (exports.perfs) { if (name) { Performances.mark(name + '_stop'); Performances.measure(name, name + '_start', name + '_stop'); if (!_.contains(names, name)) names.push(name); } else { Performances.mark(ElemMeasureStop); Performances.measure(ElemMeasure, ElemMeasureStart, ElemMeasureStop); } } }; exports.collectMeasures = function() { if (!exports.perfs) return []; var results = []; _.each(names, function(name) { results = results.concat(Performances.getEntriesByName(name)); }); Performances.clearMarks(); Performances.clearMeasures(); names = [ElemMeasure]; return results; }; exports.printMeasures = function() { if (!exports.perfs) return; if (globalObject.console) console.table(exports.collectMeasures()); }; exports.defer = function(cb) { globalObject.requestAnimationFrame.call(globalObject, cb); }; exports.defered = function(cb) { return function() { exports.defer(cb); }; }; exports.__internalAccess = {}; if (!Function.prototype.bind) { if (globalObject.console) console.error('[ELEMJS] No Function.prototype.bind, using polyfill ...'); Function.prototype.bind = function(oThis) { if (typeof this !== "function") { throw new TypeError("Function.prototype.bind - can't call bounded element"); } var aArgs = Array.prototype.slice.call(arguments, 1); var fToBind = this; var fNOP = function() {}; var fBound = function() { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } },{"./utils":7}],2:[function(require,module,exports){ var Common = require('./common'); var State = require('./state'); var _ = require('./utils'); var mounted = {}; function hasData(node, name) { return node.attributes && node.attributes['data-' + name]; } function data(node, name) { if (node.dataset) return node.dataset[name]; return node.attributes['data-' + name]; } function unmountComponent(el) { if (mounted[el]) { mounted[el](); delete mounted[el]; // TODO : find a way to remove all listeners } } function mountComponent(el, opts) { var Elem = Common.__internalAccess.api; var name = opts.name || 'Component'; var defaultProps = opts.defaultProps || function() { return {}; }; var initialState = opts.initialState || function() { return {}; }; var state = State(initialState()); var props = defaultProps(); opts.props = props; opts.state = state.all(); opts.setState = state.set; opts.replaceState = state.replace; state.onChange(function() { opts.state = state.all(); }); var eventCallbacks = {}; var oldHandlers = []; var innerComponents = []; // autobinding _.each(_.keys(opts), function(k) { if (_.isFunction(opts[k])) { opts[k] = opts[k].bind(opts); } }); var init = (opts.init || function() {}); var beforeRender = (opts.beforeRender || function() {}); var render = (opts.render || function() {}); var afterRender = (opts.afterRender || function() {}); var unmount = (opts.unmount || function() {}); var getDOMNode = function() { return _.findNode(el); }; opts.context = { refs: {}, getDOMNode: getDOMNode }; var eventsCallback = function(e) { // bubbles listener, TODO : handle mouse event in a clever way e = e || window.event; var node = e.target || e.srcElement; var name = data(node, 'nodeid') + '_' + e.type; //node.dataset.nodeid + "_" + e.type; if (eventCallbacks[name]) { eventCallbacks[name](e); } else { while (!eventCallbacks[name] && node && node !== null && hasData(node, 'nodeid')) { //node.dataset && node.dataset.nodeid) { node = node.parentElement; if (node && node !== null && hasData(node, 'nodeid')) { //node.dataset && node.dataset.nodeid) { name = data(node, 'nodeid') + '_' + e.type; //node.dataset.nodeid + "_" + e.type; } } if (eventCallbacks[name]) { eventCallbacks[name](e); } } }; unmountComponent(el); mounted[el] = function() { unmount(state, _.clone(props), opts.context); state.replace({}, true); _.off(el, Common.events, eventsCallback); }; init(state, _.clone(props)); _.on(el, Common.events, eventsCallback); function rerender() { Common.markStart(name + '.globalRendering'); _.each(oldHandlers, function(handler) { delete eventCallbacks[handler]; }); oldHandlers = []; var focus = document.activeElement || {}; // TODO : check if input/select/textarea, remember cursor position here var key = focus.dataset ? focus.dataset.key : (focus.attributes || [])['key']; // TODO : maybe a bug here opts.context.refs = {}; var waitingHandlers = []; _.each(innerComponents, function(c) { unmountComponent(c); }); innerComponents = []; beforeRender(state, _.clone(props), opts.context); Common.markStart(name + '.render'); var elemToRender = render(state, _.clone(props), opts.context); Common.markStop(name + '.render'); Elem.render(elemToRender, el, { waitingHandlers: waitingHandlers, __rootListener: true, refs: opts.context.refs, __innerComponents: innerComponents }); afterRender(state, _.clone(props), opts.context); if (key) { var focusNode = document.querySelector('[data-key="' + key + '"]'); //$('[data-key="' + key + '"]'); _.focus(focusNode); // focusNode.focus(); // TODO : maybe a bug here if (focusNode.value) { //focusNode.val()) { var strLength = focusNode.value.length * 2; // focusNode.val().length * 2; focusNode.setSelectionRange(strLength, strLength); //focusNode[0].setSelectionRange(strLength, strLength); // TODO : handle other kind of input ... like select, etc ... } } _.each(waitingHandlers, function(handler) { oldHandlers.push(handler.id + '_' + handler.event.replace('on', '')); eventCallbacks[handler.id + '_' + handler.event.replace('on', '')] = function() { handler.callback.apply({ render: render }, arguments); } }); Common.markStop(name + '.globalRendering'); } rerender(); state.onChange(rerender); //Common.defered(rerender)); return state; } function serverSideComponent(opts, nodataid) { var Elem = Common.__internalAccess.api; var name = opts.name || 'Component'; var defaultProps = opts.defaultProps || function() { return {}; }; var initialState = opts.initialState || function() { return {}; }; var state = State(initialState()); var props = defaultProps(); opts.props = props; opts.state = state.all(); opts.setState = state.set; opts.replaceState = state.replace; opts.context = { refs: refs, getDOMNode: function() {} }; // autobinding _.each(_.keys(opts), function(k) { if (_.isFunction(opts[k])) { opts[k] = opts[k].bind(opts); } }); var render = opts.render; var afterRender = opts.afterRender || function() {}; if (opts.init) { opts.init(state, _.clone(props)); } Common.markStart(name + '.globalRendering'); var refs = {}; Common.markStart(name + '.render'); var elemToRender = render(state, _.clone(props), opts.context); Common.markStop(name + '.render'); var str = Elem.renderToString(elemToRender, { waitingHandlers: [], __rootListener: true, refs: refs, __noDataId: nodataid, __innerComponents: [] }); afterRender(state, _.clone(props), opts.context); Common.markStop(name + '.globalRendering'); return str; } function factory(opts) { var defaultProps = {}; if (opts.defaultProps) { defaultProps = opts.defaultProps(); } return function(props, to) { var api = { __componentFactory: true, renderToStaticHtml: function() { var opt = _.clone(opts); opt.props = _.extend(_.clone(defaultProps || {}), props || {}); return serverSideComponent(opt, true); }, renderToString: function() { var opt = _.clone(opts); opt.props = _.extend(_.clone(defaultProps || {}), props || {}); return serverSideComponent(opt); }, renderTo: function(el, defer) { var opt = _.clone(opts); opt.defaultProps = function() { return _.extend(_.clone(defaultProps || {}), props || {}); }; if (defer) { Common.defer(function() { mountComponent(el, opt); }); } else { return mountComponent(el, opt); } } }; if (to) return api.renderTo(to); return api; } } exports.unmountComponent = unmountComponent; exports.component = function(opts) { if (!opts.container) return factory(opts); var el = opts.container; mountComponent(el, opts); }; exports.componentToString = function(opts) { var opt = _.clone(opts); opt.props = _.extend(_.clone(opts.props || {}), props || {}); return serverSideComponent(opt); }; },{"./common":1,"./state":5,"./utils":7}],3:[function(require,module,exports){ var Common = require('./common'); var _ = require('./utils'); var Components = require('./component'); var state = require('./state'); var registerWebComponent = require('./webcomponent').registerWebComponent; var Stringifier = require('./stringify'); var Dispatcher = require('./events'); exports.svgNS = "http://www.w3.org/2000/svg"; function styleToString(attrs) { if (_.isUndefined(attrs)) return ''; var attrsArray = _.map(_.keys(attrs), function(key) { var keyName = _.dasherize(key); if (key === 'className') { keyName = 'class'; } var value = attrs[key]; if (!_.isUndefined(value) && _.isFunction(value)) { value = value(); } if (!_.isUndefined(value)) { return keyName + ': ' + value + ';'; } else { return undefined; } }); attrsArray = _.filter(attrsArray, function(item) { return !_.isUndefined(item); }); return attrsArray.join(' '); } function classToArray(attrs) { /* Handle class as object with boolean values */ if (_.isUndefined(attrs)) return []; var attrsArray = _.map(_.keys(attrs), function(key) { var value = attrs[key]; if (!_.isUndefined(value) && value === true) { return _.dasherize(key); } else { return undefined; } }); attrsArray = _.filter(attrsArray, function(item) { return !_.isUndefined(item); }); return attrsArray; } function wrapChildren(children) { if (children === 0) { return children; } else if (children === '') { return []; } return children || []; } function buildRef(id) { return { getDOMNode: function() { return _.findNode('[data-nodeid="' + id + '"]'); } }; } function extractEventHandlers(attrs, nodeId, context) { _.each(_.keys(attrs), function(key) { var keyName = _.dasherize(key); if (_.startsWith(keyName, 'on')) { if (context && context.waitingHandlers) { context.waitingHandlers.push({ root: context.root, id: nodeId, event: keyName.toLowerCase(), callback: attrs[key] }); } } if (keyName === 'ref' && context && context.refs) context.refs[attrs[key]] = buildRef(nodeId); }); } function asAttribute(key, value) { return { key: key, value: value }; } function attributesToArray(attrs) { if (_.isUndefined(attrs)) return []; var attrsArray = []; _.each(_.keys(attrs), function(key) { var keyName = _.dasherize(key); if (key === 'className') { keyName = 'class'; } if (!_.startsWith(keyName, 'on') && keyName !== 'ref') { var value = attrs[key]; if (!_.isUndefined(value) && _.isFunction(value)) { value = value(); } if (!_.isUndefined(value)) { if (_.isObject(value) && keyName === 'style') { attrsArray.push(asAttribute('style', styleToString(value))); } else if (_.isArray(value) && keyName === 'class') { attrsArray.push(asAttribute(keyName, value.join(' '))); } else if (_.isObject(value) && keyName === 'class') { attrsArray.push(asAttribute(keyName, classToArray(value).join(' '))); } else { attrsArray.push(asAttribute(keyName, value)); } } } }); return attrsArray; } function el(name, attrs, children) { var svg = attrs.namespace; delete attrs.namespace; var nodeId = _.uniqueId('node_'); if (_.isUndefined(children) && !_.isUndefined(attrs) && !attrs.__isAttrs) { children = attrs; attrs = {}; } if (arguments.length > 3) { name = arguments[0]; if (!attrs.isElement) { attrs = arguments[1]; } else { attrs = {}; } children = [].concat(arguments); children.shift(); children.shift(); } name = _.escape(name) || 'unknown'; attrs = attrs || {}; children = wrapChildren(children); if (_.isRegExp(children) || _.isUndefined(children) || _.isNull(children)) children = []; if (_.isArray(children)) { children = _.chain(children).map(function(child) { if (_.isFunction(child)) { return child(); } else { return child; } }).filter(function(item) { return !_.isUndefined(item); }).value(); } var selfCloseTag = _.contains(Common.voidElements, name.toUpperCase()) && (_.isNull(children) || _.isUndefined(children) || (_.isArray(children) && children.length === 0)); var attrsArray = attributesToArray(attrs); attrsArray.push(asAttribute('data-nodeid', _.escape(nodeId))); if (Common.debug) attrsArray.push(asAttribute('title', _.escape(nodeId))); return { name: name, attrs: attrs, children: children, isElement: true, nodeId: nodeId, toJsonString: function(pretty) { if (pretty) return JSON.stringify(this, null, 2); return JSON.stringify(this); }, toHtmlNode: function(doc, context) { var elemName = this.name; extractEventHandlers(attrs, nodeId, context); var element = undefined; if (svg) { element = doc.createElementNS(svg, _.escape(name)); } else { element = doc.createElement(_.escape(name)); } _.each(attrsArray, function(item) { if (elemName && elemName === 'input' && item.key === 'value') { element.value = item.value; } else { element.setAttribute(item.key, item.value); } }); function appendSingleNode(__children, __element) { if (_.isNumber(__children)) { __element.appendChild(doc.createTextNode(__children + '')); } else if (_.isString(__children)) { __element.appendChild(doc.createTextNode(__children)); } else if (_.isBoolean(__children)) { __element.appendChild(doc.createTextNode(__children + '')); } else if (_.isObject(__children) && __children.isElement) { __element.appendChild(__children.toHtmlNode(doc, context)); } else if (_.isObject(__children) && __children.__asHtml) { __element.innerHTML = __children.__asHtml; } else if (__children.__componentFactory) { var compId = _.escape(_.uniqueId('component_')); var span = doc.createElement('span'); span.setAttribute('data-componentid', compId); __element.appendChild(span); context.__innerComponents.push('[data-componentid="' + compId + '"]'); __children.renderTo('[data-componentid="' + compId + '"]', true); } else { __element.appendChild(doc.createTextNode(__children.toString())); } } if (!selfCloseTag) { if (_.isArray(children)) { _.each(children, function(child) { appendSingleNode(child, element); }); } else { appendSingleNode(children, element); } } return element; } }; } function renderToNode(el, doc, context) { if (_.isFunction(el)) el = el((context || { props: {} }).props) if (!_.isUndefined(el)) { if (_.isArray(el)) { return _.chain(el).map(function(item) { if (_.isFunction(item)) { return item(); } else { return item; } }).filter(function(item) { return !_.isUndefined(item); }).map(function(item) { return item.toHtmlNode(doc, context); }).value(); } else { return [el.toHtmlNode(doc, context)]; } } else { return []; } } exports.renderToString = function(el, context) { Common.markStart('Elem.renderToString'); var str = _.map(renderToNode(el, Stringifier(context)), function(n) { return n.toHtmlString(); }).join(''); Common.markStop('Elem.renderToString'); return str; }; exports.renderToStaticHtml = function(el) { Common.markStart('Elem.renderToStaticHtml'); var str = _.map(renderToNode(el, Stringifier({ __noDataId: true })), function(n) { return n.toHtmlString(); }).join(''); Common.markStop('Elem.renderToStaticHtml'); return str; } exports.el = el; exports.jsx = function(name, attrs) { for (var _len = arguments.length, children = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } var flatChildren = children; if (children !== undefined && children.length === 1) { flatChildren = children[0]; } return attrs === null ? vel(name, flatChildren) : el(name, attrs, flatChildren); } exports.sel = function(name, children) { return el(name, {}, children); }; // simple node sel(name, children) exports.vel = function(name, attrs) { return el(name, attrs, []); }; // void node, cel(name, attrs) exports.svg = function(name, attrs, children) { attrs.namespace = exports.svgNS; if (!children) { return el(name, {}, attrs); } return el(name, attrs, children); }; exports.vsvg = function(name, attrs) { attrs.namespace = exports.svgNS; return el(name, attrs, []); }; exports.nbsp = function(times) { return el('span', { __asHtml: _.times(times || 1, function() { return '&nbsp;'; }) }); }; exports.text = function(text) { return el('span', {}, text); }; exports.render = function(el, node, context) { Common.markStart('Elem.render'); var waitingHandlers = (context || {}).waitingHandlers || []; var refs = (context || {}).refs || {}; var props = (context || {}).props || {}; var __innerComponents = (context || {}).__innerComponents || []; var doc = document; if (node.ownerDocument) { doc = node.ownerDocument; } if (_.isString(node)) { node = doc.querySelector(node); } if (!_.isUndefined(node) && !_.isNull(node)) { var htmlNode = renderToNode(el, doc, { root: node, waitingHandlers: waitingHandlers, refs: refs, props: props, __innerComponents: __innerComponents }); while (!_.isUndefined(node) && !_.isNull(node) && node.firstChild) { node.removeChild(node.firstChild); } _.each(htmlNode, function(n) { if (!_.isUndefined(node) && !_.isNull(node)) node.appendChild(n); }); if (!(context && context.__rootListener)) { // external listener here _.each(waitingHandlers, function(handler) { // handler on each concerned node _.on('[data-nodeid="' + handler.id + '"]', [handler.event.replace('on', '')], function() { handler.callback.apply({}, arguments); }); }); } } Common.markStop('Elem.render'); }; exports.unmountComponent = Components.unmountComponent; exports.component = Components.component; exports.componentToString = Components.componentToString; exports.state = state; exports.Utils = _; exports.registerWebComponent = registerWebComponent; exports.dispatcher = Dispatcher; exports.Perf = { start: function() { Common.perfs = true; }, stop: function() { Common.stop = false; }, markStart: Common.markStart, markStop: Common.markStop, collectMeasures: Common.collectMeasures, printMeasures: Common.printMeasures }; exports.defer = Common.defer; exports.predicate = function(predicate, what) { if (_.isFunction(predicate)) { if (predicate() === true) { return what; } else { return undefined; } } else { if (predicate === true) { return what; } else { return undefined; } } }; exports.style = function(obj) { var result = {}; var keys = _.keys(obj); _.each(keys, function(key) { var clazz = obj[key]; if (_.isObject(clazz)) { result[key] = _.extend({}, { extend: function(o) { return _.extend({}, o, clazz); } }, clazz); } }); result.extend = _.extend({}, { extend: function(o) { return _.extend({}, o, obj); } }, obj); return result; }; Common.__internalAccess.api = exports; if (typeof define === 'function' && define.amd) { define('elem', [], function() { return module.exports; }); } },{"./common":1,"./component":2,"./events":4,"./state":5,"./stringify":6,"./utils":7,"./webcomponent":8}],4:[function(require,module,exports){ var _ = require('./utils'); var eventSplitter = /\s+/; module.exports = function() { var callbacks = []; function fireCallbacks(names, event) { var eventNames = [names]; if (eventSplitter.test(names)) { eventNames = names.split(eventSplitter); } _.each(eventNames, function(name) { _.each(callbacks, function(callbackHash) { if (callbackHash.name === 'all') { callbackHash.callback(name, event); } else if (callbackHash.name === name) { callbackHash.callback(event); } }); }); } return { trigger: fireCallbacks, dispatch: fireCallbacks, on: function(name, callback) { this.off(name, callback); callbacks.push({ name: name, callback: callback }); }, off: function(name, callback) { callbacks = _.filter(callbacks, function(obj) { if (obj.name === name && obj.callback === callback) { return false; } return true; }); }, }; }; },{"./utils":7}],5:[function(require,module,exports){ var _ = require('./utils'); module.exports = function(mod) { var theModel = _.extend({}, mod || {}); var callbacks = []; function fireCallbacks() { _.each(callbacks, function(callback) { callback(); }); } var api = function() { return _.clone(theModel); }; function set(obj, silentOrCallback) { var silent = _.isBoolean(silentOrCallback) && silentOrCallback === true; if (!_.isUndefined(obj) && _.isObject(obj)) { _.map(_.keys(obj), function(k) { theModel[k] = obj[k]; }); if (!silent) fireCallbacks(); if (!silent)(silentOrCallback || function() {})(); } } return _.extend(api, { onChange: function(callback) { callbacks.push(callback); }, get: function(key) { return theModel[key]; }, all: function() { return _.clone(theModel); }, forceUpdate: function() { fireCallbacks(); }, set: set, replace: function(obj, silentOrCallback) { theModel = {}; set(obj, silentOrCallback); }, remove: function(key) { delete theModel[key]; fireCallbacks(); } }); }; },{"./utils":7}],6:[function(require,module,exports){ var Common = require('./common'); var _ = require('./utils'); module.exports = function stringifyDoc(ctx) { ctx = ctx || {}; function node(name) { var attrs = []; var children = []; return { setAttribute: function(key, value) { if (key === 'data-nodeid') { if (!ctx.__noDataId) { attrs.push('data-snodeid' + '="' + value + '"'); } } else { attrs.push(key + '="' + value + '"'); } }, appendChild: function(child) { children.push(child); }, toHtmlString: function() { var selfCloseTag = _.contains(Common.voidElements, name.toUpperCase()) && children.length === 0; if (selfCloseTag) return '<' + name + ' ' + attrs.join(' ') + ' />'; return '<' + name + ' ' + attrs.join(' ') + '>' + _.map(children, function(child) { return child.toHtmlString(); }).join('') + '</' + name + '>'; } } } return { createElement: node, createTextNode: function(value) { return { toHtmlString: function() { return value; } }; } }; } },{"./common":1,"./utils":7}],7:[function(require,module,exports){ (function (global){ function getGlobalObject() { // Workers don’t have `window`, only `self` if (typeof self !== undefined) { return self; } if (typeof global !== undefined) { return global; } if (typeof window !== undefined) { return window; } // Not all environments allow eval and Function // Use only as a last resort: return new Function('return this')(); } //var __idCounter = 0; var globalObject = getGlobalObject() || {}; //global || window || {}; globalObject.__ElemInternals = globalObject.__ElemInternals || {}; globalObject.__ElemInternals.Utils = globalObject.__ElemInternals.Utils || {}; globalObject.__ElemInternals.Utils.__idCounter = globalObject.__ElemInternals.Utils.__idCounter || 0; var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var createEscaper = function(map, keys) { var escaper = function(match) { return map[match]; }; var source = '(?:' + keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; function keys(obj) { if (!isObject(obj)) return []; if (Object.keys) return Object.keys(obj); var keys = []; for (var key in obj) if (has(obj, key)) keys.push(key); return keys; } function values(obj) { var keys = keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; } function indexOf(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; } function each(obj, func) { if (obj == null) return obj; var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { func(obj[i], i, obj); } } else { var keys = keys(obj); for (i = 0, length = keys.length; i < length; i++) { func(obj[keys[i]], keys[i], obj); } } return obj; } function map(obj, func) { if (obj == null) return []; var keys = obj.length !== +obj.length && keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = func(obj[currentKey], currentKey, obj); } return results; } function filter(obj, predicate) { var results = []; if (obj == null) return results; each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; } function reduce(obj, iteratee, memo, context) { if (obj == null) obj = []; var keys = obj.length !== +obj.length && keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; } function reject(obj, predicate, context) { return filter(obj, negate(predicate), context); } function where(obj, attrs) { return filter(obj, matches(attrs)); } function matches(attrs) { var pairs = pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; } function identity(value) { return value; } function property(key) { return function(obj) { return obj[key]; }; } function negate(predicate) { return function() { return !predicate.apply(this, arguments); }; } function pairs(obj) { var keys = keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; } function chain(obj) { var internalObj = obj; var under = this; function chainableApi() { return { value: function() { return internalObj; }, map: function(func) { internalObj = under.map(internalObj, func); return this; }, filter: function(func) { internalObj = under.filter(internalObj, func); return this; }, each: function(func) { under.each(internalObj, func); return this; }, values: function() { return under.values(); }, keys: function() { return under.keys(); }, reduce: function(iteratee, memo, context) { return under.reduce(internalObj, iteratee, memo, context); }, reject: function(predicate, context) { internalObj = under.reject(internalObj, predicate, context); return this; }, where: function(attrs) { internalObj = under.where(internalObj, attrs); return this; } }; } return chainableApi(); } function contains(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = values(obj); return indexOf(obj, target) >= 0; } function uniqueId(prefix) { var id = ++globalObject.__ElemInternals.Utils.__idCounter + ''; return prefix ? prefix + id : id; } function times(n, func) { var results = []; for (var i = 0; i < n; i++) { results.push(func(n)); } return results; } function clone(obj) { if (!isObject(obj)) return obj; return isArray(obj) ? obj.slice() : extend({}, obj); } function extend(obj) { if (!isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (Object.prototype.hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; } function isUndefined(obj) { return obj === void 0; } function isArray(obj) { if (Array.isArray) return Array.isArray(obj); return Object.prototype.toString.call(obj) === '[object Array]'; } function isObject(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; } function isNumber(obj) { return Object.prototype.toString.call(obj) === '[object Number]'; } function isString(obj) { return Object.prototype.toString.call(obj) === '[object String]'; } function isBoolean(obj) { return obj === true || obj === false || Object.prototype.toString.call(obj) === '[object Boolean]'; } function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; } function isFunction(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } function isNull(obj) { return obj === null; } function isNaN(obj) { return isNumber(obj) && obj !== +obj; } function has(obj, key) { return obj != null && Object.prototype.hasOwnProperty.call(obj, key); } function dasherize(what) { return what.replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .toLowerCase().replace(/_/g, '-'); } function startsWith(source, start) { return source.indexOf(start) === 0; } function focus(elem) { if (elem.focus) elem.focus(); } function hasFocus(elem) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); } function on(node, types, callback) { var actual = isString(node) ? document.querySelector(node) : node; each(types, function(type) { if (actual && actual !== null) { if (actual.addEventListener) { actual.addEventListener(type, callback, false); // does not work in ff 3.5 without false } else if (actual.attachEvent) { actual.addEventListener(type, callback); // work in ie } } }); } function off(node, types, callback) { var actual = isString(node) ? document.querySelector(node) : node; each(types, function(type) { if (actual && actual !== null) { if (actual.removeEventListener) { actual.removeEventListener(type, callback, false); // does not work in ff 3.5 without false } } }); } function findNode(selector) { return document.querySelector(selector); } // Works with deep structures function keyMirror(obj, p) { var prefix = p; if (!prefix) { prefix = ''; } var ret = {}; var key; if (!(obj instanceof Object && !Array.isArray(obj))) { throw new Error('keyMirror(...): Argument must be an object.'); } for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } if (obj[key] instanceof Object) { ret[key] = keyMirror(obj[key], key + '.'); } else { ret[key] = prefix + key; } } return ret; } function memoize(func) { var cache = undefined; return function() { if (!cache) { cache = func(); } return cache; }; } exports.escape = createEscaper(escapeMap, keys); exports.keys = keys; exports.values = values; exports.indexOf = indexOf; exports.each = each; exports.map = map; exports.filter = filter; exports.chain = chain; exports.contains = contains; exports.uniqueId = uniqueId; exports.times = times; exports.clone = clone; exports.extend = extend; exports.isUndefined = isUndefined; exports.isArray = isArray; exports.isObject = isObject; exports.isNumber = isNumber; exports.isString = isString; exports.isBoolean = isBoolean; exports.isRegExp = isRegExp; exports.isFunction = isFunction; exports.isNull = isNull; exports.isNaN = isNaN; exports.has = has; exports.dasherize = dasherize; exports.startsWith = startsWith; exports.focus = focus; exports.hasFocus = hasFocus; exports.on = on; exports.off = off; exports.findNode = findNode; exports.reduce = reduce; exports.reject = reject; exports.where = where; exports.matches = matches; exports.negate = negate; exports.property = property; exports.identity = identity; exports.pairs = pairs; exports.keyMirror = keyMirror; exports.globalObject = getGlobalObject; exports.memoize = memoize; exports.memoGobalObject = memoize(getGlobalObject); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],8:[function(require,module,exports){ var EventBus = require('./events'); var Utils = require('./utils'); var registrationFunction = undefined try { registrationFunction = (document.registerElement || document.register || function() { if (window.console) console.error('[ELEMJS] No registerElement function, webcomponents will not work !!!'); }).bind(document); } catch (e) {} var Bus = EventBus(); function registerWebComponent(tag, elem) { var thatDoc = document; var ElementProto = Object.create(HTMLElement.prototype); ElementProto.createdCallback = function() { var elemInstance = Utils.extend({}, elem); this._id = Utils.uniqueId('WebComponent_'); var props = {}; for (var i in this.attributes) { var item = this.attributes[i]; props[item.name] = item.value; } this.props = props; var theNode = undefined; theNode = thatDoc.createElement('content'); theNode.setAttribute('class', 'elemcomponent'); theNode.setAttribute('id', this._id); if (props.shadow) { var shadowRoot = this.createShadowRoot(); shadowRoot.appendChild(theNode); } else { this.appendChild(theNode); } this._theNode = theNode; this._internalBus = EventBus(); this._internalBus._trigger = this._internalBus.trigger; this._internalBus.trigger = function(name, evt) { Bus.trigger('ElemEvent', { name: name, id: this._id, payload: evt }); }.bind(this); Bus.on('ElemEvent', function(evt) { var from = evt.id; if (from !== this._id) { var name = evt.name; var payload = evt.payload; this._internalBus._trigger(name, payload); } }.bind(this)); props.componentsBus = this._internalBus; if (props.renderOnly && props.renderOnly === true) { this.renderedElement = Elem.render(elemInstance, node); } else { this.renderedElement = Elem.component({ container: theNode, init: elemInstance.init, render: elemInstance.render, defaultProps: function() { return props; }, initialState: elemInstance.initialState }); } }; ElementProto.attributeChangedCallback = function(attr, oldVal, newVal) { var elemInstance = Utils.extend({}, elem); this.props[attr] = newVal; var props = this.props; if (this.props.renderOnly && this.props.renderOnly === true) { this.renderedElement = Elem.render(elemInstance, this._node); } else { this.renderedElement = Elem.component({ container: this._node, init: elemInstance.init, render: elemInstance.render, props: props, state: elemInstance.state }); } }; registrationFunction(tag, { prototype: ElementProto }); } if (registrationFunction) { exports.registerWebComponent = registerWebComponent; } else { exports.registerWebComponent = function() { if (window.console) console.error('[ELEMJS] WebComponent not available here :('); }; } },{"./events":4,"./utils":7}]},{},[3])(3) });
ybonnel/Elem
dist/elem.js
JavaScript
apache-2.0
41,774
/*! * Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); $(window).on('scroll', function() { var y_scroll_pos = window.pageYOffset; $('.timeline-image').css('background-color', '#fed136').each(function(){ var element = $(this); if(element.offset().top > y_scroll_pos + $(window).height()/3 && element.offset().top < y_scroll_pos + 2* $(window).height()/3){ element.css('background-color', '#9a0000'); } }); });
thinkivy/korea
js/agency.js
JavaScript
apache-2.0
1,181
// 热门推荐 module.exports = function recommend() { var t = t || { }; t = { init: function () { this.tap() }, tap: function () { $('.hot-lesson ul li').tooltip('tag', { type: 'mouseover', selected: 'on', contentClass: '#hot-lessonbox .one-classfiy-lesson' }) } }, t.init(); }();
feichanglaoshuai/jkxy
第11周/作业/极客学院首页/modules/recommend.js
JavaScript
apache-2.0
351