<commit_before>"use strict";

/*global module, require*/

var d3 = require("d3"),

    svgTextWrapping = require("./svg-text-wrapping.js"),
    helpers = require("../helpers.js"),
    callbacks = helpers.callbackHandler,
    edgePath = require("../layout/edge-path.js"),

    empty = d3.select();

/*
 Draws parts which are common to all types of node.
 */
module.exports = function(container, defs, getNodeCollection, getLayout, viewport, transitions, drawEdges, redrawNode, selectNodes, update) {
    /*
     Used to tidy up the beginnings of edges.
     */
    var drawJunctionMasks = function(nodeData, keepMissing) {
	var junctionMasks = defs.selectAll("mask.junction-mask")
		.data(
		    nodeData,
		    function(d, i) {
			return d.id;
		    }
		);

	if (!keepMissing) {
	    junctionMasks.exit().remove();
	}

	var newMasks = junctionMasks.enter().append("mask")
		.classed("junction-mask", true)
		.attr("id", function(d, i) {
		    return "cut-" + d.id;
		})
	/*
	 This is some dark magic which controls the size of the buffer we are masking against.

	 See: http://www.w3.org/TR/2003/REC-SVG11-20030114/masking.html
	 */
		.attr("maskUnits", "userSpaceOnUse")
		.attr("x", "-50000%")
		.attr("y", "-50000%")
		.attr("width", "100000%")
		.attr("height", "100000%");

	newMasks.append("circle")
	    .classed("background-mask", true)
	    .attr("r", 10000)
	    .attr("fill", "white")
	    .attr("stroke", "none");

	transitions.maybeTransition(
	    junctionMasks.select(".background-mask"))
	    .attr("cx", function(d, i) {
		return d.edgeJunction[0];
	    })
	    .attr("cy", function(d, i) {
		return d.edgeJunction[1];
	    });

	newMasks
	    .append("circle")
	    .classed("hidden-mask", true)
	    .attr("fill", "black")
	    .attr("stroke", "none");

	transitions.maybeTransition(
	    junctionMasks.select(".hidden-mask"))
	    .attr("r", function(d, i) {
		return (d.type === "process" && d.detail) ? 7 : 5;
	    })
	    .attr("cx", function(d, i) {
		return d.edgeJunction[0];
	    })
	    .attr("cy", function(d, i) {
		return d.edgeJunction[1];
	    });
    },

	/*
	 When we move or resize a node, we redraw it individually to prevent slowdown.

	 This function lets us also redraw its incoming and outgoing edges at the some time.
	 */
	redrawEdgesToNode = function(edgesInCoords, edgesOutCoords, nodeId) {
	    var direction = getLayout().getOrientationCoords(),
		nodeCollection = getNodeCollection(),
		node = nodeCollection.get(nodeId),
		edgesSelection = d3.select("#non-existant-element"),

		outgoing = node.edges().forEach(function(e) {
		    var element = d3.select("#edge-" + e.parent().id + "-to-" + e.node().id),
			d = element.datum();

		    d.path = edgePath(
			edgesOutCoords,
			/* Find the existing edge and use the last coordinate of its path as the start point. */
			d.path.pop(),
			direction
		    );

		    edgesSelection[0].push(element.node());
		}),

		incoming = nodeCollection.edgesToNode(node)
		    .forEach(function(e) {
			var element = d3.select("#edge-" + e.parent().id + "-to-" + e.node().id),
			    d = element.datum();

			d.path = edgePath(
			    /* Find the existing edge and use the first coordinate of its path as the start point. */
			    d.path[0],
			    edgesInCoords,
			    direction
			);

			edgesSelection[0].push(element.node());
		    });

	    drawEdges(
		edgesSelection,
		empty
	    );
	},

	drawMoveHandle = function(nodes, newNodes) {
	    var tryDrag = function(g, c) {
		var target = document.elementFromPoint(
		    d3.event.sourceEvent.clientX,
		    d3.event.sourceEvent.clientY
		);

		if (target && target.tagName.toLowerCase() === "input") {
		    // Inside a text input

		} else if (d3.event && d3.event.sourceEvent && d3.event.sourceEvent.button === 2) {
		    // Right-mouse button
		    d3.event.sourceEvent.preventDefault();
		    d3.event.sourceEvent.stopPropagation();

		} else {
		    c(g);
		}
	    },

		dragNode = d3.behavior.drag()
		    .origin(function(d){
			return {
			    x: d.x,
			    y: d.y
			};
		    })
		    .on("dragstart", function(d){
			tryDrag(
			    d3.select(this),
			    function(g) {
				d3.event.sourceEvent.stopPropagation();
				transitions.enabled(false);
			    }
			);
		    })
		    .on("drag", function(d) {
			tryDrag(
			    d3.select(this),
			    function(g) {
				var x = d3.event.x,
				    y = d3.event.y,
				    layout = getLayout();

				layout.setPosition(d.id, [x, y]);
				d.x = x;
				d.y = y;

				/*
				 Update some properties on the view model which depend on its size and position.
				 */
				d.resize(d.size);

				redrawNode(g);
				drawJunctionMasks([d], true);
				redrawEdgesToNode(d.edgeEnd, d.edgeJunction, d.id);
			    }
			);
		    })
		    .on("dragend", function(d) {
			update();
			transitions.enabled(true);
		    });

	    newNodes.call(dragNode);

	    newNodes.on("contextmenu", function(d, i){
		d3.event.stopPropagation();
		d3.event.preventDefault();

		var l = getLayout();
		l.setSize(d.id, null);
		l.setPosition(d.id, null);

		update();
	    });
	},

	dragResize = d3.behavior.drag()
    	    .origin(function(d){
		return {
		    x: d.size[0],
		    y: d.size[1]
		};
	    })
	    .on("dragstart", function(d){
		d3.event.sourceEvent.stopPropagation();
		transitions.enabled(false);
	    })
	    .on("drag", function(d){
		var x = d3.event.x,
		    y = d3.event.y,
		    layout = getLayout();

		layout.setSize(d.id, [x, y]);
		d.resize(layout.getSize(d.id));

		redrawNode(
		    d3.select(this.parentElement)
		);

		drawJunctionMasks([d], true);
		redrawEdgesToNode(d.edgeEnd, d.edgeJunction, d.id);
	    })
	    .on("dragend", function(d) {
		update();
		transitions.enabled(true);
	    }),

	drawResizeHandle = function(nodes, newNodes) {
	    newNodes.append("g")
		.classed("resize-handle", true)
		.call(dragResize)
		.append("text")
		.text("⇘")
		.classed("no-select", true);

	    nodes.select("g.resize-handle")
		.attr("transform", function(d, i) {
		    return "translate(" + (d.size[0] - 8) + "," + (d.size[1] - 0.5) + ")";
		});

	},

	drawNodeName = function(nodes, newNodes) {
	    newNodes.append("g")
		.classed("name", true)
		.on("click", centreNode)
		.append("text");

	    nodes.select("g.name")
		.attr("transform", function(d, i) {
		    return "translate(" + d.margin.horizontal + "," + d.margin.vertical + ")";
		})
		.style("visibility", function(d, i) {
		    /*
		     If the node is centred, we'll provide a text box for the user to edit it instead of display SVG text.
		     */
		    return d.centred ? "hidden" : "visible";
		})
		.select("text")
		.call(
		    svgTextWrapping,
		    function(d, i) {
			return d.name;
		    },
		    function(d) {
			return d.innerWidth;
		    },
		    function(d) {
			return d.innerHeight;
		    }
		);
	};

    var closeEnough = function(bbox, x, y) {
	return (bbox.x >= x || (bbox.x + bbox.width) <= x) &&
	    (bbox.y >= y || (bbox.y + bbox.height) <= y);
    },

	centreNode = function(d, i) {
	    if (!d3.event.defaultPrevented) {
		viewport.centreNode(d.id);
	    }
	},

	drawNodes = function(nodes, newNodes) {
	    newNodes
		.append("rect")
		.classed("node-box", true)
		.on("click", centreNode)
		.each(function(d, i) {
		    d3.select(this).classed("node-box-" + d.type, true);
		});

	    nodes
		.classed("selected", function(d, i) {
		    return d.selected;
		})
		.select("rect.node-box")
		.attr("width", function(d, i) {
		    return d.size[0] + "px";
		})
		.attr("height", function(d, i) {
		    return d.size[1] + "px";
		});

	    drawNodeName(nodes, newNodes);

	    transitions.maybeTransition(nodes).attr("transform", function(d, i){
		return "translate(" + (d.x) + "," + d.y + ")";
	    });

	    drawMoveHandle(nodes, newNodes);
	    drawResizeHandle(nodes, newNodes);
	};

    return {
	redrawNode: function(nodes, newNodes) {
	    drawNodes(nodes, newNodes);
	},

	draw: function(nodeData) {
	    var nodes = selectNodes()
		    .data(
			nodeData,
			function(d, i) {
			    return d.id;
			}
		    );

	    var newNodes = nodes.enter()
		    .append("g")
		    .classed("process-node", true);

	    transitions.fadeOut(nodes);

	    drawNodes(nodes, newNodes);
	    drawJunctionMasks(nodeData);

	    return {
		nodes: nodes,
		newNodes: newNodes
	    };
	}
    };
};
<commit_msg>Added some transitions.<commit_after>"use strict";

/*global module, require*/

var d3 = require("d3"),

    svgTextWrapping = require("./svg-text-wrapping.js"),
    helpers = require("../helpers.js"),
    callbacks = helpers.callbackHandler,
    edgePath = require("../layout/edge-path.js"),

    empty = d3.select();

/*
 Draws parts which are common to all types of node.
 */
module.exports = function(container, defs, getNodeCollection, getLayout, viewport, transitions, drawEdges, redrawNode, selectNodes, update) {
    /*
     Used to tidy up the beginnings of edges.
     */
    var drawJunctionMasks = function(nodeData, keepMissing) {
	var junctionMasks = defs.selectAll("mask.junction-mask")
		.data(
		    nodeData,
		    function(d, i) {
			return d.id;
		    }
		);

	if (!keepMissing) {
	    junctionMasks.exit().remove();
	}

	var newMasks = junctionMasks.enter().append("mask")
		.classed("junction-mask", true)
		.attr("id", function(d, i) {
		    return "cut-" + d.id;
		})
	/*
	 This is some dark magic which controls the size of the buffer we are masking against.

	 See: http://www.w3.org/TR/2003/REC-SVG11-20030114/masking.html
	 */
		.attr("maskUnits", "userSpaceOnUse")
		.attr("x", "-50000%")
		.attr("y", "-50000%")
		.attr("width", "100000%")
		.attr("height", "100000%");

	newMasks.append("circle")
	    .classed("background-mask", true)
	    .attr("r", 10000)
	    .attr("fill", "white")
	    .attr("stroke", "none");

	transitions.maybeTransition(
	    junctionMasks.select(".background-mask"))
	    .attr("cx", function(d, i) {
		return d.edgeJunction[0];
	    })
	    .attr("cy", function(d, i) {
		return d.edgeJunction[1];
	    });

	newMasks
	    .append("circle")
	    .classed("hidden-mask", true)
	    .attr("fill", "black")
	    .attr("stroke", "none");

	transitions.maybeTransition(
	    junctionMasks.select(".hidden-mask"))
	    .attr("r", function(d, i) {
		return (d.type === "process" && d.detail) ? 7 : 5;
	    })
	    .attr("cx", function(d, i) {
		return d.edgeJunction[0];
	    })
	    .attr("cy", function(d, i) {
		return d.edgeJunction[1];
	    });
    },

	/*
	 When we move or resize a node, we redraw it individually to prevent slowdown.

	 This function lets us also redraw its incoming and outgoing edges at the some time.
	 */
	redrawEdgesToNode = function(edgesInCoords, edgesOutCoords, nodeId) {
	    var direction = getLayout().getOrientationCoords(),
		nodeCollection = getNodeCollection(),
		node = nodeCollection.get(nodeId),
		edgesSelection = d3.select("#non-existant-element"),

		outgoing = node.edges().forEach(function(e) {
		    var element = d3.select("#edge-" + e.parent().id + "-to-" + e.node().id),
			d = element.datum();

		    d.path = edgePath(
			edgesOutCoords,
			/* Find the existing edge and use the last coordinate of its path as the start point. */
			d.path.pop(),
			direction
		    );

		    edgesSelection[0].push(element.node());
		}),

		incoming = nodeCollection.edgesToNode(node)
		    .forEach(function(e) {
			var element = d3.select("#edge-" + e.parent().id + "-to-" + e.node().id),
			    d = element.datum();

			d.path = edgePath(
			    /* Find the existing edge and use the first coordinate of its path as the start point. */
			    d.path[0],
			    edgesInCoords,
			    direction
			);

			edgesSelection[0].push(element.node());
		    });

	    drawEdges(
		edgesSelection,
		empty
	    );
	},

	drawMoveHandle = function(nodes, newNodes) {
	    var tryDrag = function(g, c) {
		var target = document.elementFromPoint(
		    d3.event.sourceEvent.clientX,
		    d3.event.sourceEvent.clientY
		);

		if (target && target.tagName.toLowerCase() === "input") {
		    // Inside a text input

		} else if (d3.event && d3.event.sourceEvent && d3.event.sourceEvent.button === 2) {
		    // Right-mouse button
		    d3.event.sourceEvent.preventDefault();
		    d3.event.sourceEvent.stopPropagation();

		} else {
		    c(g);
		}
	    },

		dragNode = d3.behavior.drag()
		    .origin(function(d){
			return {
			    x: d.x,
			    y: d.y
			};
		    })
		    .on("dragstart", function(d){
			tryDrag(
			    d3.select(this),
			    function(g) {
				d3.event.sourceEvent.stopPropagation();
				transitions.enabled(false);
			    }
			);
		    })
		    .on("drag", function(d) {
			tryDrag(
			    d3.select(this),
			    function(g) {
				var x = d3.event.x,
				    y = d3.event.y,
				    layout = getLayout();

				layout.setPosition(d.id, [x, y]);
				d.x = x;
				d.y = y;

				/*
				 Update some properties on the view model which depend on its size and position.
				 */
				d.resize(d.size);

				redrawNode(g);
				drawJunctionMasks([d], true);
				redrawEdgesToNode(d.edgeEnd, d.edgeJunction, d.id);
			    }
			);
		    })
		    .on("dragend", function(d) {
			update();
			transitions.enabled(true);
		    });

	    newNodes.call(dragNode);

	    newNodes.on("contextmenu", function(d, i){
		d3.event.stopPropagation();
		d3.event.preventDefault();

		var l = getLayout();
		l.setSize(d.id, null);
		l.setPosition(d.id, null);

		update();
	    });
	},

	dragResize = d3.behavior.drag()
    	    .origin(function(d){
		return {
		    x: d.size[0],
		    y: d.size[1]
		};
	    })
	    .on("dragstart", function(d){
		d3.event.sourceEvent.stopPropagation();
		transitions.enabled(false);
	    })
	    .on("drag", function(d){
		var x = d3.event.x,
		    y = d3.event.y,
		    layout = getLayout();

		layout.setSize(d.id, [x, y]);
		d.resize(layout.getSize(d.id));

		redrawNode(
		    d3.select(this.parentElement)
		);

		drawJunctionMasks([d], true);
		redrawEdgesToNode(d.edgeEnd, d.edgeJunction, d.id);
	    })
	    .on("dragend", function(d) {
		update();
		transitions.enabled(true);
	    }),

	drawResizeHandle = function(nodes, newNodes) {
	    newNodes.append("g")
		.classed("resize-handle", true)
		.call(dragResize)
		.append("text")
		.text("⇘")
		.classed("no-select", true);

	    transitions.maybeTransition(
		nodes.select("g.resize-handle"))
		.attr("transform", function(d, i) {
		    return "translate(" + (d.size[0] - 8) + "," + (d.size[1] - 0.5) + ")";
		});
	},

	drawNodeName = function(nodes, newNodes) {
	    newNodes.append("g")
		.classed("name", true)
		.on("click", centreNode)
		.append("text");

	    var names = nodes.select("g.name")
		.style("visibility", function(d, i) {
		    /*
		     If the node is centred, we'll provide a text box for the user to edit it instead of display SVG text.
		     */
		    return d.centred ? "hidden" : "visible";
		});

	    transitions.maybeTransition(names)
	    	.attr("transform", function(d, i) {
		    return "translate(" + d.margin.horizontal + "," + d.margin.vertical + ")";
		});

	    names
		.select("text")
		.call(
		    svgTextWrapping,
		    function(d, i) {
			return d.name;
		    },
		    function(d) {
			return d.innerWidth;
		    },
		    function(d) {
			return d.innerHeight;
		    }
		);
	};

    var closeEnough = function(bbox, x, y) {
	return (bbox.x >= x || (bbox.x + bbox.width) <= x) &&
	    (bbox.y >= y || (bbox.y + bbox.height) <= y);
    },

	centreNode = function(d, i) {
	    if (!d3.event.defaultPrevented) {
		viewport.centreNode(d.id);
	    }
	},

	drawNodes = function(nodes, newNodes) {
	    newNodes
		.append("rect")
		.classed("node-box", true)
		.on("click", centreNode)
		.each(function(d, i) {
		    d3.select(this).classed("node-box-" + d.type, true);
		});

	    var rects = nodes
		.classed("selected", function(d, i) {
		    return d.selected;
		})
		    .select("rect.node-box");

	    transitions.maybeTransition(rects)
		.attr("width", function(d, i) {
		    return d.size[0] + "px";
		})
		.attr("height", function(d, i) {
		    return d.size[1] + "px";
		});

	    drawNodeName(nodes, newNodes);

	    transitions.maybeTransition(nodes)
		.attr("transform", function(d, i){
		    return "translate(" + (d.x) + "," + d.y + ")";
		});

	    drawMoveHandle(nodes, newNodes);
	    drawResizeHandle(nodes, newNodes);
	};

    return {
	redrawNode: function(nodes, newNodes) {
	    drawNodes(nodes, newNodes);
	},

	draw: function(nodeData) {
	    var nodes = selectNodes()
		    .data(
			nodeData,
			function(d, i) {
			    return d.id;
			}
		    );

	    var newNodes = nodes.enter()
		    .append("g")
		    .classed("process-node", true);

	    transitions.fadeOut(nodes);

	    drawNodes(nodes, newNodes);
	    drawJunctionMasks(nodeData);

	    return {
		nodes: nodes,
		newNodes: newNodes
	    };
	}
    };
};
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import ArticleEditor from './components/ArticleEditor';
import { createArticle } from 'app/actions/ArticleActions';
import { uploadFile } from 'app/actions/FileActions';
import { reduxForm } from 'redux-form';
import { compose } from 'redux';
import { LoginPage } from 'app/components/LoginForm';
import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn';

const mapStateToProps = () => ({
  isNew: true,
  article: {},
  initialValues: {
    content: ''
  }
});

const mapDispatchToProps = { submitArticle: createArticle, uploadFile };

export default compose(
  replaceUnlessLoggedIn(LoginPage),
  connect(mapStateToProps, mapDispatchToProps)
)(ArticleEditor);
<commit_msg>Remove unused import<commit_after>import { connect } from 'react-redux';
import ArticleEditor from './components/ArticleEditor';
import { createArticle } from 'app/actions/ArticleActions';
import { uploadFile } from 'app/actions/FileActions';
import { compose } from 'redux';
import { LoginPage } from 'app/components/LoginForm';
import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn';

const mapStateToProps = () => ({
  isNew: true,
  article: {},
  initialValues: {
    content: ''
  }
});

const mapDispatchToProps = { submitArticle: createArticle, uploadFile };

export default compose(
  replaceUnlessLoggedIn(LoginPage),
  connect(mapStateToProps, mapDispatchToProps)
)(ArticleEditor);
<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Route.extend(AuthenticatedRouteMixin, {
  currentUser: service('current-user'),
  model() {
    return this.store.query('convention', {
      'status': 10,
      'persons__owners': this.currentUser.user.id,
    });
  },
});
<commit_msg>connect to owners<commit_after>import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Route.extend(AuthenticatedRouteMixin, {
  currentUser: service('current-user'),
  model() {
    return this.store.query('convention', {
      'status': 10,
      'owners': this.currentUser.user.id,
    });
  },
});
<|endoftext|>


<commit_before>define(['backbone', 'backbone.pageable.collection', 'config', 'communicator', 'plugin/geojson_features/models/feature', 'erfgeoviewer.common'],
  function(Backbone, PageableCollection, Config, Communicator, ResultModel, App) {

    var DelvingResultModel = ResultModel.extend({
      parse: function(fields) {

        var f = {
          title: fields['dc:title'],
          description: fields['dc:description'],
          spatial: this.parseDctermsSpatial(fields)
        };

        if (_.isArray(f.title)) f.title = f.title.join(', ');

        // Image
        var img, ext;
        if (_.isArray(fields['edm:object'])) {
          ext = fields['edm:object'][0].match(/\.[0-9a-z]+$/i);
          if (ext && _.contains(['.jpg', '.jpeg', '.png', '.gif'], ext[0]) || fields['edm:type'][0] == "IMAGE")
            img = fields['edm:object'][0];
        }
        if (img) f.image = img;

        return f;
      },

      parseDctermsSpatial: function(fields) {
        var geoJSONStrings = [],
          dcTermsSpatial,
          geosHasGeometry,
          geosAsWKT,
          lat,
          long;

        if ( _.isArray(dcTermsSpatial = _.property('dcterms:spatial')(fields)) ) {
          _.each(dcTermsSpatial, function(term) {
            if ( _.isArray(geosHasGeometry = _.property('geos:hasGeometry')(term)) ) {
              _.each(geosHasGeometry, function(geometry) {
                if ( _.isArray(geosAsWKT = _.property('geos:asWKT')(geometry)) ) {
                  _.each(geosAsWKT, function(wkt) {
                    geoJSONStrings.push(wkt);
                  });
                }
              });
            }
            else if ( (lat = _.property('geo:lat')(term)) && (long = _.property('geo:long')(term)) ) {
              geoJSONStrings.push('POINT(' + long + ' ' + lat + ')');
            }
          });
        }

        return geoJSONStrings;
      }
    });

    var MODE_ADVANCED = 'advanced',
      MODE_SIMPLE = 'simple';

    return PageableCollection.extend({

      model: DelvingResultModel,

      searchMode: 'simple',

      queryParams: {
        currentPage: null,
        pageSize: null,
        totalPages: null,
        totalRecords: null,
//        facets: 'dc:subject:4,dc:type:4,edm:dataProvider:4',
        maximumRecords: function() {
          return this.state.maxRecords;
        },
        startRecord: function() {
          return (this.state.currentPage -1) * this.state.pageSize +1;
        },
        query: function() {
          var query = {
            type: 'AND',
            values: [
              this.state.terms
            ]
          };

          if (_.isEmpty(this.state.facets) && _.isObject(Config.zoek_en_vind.facets)) {
            query.values.push(Config.zoek_en_vind.facets);
          }
          else if (!_.isEmpty(this.state.facets) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: this.state.facets
            });
          }

          if (!_.isEmpty(this.state.date.from) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year >= ' + this.state.date.from]
            });
          }

          if (!_.isEmpty(this.state.date.to) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year <= ' + this.state.date.to]
            });
          }

          if (App.mode == 'mapmaker' && _.isEmpty(this.state.geoFence)) {
            // Add filter to only return items with geo info #8899
            query.values.push({
              type: 'AND',
              values: [
                'minGeoLat=-90',
                'minGeoLong=-180',
                'maxGeoLat=90',
                'maxGeoLong=180'
              ]
            });
          }

          if (!_.isEmpty(this.state.geoFence)) {
            query.values.push(this.state.geoFence);
          }

          return this.renderQuery(query);
        }
      },
      state: {
        d: 100,
        firstPage: 1,
        pageSize: 30,
        maxRecords: 30,
        terms: "*",
        date: {
          from: '',
          to: ''
        },
        facets: [], // Always AND
        facetConfig: null,
        geoFence: null
      },
      url: Config.zoek_en_vind.uri + '/search',

      initialize: function() {
        Communicator.mediator.on('search:toggleAdvancedSearch', this.toggleSearchMode, this);
      },

      toggleSearchMode: function() {
        this.searchMode = this.searchMode == MODE_SIMPLE ? MODE_ADVANCED : MODE_SIMPLE;
      },

      renderQuery: function(query) {
        var self = this;

        _.each(query.values, function(value, key) {
          if (_.isObject(value)) {
            query.values[key] = '(' + self.renderQuery(value) + ')';
          }
        });

        return query.values.join(' ' + query.type + ' ');
      },
      getFacetConfig: function() {
        return new Backbone.Collection(this.state.facetConfig);
      },
      getFacetState: function(resp) {
        var facetConfig = [];

        _.each(resp.result.facets, function(options, name) {
          if (!_.isUndefined(Config.zoek_en_vind.facetLabels)
          && !_.isUndefined(Config.zoek_en_vind.facetLabels[name])) {
            name = Config.zoek_en_vind.facetLabels[name];
          }
          facetConfig.push({
            name: name,
            options: options
          });
        });

        return facetConfig;
      },
      hasNext: function() {
        return this.hasNextPage();
      },
      hasPrevious: function() {
        return this.hasPreviousPage();
      },
      parseRecords: function(resp) {
        return resp.result.items;
      },
      parseState: function(resp) {
        return {
          facetConfig: this.getFacetState(resp),
          totalRecords: resp.result.total
        }
      }

    });

  });<commit_msg>use shortened description as a title if the title isn't avail, but desc is<commit_after>define(['backbone', 'backbone.pageable.collection', 'config', 'communicator', 'plugin/geojson_features/models/feature', 'erfgeoviewer.common'],
  function(Backbone, PageableCollection, Config, Communicator, ResultModel, App) {

    var DelvingResultModel = ResultModel.extend({
      parse: function(fields) {

        var f = {
          title: fields['dc:title'],
          description: fields['dc:description'],
          spatial: this.parseDctermsSpatial(fields)
        };

        if (_.isArray(f.title)) f.title = f.title.join(', ');

        // Image
        var img, ext;
        if (_.isArray(fields['edm:object'])) {
          ext = fields['edm:object'][0].match(/\.[0-9a-z]+$/i);
          if (ext && _.contains(['.jpg', '.jpeg', '.png', '.gif'], ext[0]) || fields['edm:type'][0] == "IMAGE")
            img = fields['edm:object'][0];
        }
        if (img) f.image = img;

        // Title defaults to a shortened description if need be
        if (!fields['dc:title'] && fields['dc:description']) {
          var words = fields['dc:description'][0].split(/\s+/);
          var max = 250;
          var newtitle;
          for (var i = words.length; i >= 0; i--) {
            newtitle = words.slice([0, i]).join(" ");
            if (newtitle.length < max) break;
          }
          f.title = newtitle;
        }

        return f;
      },

      parseDctermsSpatial: function(fields) {
        var geoJSONStrings = [],
          dcTermsSpatial,
          geosHasGeometry,
          geosAsWKT,
          lat,
          long;

        if ( _.isArray(dcTermsSpatial = _.property('dcterms:spatial')(fields)) ) {
          _.each(dcTermsSpatial, function(term) {
            if ( _.isArray(geosHasGeometry = _.property('geos:hasGeometry')(term)) ) {
              _.each(geosHasGeometry, function(geometry) {
                if ( _.isArray(geosAsWKT = _.property('geos:asWKT')(geometry)) ) {
                  _.each(geosAsWKT, function(wkt) {
                    geoJSONStrings.push(wkt);
                  });
                }
              });
            }
            else if ( (lat = _.property('geo:lat')(term)) && (long = _.property('geo:long')(term)) ) {
              geoJSONStrings.push('POINT(' + long + ' ' + lat + ')');
            }
          });
        }

        return geoJSONStrings;
      }
    });

    var MODE_ADVANCED = 'advanced',
      MODE_SIMPLE = 'simple';

    return PageableCollection.extend({

      model: DelvingResultModel,

      searchMode: 'simple',

      queryParams: {
        currentPage: null,
        pageSize: null,
        totalPages: null,
        totalRecords: null,
//        facets: 'dc:subject:4,dc:type:4,edm:dataProvider:4',
        maximumRecords: function() {
          return this.state.maxRecords;
        },
        startRecord: function() {
          return (this.state.currentPage -1) * this.state.pageSize +1;
        },
        query: function() {
          var query = {
            type: 'AND',
            values: [
              this.state.terms
            ]
          };

          if (_.isEmpty(this.state.facets) && _.isObject(Config.zoek_en_vind.facets)) {
            query.values.push(Config.zoek_en_vind.facets);
          }
          else if (!_.isEmpty(this.state.facets) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: this.state.facets
            });
          }

          if (!_.isEmpty(this.state.date.from) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year >= ' + this.state.date.from]
            });
          }

          if (!_.isEmpty(this.state.date.to) && this.searchMode == MODE_ADVANCED) {
            query.values.push({
              type: 'AND',
              values: ['dc:date.year <= ' + this.state.date.to]
            });
          }

          if (App.mode == 'mapmaker' && _.isEmpty(this.state.geoFence)) {
            // Add filter to only return items with geo info #8899
            query.values.push({
              type: 'AND',
              values: [
                'minGeoLat=-90',
                'minGeoLong=-180',
                'maxGeoLat=90',
                'maxGeoLong=180'
              ]
            });
          }

          if (!_.isEmpty(this.state.geoFence)) {
            query.values.push(this.state.geoFence);
          }

          return this.renderQuery(query);
        }
      },
      state: {
        d: 100,
        firstPage: 1,
        pageSize: 30,
        maxRecords: 30,
        terms: "*",
        date: {
          from: '',
          to: ''
        },
        facets: [], // Always AND
        facetConfig: null,
        geoFence: null
      },
      url: Config.zoek_en_vind.uri + '/search',

      initialize: function() {
        Communicator.mediator.on('search:toggleAdvancedSearch', this.toggleSearchMode, this);
      },

      toggleSearchMode: function() {
        this.searchMode = this.searchMode == MODE_SIMPLE ? MODE_ADVANCED : MODE_SIMPLE;
      },

      renderQuery: function(query) {
        var self = this;

        _.each(query.values, function(value, key) {
          if (_.isObject(value)) {
            query.values[key] = '(' + self.renderQuery(value) + ')';
          }
        });

        return query.values.join(' ' + query.type + ' ');
      },
      getFacetConfig: function() {
        return new Backbone.Collection(this.state.facetConfig);
      },
      getFacetState: function(resp) {
        var facetConfig = [];

        _.each(resp.result.facets, function(options, name) {
          if (!_.isUndefined(Config.zoek_en_vind.facetLabels)
          && !_.isUndefined(Config.zoek_en_vind.facetLabels[name])) {
            name = Config.zoek_en_vind.facetLabels[name];
          }
          facetConfig.push({
            name: name,
            options: options
          });
        });

        return facetConfig;
      },
      hasNext: function() {
        return this.hasNextPage();
      },
      hasPrevious: function() {
        return this.hasPreviousPage();
      },
      parseRecords: function(resp) {
        return resp.result.items;
      },
      parseState: function(resp) {
        return {
          facetConfig: this.getFacetState(resp),
          totalRecords: resp.result.total
        }
      }

    });

  });<|endoftext|>


<commit_before>import StringUtils from "../util/floatz.util.strings.js";

/**
 * Constants
 */
const BLOCK = "block";
const DISPLAY = "display";
const HIDDEN = "hidden";
const NONE = "none";
const PREV_DISPLAY = "flz-prev-display";
const PREV_INLINE_DISPLAY = "flz-prev-inline-display";
const PX = "px";
const STYLE = "style";

/**
 * DOM utilities.
 */
export default class DOM {

	/**
	 * Check if element is the window.
	 *
	 * @param element Element
	 * @returns {boolean} true if window, false if not
	 */
	static isWindow(element) {
		return !!(element.document && element.location);
	}

	/**
	 * Query elements.
	 *
	 * Syntax: DOM.query(<selectors>[,<context>]);
	 *
	 * @param {string} selectors String with selectors
	 * @param {(Node|DOMElement|Object)=} context Context native element or DOMElement (optional, default is window)
	 * @returns {!Array} Array of DOMElement items
	 */
	static query(selectors, context = window) {
		// TODO: Support class or id as context?
		let root = DOM.isWindow(context) ? window.document.documentElement : context;
		if (root instanceof DOMElement) {
			root = root.origNode();
		}
		let nodes = [];
		try {
			nodes = root.querySelectorAll(selectors);
		} catch (err) {
			// Nothing to do
		}
		let elements = [];
		for (let node of nodes) {
			elements.push(new DOMElement(node));
		}
		return elements;
	}

	/**
	 * Query element by id.
	 *
	 * @param id Element id
	 * @returns {DOMElement} DOMElement or null if not found
	 */
	static queryById(id) {
		let element = document.getElementById(id);
		return element ? new DOMElement(element) : null;
	}

	/**
	 * Query only unique element.
	 *
	 * @param selector Selector
	 * @returns {DOMElement} DOMElement or null if not found
	 */
	static queryUnique(selector) {
		let element = document.querySelector(selector);
		return element ? new DOMElement(element) : null;
	}

	/**
	 * Create event.
	 *
	 * @param {string} eventName Event name
	 * @param {boolean} bubbles Event bubbles up.
	 * @param {boolean} cancelable Event can be canceled.
	 * @returns {Event} Event
	 */
	static createEvent(eventName, bubbles = false, cancelable = false) {
		if (typeof window.Event === "function") {
			return new Event(eventName, {"bubbles": bubbles, "cancelable": cancelable});
		} else {
			let event = document.createEvent('Event');
			event.initEvent(eventName, bubbles, cancelable);
			return event;
		}
	}

	/**
	 * Add event listener.
	 *
	 * @param element Element
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 */
	static addEvent(element, event, handler, capture = false) {
		let eventName = event instanceof Event ? event.type : event;
		if (element.addEventListener) {
			element.addEventListener(eventName, handler, capture);
		} else if (element.attachEvent) {
			element.attachEvent(eventName, handler);
		}
	}

	/**
	 * Remove event listener.
	 *
	 * @param element Element
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 */
	static removeEvent(element, event, handler, capture = false) {
		let eventName = event instanceof Event ? event.type : event;
		if (element.removeEventListener) {
			element.removeEventListener(eventName, handler, capture);
		} else if (element.detachEvent) {
			element.detachEvent(eventName, handler);
		}
	}

	/**
	 * Trigger event.
	 *
	 * @param element Element
	 * @param event Event name or event
	 */
	static dispatchEvent(element, event) {
		element.dispatchEvent(event instanceof Event ? event : DOM.createEvent(event));
	}
}

/**
 * DOM Element returned from queries in DOM utilities.
 */
export class DOMElement {

	/**
	 * Constructor.
	 * @param node Original node
	 */
	constructor(node) {
		this._origNode = node;
		this._tagName = node.tagName.toLowerCase();
	}

	/**
	 * Get original node.
	 *
	 * @returns Original node
	 */
	origNode() {
		return this._origNode;
	}

	/**
	 * Get id.
	 *
	 * @return Element id or null
	 */
	id() {
		return this._origNode.id;
	}

	/**
	 * Get tag name.
	 *
	 * @returns {string|*}
	 */
	tag() {
		return this._tagName;
	}

	/**
	 * Get / set height.
	 * @param {number=} value Value to set (optional)
	 * @returns {number|DOMElement} Height in px or DOMElement for chaining when used as setter
	 */
	height(value) {
		if (value === undefined) {
			return this._origNode.getBoundingClientRect().height;
		} else {
			this._origNode.style.height = `${value}${PX}`;
			return this;
		}
	}

	/**
	 * Get / set width.
	 *
	 * @param {number=} value Value to set (optional)
	 * @returns {number|DOMElement} Width in px or DOMElement for chaining when used as setter
	 */
	width(value) {
		if (value === undefined) {
			return this._origNode.getBoundingClientRect().width;
		} else {
			this._origNode.style.width = `${value}${PX}`;
			return this;
		}
	}

	/**
	 * Get fixed position relative to scroll container.
	 *
	 * @returns {{top: (Number|number), left: (Number|number), bottom: *, right: *}}
	 */
	position() {
		return {
			top: this._origNode.offsetTop,
			left: this._origNode.offsetLeft,
			bottom: this._origNode.offsetTop + this._origNode.offsetHeight,
			right: this._origNode.offsetLeft + this._origNode.offsetWidth

		}
	}

	/**
	 * Get scroll position relative to visible viewport.
	 *
	 * @returns {{top: Number, left: Number, bottom: Number, right: Number}}
	 */
	offset() {
		return {
			top: this._origNode.getBoundingClientRect().top,
			left: this._origNode.getBoundingClientRect().left,
			bottom: this._origNode.getBoundingClientRect().bottom,
			right: this._origNode.getBoundingClientRect().right
		}
	}

	/**
	 * Check if class is set.
	 *
	 * @param className Class name
	 * @returns {boolean} true if set, false if not
	 */
	hasClass(className) {
		if (this._origNode.classList) {
			return this._origNode.classList.contains(className);
		} else {
			console.error("classList not available");
			return false;
		}
	}

	/**
	 * Add class.
	 *
	 * @param {...string} classNames Class names
	 * @returns {DOMElement} DOMElement for chaining
	 */
	addClass(...classNames) {
		if (this._origNode.classList) {
			this._origNode.classList.add(...classNames);
		} else {
			console.error("classList not available");
		}
		return this;
	}

	/**
	 * Replace class.
	 *
	 * @param className Class name to be replaced
	 * @param otherClassName Class name to be set
	 *
	 * @returns {DOMElement} DOMElement for chaining
	 */
	replaceClass(className, otherClassName) {
		if (this._origNode.classList) {
			if (this._origNode.classList.replace) {
				this._origNode.classList.replace(className, otherClassName);
			} else {
				this.removeClass(className).addClass(otherClassName);
			}
		} else {
			console.error("classList not available");
		}
		return this;
	}

	/**
	 * Remove class.
	 *
	 * @param {...string} classNames Class names
	 * @returns {DOMElement} DOMElement for chaining
	 */
	removeClass(...classNames) {
		if (this._origNode.classList) {
			this._origNode.classList.remove(...classNames);
		} else {
			console.error("classList not available");
		}

		// Remove class attribute if we have no more class set
		if (this.attr("class") === "") {
			this.removeAttr("class");
		}

		return this;
	}

	/**
	 * Toggle class.
	 *
	 * @param {string} className Class name
	 * @param {boolean=} force Force add or remove (optional)
	 * @returns {DOMElement}
	 */
	toggleClass(className, force) {
		if (this._origNode.classList) {
			this._origNode.classList.toggle(className, force)
		} else {
			console.error("classList not available");
		}

		// Remove class attribute if we have no more class set
		if (this.attr("class") === "") {
			this.removeAttr("class");
		}

		return this;
	}

	/**
	 * Check if element is hidden.
	 *
	 * @returns {boolean} true if hidden, false if visible
	 */
	hidden() {
		let computedStyles = window.getComputedStyle(this._origNode);
		return computedStyles.display.toLowerCase() === NONE || computedStyles.visibility.toLowerCase() === HIDDEN;
	}

	/**
	 * Check if element is visible.
	 *
	 * @returns {boolean} true if visible, false if hidden
	 */
	visible() {
		return !this.hidden();
	}

	/**
	 * Get / set attribute value.
	 *
	 * @param name Attribute name
	 * @param {string=} value Attribute value (optional)
	 * @returns {*} Attribute value or DOMElement for chaining when used as setter
	 */
	attr(name, value) {
		if (value === undefined) {
			return this._origNode.getAttribute(name);
		} else {
			this._origNode.setAttribute(name, value);
			return this;
		}
	}

	/**
	 * Remove attribute.
	 *
	 * @param attrName Attribute name
	 * @returns {DOMElement} DOMElement for chaining
	 */
	removeAttr(attrName) {
		this._origNode.removeAttribute(attrName);
		return this;
	}

	/**
	 * Get / set css style.
	 *
	 * If the last style is removed the attribute style is removed as well.
	 * Style can be removed if value is null.
	 *
	 * @param style Style name
	 * @param {?string=} value Style value (optional)
	 * @returns {*} Style value or DOMElement for chaining when used as setter
	 */
	css(style, value) {
		if (value === undefined) {
			return window.getComputedStyle(this._origNode)[style];
		} else {
			this._origNode.style[style] = value;
			if (this.attr(STYLE) === "") {
				this.removeAttr(STYLE);
			}
			return this;
		}
	}

	/**
	 * Get parent.
	 *
	 * @returns {DOMElement} Parent element
	 */
	parent() {
		// TODO Cache parent?
		return new DOMElement(this._origNode.parentNode);
	}

	/**
	 * Show element.
	 *
	 * Is able to save/restore the initial display value even if its an inline style.
	 *
	 * TODO Add easing
	 */
	show() {
		// TODO Add easing
		return _showOrHide(this, this.hidden(), BLOCK);
	}

	/**
	 * Hide element.
	 *
	 * Is able to save/restore the initial display value even if its an inline style.
	 */
	hide() {
		// TODO Add easing
		return _showOrHide(this, this.visible(), NONE);
	}

	/**
	 * Add event listener.
	 *
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 * return {DOMElement} DOMElement for chaining
	 */
	addEvent(event, handler, capture = false) {
		DOM.addEvent(this._origNode, event, handler, capture);
		return this;
	}

	/**
	 * Remove event listener.
	 *
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 * return {DOMElement} DOMElement for chaining
	 */
	removeEvent(event, handler, capture = false) {
		DOM.removeEvent(this._origNode, event, handler, capture);
		return this;
	}

	/**
	 * Trigger event.
	 *
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @returns {DOMElement} DOMElement for chaining
	 */
	dispatchEvent(event) {
		DOM.dispatchEvent(this._origNode, event);
		return this;
	}
}

///////////////////////////////////////
// Private member functions

/**
 * Check if inline style is set.
 *
 * Info: Potential spaces are ignored.
 *
 * @param domElement {DOMElement}
 * @param style Style
 * @returns {boolean} State of inline style
 * @private
 */
function _hasInlineStyle(domElement, style) {
	if (domElement.attr(STYLE) !== null) {
		return StringUtils.nospace(domElement.attr(STYLE)).includes(StringUtils.nospace(style));
	}
	return false;
}

/**
 * Show / hide _element.
 *
 * @param domElement {DOMElement}
 * @param handle Condition if _element visibility should be changed
 * @param value Display value (BLOCK or NONE)
 * @returns {DOMElement} DOM Element
 * @private
 */
function _showOrHide(domElement, handle, value) {
	if (handle) {
		let prevInlineDisplay = domElement.attr(PREV_INLINE_DISPLAY);
		if (prevInlineDisplay === null) {
			if (domElement.attr(PREV_DISPLAY) === null) {
				_rememberDisplayValue(domElement);
				domElement.css(DISPLAY, value);
			}
			else {
				_restoreDisplayValue(domElement, PREV_DISPLAY, null);
			}
		} else {
			_restoreDisplayValue(domElement, PREV_INLINE_DISPLAY, prevInlineDisplay);
		}
	}
	return domElement;
}

/**
 * Remember display value.
 *
 * @param domElement {DOMElement}
 * @private
 */
function _rememberDisplayValue(domElement) {
	if (_hasInlineStyle(domElement, DISPLAY)) {
		// Remember old inline display value
		domElement.attr(PREV_INLINE_DISPLAY, domElement.css(DISPLAY));
	} else {
		// Remember old display value
		domElement.attr(PREV_DISPLAY, domElement.css(DISPLAY));
	}
}

/**
 * Restore previous display value.
 *
 * @param domElement {DOMElement}
 * @param prevValueAttr Attribute for previous value
 * @param preValue Previous Value
 * @private
 */
function _restoreDisplayValue(domElement, prevValueAttr, preValue) {
	domElement.css(DISPLAY, preValue);
	domElement.removeAttr(prevValueAttr);
}
<commit_msg>Refactoring dispatchEvent.<commit_after>import StringUtils from "../util/floatz.util.strings.js";

/**
 * Constants
 */
const BLOCK = "block";
const DISPLAY = "display";
const HIDDEN = "hidden";
const NONE = "none";
const PREV_DISPLAY = "flz-prev-display";
const PREV_INLINE_DISPLAY = "flz-prev-inline-display";
const PX = "px";
const STYLE = "style";

/**
 * DOM utilities.
 */
export default class DOM {

	/**
	 * Check if element is the window.
	 *
	 * @param element Element
	 * @returns {boolean} true if window, false if not
	 */
	static isWindow(element) {
		return !!(element.document && element.location);
	}

	/**
	 * Query elements.
	 *
	 * Syntax: DOM.query(<selectors>[,<context>]);
	 *
	 * @param {string} selectors String with selectors
	 * @param {(Node|DOMElement|Object)=} context Context native element or DOMElement (optional, default is window)
	 * @returns {!Array} Array of DOMElement items
	 */
	static query(selectors, context = window) {
		// TODO: Support class or id as context?
		let root = DOM.isWindow(context) ? window.document.documentElement : context;
		if (root instanceof DOMElement) {
			root = root.origNode();
		}
		let nodes = [];
		try {
			nodes = root.querySelectorAll(selectors);
		} catch (err) {
			// Nothing to do
		}
		let elements = [];
		for (let node of nodes) {
			elements.push(new DOMElement(node));
		}
		return elements;
	}

	/**
	 * Query element by id.
	 *
	 * @param id Element id
	 * @returns {DOMElement} DOMElement or null if not found
	 */
	static queryById(id) {
		let element = document.getElementById(id);
		return element ? new DOMElement(element) : null;
	}

	/**
	 * Query only unique element.
	 *
	 * @param selector Selector
	 * @returns {DOMElement} DOMElement or null if not found
	 */
	static queryUnique(selector) {
		let element = document.querySelector(selector);
		return element ? new DOMElement(element) : null;
	}

	/**
	 * Create event.
	 *
	 * @param {string} eventName Event name
	 * @param {boolean} bubbles Event bubbles up.
	 * @param {boolean} cancelable Event can be canceled.
	 * @returns {Event} Event
	 */
	static createEvent(eventName, bubbles = false, cancelable = false) {
		if (typeof window.Event === "function") {
			return new Event(eventName, {"bubbles": bubbles, "cancelable": cancelable});
		} else {
			let event = document.createEvent('Event');
			event.initEvent(eventName, bubbles, cancelable);
			return event;
		}
	}

	/**
	 * Add event listener.
	 *
	 * @param element Element
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 */
	static addEvent(element, event, handler, capture = false) {
		let eventName = event instanceof Event ? event.type : event;
		if (element.addEventListener) {
			element.addEventListener(eventName, handler, capture);
		} else if (element.attachEvent) {
			element.attachEvent(eventName, handler);
		}
	}

	/**
	 * Remove event listener.
	 *
	 * @param element Element
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 */
	static removeEvent(element, event, handler, capture = false) {
		let eventName = event instanceof Event ? event.type : event;
		if (element.removeEventListener) {
			element.removeEventListener(eventName, handler, capture);
		} else if (element.detachEvent) {
			element.detachEvent(eventName, handler);
		}
	}

	/**
	 * Trigger event.
	 *
	 * @param element Element
	 * @param event Event name or event
	 * @return {boolean} true for canceled, false if event has not been cancelled
	 */
	static dispatchEvent(element, event) {
		return element.dispatchEvent(event instanceof Event ? event : DOM.createEvent(event));
	}
}

/**
 * DOM Element returned from queries in DOM utilities.
 */
export class DOMElement {

	/**
	 * Constructor.
	 * @param node Original node
	 */
	constructor(node) {
		this._origNode = node;
		this._tagName = node.tagName.toLowerCase();
	}

	/**
	 * Get original node.
	 *
	 * @returns Original node
	 */
	origNode() {
		return this._origNode;
	}

	/**
	 * Get id.
	 *
	 * @return Element id or null
	 */
	id() {
		return this._origNode.id;
	}

	/**
	 * Get tag name.
	 *
	 * @returns {string|*}
	 */
	tag() {
		return this._tagName;
	}

	/**
	 * Get / set height.
	 * @param {number=} value Value to set (optional)
	 * @returns {number|DOMElement} Height in px or DOMElement for chaining when used as setter
	 */
	height(value) {
		if (value === undefined) {
			return this._origNode.getBoundingClientRect().height;
		} else {
			this._origNode.style.height = `${value}${PX}`;
			return this;
		}
	}

	/**
	 * Get / set width.
	 *
	 * @param {number=} value Value to set (optional)
	 * @returns {number|DOMElement} Width in px or DOMElement for chaining when used as setter
	 */
	width(value) {
		if (value === undefined) {
			return this._origNode.getBoundingClientRect().width;
		} else {
			this._origNode.style.width = `${value}${PX}`;
			return this;
		}
	}

	/**
	 * Get fixed position relative to scroll container.
	 *
	 * @returns {{top: (Number|number), left: (Number|number), bottom: *, right: *}}
	 */
	position() {
		return {
			top: this._origNode.offsetTop,
			left: this._origNode.offsetLeft,
			bottom: this._origNode.offsetTop + this._origNode.offsetHeight,
			right: this._origNode.offsetLeft + this._origNode.offsetWidth

		}
	}

	/**
	 * Get scroll position relative to visible viewport.
	 *
	 * @returns {{top: Number, left: Number, bottom: Number, right: Number}}
	 */
	offset() {
		return {
			top: this._origNode.getBoundingClientRect().top,
			left: this._origNode.getBoundingClientRect().left,
			bottom: this._origNode.getBoundingClientRect().bottom,
			right: this._origNode.getBoundingClientRect().right
		}
	}

	/**
	 * Check if class is set.
	 *
	 * @param className Class name
	 * @returns {boolean} true if set, false if not
	 */
	hasClass(className) {
		if (this._origNode.classList) {
			return this._origNode.classList.contains(className);
		} else {
			console.error("classList not available");
			return false;
		}
	}

	/**
	 * Add class.
	 *
	 * @param {...string} classNames Class names
	 * @returns {DOMElement} DOMElement for chaining
	 */
	addClass(...classNames) {
		if (this._origNode.classList) {
			this._origNode.classList.add(...classNames);
		} else {
			console.error("classList not available");
		}
		return this;
	}

	/**
	 * Replace class.
	 *
	 * @param className Class name to be replaced
	 * @param otherClassName Class name to be set
	 *
	 * @returns {DOMElement} DOMElement for chaining
	 */
	replaceClass(className, otherClassName) {
		if (this._origNode.classList) {
			if (this._origNode.classList.replace) {
				this._origNode.classList.replace(className, otherClassName);
			} else {
				this.removeClass(className).addClass(otherClassName);
			}
		} else {
			console.error("classList not available");
		}
		return this;
	}

	/**
	 * Remove class.
	 *
	 * @param {...string} classNames Class names
	 * @returns {DOMElement} DOMElement for chaining
	 */
	removeClass(...classNames) {
		if (this._origNode.classList) {
			this._origNode.classList.remove(...classNames);
		} else {
			console.error("classList not available");
		}

		// Remove class attribute if we have no more class set
		if (this.attr("class") === "") {
			this.removeAttr("class");
		}

		return this;
	}

	/**
	 * Toggle class.
	 *
	 * @param {string} className Class name
	 * @param {boolean=} force Force add or remove (optional)
	 * @returns {DOMElement}
	 */
	toggleClass(className, force) {
		if (this._origNode.classList) {
			this._origNode.classList.toggle(className, force)
		} else {
			console.error("classList not available");
		}

		// Remove class attribute if we have no more class set
		if (this.attr("class") === "") {
			this.removeAttr("class");
		}

		return this;
	}

	/**
	 * Check if element is hidden.
	 *
	 * @returns {boolean} true if hidden, false if visible
	 */
	hidden() {
		let computedStyles = window.getComputedStyle(this._origNode);
		return computedStyles.display.toLowerCase() === NONE || computedStyles.visibility.toLowerCase() === HIDDEN;
	}

	/**
	 * Check if element is visible.
	 *
	 * @returns {boolean} true if visible, false if hidden
	 */
	visible() {
		return !this.hidden();
	}

	/**
	 * Get / set attribute value.
	 *
	 * @param name Attribute name
	 * @param {string=} value Attribute value (optional)
	 * @returns {*} Attribute value or DOMElement for chaining when used as setter
	 */
	attr(name, value) {
		if (value === undefined) {
			return this._origNode.getAttribute(name);
		} else {
			this._origNode.setAttribute(name, value);
			return this;
		}
	}

	/**
	 * Remove attribute.
	 *
	 * @param attrName Attribute name
	 * @returns {DOMElement} DOMElement for chaining
	 */
	removeAttr(attrName) {
		this._origNode.removeAttribute(attrName);
		return this;
	}

	/**
	 * Get / set css style.
	 *
	 * If the last style is removed the attribute style is removed as well.
	 * Style can be removed if value is null.
	 *
	 * @param style Style name
	 * @param {?string=} value Style value (optional)
	 * @returns {*} Style value or DOMElement for chaining when used as setter
	 */
	css(style, value) {
		if (value === undefined) {
			return window.getComputedStyle(this._origNode)[style];
		} else {
			this._origNode.style[style] = value;
			if (this.attr(STYLE) === "") {
				this.removeAttr(STYLE);
			}
			return this;
		}
	}

	/**
	 * Get parent.
	 *
	 * @returns {DOMElement} Parent element
	 */
	parent() {
		// TODO Cache parent?
		return new DOMElement(this._origNode.parentNode);
	}

	/**
	 * Show element.
	 *
	 * Is able to save/restore the initial display value even if its an inline style.
	 *
	 * TODO Add easing
	 */
	show() {
		// TODO Add easing
		return _showOrHide(this, this.hidden(), BLOCK);
	}

	/**
	 * Hide element.
	 *
	 * Is able to save/restore the initial display value even if its an inline style.
	 */
	hide() {
		// TODO Add easing
		return _showOrHide(this, this.visible(), NONE);
	}

	/**
	 * Add event listener.
	 *
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 * return {DOMElement} DOMElement for chaining
	 */
	addEvent(event, handler, capture = false) {
		DOM.addEvent(this._origNode, event, handler, capture);
		return this;
	}

	/**
	 * Remove event listener.
	 *
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @param handler Event handler
	 * @param capture true for capture phase, false for bubbling phase
	 * return {DOMElement} DOMElement for chaining
	 */
	removeEvent(event, handler, capture = false) {
		DOM.removeEvent(this._origNode, event, handler, capture);
		return this;
	}

	/**
	 * Trigger event.
	 *
	 * @param {string|Event|CustomEvent} event Event name or event
	 * @returns {boolean} true if cancelled, false if event has not been cancelled
	 */
	dispatchEvent(event) {
		return DOM.dispatchEvent(this._origNode, event);
	}
}

///////////////////////////////////////
// Private member functions

/**
 * Check if inline style is set.
 *
 * Info: Potential spaces are ignored.
 *
 * @param domElement {DOMElement}
 * @param style Style
 * @returns {boolean} State of inline style
 * @private
 */
function _hasInlineStyle(domElement, style) {
	if (domElement.attr(STYLE) !== null) {
		return StringUtils.nospace(domElement.attr(STYLE)).includes(StringUtils.nospace(style));
	}
	return false;
}

/**
 * Show / hide _element.
 *
 * @param domElement {DOMElement}
 * @param handle Condition if _element visibility should be changed
 * @param value Display value (BLOCK or NONE)
 * @returns {DOMElement} DOM Element
 * @private
 */
function _showOrHide(domElement, handle, value) {
	if (handle) {
		let prevInlineDisplay = domElement.attr(PREV_INLINE_DISPLAY);
		if (prevInlineDisplay === null) {
			if (domElement.attr(PREV_DISPLAY) === null) {
				_rememberDisplayValue(domElement);
				domElement.css(DISPLAY, value);
			}
			else {
				_restoreDisplayValue(domElement, PREV_DISPLAY, null);
			}
		} else {
			_restoreDisplayValue(domElement, PREV_INLINE_DISPLAY, prevInlineDisplay);
		}
	}
	return domElement;
}

/**
 * Remember display value.
 *
 * @param domElement {DOMElement}
 * @private
 */
function _rememberDisplayValue(domElement) {
	if (_hasInlineStyle(domElement, DISPLAY)) {
		// Remember old inline display value
		domElement.attr(PREV_INLINE_DISPLAY, domElement.css(DISPLAY));
	} else {
		// Remember old display value
		domElement.attr(PREV_DISPLAY, domElement.css(DISPLAY));
	}
}

/**
 * Restore previous display value.
 *
 * @param domElement {DOMElement}
 * @param prevValueAttr Attribute for previous value
 * @param preValue Previous Value
 * @private
 */
function _restoreDisplayValue(domElement, prevValueAttr, preValue) {
	domElement.css(DISPLAY, preValue);
	domElement.removeAttr(prevValueAttr);
}
<|endoftext|>


<commit_before>'use strict';

(function() {
  angular.module('ncsaas')
    .service('customersService', [
      'baseServiceClass', '$state', '$q', '$http', 'ENV', 'currentStateService', 'usersService', customersService]);

  function customersService(baseServiceClass, $state, $q, $http, ENV, currentStateService, usersService) {
    var ServiceClass = baseServiceClass.extend({
      filterByCustomer: false,
      countryChoices: [],

      init:function() {
        this._super();
        this.endpoint = '/customers/';
      },
      getPersonalOrFirstCustomer: function(username) {
        var deferred = $q.defer();
        /*jshint camelcase: false */
        this.getList().then(
          function(customers) {
            for(var i = 0; i < customers.length; i++) {
              if (customers[i].name === username) {
                deferred.resolve(customers[i]);
              }
            }
            if (customers.length !== 0) {
              deferred.resolve(customers[0]);
            } else {
              $state.go('initialdata.view');
              deferred.reject();
            }
          }
        );

        return deferred.promise;
      },
      getBalanceHistory: function(uuid) {
        var query = {UUID: uuid, operation: 'balance_history'};
        return this.getList(query);
      },
      getCounters: function(query) {
        var query = angular.extend({operation: 'counters'}, query);
        return this.getFactory(false).get(query).$promise;
      },
      getTopMenuList: function () {
        var deferred = $q.defer();

        this.pageSize = ENV.topMenuCustomersCount;
        this.cacheTime = ENV.topMenuCustomersCacheTime;
        this.getList().then(function(response) {
          deferred.resolve(response);
        });
        // reset pageSize
        this.pageSize = ENV.pageSize;

        return deferred.promise;
      },
      isOwnerOrStaff: function() {
        return usersService.getCurrentUser().then(function(user) {
          if (user.is_staff) {
            return $q.when(true);
          }
          return currentStateService.getCustomer().then(function(customer) {
            for (var i = 0; i < customer.owners.length; i++) {
              if (user.uuid === customer.owners[i].uuid) {
                return $q.when(true);
              }
            }
            return $q.when(false);
          });
        });
      },
      loadCountries: function() {
        var vm = this;
        if (vm.countryChoices.length != 0) {
          return $q.when(vm.countryChoices);
        } else {
          return $http({
            method: 'OPTIONS',
            url: ENV.apiEndpoint + 'api/customers/'
          }).then(function(response) {
            vm.countryChoices = response.data.actions.POST.country.choices;
            return vm.countryChoices;
          });
        }
      }
    });
    return new ServiceClass();
  }

})();
<commit_msg>Skip check if customer is empty (SAAS-1415)<commit_after>'use strict';

(function() {
  angular.module('ncsaas')
    .service('customersService', [
      'baseServiceClass', '$state', '$q', '$http', 'ENV', 'currentStateService', 'usersService', customersService]);

  function customersService(baseServiceClass, $state, $q, $http, ENV, currentStateService, usersService) {
    var ServiceClass = baseServiceClass.extend({
      filterByCustomer: false,
      countryChoices: [],

      init:function() {
        this._super();
        this.endpoint = '/customers/';
      },
      getPersonalOrFirstCustomer: function(username) {
        var deferred = $q.defer();
        /*jshint camelcase: false */
        this.getList().then(
          function(customers) {
            for(var i = 0; i < customers.length; i++) {
              if (customers[i].name === username) {
                deferred.resolve(customers[i]);
              }
            }
            if (customers.length !== 0) {
              deferred.resolve(customers[0]);
            } else {
              $state.go('initialdata.view');
              deferred.reject();
            }
          }
        );

        return deferred.promise;
      },
      getBalanceHistory: function(uuid) {
        var query = {UUID: uuid, operation: 'balance_history'};
        return this.getList(query);
      },
      getCounters: function(query) {
        var query = angular.extend({operation: 'counters'}, query);
        return this.getFactory(false).get(query).$promise;
      },
      getTopMenuList: function () {
        var deferred = $q.defer();

        this.pageSize = ENV.topMenuCustomersCount;
        this.cacheTime = ENV.topMenuCustomersCacheTime;
        this.getList().then(function(response) {
          deferred.resolve(response);
        });
        // reset pageSize
        this.pageSize = ENV.pageSize;

        return deferred.promise;
      },
      isOwnerOrStaff: function() {
        return usersService.getCurrentUser().then(function(user) {
          if (user.is_staff) {
            return $q.when(true);
          }
          return currentStateService.getCustomer().then(function(customer) {
            if (!customer) {
              return $q.when(false);
            }
            for (var i = 0; i < customer.owners.length; i++) {
              if (user.uuid === customer.owners[i].uuid) {
                return $q.when(true);
              }
            }
            return $q.when(false);
          });
        });
      },
      loadCountries: function() {
        var vm = this;
        if (vm.countryChoices.length != 0) {
          return $q.when(vm.countryChoices);
        } else {
          return $http({
            method: 'OPTIONS',
            url: ENV.apiEndpoint + 'api/customers/'
          }).then(function(response) {
            vm.countryChoices = response.data.actions.POST.country.choices;
            return vm.countryChoices;
          });
        }
      }
    });
    return new ServiceClass();
  }

})();
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('dimApp').directive('dimFarming', Farming);

  function Farming() {
    return {
      controller: FarmingCtrl,
      controllerAs: 'vm',
      bindToController: true,
      scope: {},
      template: `

{{vm.service.itemsMoved}}

DIM is moving Engram and Glimmer items from {{vm.service.store.name}} to the vault and leaving one space open per item type to prevent anything from going to the Postmaster.

<input id="farm-greens" type='checkbox' ng-model='vm.settings.farmGreens' />{{::'farming_config1' | translate}}

{{::'farming_quickmove' | translate}}

<dim-simple-item ng-repeat="item in vm.service.consolidate track by $index" item-data="item" ng-click="vm.consolidate(item, vm.service.store)"></dim-simple-item>

          <button ng-click="vm.stop($event)">{{::'stop' | translate}}</button>

`
    };
  }

  FarmingCtrl.$inject = ['dimFarmingService', 'dimItemMoveService', 'dimSettingsService'];

  function FarmingCtrl(dimFarmingService, dimItemMoveService, dimSettingsService) {
    var vm = this;

    angular.extend(vm, {
      service: dimFarmingService,
      settings: dimSettingsService.farming,
      consolidate: dimItemMoveService.consolidate,
      stop: function($event) {
        $event.preventDefault();
        dimFarmingService.stop();
      }
    });
  }
})();
<commit_msg>remove spans<commit_after>(function() {
  'use strict';

  angular.module('dimApp').directive('dimFarming', Farming);

  function Farming() {
    return {
      controller: FarmingCtrl,
      controllerAs: 'vm',
      bindToController: true,
      scope: {},
      template: `

{{vm.service.itemsMoved}}

DIM is moving Engram and Glimmer items from {{vm.service.store.name}} to the vault and leaving one space open per item type to prevent anything from going to the Postmaster.

{{::'configuration' | translate}}

<input id="farm-greens" type='checkbox' ng-model='vm.settings.farmGreens' />{{::'farming_config1' | translate}}

{{::'farming_quickmove' | translate}}

<dim-simple-item ng-repeat="item in vm.service.consolidate track by $index" item-data="item" ng-click="vm.consolidate(item, vm.service.store)"></dim-simple-item>

          <button ng-click="vm.stop($event)">{{::'stop' | translate}}</button>

`
    };
  }

  FarmingCtrl.$inject = ['dimFarmingService', 'dimItemMoveService', 'dimSettingsService'];

  function FarmingCtrl(dimFarmingService, dimItemMoveService, dimSettingsService) {
    var vm = this;

    angular.extend(vm, {
      service: dimFarmingService,
      settings: dimSettingsService.farming,
      consolidate: dimItemMoveService.consolidate,
      stop: function($event) {
        $event.preventDefault();
        dimFarmingService.stop();
      }
    });
  }
})();
<|endoftext|>


<commit_before>/**
 * This is the File upload editor used with Backbone.Forms
 *
 * [Req: jQuery-file-upload.js]
 *
 * @author Tim.Liu
 * @update 2013.04.01
 *
 */
(function() {

    //editor UI::
    var FileEleView = Backbone.Marionette.ItemView.extend({
        template: '#custom-tpl-widget-editor-file-item',
        tagName: 'tr',
        initialize: function(options) {
            //Add actions:
            _.extend(this.model.attributes, {
                actions: [{
                    action: 'delete',
                    label: 'Delete',
                    labelCls: 'important',
                    method: this.model.get('delete_type'),
                    url: this.model.get('delete_url')
                }]
            });
        }
        /**
         * Write the aciton listeners down below in the EditorView._actions
         */
    });
    var EditorView = Backbone.Marionette.CompositeView.extend({
        template: '#custom-tpl-widget-editor-file',
        className: 'custom-form-editor-file',
        itemView: FileEleView,
        itemViewContainer: 'tbody',

        ui: {
            uploader: '.fileupload-field',
            dropzone: '.fileupload-dropzone',
            progress: '.fileupload-progress',
            progressbar: '.fileupload-progress-bar',
            progressfileQ: '.fileupload-progress-fileQ',
            filelist: '.file-editor-body'
        },

        events: {
            'click .action-trigger': '_runAction'
        },

        _runAction: function(e) {
            e.stopPropagation();
            var action = e.target.attributes.action.value;
            if (this._actions[action]) this._actions[action]({
                url: e.target.attributes._url.value,
                type: e.target.attributes._method.value,
            }, this);
        },

        _actions: {
            'delete': function(info, editor) {
                $.ajax({
                    url: info.url,
                    type: info.type,
                    success: function() {
                        editor.collection.fetch();
                    },
                    error: function(err) {
                        Application.error('File Deletion Error', err);
                    }
                });
            },
        },

        initialize: function() {
            this.listenTo(this.collection, 'reset', function() {
                if (this.collection.length === 0) this.ui.filelist.hide();
                else this.ui.filelist.show();
            });
            this.listenTo(this.collection, 'error', function(err) {
                Application.error('File List Reading Error', err);
            })
        },

        onRender: function() {
            var that = this;
            this.ui.uploader.fileupload({
                dropzone: this.ui.dropzone,
                dataType: 'json',
                //success
                done: function(e, res) {
                    that.collection.fetch({
                        timeout: 4500
                    });
                },
                fail: function(e, res) {
                    Application.error('File Upload Failed', $.parseJSON(res.xhr().response).error);
                },
                //progress
                //add
            });
            this.collection.fetch({
                timeout: 4500
            });
        },
    });

    //editor tpl::
    Template.extend(
        'custom-tpl-widget-editor-file', [
        '
',
        '
',
        '
',
        ' Choose File',
        '<input class="fileupload-field" type="file" name="files[]" data-url="{{meta.url}}" multiple>',
        '
',
        '
',
        '

Or...Drop you file(s) here...

',
        '
',
        '

',
        '

',
        '
',
        '
',
        '
',
        '
',
        '
',
        '
',
        'Name	',
        'Size	',
        '{{#unless meta.noActions}}Action	{{/unless}}',
        '
',
        '
',
        '

',
        '
',
        '
',
        '

', ]);
    Template.extend(
        'custom-tpl-widget-editor-file-item', [
        '{{name}}	',
        '{{size}}	',
        '{{#unless _options.noActions}}{{#each actions}}{{this.label}} {{/each}}{{/unless}}	']);

    //editor hook::
    Backbone.Form.editors['File'] = Backbone.Form.editors.Base.extend({

        events: {
            'change': function() {
                // The 'change' event should be triggered whenever something happens
                // that affects the result of `this.getValue()`.
                this.trigger('change', this);
            },
            'focus': function() {
                // The 'focus' event should be triggered whenever an input within
                // this editor becomes the `document.activeElement`.
                this.trigger('focus', this);
                // This call automatically sets `this.hasFocus` to `true`.
            },
            'blur': function() {
                // The 'blur' event should be triggered whenever an input within
                // this editor stops being the `document.activeElement`.
                this.trigger('blur', this);
                // This call automatically sets `this.hasFocus` to `false`.
            }
        },

        initialize: function(options) {
            // Call parent constructor
            Backbone.Form.editors.Base.prototype.initialize.call(this, options);

            // Custom setup code.
            // this.schema.options
            this._options = options.schema.options || options.schema;
            this._options.url = this._options.url || '/uploads/' + this._options.hostName + '/' + (this._options.hostType === 'table' ? this.model.id : 'shared') + '/' + this.key;
            this.FileCollection = Backbone.Collection.extend({
                url: this._options.url + '?listing=' + (new Date()).getTime(),
                model: Backbone.Model.extend({
                    defaults: {
                        _options: this._options
                    }
                })
            });
        },

        render: function() {
            if (this._options.hostType === 'table' && !this.model.id) {
                //new table record...
                this.$el.html('
Create your record before uploading file(s) to it.
');
            } else {
                this.delegatedEditor = new EditorView({
                    model: new Backbone.Model({
                        meta: {
                            url: this._options.url,
                            noActions: this._options.noActions,
                        }
                    }),
                    collection: new this.FileCollection()
                });
                this.delegatedEditor.listenTo(this.form, 'close', this.delegatedEditor.close);
                this.$el.html(this.delegatedEditor.render().el);
            }

            return this;
        },

        getValue: function() {
            //return this.$el.val();
        },

        setValue: function(value) {
            //this.$el.val(value);
        },

        focus: function() {
            if (this.hasFocus) return;

            // This method call should result in an input within this edior
            // becoming the `document.activeElement`.
            // This, in turn, should result in this editor's `focus` event
            // being triggered, setting `this.hasFocus` to `true`.
            // See above for more detail.
            this.$el.focus();
        },

        blur: function() {
            if (!this.hasFocus) return;

            this.$el.blur();
        }
    });
})();<commit_msg>Fixed typo in file upload editor<commit_after>/**
 * This is the File upload editor used with Backbone.Forms
 *
 * [Req: jQuery-file-upload.js]
 *
 * @author Tim.Liu
 * @update 2013.04.01
 *
 */
(function() {

    //editor UI::
    var FileEleView = Backbone.Marionette.ItemView.extend({
        template: '#custom-tpl-widget-editor-file-item',
        tagName: 'tr',
        initialize: function(options) {
            //Add actions:
            _.extend(this.model.attributes, {
                actions: [{
                    action: 'delete',
                    label: 'Delete',
                    labelCls: 'important',
                    method: this.model.get('delete_type'),
                    url: this.model.get('delete_url')
                }]
            });
        }
        /**
         * Write the aciton listeners down below in the EditorView._actions
         */
    });
    var EditorView = Backbone.Marionette.CompositeView.extend({
        template: '#custom-tpl-widget-editor-file',
        className: 'custom-form-editor-file',
        itemView: FileEleView,
        itemViewContainer: 'tbody',

        ui: {
            uploader: '.fileupload-field',
            dropzone: '.fileupload-dropzone',
            progress: '.fileupload-progress',
            progressbar: '.fileupload-progress-bar',
            progressfileQ: '.fileupload-progress-fileQ',
            filelist: '.file-editor-body'
        },

        events: {
            'click .action-trigger': '_runAction'
        },

        _runAction: function(e) {
            e.stopPropagation();
            var action = e.target.attributes.action.value;
            if (this._actions[action]) this._actions[action]({
                url: e.target.attributes._url.value,
                type: e.target.attributes._method.value,
            }, this);
        },

        _actions: {
            'delete': function(info, editor) {
                $.ajax({
                    url: info.url,
                    type: info.type,
                    success: function() {
                        editor.collection.fetch();
                    },
                    error: function(err) {
                        Application.error('File Deletion Error', err);
                    }
                });
            },
        },

        initialize: function() {
            this.listenTo(this.collection, 'reset', function() {
                if (this.collection.length === 0) this.ui.filelist.hide();
                else this.ui.filelist.show();
            });
            this.listenTo(this.collection, 'error', function(err) {
                Application.error('File List Reading Error', err);
            })
        },

        onRender: function() {
            var that = this;
            this.ui.uploader.fileupload({
                dropzone: this.ui.dropzone,
                dataType: 'json',
                //success
                done: function(e, res) {
                    that.collection.fetch({
                        timeout: 4500
                    });
                },
                fail: function(e, res) {
                    Application.error('File Upload Failed', $.parseJSON(res.xhr().response).error);
                },
                //progress
                //add
            });
            this.collection.fetch({
                timeout: 4500
            });
        },
    });

    //editor tpl::
    Template.extend(
        'custom-tpl-widget-editor-file', [
        '
',
        '
',
        '
',
        ' Choose File',
        '<input class="fileupload-field" type="file" name="files[]" data-url="{{meta.url}}" multiple>',
        '
',
        '
',
        '

Or...Drop your file(s) here...

',
        '
',
        '

',
        '

',
        '
',
        '
',
        '
',
        '
',
        '
',
        '
',
        'Name	',
        'Size	',
        '{{#unless meta.noActions}}Action	{{/unless}}',
        '
',
        '
',
        '

',
        '
',
        '
',
        '

', ]);
    Template.extend(
        'custom-tpl-widget-editor-file-item', [
        '{{name}}	',
        '{{size}}	',
        '{{#unless _options.noActions}}{{#each actions}}{{this.label}} {{/each}}{{/unless}}	']);

    //editor hook::
    Backbone.Form.editors['File'] = Backbone.Form.editors.Base.extend({

        events: {
            'change': function() {
                // The 'change' event should be triggered whenever something happens
                // that affects the result of `this.getValue()`.
                this.trigger('change', this);
            },
            'focus': function() {
                // The 'focus' event should be triggered whenever an input within
                // this editor becomes the `document.activeElement`.
                this.trigger('focus', this);
                // This call automatically sets `this.hasFocus` to `true`.
            },
            'blur': function() {
                // The 'blur' event should be triggered whenever an input within
                // this editor stops being the `document.activeElement`.
                this.trigger('blur', this);
                // This call automatically sets `this.hasFocus` to `false`.
            }
        },

        initialize: function(options) {
            // Call parent constructor
            Backbone.Form.editors.Base.prototype.initialize.call(this, options);

            // Custom setup code.
            // this.schema.options
            this._options = options.schema.options || options.schema;
            this._options.url = this._options.url || '/uploads/' + this._options.hostName + '/' + (this._options.hostType === 'table' ? this.model.id : 'shared') + '/' + this.key;
            this.FileCollection = Backbone.Collection.extend({
                url: this._options.url + '?listing=' + (new Date()).getTime(),
                model: Backbone.Model.extend({
                    defaults: {
                        _options: this._options
                    }
                })
            });
        },

        render: function() {
            if (this._options.hostType === 'table' && !this.model.id) {
                //new table record...
                this.$el.html('
Create your record before uploading file(s) to it.
');
            } else {
                this.delegatedEditor = new EditorView({
                    model: new Backbone.Model({
                        meta: {
                            url: this._options.url,
                            noActions: this._options.noActions,
                        }
                    }),
                    collection: new this.FileCollection()
                });
                this.delegatedEditor.listenTo(this.form, 'close', this.delegatedEditor.close);
                this.$el.html(this.delegatedEditor.render().el);
            }

            return this;
        },

        getValue: function() {
            //return this.$el.val();
        },

        setValue: function(value) {
            //this.$el.val(value);
        },

        focus: function() {
            if (this.hasFocus) return;

            // This method call should result in an input within this edior
            // becoming the `document.activeElement`.
            // This, in turn, should result in this editor's `focus` event
            // being triggered, setting `this.hasFocus` to `true`.
            // See above for more detail.
            this.$el.focus();
        },

        blur: function() {
            if (!this.hasFocus) return;

            this.$el.blur();
        }
    });
})();<|endoftext|>


<commit_before>var GOVUK = GOVUK || {};
GOVUK.registers = GOVUK.registers || {};

GOVUK.registers.analytics = (function () {
  var setupGA, setupEvents, sendPageview, sendEvent;

  var trackerId;
  var isTrackerPresent = function(){
    return (typeof trackerId !== 'undefined') && (trackerId !== '');
  };

  var checkTrackerAndExecute = function(fnToExecute, errorMsg){
    if(isTrackerPresent()){
        fnToExecute();
    } else {
      console.error("GA tracker not present. " + errorMsg || "");
    }
  };

  sendEvent = function(category, action, targetLabel, fnHitCallback){
    checkTrackerAndExecute(function(){
      callbackExecuted = false;
      var executeHitCallback = function () {
        if (!callbackExecuted) {
          callbackExecuted = true;
          fnHitCallback();
        }
      }
      setTimeout(executeHitCallback, 1000);

      ga('send', 'event', category, action, targetLabel, { hitCallback: executeHitCallback });
    }, "Cannot send event.")
  };

  sendPageview = function(){
    checkTrackerAndExecute(function(){
      ga('send', 'pageview');
    }, "Cannot send pageview.");
  };

  setupGA = function(trackingId) {
    trackerId = trackingId;
    checkTrackerAndExecute(function(){
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
              m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', trackerId, 'auto');
    }, "Cannot initialise GA.");
  };

  setupEvent = function(elems, category, action, fnLabel){
    checkTrackerAndExecute(function(){
      for(var i=0; i < elems.length; i++) {
        elems[i].addEventListener("click", function(e){
          e.preventDefault();
          var targetLabel = fnLabel(e);
          sendEvent(category, action, targetLabel, function(){ document.location = e.target.href; });
        }, false);
      };
    }, "Cannot setup event");
  };

  return {
    setupGA: setupGA,
    setupEvent: setupEvent,
    sendPageview: sendPageview,
    sendEvent: sendEvent
  };
}());

GOVUK.registers.analytics.setupGA(gaTrackingId);
GOVUK.registers.analytics.sendPageview();
<commit_msg>Add crucial semicolon<commit_after>var GOVUK = GOVUK || {};
GOVUK.registers = GOVUK.registers || {};

GOVUK.registers.analytics = (function () {
  var setupGA, setupEvents, sendPageview, sendEvent;

  var trackerId;
  var isTrackerPresent = function(){
    return (typeof trackerId !== 'undefined') && (trackerId !== '');
  };

  var checkTrackerAndExecute = function(fnToExecute, errorMsg){
    if(isTrackerPresent()){
        fnToExecute();
    } else {
      console.error("GA tracker not present. " + errorMsg || "");
    }
  };

  sendEvent = function(category, action, targetLabel, fnHitCallback){
    checkTrackerAndExecute(function(){
      callbackExecuted = false;
      var executeHitCallback = function () {
        if (!callbackExecuted) {
          callbackExecuted = true;
          fnHitCallback();
        }
      };
      setTimeout(executeHitCallback, 1000);

      ga('send', 'event', category, action, targetLabel, { hitCallback: executeHitCallback });
    }, "Cannot send event.")
  };

  sendPageview = function(){
    checkTrackerAndExecute(function(){
      ga('send', 'pageview');
    }, "Cannot send pageview.");
  };

  setupGA = function(trackingId) {
    trackerId = trackingId;
    checkTrackerAndExecute(function(){
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
              m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', trackerId, 'auto');
    }, "Cannot initialise GA.");
  };

  setupEvent = function(elems, category, action, fnLabel){
    checkTrackerAndExecute(function(){
      for(var i=0; i < elems.length; i++) {
        elems[i].addEventListener("click", function(e){
          e.preventDefault();
          var targetLabel = fnLabel(e);
          sendEvent(category, action, targetLabel, function(){ document.location = e.target.href; });
        }, false);
      };
    }, "Cannot setup event");
  };

  return {
    setupGA: setupGA,
    setupEvent: setupEvent,
    sendPageview: sendPageview,
    sendEvent: sendEvent
  };
}());

GOVUK.registers.analytics.setupGA(gaTrackingId);
GOVUK.registers.analytics.sendPageview();
<|endoftext|>


<commit_before>var Actor = function(args) {
  this.context = args.context;
  this.x = args.startX;
  this.y = args.startY;
  this.name = args.name;
  this.radius = 6;
  this.direction = args.direction;
  this.speed = PAC_MOVE_DELAY;
  this.mouthPos = 0.0;
  this.mouthIsOpening = true;
  this.moveIntervalID = false;
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
}
Actor.prototype.clear = function() {
  this.context.clearRect(this.x - this.radius, this.y - this.radius, 2 * this.radius, 2 * this.radius);
};
Actor.prototype.render = function() {
  this.context.fillStyle = nameToColor[this.name];
  this.context.beginPath();

  var arcStart, arcEnd;
  var cheekX = 0;
  var cheekY = 0;
  switch(this.direction) {
    case "up":
      arcStart = (1.5 + this.mouthPos) * Math.PI;
      arcEnd = (3.5 - this.mouthPos) * Math.PI;
      cheekY = 2.5;
    break;
    case "down":
      arcStart = (0.5 + this.mouthPos) * Math.PI;
      arcEnd = (2.5 - this.mouthPos) * Math.PI;
      cheekY = -2.5;
    break;
    case "left":
      arcStart = (1.0 + this.mouthPos) * Math.PI;
      arcEnd = (3.0 - this.mouthPos) * Math.PI;
      cheekX = 2.5;
    break;
    case "right":
      arcStart = (0.0 + this.mouthPos) * Math.PI;
      arcEnd = (2.0 - this.mouthPos) * Math.PI;
      cheekX = -2.5;
    break;
  }

  if(this.name == "m") {
    this.context.arc(this.x, this.y, this.radius, arcStart, arcEnd, false);
    this.context.lineTo(this.x + cheekX, this.y + cheekY);
  }

  this.context.closePath();
  this.context.fill();
};
Actor.prototype.detectCollision = function(keyPressed) {
  var collision = "none";
  var xMod, yMod;
  var direction = keyPressed ? keyPressed : this.direction
  switch(direction) {
    case "up": xMod = 0; yMod = -1; break;
    case "down": xMod = 0; yMod = 1; break;
    case "left": xMod = -1; yMod = 0; break;
    case "right": xMod = 1; yMod = 0; break;
  }
  var x = Math.floor(this.x / 8);
  var y = Math.floor(this.y / 8) - 3;

  var cell = gameBoard.getCell({
    x: x + xMod,
    y: y + yMod
  });
  if(cell == "x" || cell == "-") {
    collision = "wall";
  }
  else if(cell == ".") {
    collision = "pellet";
  }
  else if(cell == "o") {
    collision = "powerPellet";
  }
  else if(cell == "b" || cell == "i" || cell == "p" || cell == "c") {
    collision = "ghost";
  }

  return collision;
};
Actor.prototype.move = function() {
  this.mouthPos = Math.floor((this.mouthPos + ((this.mouthIsOpening ? 1 : -1) * 0.08)) * 100) / 100;
  if(this.mouthPos <= 0) {
    this.mouthIsOpening = true;
  }
  else if(this.mouthPos >= 0.4) {
    this.mouthIsOpening = false;
  }
  var xInTile = this.x % 8;
  var yInTile = this.y % 8;
  switch(this.direction) {
    case "up": this.y--; break;
    case "down": this.y++; break;
    case "left": this.x--; break;
    case "right": this.x++; break;
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  if(this.x + 8 <= 0) {
    if(this.direction == "left") {
      this.x = BOARD_WIDTH;
    }
  }
  else if(this.x - 8 > BOARD_WIDTH) {
    if(this.direction == "right") {
      this.x = 0 - 8;
    }
  }
  else {
    if(this.keyStates[this.direction] === false) {
      if(newDirection) {
        if(this.detectCollision(newDirection) != "wall") {
          this.direction = newDirection;
        }
      }
    }
    if(xInTile == 4 && yInTile == 4 && this.detectCollision() == "wall") {
      if(newDirection && this.detectCollision(newDirection) != "wall") {
        this.direction = newDirection;
      }
      else {
        clearInterval(this.moveIntervalID);
        this.moveIntervalID = false;
      }
    }
  }
  return {x: this.x, y: this.y}
};
Actor.prototype.moveTowardCenter = function() {
  var xInTile = this.x % 8;
  var yInTile = this.y % 8;
  if((this.direction == "up" || this.direction == "down") && xInTile != 4) {
    this.x += xInTile < 4 ? 1 : -1;
  }
  else if((this.direction == "left" || this.direction == "right") && yInTile != 4) {
    this.y += yInTile < 4 ? 1 : -1;
  }
};
Actor.prototype.handleKeyUp = function(keyPressed) {
  this.keyStates[keyPressed] = false;
};
<commit_msg>Remove redundant expressions from Actor.move<commit_after>var Actor = function(args) {
  this.context = args.context;
  this.x = args.startX;
  this.y = args.startY;
  this.name = args.name;
  this.radius = 6;
  this.direction = args.direction;
  this.speed = PAC_MOVE_DELAY;
  this.mouthPos = 0.0;
  this.mouthIsOpening = true;
  this.moveIntervalID = false;
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
}
Actor.prototype.clear = function() {
  this.context.clearRect(this.x - this.radius, this.y - this.radius, 2 * this.radius, 2 * this.radius);
};
Actor.prototype.render = function() {
  this.context.fillStyle = nameToColor[this.name];
  this.context.beginPath();

  var arcStart, arcEnd;
  var cheekX = 0;
  var cheekY = 0;
  switch(this.direction) {
    case "up":
      arcStart = (1.5 + this.mouthPos) * Math.PI;
      arcEnd = (3.5 - this.mouthPos) * Math.PI;
      cheekY = 2.5;
    break;
    case "down":
      arcStart = (0.5 + this.mouthPos) * Math.PI;
      arcEnd = (2.5 - this.mouthPos) * Math.PI;
      cheekY = -2.5;
    break;
    case "left":
      arcStart = (1.0 + this.mouthPos) * Math.PI;
      arcEnd = (3.0 - this.mouthPos) * Math.PI;
      cheekX = 2.5;
    break;
    case "right":
      arcStart = (0.0 + this.mouthPos) * Math.PI;
      arcEnd = (2.0 - this.mouthPos) * Math.PI;
      cheekX = -2.5;
    break;
  }

  if(this.name == "m") {
    this.context.arc(this.x, this.y, this.radius, arcStart, arcEnd, false);
    this.context.lineTo(this.x + cheekX, this.y + cheekY);
  }

  this.context.closePath();
  this.context.fill();
};
Actor.prototype.detectCollision = function(keyPressed) {
  var collision = "none";
  var xMod, yMod;
  var direction = keyPressed ? keyPressed : this.direction
  switch(direction) {
    case "up": xMod = 0; yMod = -1; break;
    case "down": xMod = 0; yMod = 1; break;
    case "left": xMod = -1; yMod = 0; break;
    case "right": xMod = 1; yMod = 0; break;
  }
  var x = Math.floor(this.x / 8);
  var y = Math.floor(this.y / 8) - 3;

  var cell = gameBoard.getCell({
    x: x + xMod,
    y: y + yMod
  });
  if(cell == "x" || cell == "-") {
    collision = "wall";
  }
  else if(cell == ".") {
    collision = "pellet";
  }
  else if(cell == "o") {
    collision = "powerPellet";
  }
  else if(cell == "b" || cell == "i" || cell == "p" || cell == "c") {
    collision = "ghost";
  }

  return collision;
};
Actor.prototype.move = function() {
  this.mouthPos = Math.floor((this.mouthPos + ((this.mouthIsOpening ? 1 : -1) * 0.08)) * 100) / 100;
  if(this.mouthPos <= 0) {
    this.mouthIsOpening = true;
  }
  else if(this.mouthPos >= 0.4) {
    this.mouthIsOpening = false;
  }

  switch(this.direction) {
    case "up": this.y--; break;
    case "down": this.y++; break;
    case "left": this.x--; break;
    case "right": this.x++; break;
  }

  if(this.x + 8 <= 0) {
    if(this.direction == "left") {
      this.x = BOARD_WIDTH;
    }
  }
  else if(this.x - 8 > BOARD_WIDTH) {
    if(this.direction == "right") {
      this.x = 0 - 8;
    }
  }
  return {x: this.x, y: this.y}
};
Actor.prototype.moveTowardCenter = function() {
  var xInTile = this.x % 8;
  var yInTile = this.y % 8;
  if((this.direction == "up" || this.direction == "down") && xInTile != 4) {
    this.x += xInTile < 4 ? 1 : -1;
  }
  else if((this.direction == "left" || this.direction == "right") && yInTile != 4) {
    this.y += yInTile < 4 ? 1 : -1;
  }
};
Actor.prototype.handleKeyUp = function(keyPressed) {
  this.keyStates[keyPressed] = false;
};
<|endoftext|>