<commit_before>//     Twig.js
//     Copyright (c) 2011-2013 John Roepke
//                   2012 Hadrien Lanneau
//     Available under the BSD 2-Clause License
//     https://github.com/justjohn/twig.js

// ## twig.functions.js
//
// This file handles parsing filters.
var Twig = (function (Twig) {

    // Determine object type
    function is(type, obj) {
        var clas = Object.prototype.toString.call(obj).slice(8, -1);
        return obj !== undefined && obj !== null && clas === type;
    }

    Twig.functions = {
        //  attribute, block, constant, date, dump, parent, random,.

        // Range function from http://phpjs.org/functions/range:499
        // Used under an MIT License
        range: function (low, high, step) {
            // http://kevin.vanzonneveld.net
            // +   original by: Waldo Malqui Silva
            // *     example 1: range ( 0, 12 );
            // *     returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
            // *     example 2: range( 0, 100, 10 );
            // *     returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
            // *     example 3: range( 'a', 'i' );
            // *     returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
            // *     example 4: range( 'c', 'a' );
            // *     returns 4: ['c', 'b', 'a']
            var matrix = [];
            var inival, endval, plus;
            var walker = step || 1;
            var chars = false;

            if (!isNaN(low) && !isNaN(high)) {
                inival = parseInt(low, 10);
                endval = parseInt(high, 10);
            } else if (isNaN(low) && isNaN(high)) {
                chars = true;
                inival = low.charCodeAt(0);
                endval = high.charCodeAt(0);
            } else {
                inival = (isNaN(low) ? 0 : low);
                endval = (isNaN(high) ? 0 : high);
            }

            plus = ((inival > endval) ? false : true);
            if (plus) {
                while (inival <= endval) {
                    matrix.push(((chars) ? String.fromCharCode(inival) : inival));
                    inival += walker;
                }
            } else {
                while (inival >= endval) {
                    matrix.push(((chars) ? String.fromCharCode(inival) : inival));
                    inival -= walker;
                }
            }

            return matrix;
        },
        cycle: function(arr, i) {
            var pos = i % arr.length;
            return arr[pos];
        },
        dump: function() {
            var EOL = '\n',
            	indentChar = '  ',
            	indentTimes = 0,
            	out = '',
				args = Array.prototype.slice.call(arguments),
				indent = function(times) {
                	var ind	 = '';
                    while (times > 0) {
                        times--;
                        ind += indentChar;
                    }
                    return ind;
                },
				displayVar = function(variable) {
                    out += indent(indentTimes);
                    if (typeof(variable) === 'object') {
                        dumpVar(variable);
                    } else if (typeof(variable) === 'function') {
                        out += 'function()' + EOL;
                    } else if (typeof(variable) === 'string') {
                        out += 'string(' + variable.length + ') "' + variable + '"' + EOL;
                    } else if (typeof(variable) === 'number') {
                        out += 'number(' + variable + ')' + EOL;
                    } else if (typeof(variable) === 'boolean') {
                        out += 'bool(' + variable + ')' + EOL;
                    }
                },
             	dumpVar = function(variable) {
					var	i;
	                if (variable === null) {
	                    out += 'NULL' + EOL;
	                } else if (variable === undefined) {
	                    out += 'undefined' + EOL;
	                } else if (typeof variable === 'object') {
	                    out += indent(indentTimes) + typeof(variable);
	                    indentTimes++;
	                    out += '(' + (function(obj) {
	                        var size = 0, key;
	                        for (key in obj) {
	                            if (obj.hasOwnProperty(key)) {
	                                size++;
	                            }
	                        }
	                        return size;
	                    })(variable) + ') {' + EOL;
	                    for (i in variable) {
	                        out += indent(indentTimes) + '[' + i + ']=> ' + EOL;
	                        displayVar(variable[i]);
	                    }
	                    indentTimes--;
	                    out += indent(indentTimes) + '}' + EOL;
	                } else {
	                    displayVar(variable);
	                }
	            };

			// handle no argument case by dumping the entire render context
			if (args.length == 0) args.push(this.context);

			Twig.forEach(args, function(variable) {
				dumpVar(variable);
			});

            return out;
        },
        date: function(date, time) {
            var dateObj;
            if (date === undefined) {
                dateObj = new Date();
            } else if (Twig.lib.is("Date", date)) {
                dateObj = date;
            } else if (Twig.lib.is("String", date)) {
                dateObj = new Date(Twig.lib.strtotime(date) * 1000);
            } else if (Twig.lib.is("Number", date)) {
                // timestamp
                dateObj = new Date(date * 1000);
            } else {
                throw new Twig.Error("Unable to parse date " + date);
            }
            return dateObj;
        },
        block: function(block) {
            return this.blocks[block];
        },
        parent: function() {
            // Add a placeholder
            return Twig.placeholders.parent;
        },
        attribute: function(object, method, params) {
            if (object instanceof Object) {
                if (object.hasOwnProperty(method)) {
                    if (typeof object[method] === "function") {
                        return object[method].apply(undefined, params);
                    }
                    else {
                        return object[method];
                    }
                }
            }
            // Array will return element 0-index
            return object[method] || undefined;
        },
        template_from_string: function(template) {
            if (template === undefined) {
                template = '';
            }
            return new Twig.Template({
                data: template
            });
        }
    };

    Twig._function = function(_function, value, params) {
        if (!Twig.functions[_function]) {
            throw "Unable to find function " + _function;
        }
        return Twig.functions[_function](value, params);
    };

    Twig._function.extend = function(_function, definition) {
        Twig.functions[_function] = definition;
    };

    return Twig;

})(Twig || { });
<commit_msg>#168 Inherit parent template options in template_from_string<commit_after>//     Twig.js
//     Copyright (c) 2011-2013 John Roepke
//                   2012 Hadrien Lanneau
//     Available under the BSD 2-Clause License
//     https://github.com/justjohn/twig.js

// ## twig.functions.js
//
// This file handles parsing filters.
var Twig = (function (Twig) {

    // Determine object type
    function is(type, obj) {
        var clas = Object.prototype.toString.call(obj).slice(8, -1);
        return obj !== undefined && obj !== null && clas === type;
    }

    Twig.functions = {
        //  attribute, block, constant, date, dump, parent, random,.

        // Range function from http://phpjs.org/functions/range:499
        // Used under an MIT License
        range: function (low, high, step) {
            // http://kevin.vanzonneveld.net
            // +   original by: Waldo Malqui Silva
            // *     example 1: range ( 0, 12 );
            // *     returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
            // *     example 2: range( 0, 100, 10 );
            // *     returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
            // *     example 3: range( 'a', 'i' );
            // *     returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
            // *     example 4: range( 'c', 'a' );
            // *     returns 4: ['c', 'b', 'a']
            var matrix = [];
            var inival, endval, plus;
            var walker = step || 1;
            var chars = false;

            if (!isNaN(low) && !isNaN(high)) {
                inival = parseInt(low, 10);
                endval = parseInt(high, 10);
            } else if (isNaN(low) && isNaN(high)) {
                chars = true;
                inival = low.charCodeAt(0);
                endval = high.charCodeAt(0);
            } else {
                inival = (isNaN(low) ? 0 : low);
                endval = (isNaN(high) ? 0 : high);
            }

            plus = ((inival > endval) ? false : true);
            if (plus) {
                while (inival <= endval) {
                    matrix.push(((chars) ? String.fromCharCode(inival) : inival));
                    inival += walker;
                }
            } else {
                while (inival >= endval) {
                    matrix.push(((chars) ? String.fromCharCode(inival) : inival));
                    inival -= walker;
                }
            }

            return matrix;
        },
        cycle: function(arr, i) {
            var pos = i % arr.length;
            return arr[pos];
        },
        dump: function() {
            var EOL = '\n',
            	indentChar = '  ',
            	indentTimes = 0,
            	out = '',
				args = Array.prototype.slice.call(arguments),
				indent = function(times) {
                	var ind	 = '';
                    while (times > 0) {
                        times--;
                        ind += indentChar;
                    }
                    return ind;
                },
				displayVar = function(variable) {
                    out += indent(indentTimes);
                    if (typeof(variable) === 'object') {
                        dumpVar(variable);
                    } else if (typeof(variable) === 'function') {
                        out += 'function()' + EOL;
                    } else if (typeof(variable) === 'string') {
                        out += 'string(' + variable.length + ') "' + variable + '"' + EOL;
                    } else if (typeof(variable) === 'number') {
                        out += 'number(' + variable + ')' + EOL;
                    } else if (typeof(variable) === 'boolean') {
                        out += 'bool(' + variable + ')' + EOL;
                    }
                },
             	dumpVar = function(variable) {
					var	i;
	                if (variable === null) {
	                    out += 'NULL' + EOL;
	                } else if (variable === undefined) {
	                    out += 'undefined' + EOL;
	                } else if (typeof variable === 'object') {
	                    out += indent(indentTimes) + typeof(variable);
	                    indentTimes++;
	                    out += '(' + (function(obj) {
	                        var size = 0, key;
	                        for (key in obj) {
	                            if (obj.hasOwnProperty(key)) {
	                                size++;
	                            }
	                        }
	                        return size;
	                    })(variable) + ') {' + EOL;
	                    for (i in variable) {
	                        out += indent(indentTimes) + '[' + i + ']=> ' + EOL;
	                        displayVar(variable[i]);
	                    }
	                    indentTimes--;
	                    out += indent(indentTimes) + '}' + EOL;
	                } else {
	                    displayVar(variable);
	                }
	            };

			// handle no argument case by dumping the entire render context
			if (args.length == 0) args.push(this.context);

			Twig.forEach(args, function(variable) {
				dumpVar(variable);
			});

            return out;
        },
        date: function(date, time) {
            var dateObj;
            if (date === undefined) {
                dateObj = new Date();
            } else if (Twig.lib.is("Date", date)) {
                dateObj = date;
            } else if (Twig.lib.is("String", date)) {
                dateObj = new Date(Twig.lib.strtotime(date) * 1000);
            } else if (Twig.lib.is("Number", date)) {
                // timestamp
                dateObj = new Date(date * 1000);
            } else {
                throw new Twig.Error("Unable to parse date " + date);
            }
            return dateObj;
        },
        block: function(block) {
            return this.blocks[block];
        },
        parent: function() {
            // Add a placeholder
            return Twig.placeholders.parent;
        },
        attribute: function(object, method, params) {
            if (object instanceof Object) {
                if (object.hasOwnProperty(method)) {
                    if (typeof object[method] === "function") {
                        return object[method].apply(undefined, params);
                    }
                    else {
                        return object[method];
                    }
                }
            }
            // Array will return element 0-index
            return object[method] || undefined;
        },
        template_from_string: function(template) {
            if (template === undefined) {
                template = '';
            }
            return new Twig.Template({
                options: this.options,
                data: template
            });
        }
    };

    Twig._function = function(_function, value, params) {
        if (!Twig.functions[_function]) {
            throw "Unable to find function " + _function;
        }
        return Twig.functions[_function](value, params);
    };

    Twig._function.extend = function(_function, definition) {
        Twig.functions[_function] = definition;
    };

    return Twig;

})(Twig || { });
<|endoftext|>


<commit_before>(function($)
{
  $.dm.loadedJavascripts = new Array();
  $.dm.loadedStylesheets = new Array();

  $.fn.extend({

    dmDroppableInput: function()
    {
      var $input = this;

      if (!$input.hasClass('ui-droppable'))
      {
        if($input.hasClass('page_only'))
        {
          accept = '#dm_page_bar li';
        }
        else if($input.hasClass('media_only'))
        {
          accept = '#dm_media_bar li';
        }
        else
        {
          accept = '#dm_page_bar li, #dm_media_bar li.file';
        }

        $input.droppable({
          accept: accept,
          activeClass: 'droppable_active',
          hoverClass: 'droppable_hover',
          //          tolerance:    'touch',
          drop: function(e, ui)
          {
            if (ui.draggable.hasClass('file'))
            {
              $input.val('media:' + ui.draggable.attr('id').replace(/dmm/, '') + ' ' + ui.draggable.find('span.name:first').text().replace(/\s/g, ''));
            }
            else
            {
              $input.val('page:' + ui.draggable.attr('id').replace(/dmp/, '') + ' ' + ui.draggable.find('>a').text());
            }
          }
        });
      }
    },

    maxLength: function(max)
    {
      var $elem = this.addClass('dm_max_length'), $helper = $('').insertAfter($elem);

      $helper.bind('change.maxLength', function()
      {
        var freeChars = max - $elem.val().length;
        $helper.text(freeChars)[freeChars > 0 ? 'removeClass' : 'addClass']('max_length_alert');
      }).trigger('change.maxLength');

      $elem.bind('keyup click', function()
      {
        $helper.trigger('change.maxLength');
      });
    },

    outClick: function(callback)
    {
      callback = callback || null;

      if (callback == 'remove')
      {
        return $(document).unbind('mousedown.outClick');
      }
      var $elem = this;
      $(document).bind('mousedown.outClick', function(e)
      {
        var a = $elem.offset(), b = {
          top: a.top + $elem.outerHeight(),
          left: a.left + $elem.outerWidth()
        };
        if (e.pageY  b.top || e.pageX  b.left)
        {
          $(document).unbind('mousedown.outClick');
          if ($.isFunction(callback))
          {
            callback.apply($elem);
          }
          else
          {
            $elem.hide();
          }
        }
      });
    },

    dmAjaxForm: function(options)
    {
      return this.ajaxForm($.extend({
        data: $.dm.defaults.ajaxData
      }, options));
    },

    // Detects javascripts and stylesheet inclusions and append them to the document
    dmExtractEncodedAssets: function()
    {
      if($encodedAssetsDiv = this.find('div.dm_encoded_assets').orNot())
      {
        data = jQuery.parseJSON($encodedAssetsDiv.html());

        $encodedAssetsDiv.remove();

        for (i in data.css)
        {
          if (-1 == $.inArray(data.css[i], $.dm.loadedStylesheets))
          {
            $('head').append('<link rel="stylesheet" href="' + data.css[i] + '" />');
            $.dm.loadedStylesheets.push(data.css[i]);
          }
        }

        for (var i in data.js)
        {
          if (-1 == $.inArray(data.js[i], $.dm.loadedJavascripts))
          {
            ajaxDefaultData = $.ajaxSettings.data;
            $.ajaxSettings.data = null;

            $.ajax({
              url:      data.js[i],
              dataType: 'script',
              cache:    true,
              async:    false
            });

            $.ajaxSettings.data = ajaxDefaultData;

            $.dm.loadedJavascripts.push(data.js[i]);
          }
        }
      }

      return this;
    }
  });

  $.widget('ui.dmMenu', {

    options: {
      hoverClass: 'hover'
    },

    _init: function()
    {
      var menu = this;

      menu.$tabs = $('> ul > li', menu.element);

      $('> a', menu.$tabs).click(function()
      {
        if (!menu.lock)
        {
          menu.open($(this).parent());
        }
      });
    },

    open: function($tab)
    {
      var menu = this;

      $tab.addClass(this.options.hoverClass).find('> ul').outClick(function()
      {
        menu.close();
        menu.lock = true;
        $(document).bind('mouseup', function()
        {
          setTimeout(function()
          {
            menu.lock = false;
          }, 50);
        });
      });

      menu.$tabs.not($tab).bind('mouseover', function()
      {
        menu.close().open($(this));
      });
    },

    close: function()
    {
      this.lock = false;
      this.$tabs.unbind('mouseover').filter('li.' + this.options.hoverClass).removeClass(this.options.hoverClass).outClick('remove');
      return this;
    }

  });

	/*
	 * Make ui dialogs position: fixed
	 */
	$(function()
  {
		if ($.ui.dialog)
		{
			$.ui.dialog.prototype._position = function(pos)
			{
				var wnd = $(window), pTop = 0, pLeft = 0, minTop = pTop;

				if ($.inArray(pos, ['center', 'top', 'right', 'bottom', 'left']) >= 0)
				{
					pos = [pos == 'right' || pos == 'left' ? pos : 'center', pos == 'top' || pos == 'bottom' ? pos : 'middle'];
				}

				if (pos.constructor != Array && pos.constructor != Object)
				{
					pos = ['center', 'middle'];
				}

				if (pos[0].constructor == Number)
				{
					pLeft += pos[0];
				}
				else
				{
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
				}

				if (pos[1].constructor == Number)
				{
					pTop += pos[1];
				}
				else
				{
					var dialogHeight = 350;
					pTop += (wnd.height() - dialogHeight) / 2;
				}

				// prevent the dialog from being too high (make sure the titlebar is accessible)
				pTop = Math.max(pTop, minTop);
				this.uiDialog.css({
					position: 'fixed',
					top: pTop,
					left: pLeft
				});
			};
		}
  });

})(jQuery);<commit_msg>[Diem] - javascript plugin dmDroppableInput now accepts a callback as its first argument<commit_after>(function($)
{
  $.dm.loadedJavascripts = new Array();
  $.dm.loadedStylesheets = new Array();

  $.fn.extend({

    dmDroppableInput: function(callback)
    {
      var $input = this;

      if (!$input.hasClass('ui-droppable'))
      {
        if($input.hasClass('page_only'))
        {
          accept = '#dm_page_bar li';
        }
        else if($input.hasClass('media_only'))
        {
          accept = '#dm_media_bar li';
        }
        else
        {
          accept = '#dm_page_bar li, #dm_media_bar li.file';
        }

        $input.droppable({
          accept: accept,
          activeClass: 'droppable_active',
          hoverClass: 'droppable_hover',
          //          tolerance:    'touch',
          drop: function(e, ui)
          {
            if (ui.draggable.hasClass('file'))
            {
              $input.val('media:' + ui.draggable.attr('id').replace(/dmm/, '') + ' ' + ui.draggable.find('span.name:first').text().replace(/\s/g, ''));
            }
            else
            {
              $input.val('page:' + ui.draggable.attr('id').replace(/dmp/, '') + ' ' + ui.draggable.find('>a').text());
            }

            callback && $.isFunction(callback) && callback.apply($input);
          }
        });
      }
    },

    maxLength: function(max)
    {
      var $elem = this.addClass('dm_max_length'), $helper = $('').insertAfter($elem);

      $helper.bind('change.maxLength', function()
      {
        var freeChars = max - $elem.val().length;
        $helper.text(freeChars)[freeChars > 0 ? 'removeClass' : 'addClass']('max_length_alert');
      }).trigger('change.maxLength');

      $elem.bind('keyup click', function()
      {
        $helper.trigger('change.maxLength');
      });
    },

    outClick: function(callback)
    {
      callback = callback || null;

      if (callback == 'remove')
      {
        return $(document).unbind('mousedown.outClick');
      }
      var $elem = this;
      $(document).bind('mousedown.outClick', function(e)
      {
        var a = $elem.offset(), b = {
          top: a.top + $elem.outerHeight(),
          left: a.left + $elem.outerWidth()
        };
        if (e.pageY  b.top || e.pageX  b.left)
        {
          $(document).unbind('mousedown.outClick');
          if ($.isFunction(callback))
          {
            callback.apply($elem);
          }
          else
          {
            $elem.hide();
          }
        }
      });
    },

    dmAjaxForm: function(options)
    {
      return this.ajaxForm($.extend({
        data: $.dm.defaults.ajaxData
      }, options));
    },

    // Detects javascripts and stylesheet inclusions and append them to the document
    dmExtractEncodedAssets: function()
    {
      if($encodedAssetsDiv = this.find('div.dm_encoded_assets').orNot())
      {
        data = jQuery.parseJSON($encodedAssetsDiv.html());

        $encodedAssetsDiv.remove();

        for (i in data.css)
        {
          if (-1 == $.inArray(data.css[i], $.dm.loadedStylesheets))
          {
            $('head').append('<link rel="stylesheet" href="' + data.css[i] + '" />');
            $.dm.loadedStylesheets.push(data.css[i]);
          }
        }

        for (var i in data.js)
        {
          if (-1 == $.inArray(data.js[i], $.dm.loadedJavascripts))
          {
            ajaxDefaultData = $.ajaxSettings.data;
            $.ajaxSettings.data = null;

            $.ajax({
              url:      data.js[i],
              dataType: 'script',
              cache:    true,
              async:    false
            });

            $.ajaxSettings.data = ajaxDefaultData;

            $.dm.loadedJavascripts.push(data.js[i]);
          }
        }
      }

      return this;
    }
  });

  $.widget('ui.dmMenu', {

    options: {
      hoverClass: 'hover'
    },

    _init: function()
    {
      var menu = this;

      menu.$tabs = $('> ul > li', menu.element);

      $('> a', menu.$tabs).click(function()
      {
        if (!menu.lock)
        {
          menu.open($(this).parent());
        }
      });
    },

    open: function($tab)
    {
      var menu = this;

      $tab.addClass(this.options.hoverClass).find('> ul').outClick(function()
      {
        menu.close();
        menu.lock = true;
        $(document).bind('mouseup', function()
        {
          setTimeout(function()
          {
            menu.lock = false;
          }, 50);
        });
      });

      menu.$tabs.not($tab).bind('mouseover', function()
      {
        menu.close().open($(this));
      });
    },

    close: function()
    {
      this.lock = false;
      this.$tabs.unbind('mouseover').filter('li.' + this.options.hoverClass).removeClass(this.options.hoverClass).outClick('remove');
      return this;
    }

  });

	/*
	 * Make ui dialogs position: fixed
	 */
	$(function()
  {
		if ($.ui.dialog)
		{
			$.ui.dialog.prototype._position = function(pos)
			{
				var wnd = $(window), pTop = 0, pLeft = 0, minTop = pTop;

				if ($.inArray(pos, ['center', 'top', 'right', 'bottom', 'left']) >= 0)
				{
					pos = [pos == 'right' || pos == 'left' ? pos : 'center', pos == 'top' || pos == 'bottom' ? pos : 'middle'];
				}

				if (pos.constructor != Array && pos.constructor != Object)
				{
					pos = ['center', 'middle'];
				}

				if (pos[0].constructor == Number)
				{
					pLeft += pos[0];
				}
				else
				{
					pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
				}

				if (pos[1].constructor == Number)
				{
					pTop += pos[1];
				}
				else
				{
					var dialogHeight = 350;
					pTop += (wnd.height() - dialogHeight) / 2;
				}

				// prevent the dialog from being too high (make sure the titlebar is accessible)
				pTop = Math.max(pTop, minTop);
				this.uiDialog.css({
					position: 'fixed',
					top: pTop,
					left: pLeft
				});
			};
		}
  });

})(jQuery);<|endoftext|>


<commit_before>"use strict";

// Show a marker on the map for a given location, and allow dragging it to a
// different location.

var $ = require('jquery'),
    _ = require('underscore'),
    Bacon = require('baconjs'),
    U = require('treemap/utility'),
    L = require('leaflet');

var marker,
    firstMoveBus = new Bacon.Bus(),
    moveBus = new Bacon.Bus(),
    markerWasMoved,
    trackingMarker,
    config,
    lastMarkerLocation,
    map;

exports = module.exports = {

    init: function(theConfig, theMap) {
        map = theMap;
        config = theConfig;
    },

    bindPopup: function(pop) { marker.bindPopup(pop); },
    unbindPopup: function() { marker.unbindPopup(); },

    // Allows clients to be notified when a newly-placed marker is moved for the first time
    firstMoveStream: firstMoveBus,

    moveStream: moveBus.map(_.identity),

    // Let user place the marker by clicking the map
    enablePlacing: function () {
        // Add a 'tracking marker' that follows the mouse, until
        // the object is placed
        if (!trackingMarker) {
            trackingMarker = L.marker({lat:0, lng:0}, {
                icon: getMarkerIcon(false)
            });

            map.on('mousemove', function(event) {
                trackingMarker.setLatLng(event.latlng);
            });
        }

        trackingMarker.addTo(map);

        map.on('click', onMarkerPlacedByClick);
    },

    disablePlacing: function() {
        if (trackingMarker) {
            map.removeLayer(trackingMarker);
        }

        map.off('click', onMarkerPlacedByClick);
    },

    // Put marker at the specified location (WebMercator, {x: lon, y: lat})
    place: function (location) {
        // If we're tracking mouse movements, remove the tracker
        if (trackingMarker) {
            map.removeLayer(trackingMarker);
        }

        var latlng;

        if (location.x && location.y) {
            latlng = U.webMercatorToLeafletLatLng(location.x, location.y);
        } else {
            latlng = location;
        }

        if (marker) {
            marker.setLatLng(latlng);
        } else {
            marker = L.marker(latlng, {
                icon: getMarkerIcon(true)
            });
            marker.on('dragend', onMarkerMoved);
        }

        showViewMarker();
        markerWasMoved = false;
    },

    enableMoving: enableMoving,
    disableMoving: disableMoving,

    // Hide/deactivate/clear everything (but keep feature so its location can still be retrieved)
    hide: function () {
        if (marker) {
            lastMarkerLocation = marker.getLatLng();
            map.removeLayer(marker);
        }

        if (trackingMarker) {
            map.removeLayer(trackingMarker);
        }

        markerWasMoved = false;
    },

    // Return current marker location
    getLocation: function () {
        var latlng = marker ? marker.getLatLng() : lastMarkerLocation;

        return U.lonLatToWebMercator(latlng.lng, latlng.lat);
    },

    // Returns "True" if user dragged the marker; false otherwise
    wasMoved: function() {
        return markerWasMoved;
    }
};

function onMarkerPlacedByClick(event) {
    exports.disablePlacing();
    exports.place(event.latlng);

    enableMoving();
    onMarkerMoved();
}

// Let user move the marker by dragging it with the mouse
function enableMoving() {
    marker.dragging.enable();
    showFirstEditMarker();
    markerWasMoved = false;
}

// Prevent user from dragging the marker
function disableMoving() {
    marker.dragging.disable();
    showViewMarker();
}

var showViewMarker = _.partial(showMarker, false, ''),
    showFirstEditMarker = _.partial(showMarker, true, 'animated');

function showMarker(inEditMode, className) {
    marker.setIcon(getMarkerIcon(inEditMode, className));
    marker.addTo(map);
}

function getMarkerIcon(inEditMode, className) {
    return L.icon({
        iconUrl: config.staticUrl +
            (inEditMode ? 'img/mapmarker_editmode.png' :
                          'img/mapmarker_viewmode.png'),
        // Use half actual size to look good on IOS retina display
        iconSize: [78, 75],
        iconAnchor: [36, 62],
        className: className
    });
}

function onMarkerMoved() {
    moveBus.push(marker.getLatLng());
    if (!markerWasMoved) {
        markerWasMoved = true;
        firstMoveBus.push(marker.getLatLng());
        marker.setIcon(getMarkerIcon(true, ''));
    }
}
<commit_msg>Really disable moving markers. Fixes #831.<commit_after>"use strict";

// Show a marker on the map for a given location, and allow dragging it to a
// different location.

var $ = require('jquery'),
    _ = require('underscore'),
    Bacon = require('baconjs'),
    U = require('treemap/utility'),
    L = require('leaflet');

var marker,
    markerDraggingContext,
    firstMoveBus = new Bacon.Bus(),
    moveBus = new Bacon.Bus(),
    markerWasMoved,
    trackingMarker,
    config,
    lastMarkerLocation,
    map;

exports = module.exports = {

    init: function(theConfig, theMap) {
        map = theMap;
        config = theConfig;
    },

    bindPopup: function(pop) { marker.bindPopup(pop); },
    unbindPopup: function() { marker.unbindPopup(); },

    // Allows clients to be notified when a newly-placed marker is moved for the first time
    firstMoveStream: firstMoveBus,

    moveStream: moveBus.map(_.identity),

    // Let user place the marker by clicking the map
    enablePlacing: function () {
        // Add a 'tracking marker' that follows the mouse, until
        // the object is placed
        if (!trackingMarker) {
            trackingMarker = L.marker({lat:0, lng:0}, {
                icon: getMarkerIcon(false)
            });

            map.on('mousemove', function(event) {
                trackingMarker.setLatLng(event.latlng);
            });
        }

        trackingMarker.addTo(map);

        map.on('click', onMarkerPlacedByClick);
    },

    disablePlacing: function() {
        if (trackingMarker) {
            map.removeLayer(trackingMarker);
        }

        map.off('click', onMarkerPlacedByClick);
    },

    // Put marker at the specified location (WebMercator, {x: lon, y: lat})
    place: function (location) {
        // If we're tracking mouse movements, remove the tracker
        if (trackingMarker) {
            map.removeLayer(trackingMarker);
        }

        var latlng;

        if (location.x && location.y) {
            latlng = U.webMercatorToLeafletLatLng(location.x, location.y);
        } else {
            latlng = location;
        }

        if (marker) {
            marker.setLatLng(latlng);
        } else {
            marker = L.marker(latlng, {
                icon: getMarkerIcon(true)
            });
            marker.on('dragend', onMarkerMoved);
        }

        showViewMarker();
        markerWasMoved = false;
    },

    enableMoving: enableMoving,
    disableMoving: disableMoving,

    // Hide/deactivate/clear everything (but keep feature so its location can still be retrieved)
    hide: function () {
        if (marker) {
            lastMarkerLocation = marker.getLatLng();
            map.removeLayer(marker);
        }

        if (trackingMarker) {
            map.removeLayer(trackingMarker);
        }

        markerWasMoved = false;
    },

    // Return current marker location
    getLocation: function () {
        var latlng = marker ? marker.getLatLng() : lastMarkerLocation;

        return U.lonLatToWebMercator(latlng.lng, latlng.lat);
    },

    // Returns "True" if user dragged the marker; false otherwise
    wasMoved: function() {
        return markerWasMoved;
    }
};

function onMarkerPlacedByClick(event) {
    exports.disablePlacing();
    exports.place(event.latlng);

    enableMoving();
    onMarkerMoved();
}

// Let user move the marker by dragging it with the mouse
function enableMoving() {
    showFirstEditMarker();
    markerWasMoved = false;

    // Normally we'd simply use:
    // marker.dragging.enable/disable
    //
    // However, the dragging context gets lost
    // somewhere between here and "disableMoving"
    //
    // Once lost we can't unbind the drag handler
    // and we're stuck. The workaround is to
    // hang on to the most recently added context
    // and disable when needed
    markerDraggingContext = marker.dragging;
    markerDraggingContext.enable();
}

// Prevent user from dragging the marker
function disableMoving() {
    if (markerDraggingContext) {
        markerDraggingContext.disable();
    }
    showViewMarker();
}

var showViewMarker = _.partial(showMarker, false, ''),
    showFirstEditMarker = _.partial(showMarker, true, 'animated');

function showMarker(inEditMode, className) {
    marker.setIcon(getMarkerIcon(inEditMode, className));
    marker.addTo(map);
}

function getMarkerIcon(inEditMode, className) {
    return L.icon({
        iconUrl: config.staticUrl +
            (inEditMode ? 'img/mapmarker_editmode.png' :
                          'img/mapmarker_viewmode.png'),
        // Use half actual size to look good on IOS retina display
        iconSize: [78, 75],
        iconAnchor: [36, 62],
        className: className
    });
}

function onMarkerMoved() {
    moveBus.push(marker.getLatLng());
    if (!markerWasMoved) {
        markerWasMoved = true;
        firstMoveBus.push(marker.getLatLng());
        marker.setIcon(getMarkerIcon(true, ''));
    }
}
<|endoftext|>


<commit_before>/*
  FlagstoneJS v3.3.3
  (c) 2015-2017 Depth Development. http://depthdev.com
  License: MIT
*/
!function(e,t){"use strict";e.flagstone=function(n){function r(n){function r(){for(var e=0,t=x.length;e<t;e++)Math.random()<O&&x.splice(e,0,!1)}function a(){h.style.visibility="hidden"}function o(){var t=[T],n=0,r=k.length;for(C=[];n<r;n++){if(n<T)x[n]?(x[n].style.top=y+"px",x[n].style[B]=w*n+(n?D*n+y:y)+"px",_&&(x[n].style.height=x[n].style.width),t[n]=k[n]+y,U(x[n],n),C.push([x[n]])):T>1&&(t[n]=w+y);else{var a=Math.min.apply(null,t),o=t.indexOf(a);x[n]?(x[n].style.top=a+D+"px",x[n].style[B]=w*o+(o?D*o+y:y)+"px",_&&(x[n].style.height=x[n].style.width),t[o]+=k[n]+D,U(x[n],n),C[o].push(x[n])):T>1&&(t[o]+=w+D)}h.style.height=(Math.max.apply(null,t)||k[0]+y)+y+"px"}e.setTimeout(function(){h.style.visibility="visible"})}function s(t){if(x.length){L=h.getBoundingClientRect().width,L<S+(y?2*y:0)&&(L=S),b=Math.floor(L/S),T=b>E?E:b,w=L/T-(D*(T-1)+2*y)/T,k=[];for(var n=0,r=x.length;n<r;n++)x[n]&&(x[n].style.width=w+"px",x[n].style.marginTop="0px"),k.push(_||!x[n]?w:x[n].offsetHeight);L===h.getBoundingClientRect().width||t?o():s(!0),A&&(t||e.setTimeout(function(){s(!0)},F+17))}}function i(){var t=Date.now(),n=h.getElementsByTagName("img");n.length&&!function(){var r=e.setInterval(function(){for(var a=[],o=0,i=n.length;o<i;o++)a[o]=n[o].naturalHeight;(a.indexOf(0)===-1||t+q<Date.now())&&(e.clearInterval(r),e.setTimeout(function(){s(!0)}))},I)}()}function l(t){if("keydown"!==t.type||13===t.keyCode||32===t.keyCode){for(var n=t.target;n&&!n.classList.contains(M);)n=n.parentElement;h.removeChild(n),e.MutationObserver||Z()}}function d(t){"keydown"===t.type&&13!==t.keyCode&&32!==t.keyCode||e.setTimeout(s,Q)}function g(t){function n(){var t=r.getBoundingClientRect().height+a;for(i=0;i<d;i++)o[i].style.marginTop=t-m+"px";G=e[(J?"request":"cancel")+"AnimationFrame"](n)}if("keydown"!==t.type||13===t.keyCode||32===t.keyCode){for(var r=t.target;r&&!r.classList.contains(M);)r=r.parentElement;for(var a=e.parseFloat(r.style.top),o=[],s=!1,i=0,l=0,d=C.length,g=0;i<d&&!s;i++)for(l=0,g=C[i].length;l<g;l++)s&&o.push(C[i][l]),C[i][l]===r&&(s=!0);if(o.length){var m=e.parseFloat(o[0].style.top)-D;d=o.length,J=!1,e.cancelAnimationFrame(G),e.clearTimeout(K),J=!0,G=e.requestAnimationFrame(n),K=e.setTimeout(function(){J=!1,e.cancelAnimationFrame(G)},j)}}}function m(){e.clearTimeout(V),V=e.setTimeout(s,X)}function v(){a(),e.clearTimeout(Y),Y=e.setTimeout(Z)}function f(){e.removeEventListener("resize",m),t.head.removeChild(t.getElementById("flagstone-"+c+"-styles"))}function u(e){e.margin||0===e.margin?(y=e.margin,D=e.margin):(y=e.bedPadding||y,D=e.stonesMargin||D),S=e.minWidth||S,E=e.maxColumns||E,W=e.dragAndDrop===!0||e.dragAndDrop===!1?e.dragAndDrop:W,U=e.callback||U,Z()}var c=e.flagstone.index,p=n?n.nodeName?{elem:n}:n:{elem:t.getElementsByClassName("flagstone")[0]},h=p.elem,y=p.margin||0===p.margin?p.margin:p.bedPadding||0===p.bedPadding?p.bedPadding:10,L=0,S=p.minWidth||280,E=p.maxColumns||5,b=0,T=0,x=[],D=p.margin||0===p.margin?p.margin:p.stonesMargin||0===p.stonesMargin?p.stonesMargin:10,w=L/T-D*(T+1)/T,k=[],C=[],M="flagstone-"+c+"-bed__stone",A=p.flow,B=p.direction?p.direction.toLowerCase():"left",P=p.random,O=p.spaceFrequency||.4,z=p.space,F=p.animationDuration||0,N=p.animationDuration?p.animationDuration/1e3:0,R=p.animationTimingFunction||"linear",X=p.resizeDelay||0===p.resizeDelay?p.resizeDelay:250,_=p.square,q=p.imagesLoadedQueryDuration||2500,I=p.imagesLoadedQueryFrequency||100,W=p.dragAndDrop,H=p.dragAndDropAutoDelay,Q=p.eventResetDelay||0,j=p.eventResizeDuration||0,G=null,J=!1,K=null,U=p.callback||function(){},V=null,Y=null,Z=null,$={dragStone:null,targetStone:null,targetStoneMouseXPercent:0,autoDropTimer:null,autoDrop:function(){$.targetStone.classList.contains(M)&&($.targetStoneMouseXPercent<.5?$.dragStone!==$.targetStone.previousElementSibling&&($.targetStone.parentElement.insertBefore($.dragStone,$.targetStone),$.targetStone.classList.remove("flagstone-left"),$.targetStone.classList.remove("flagstone-dragover")):$.dragStone!==$.targetStone.nextElementSibling&&($.targetStone.parentElement.insertBefore($.dragStone,$.targetStone.nextElementSibling),$.targetStone.classList.remove("flagstone-right"),$.targetStone.classList.remove("flagstone-dragover")),e.clearTimeout($.autoDropTimer),$.autoDropTimer=e.setTimeout($.autoDrop,H))},dragStart:function(e){e.dataTransfer.setData("text",this.id),$.dragStone=this,$.dragStone.classList.add("flagstone-drag")},dragEnter:function(t){t.preventDefault(),t.stopPropagation(),this!==$.dragStone&&this!==$.targetStone&&this!==h&&(e.clearTimeout($.autoDropTimer),$.autoDropTimer=e.setTimeout($.autoDrop,H))},dragOver:function(e){e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",this!==$.dragStone&&this.hasAttribute("draggable")?($.targetStone=this,$.targetStone.classList.add("flagstone-dragover"),$.targetStoneMouseXPercent=e.offsetX/this.offsetWidth,$.targetStoneMouseXPercent<.5?($.targetStone.classList.remove("flagstone-right"),$.targetStone.classList.add("flagstone-left")):($.targetStone.classList.remove("flagstone-left"),$.targetStone.classList.add("flagstone-right")),this.classList.remove("flagstone-dragover")):this===h&&this.classList.add("flagstone-dragover")},dragEnd:function(){$.dragStone.classList.remove("flagstone-drag")},dragLeave:function(){$.targetStone&&(h.classList.remove("flagstone-dragover"),$.targetStone.classList.remove("flagstone-dragover"),$.targetStone.classList.remove("flagstone-left"),$.targetStone.classList.remove("flagstone-right"))},drop:function(t){return t.stopPropagation(),e.clearTimeout($.autoDropTimer),$.dragStone===this||!this.hasAttribute("draggable")&&this!==h||($.targetStone=this,$.targetStone===h?$.targetStone.appendChild($.dragStone):$.targetStoneMouseXPercent<.5?$.targetStone.parentElement.insertBefore($.dragStone,$.targetStone):$.targetStone.parentElement.insertBefore($.dragStone,$.targetStone.nextElementSibling),$.targetStone.classList.remove("flagstone-dragover"),$.targetStone.classList.remove("flagstone-left"),$.targetStone.classList.remove("flagstone-right"),$.dragStone.classList.remove("flagstone-drag"),e.MutationObserver||Z()),!1}};return Z=function(){x=Array.prototype.slice.call(h.children);for(var t=0,n=x.length;t<n;t++)x[t].classList.add(M);for(t=0;t<n;t++)x[t].setAttribute("draggable","false"),x[t].removeEventListener("dragstart",$.dragStart),x[t].removeEventListener("dragover",$.dragOver),x[t].removeEventListener("dragleave",$.dragLeave),x[t].removeEventListener("dragend",$.dragEnd),x[t].removeEventListener("drop",$.drop),x[t].removeEventListener("dragenter",$.dragEnter),h.removeEventListener("dragover",$.dragOver),h.removeEventListener("drop",$.drop);if(W)for(t=0;t<n;t++)x[t].setAttribute("draggable","true"),x[t].addEventListener("dragstart",$.dragStart),x[t].addEventListener("dragover",$.dragOver),x[t].addEventListener("dragleave",$.dragLeave),x[t].addEventListener("dragend",$.dragEnd),x[t].addEventListener("drop",$.drop),H&&x[t].addEventListener("dragenter",$.dragEnter),h.addEventListener("dragover",$.dragOver),h.addEventListener("drop",$.drop);(P||z)&&(P&&x.sort(function(){return.5-Math.random()}),z&&r());var a=h.getElementsByClassName("flagstone-remove");for(t=0,n=a.length;t<n;t++)a[t].removeEventListener("click",l),a[t].addEventListener("click",l),a[t].removeEventListener("keydown",l),a[t].addEventListener("keydown",l);for(a=h.getElementsByClassName("flagstone-reset"),t=0,n=a.length;t<n;t++)a[t].removeEventListener("click",d),a[t].addEventListener("click",d),a[t].removeEventListener("keydown",d),a[t].addEventListener("keydown",d);for(a=h.getElementsByClassName("flagstone-resize"),t=0,n=a.length;t<n;t++)a[t].removeEventListener("click",g),a[t].addEventListener("click",g),a[t].removeEventListener("keydown",g),a[t].addEventListener("keydown",g);s(),F&&e.setTimeout(i,F),e.setTimeout(function(){s(!0)},F)},function(){if(h.classList.add("flagstone-"+c+"-bed"),!t.getElementById("flagstone-"+c+"-styles")){var n=".flagstone-"+c+"-bed{box-sizing:border-box;list-style-type:none;overflow:hidden;position:relative;min-width:"+(S+2*y)+"px;}",r=".flagstone-"+c+"-bed__stone{box-sizing:border-box;position:absolute;top:0px;"+B+":0px;margin:0;}",a=".flagstone-"+c+"-bed__stone{transition:top "+N+"s "+R+","+B+" "+N+"s "+R+(A?",width "+N+"s "+R:"")+";}",o=n+r+a,s=t.createElement("style");s.type="text/css",s.id="flagstone-"+c+"-styles",s.appendChild(t.createTextNode(o)),t.head.appendChild(s)}if(Z(),e.removeEventListener("resize",m),e.addEventListener("resize",m),e.MutationObserver){var i=new MutationObserver(v);i.observe(h,{childList:!0})}}(),{adjust:u,destroy:f,hide:a,reset:m,hardReset:Z}}return e.flagstone.index++,new r(n)},e.flagstone.index=-1}(window,document);<commit_msg>Delete flagstone-3.3.3.min.js<commit_after><|endoftext|>


<commit_before>/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      // for antd
      test: /\.less$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader', 'less-loader'],
    }, {
      test: /\.(eot|svg|otf|ttf|woff|woff2)$/,
      loader: 'file-loader',
    }, {
      test: /\.(jpg|png|gif)$/,
      loaders: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            progressive: true,
            optimizationLevel: 7,
            interlaced: false,
            pngquant: {
              quality: '65-90',
              speed: 4,
            },
          },
        },
      ],
    }, {
      test: /\.html$/,
      loader: 'html-loader',
    }, {
      test: /\.json$/,
      loader: 'json-loader',
    }, {
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      query: {
        limit: 10000,
      },
    }],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new webpack.NamedModulesPlugin(),
  ]),
  resolve: {
    alias: options.alias,
    modules: ['app', 'node_modules'],
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  performance: options.performance || {},
});
<commit_msg>Fix imported styles<commit_after>/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    rules: [
      {
        test: /\.js$/, // Transform all .js files required somewhere with Babel
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: options.babelQuery,
        },
      },
      {
        // Preprocess our own .css files
        // This is the place to add your own loaders (e.g. sass/less etc.)
        // for a list of loaders, see https://webpack.js.org/loaders/#styling
        test: /\.css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader'],
      },
      {
        // Preprocess 3rd party .css files located in node_modules
        test: /\.css$/,
        include: /node_modules/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(eot|svg|otf|ttf|woff|woff2)$/,
        use: 'file-loader',
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              progressive: true,
              optimizationLevel: 7,
              interlaced: false,
              pngquant: {
                quality: '65-90',
                speed: 4,
              },
            },
          },
        ],
      },
      {
        test: /\.html$/,
        use: 'html-loader',
      },
      {
        test: /\.json$/,
        use: 'json-loader',
      },
      {
        test: /\.(mp4|webm)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
          },
        },
      },
    ],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new webpack.NamedModulesPlugin(),
  ]),
  resolve: {
    alias: options.alias,
    modules: ['app', 'node_modules'],
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  performance: options.performance || {},
});
<|endoftext|>


<commit_before>dojo.provide("dijit.form.InlineEditBox");

dojo.require("dojo.i18n");

dojo.require("dijit.form._FormWidget");
dojo.require("dijit._Container");
dojo.require("dijit.form.Button");

dojo.requireLocalization("dijit", "common");

dojo.declare(
	"dijit.form.InlineEditBox",
	[dijit.form._FormWidget, dijit._Container],
	// summary
	//		Wrapper widget to a text edit widget.
	//		The text is displayed on the page using normal user-styling.
	//		When clicked, the text is hidden, and the edit widget is
	//		visible, allowing the text to be updated.  Additionally,
	//		Save and Cancel button are displayed below the edit widget.
	//		When Save is clicked, the text is pulled from the edit
	//		widget and redisplayed and the edit widget is again hidden.
	//		Currently all textboxes that inherit from dijit.form.Textbox
	//		are supported edit widgets.
	//		An edit widget must support the following API to be used:
	//		String getTextValue() OR String getValue()
	//		void setTextValue(String) OR void setValue(String)
	//		void focus()
	//		It must also be able to initialize with style="display:none;" set.
{
	templatePath: dojo.moduleUrl("dijit.form", "templates/InlineEditBox.html"),

	// editing: Boolean
	//		Is the node currently in edit mode?
	editing: false,

	// autoSave: Boolean
	//				Changing the value automatically saves it, don't have to push save button
	autoSave: true,

	// buttonSave: String
	//              Save button label
	buttonSave: "",

	// buttonCancel: String
	//              Cancel button label
	buttonCancel: "",

	// renderHTML: Boolean
	//              should text render as HTML(true) or plain text(false)
	renderHTML: false,

	widgetsInTemplate: true,

	postCreate: function(){
		// look for the input widget as a child of the containerNode
		var _this = this;
		dojo.addOnLoad(function(){
			if(_this.editWidget){
				_this.containerNode.appendChild(_this.editWidget.domNode);
			}else{
				_this.editWidget = _this.getChildren()[0];
			}
			_this._setEditValue = dojo.hitch(_this.editWidget,_this.editWidget.setDisplayedValue||_this.editWidget.setValue);
			_this._getEditValue = dojo.hitch(_this.editWidget,_this.editWidget.getDisplayedValue||_this.editWidget.getValue);
			_this._setEditFocus = dojo.hitch(_this.editWidget,_this.editWidget.focus);
			_this.editWidget.onChange = dojo.hitch(_this,"_onChange");
			_this.checkForValueChange();
			_this._showText();
		});
		if(this.autoSave){
			this.buttonSpan.style.display="none";
		}
	},

	postMixInProperties: function(){
		dijit.form.InlineEditBox.superclass.postMixInProperties.apply(this, arguments);
		this.messages = dojo.i18n.getLocalization("dijit", "common", this.lang);
		dojo.forEach(["buttonSave", "buttonCancel"], function(prop){
			if(!this[prop]){ this[prop] = this.messages[prop]; }
		}, this);
	},

	_onKeyPress: function(e){
		if(this.disabled || e.altKey || e.ctrlKey){ return; }
		if(e.charCode == dojo.keys.SPACE || e.keyCode == dojo.keys.ENTER){
			dojo.stopEvent(e);
			this._onClick(e);
		}
	},

	_onMouseOver: function(){
		if(!this.editing){
			var classname = this.disabled ? "dijitDisabledClickableRegion" : "dijitClickableRegion";
			dojo.addClass(this.editable, classname);
		}
	},

	_onMouseOut: function(){
		if(!this.editing){
			var classStr = this.disabled ? "dijitDisabledClickableRegion" : "dijitClickableRegion";
			dojo.removeClass(this.editable, classStr);
		}
	},

	onClick: function(/*Event*/ e){
		// summary: callback for when button is clicked; user can override this function
	},

	_onClick: function(e){
		// summary
		// 		When user clicks the text, then start editing.
		// 		Hide the text and display the form instead.

		if(this.editing || this.disabled){ return; }
		this._onMouseOut();
		this.editing = true;

		// show the edit form and hide the read only version of the text
		this._setEditValue(this._isEmpty ? '' : (this.renderHTML ? this.editable.innerHTML : this.editable.firstChild.nodeValue));
		this._initialText = this._getEditValue();
		this._visualize();

		this._setEditFocus();
		this.saveButton.setDisabled(true);
		// moved to postCreate to always listen
		//this.editWidget.onChange = dojo.hitch(this,"_onChange");
		this.onClick();
	},

	_visualize: function(e){
		dojo.style(this.editNode, "display", this.editing ? "" : "none");
		dojo.style(this.editable, "display", this.editing ? "none" : "");
	},

	_showText: function(){
		var value = this._getEditValue();
		dijit.form.InlineEditBox.superclass.setValue.call(this, value);
		// whitespace is really hard to click so show a ?
		// TODO: show user defined message in gray
		if(/^\s*$/.test(value)){ value = "?"; this._isEmpty = true; }
		else { this._isEmpty = false; }
		if(this.renderHTML){
			this.editable.innerHTML = value;
		}else{
			this.editable.innerHTML = "";
			this.editable.appendChild(document.createTextNode(value));
		}
		this._visualize();
	},

	save: function(e){
		// summary: Callback when user presses "Save" button
		if(e){ dojo.stopEvent(e); }
		this.editing = false;
		this._showText();
	},

	cancel: function(e){
		// summary: Callback when user presses "Cancel" button
		if(e){ dojo.stopEvent(e); }
		this.editing = false;
		this._visualize();
	},

	setValue: function(/*String*/ value){
		// sets the text without informing the server
		this._setEditValue(value);
		this.editing = false;
		this._showText();
	},

	checkForValueChange: function(){
		// summary
		//		Callback when user changes input value.
		//		Enable save button if the text value is different than the original value.
		if(this.editing){
			this.saveButton.setDisabled(this._getEditValue() == this._initialText);
		}else{
			this._showText();
		}

	},

	_onBlur: function(){
		// summary:
		//	magically called when focus moves outside of the InlineEditBox widget (or it's descendants)
		if(this.autoSave){
			if(this._getEditValue() == this._initialText){
				this.cancel();
			}else{
				this.save();
			}
		}
	},

	_onChange: function(){
		// summary:
		//	This is called when the underlying widget fires an onChange event,
		//	which means that the user has presumably finished entering the value
		if(this.autoSave){
			this.save();
		}
	},

	setDisabled: function(/*Boolean*/ disabled){
		this.saveButton.setDisabled(disabled);
		this.cancelButton.setDisabled(disabled);
		this.editable.disabled = disabled;
		this.editWidget.setDisabled(disabled);
		dijit.form.InlineEditBox.superclass.setDisabled.apply(this, arguments);
	}
});
<commit_msg>InlineEditBox copies the source font into its focusNode and its inline text. Refs #3209. (Patch from Mark Hays, IBM, CCLA on file)<commit_after>dojo.provide("dijit.form.InlineEditBox");

dojo.require("dojo.i18n");

dojo.require("dijit.form._FormWidget");
dojo.require("dijit._Container");
dojo.require("dijit.form.Button");

dojo.requireLocalization("dijit", "common");

dojo.declare(
	"dijit.form.InlineEditBox",
	[dijit.form._FormWidget, dijit._Container],
	// summary
	//		Wrapper widget to a text edit widget.
	//		The text is displayed on the page using normal user-styling.
	//		When clicked, the text is hidden, and the edit widget is
	//		visible, allowing the text to be updated.  Additionally,
	//		Save and Cancel button are displayed below the edit widget.
	//		When Save is clicked, the text is pulled from the edit
	//		widget and redisplayed and the edit widget is again hidden.
	//		Currently all textboxes that inherit from dijit.form.Textbox
	//		are supported edit widgets.
	//		An edit widget must support the following API to be used:
	//		String getTextValue() OR String getValue()
	//		void setTextValue(String) OR void setValue(String)
	//		void focus()
	//		It must also be able to initialize with style="display:none;" set.
{
	templatePath: dojo.moduleUrl("dijit.form", "templates/InlineEditBox.html"),

	// editing: Boolean
	//		Is the node currently in edit mode?
	editing: false,

	// autoSave: Boolean
	//				Changing the value automatically saves it, don't have to push save button
	autoSave: true,

	// buttonSave: String
	//              Save button label
	buttonSave: "",

	// buttonCancel: String
	//              Cancel button label
	buttonCancel: "",

	// renderHTML: Boolean
	//              should text render as HTML(true) or plain text(false)
	renderHTML: false,

	widgetsInTemplate: true,

	postCreate: function(){
		// look for the input widget as a child of the containerNode
		var _this = this;
		dojo.addOnLoad(function(){
			if(_this.editWidget){
				_this.containerNode.appendChild(_this.editWidget.domNode);
			}else{
				_this.editWidget = _this.getChildren()[0];
			}
			// #3209: copy the style from the source
			// don't copy ALL properties though, just the necessary/applicable ones
			dojo.forEach(["fontSize","fontFamily","fontWeight"], function(prop){
				_this.editWidget.focusNode.style[prop]=_this._srcStyle[prop];
				_this.editable.style[prop]=_this._srcStyle[prop];
			});
			_this._setEditValue = dojo.hitch(_this.editWidget,_this.editWidget.setDisplayedValue||_this.editWidget.setValue);
			_this._getEditValue = dojo.hitch(_this.editWidget,_this.editWidget.getDisplayedValue||_this.editWidget.getValue);
			_this._setEditFocus = dojo.hitch(_this.editWidget,_this.editWidget.focus);
			_this.editWidget.onChange = dojo.hitch(_this,"_onChange");
			_this.checkForValueChange();
			_this._showText();
		});
		if(this.autoSave){
			this.buttonSpan.style.display="none";
		}
	},

	postMixInProperties: function(){
		this._srcStyle=dojo.getComputedStyle(this.srcNodeRef);
		dijit.form.InlineEditBox.superclass.postMixInProperties.apply(this, arguments);
		this.messages = dojo.i18n.getLocalization("dijit", "common", this.lang);
		dojo.forEach(["buttonSave", "buttonCancel"], function(prop){
			if(!this[prop]){ this[prop] = this.messages[prop]; }
		}, this);
	},

	_onKeyPress: function(e){
		if(this.disabled || e.altKey || e.ctrlKey){ return; }
		if(e.charCode == dojo.keys.SPACE || e.keyCode == dojo.keys.ENTER){
			dojo.stopEvent(e);
			this._onClick(e);
		}
	},

	_onMouseOver: function(){
		if(!this.editing){
			var classname = this.disabled ? "dijitDisabledClickableRegion" : "dijitClickableRegion";
			dojo.addClass(this.editable, classname);
		}
	},

	_onMouseOut: function(){
		if(!this.editing){
			var classStr = this.disabled ? "dijitDisabledClickableRegion" : "dijitClickableRegion";
			dojo.removeClass(this.editable, classStr);
		}
	},

	onClick: function(/*Event*/ e){
		// summary: callback for when button is clicked; user can override this function
	},

	_onClick: function(e){
		// summary
		// 		When user clicks the text, then start editing.
		// 		Hide the text and display the form instead.

		if(this.editing || this.disabled){ return; }
		this._onMouseOut();
		this.editing = true;

		// show the edit form and hide the read only version of the text
		this._setEditValue(this._isEmpty ? '' : (this.renderHTML ? this.editable.innerHTML : this.editable.firstChild.nodeValue));
		this._initialText = this._getEditValue();
		this._visualize();

		this._setEditFocus();
		this.saveButton.setDisabled(true);
		// moved to postCreate to always listen
		//this.editWidget.onChange = dojo.hitch(this,"_onChange");
		this.onClick();
	},

	_visualize: function(e){
		dojo.style(this.editNode, "display", this.editing ? "" : "none");
		dojo.style(this.editable, "display", this.editing ? "none" : "");
	},

	_showText: function(){
		var value = this._getEditValue();
		dijit.form.InlineEditBox.superclass.setValue.call(this, value);
		// whitespace is really hard to click so show a ?
		// TODO: show user defined message in gray
		if(/^\s*$/.test(value)){ value = "?"; this._isEmpty = true; }
		else { this._isEmpty = false; }
		if(this.renderHTML){
			this.editable.innerHTML = value;
		}else{
			this.editable.innerHTML = "";
			this.editable.appendChild(document.createTextNode(value));
		}
		this._visualize();
		// #3209: resize the textarea to match the text
		// height scales automatically; only width needs setting
		// TODO: implement resize functions in the widgets so InlineEditBox doesn't have to know about things like TextArea's iframe
		/*
		if(this.editWidget.iframe){
			dojo.contentBox(this.editWidget.iframe, {w:dojo.contentBox(this.editable).w});
		}else{
			dojo.contentBox(this.editWidget.focusNode, {w:dojo.contentBox(this.editable).w});
		}*/
	},

	save: function(e){
		// summary: Callback when user presses "Save" button
		if(e){ dojo.stopEvent(e); }
		this.editing = false;
		this._showText();
	},

	cancel: function(e){
		// summary: Callback when user presses "Cancel" button
		if(e){ dojo.stopEvent(e); }
		this.editing = false;
		this._visualize();
	},

	setValue: function(/*String*/ value){
		// sets the text without informing the server
		this._setEditValue(value);
		this.editing = false;
		this._showText();
	},

	checkForValueChange: function(){
		// summary
		//		Callback when user changes input value.
		//		Enable save button if the text value is different than the original value.
		if(this.editing){
			this.saveButton.setDisabled(this._getEditValue() == this._initialText);
		}else{
			this._showText();
		}

	},

	_onBlur: function(){
		// summary:
		//	magically called when focus moves outside of the InlineEditBox widget (or it's descendants)
		if(this.autoSave){
			if(this._getEditValue() == this._initialText){
				this.cancel();
			}else{
				this.save();
			}
		}
	},

	_onChange: function(){
		// summary:
		//	This is called when the underlying widget fires an onChange event,
		//	which means that the user has presumably finished entering the value
		if(this.autoSave){
			this.save();
		}
	},

	setDisabled: function(/*Boolean*/ disabled){
		this.saveButton.setDisabled(disabled);
		this.cancelButton.setDisabled(disabled);
		this.editable.disabled = disabled;
		this.editWidget.setDisabled(disabled);
		dijit.form.InlineEditBox.superclass.setDisabled.apply(this, arguments);
	}
});
<|endoftext|>


<commit_before>/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'app'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    },
    {
      test: /\.scss$/,
      exclude: /node_modules/,
      loaders: ['style-loader', 'css-loader', 'sass-loader'],
    },
    {
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader',
    }, {
      test: /\.(jpg|png|gif)$/,
      loaders: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            progressive: true,
            optimizationLevel: 7,
            interlaced: false,
            pngquant: {
              quality: '65-90',
              speed: 4,
            },
          },
        },
      ],
    }, {
      test: /\.kml$/,
      loader: 'raw-loader',
    },
    {
      test: /\.html$/,
      loader: 'html-loader',
    }, {
      test: /\.json$/,
      loader: 'json-loader',
    }, {
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      query: {
        limit: 10000,
      },
    }],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => {
      // check if the context was created inside the moment package
      if (!/\/moment\//.test(context.context)) {
        return;
      }
      // context needs to be modified in place
      Object.assign(context, {
        // include only japanese, korean and chinese variants
        // all tests are prefixed with './' so this must be part of the regExp
        // the default regExp includes everything; /^$/ could be used to include nothing
        regExp: /^\.\/(nl)/,
        // point to the locale data folder relative to moment/src/lib/locale
        request: '../../locale',
      });
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        AUTH0_CLIENT_ID: JSON.stringify(process.env.AUTH0_CLIENT_ID),
        AUTH0_DOMAIN: JSON.stringify(process.env.AUTH0_DOMAIN),
      },
    }),
    new webpack.NamedModulesPlugin(),
  ]),
  resolve: {
    modules: ['app', 'node_modules', 'server'],
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  performance: options.performance || {},
});
<commit_msg>Save quality as array<commit_after>/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'app'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    loaders: [{
        test: /\.js$/, // Transform all .js files required somewhere with Babel
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: options.babelQuery,
      }, {
        // Do not transform vendor's CSS with CSS-modules
        // The point is that they remain in global scope.
        // Since we require these CSS files in our JS or CSS files,
        // they will be a part of our compilation either way.
        // So, no need for ExtractTextPlugin here.
        test: /\.css$/,
        include: /node_modules/,
        loaders: ['style-loader', 'css-loader'],
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loaders: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file-loader',
      }, {
        test: /\.(jpg|png|gif)$/,
        loaders: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            query: {
              progressive: true,
              optimizationLevel: 7,
              interlaced: false,
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4,
              },
            },
          },
        ],
      }, {
        test: /\.kml$/,
        loader: 'raw-loader',
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
      }, {
        test: /\.json$/,
        loader: 'json-loader',
      }, {
        test: /\.(mp4|webm)$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
        },
      }
    ],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => {
      // check if the context was created inside the moment package
      if (!/\/moment\//.test(context.context)) {
        return;
      }
      // context needs to be modified in place
      Object.assign(context, {
        // include only japanese, korean and chinese variants
        // all tests are prefixed with './' so this must be part of the regExp
        // the default regExp includes everything; /^$/ could be used to include nothing
        regExp: /^\.\/(nl)/,
        // point to the locale data folder relative to moment/src/lib/locale
        request: '../../locale',
      });
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        AUTH0_CLIENT_ID: JSON.stringify(process.env.AUTH0_CLIENT_ID),
        AUTH0_DOMAIN: JSON.stringify(process.env.AUTH0_DOMAIN),
      },
    }),
    new webpack.NamedModulesPlugin(),
  ]),
  resolve: {
    modules: ['app', 'node_modules', 'server'],
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  performance: options.performance || {},
});<|endoftext|>


<commit_before>CMS.Use(['Core/CMS.Location'], function (CMS) {
    CMS.Page = Class.extend({

        id: null,
        locations: [],
        actions: [],

        domElement: null,

        init: function (data) {
            $.extend(this, data);
            this.domElement = $('#page-' + this.id);
            this._setupLocations();
        },

        _setupLocations: function () {
            var self = this;
            for (var i in this.locations) {
                this.locations[i] = new CMS.Location(this.locations[i]);
            }
            for (i in this.locations) {
                this.locations[i].domElement.bind('sortupdate', function (event, ui) {
                    self.updateBlockLocations(event, ui);
                });
                for (var j in this.locations) {
                    if (i != j) {
                        this.locations[i].domElement.sortable('option', 'connectWith', this.locations[j].domElement);
                        this.locations[j].domElement.sortable('option', 'connectWith', this.locations[i].domElement);
                    }
                }
            }
        },

        // Updates block locations based on the current DOM
        updateBlockLocations: function (event, ui) {
            if (null != ui.sender) { // block changed locations
                var movedBlock = null;
                var movedBlockElement = $(event.originalTarget).hasClass('block')?$(event.originalTarget):$(event.originalTarget).parents('.block:first');
                var movedBlockId = parseInt(movedBlockElement.attr('id').substring(6));
                var originalLocation = this.locations[$(ui.sender).attr('id')];
                for (i in originalLocation.blocks) {
                    if (originalLocation.blocks[i].id == movedBlockId) {
                        movedBlock = originalLocation.blocks.splice(i, 1);
                    }
                }
                this.locations[$(event.target).attr('id')].blocks.push(movedBlock[0]);
                this.locations[$(ui.sender).attr('id')].updateBlocks();
            }
            this.locations[$(event.target).attr('id')].updateBlocks();

            if (!this.saveBlocks()) {
                if (null != ui.sender) {
                    $(ui.sender).sortable('cancel');
                    this.locations[$(ui.sender).attr('id')].updateBlocks();
                } else {
                    $(event.target).sortable('cancel');
                    this.locations[$(event.target).attr('id')].updateBlocks();
                }
            }
        },

        /**
         * sends block order and location to the backend
         * this request is done synchronously so that we can ensure it succeded
         */
        saveBlocks: function () {
            var isSuccessful = false;
            var self = this;
            $.ajax({
                async: false,
                data: {
                    page: JSON.stringify({data: [this]})
                },
                dataType: 'json',
                success: function (result) {
                    if (result.code.id == 0) {
                        isSuccessful = true;
                    }
                },
                type: 'POST',
                url: this.actions['blockRearrange'].postback
            });
            return isSuccessful;
        }
    });
});<commit_msg>Fixed movedBlock not being found on move<commit_after>CMS.Use(['Core/CMS.Location'], function (CMS) {
    CMS.Page = Class.extend({

        id: null,
        locations: [],
        actions: [],

        domElement: null,

        init: function (data) {
            $.extend(this, data);
            this.domElement = $('#page-' + this.id);
            this._setupLocations();
        },

        _setupLocations: function () {
            var self = this;
            for (var i in this.locations) {
                this.locations[i] = new CMS.Location(this.locations[i]);
            }
            for (i in this.locations) {
                this.locations[i].domElement.bind('sortupdate', function (event, ui) {
                    self.updateBlockLocations(event, ui);
                });
                for (var j in this.locations) {
                    if (i != j) {
                        this.locations[i].domElement.sortable('option', 'connectWith', this.locations[j].domElement);
                        this.locations[j].domElement.sortable('option', 'connectWith', this.locations[i].domElement);
                    }
                }
            }
        },

        // Updates block locations based on the current DOM
        updateBlockLocations: function (event, ui) {
            if (null != ui.sender) { // block changed locations
                var movedBlock = null;
                console.log(event);
                var movedBlockElement = $(event.originalTarget).parents('.block-actions:first').siblings('.block:first');
                var movedBlockId = parseInt(movedBlockElement.attr('id').substring(6));
                var originalLocation = this.locations[$(ui.sender).attr('id')];
                for (i in originalLocation.blocks) {
                    if (originalLocation.blocks[i].id == movedBlockId) {
                        movedBlock = originalLocation.blocks.splice(i, 1);
                    }
                }
                this.locations[$(event.target).attr('id')].blocks.push(movedBlock[0]);
                this.locations[$(ui.sender).attr('id')].updateBlocks();
            }
            this.locations[$(event.target).attr('id')].updateBlocks();

            if (!this.saveBlocks()) {
                if (null != ui.sender) {
                    $(ui.sender).sortable('cancel');
                    this.locations[$(ui.sender).attr('id')].updateBlocks();
                } else {
                    $(event.target).sortable('cancel');
                    this.locations[$(event.target).attr('id')].updateBlocks();
                }
            }
        },

        /**
         * sends block order and location to the backend
         * this request is done synchronously so that we can ensure it succeded
         */
        saveBlocks: function () {
            var isSuccessful = false;
            var self = this;
            $.ajax({
                async: false,
                data: {
                    page: JSON.stringify({data: [this]})
                },
                dataType: 'json',
                success: function (result) {
                    if (result.code.id == 0) {
                        isSuccessful = true;
                    }
                },
                type: 'POST',
                url: this.actions['blockRearrange'].postback
            });
            return isSuccessful;
        }
    });
});<|endoftext|>


<commit_before>// Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

module.exports = require('./webpack.base.babel')({
  // In production, we skip all hot-reloading stuff
  entry: {
    index: path.join(process.cwd(), 'app/app.js'),
    share: path.join(process.cwd(), 'app/share/app.js'),
    shareApp: path.join(process.cwd(), 'app/share/share.js'),
  },

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      children: true,
      minChunks: 2,
      async: true,
    }),

    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'index.html',
      chunks: ['index'],
    }),

    // public_share.html
    new HtmlWebpackPlugin({
      template: 'app/share/public_share.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'public_share.html',
      chunks: ['share'],
    }),

    // group_share.html
    new HtmlWebpackPlugin({
      template: 'app/share/group_share.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'group_share.html',
      chunks: ['shareApp'],
    }),

    // hybrid.html
    new HtmlWebpackPlugin({
      template: 'app/hybrid/hybrid.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'hybrid.html',
      chunks: ['hybrid'],
    }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js'],
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true,

      AppCache: false,
    }),
  ],

  babelQuery: {
    plugins: [
      [
        'import',
        {
          style: 'css',
          libraryName: 'antd-mobile',
        },
      ],
    ],
  },

  performance: {
    assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
  },
});
<commit_msg>. update webpack config for production env<commit_after>// Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

module.exports = require('./webpack.base.babel')({
  // In production, we skip all hot-reloading stuff
  entry: {
    index: path.join(process.cwd(), 'app/app.js'),
    share: path.join(process.cwd(), 'app/share/app.js'),
    shareApp: path.join(process.cwd(), 'app/share/share.js'),
    hybrid: path.join(process.cwd(), 'app/hybrid/app.js'),
  },

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      children: true,
      minChunks: 2,
      async: true,
    }),

    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'index.html',
      chunks: ['index'],
    }),

    // public_share.html
    new HtmlWebpackPlugin({
      template: 'app/share/public_share.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'public_share.html',
      chunks: ['share'],
    }),

    // group_share.html
    new HtmlWebpackPlugin({
      template: 'app/share/group_share.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'group_share.html',
      chunks: ['shareApp'],
    }),

    // hybrid.html
    new HtmlWebpackPlugin({
      template: 'app/hybrid/hybrid.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
      filename: 'hybrid.html',
      chunks: ['hybrid'],
    }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js'],
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true,

      AppCache: false,
    }),
  ],

  babelQuery: {
    plugins: [
      [
        'import',
        {
          style: 'css',
          libraryName: 'antd-mobile',
        },
      ],
    ],
  },

  performance: {
    assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
  },
});
<|endoftext|>