diff --git a/.eslintrc b/.eslintrc index 22a0db488..e8bdcb6be 100644 --- a/.eslintrc +++ b/.eslintrc @@ -4,11 +4,11 @@ "dot-notation": 2, "eqeqeq": [2, "smart"], "indent": [0, 4], + "keyword-spacing": 2, "linebreak-style": [2, "unix"], "no-caller": 2, "no-catch-shadow": 2, "no-div-regex": 2, - "no-empty-label": 2, "no-extend-native": 2, "no-extra-bind": 2, "no-floating-decimal": 2, @@ -45,7 +45,6 @@ "no-use-before-define": [0, "nofunc"], "semi": [2, "always"], "semi-spacing": 2, - "space-return-throw-case": 2, "space-unary-ops": 2, "wrap-regex": 0, "quotes": [2, "single"] diff --git a/.travis.yml b/.travis.yml index ade71da59..cd30ec2ae 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,5 @@ language: node_js +node_js: + - "5.11" sudo: false -before_install: - # https://github.com/travis-ci/travis-ci/issues/3225 - - mkdir travis-phantomjs - - wget https://github.com/Medium/phantomjs/releases/download/v2.1.1/phantomjs-2.1.1-linux-x86_64.tar.bz2 -O $PWD/travis-phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2 - - tar -xvf $PWD/travis-phantomjs/phantomjs-2.1.1-linux-x86_64.tar.bz2 -C $PWD/travis-phantomjs - - export PATH=$PWD/travis-phantomjs/phantomjs-2.1.1-linux-x86_64/bin:$PATH before_script: make diff --git a/Makefile b/Makefile index ec12b7a05..f34805ada 100644 --- a/Makefile +++ b/Makefile @@ -45,10 +45,8 @@ $(BUILDJS_TARGETS): $(BUILDJS_SOURCES) build.js MODULE_TARGETS = \ js/lib/id/actions.js -ACTIONS = $(shell ./node_modules/.bin/browserify --list modules/actions/index.js) -js/lib/id/actions.js: $(ACTIONS) - node_modules/.bin/browserify modules/actions/index.js -s iD.actions > $@ - +js/lib/id/actions.js: modules/ + node_modules/.bin/rollup -f umd -n iD.actions modules/actions/index.js --no-strict > $@ dist/iD.js: \ js/lib/bootstrap-tooltip.js \ diff --git a/README.md b/README.md index 712aa93d0..a6714c942 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,8 @@ Come on in, the water's lovely. More help? Ping `jfire` or `bhousel` on (`irc.oftc.net`, in `#iD` or `#osm-dev` or `#osm`) or on the [OpenStreetMap `dev` mailing list](http://wiki.openstreetmap.org/wiki/Mailing_lists). ## Prerequisites -* [Node.js](http://nodejs.org/) version 0.10.0 or newer -* [PhantomJS](http://phantomjs.org/) version 2 or newer (for running tests) + +* [Node.js](http://nodejs.org/) version 4 or newer * Command line development tools (`make`, `git`, and a compiler) for your platform * Ubuntu: * `sudo apt-get install build-essential git` diff --git a/js/id/id.js b/js/id/id.js index 050fdcc66..b81400115 100644 --- a/js/id/id.js +++ b/js/id/id.js @@ -23,7 +23,7 @@ window.iD = function () { if (arguments.length === 1) return storage.getItem(k); else if (v === null) storage.removeItem(k); else storage.setItem(k, v); - } catch(e) { + } catch (e) { // localstorage quota exceeded /* eslint-disable no-console */ if (typeof console !== 'undefined') console.error('localStorage quota exceeded'); diff --git a/js/id/modes/save.js b/js/id/modes/save.js index ad128ecb1..8cbd3e317 100644 --- a/js/id/modes/save.js +++ b/js/id/modes/save.js @@ -15,7 +15,7 @@ iD.modes.Save = function(context) { try { var cn = graph.childNodes(e); result.push.apply(result, _.map(_.filter(cn, 'version'), 'id')); - } catch(err) { + } catch (err) { /* eslint-disable no-console */ if (typeof console !== 'undefined') console.error(err); /* eslint-enable no-console */ diff --git a/js/id/start.js b/js/id/start.js index 6d6f50c31..5d11b9790 100644 --- a/js/id/start.js +++ b/js/id/start.js @@ -1,2 +1 @@ (function () { -'use strict'; diff --git a/js/lib/id/actions.js b/js/lib/id/actions.js index 60ba923de..b1ae56512 100644 --- a/js/lib/id/actions.js +++ b/js/lib/id/actions.js @@ -1,2236 +1,2209 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.iD || (g.iD = {})).actions = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 2; j++) { - if (segment[j] !== member) - continue; - - if (j === 0) { - memberIndex = segment[j + 1].index; - } else if (j === segment.length - 1) { - memberIndex = segment[j - 1].index + 1; - } else { - memberIndex = Math.min(segment[j - 1].index + 1, segment[j + 1].index + 1); - } - } - } - } - - return graph.replace(relation.addMember(member, memberIndex)); - }; -}; - -},{}],3:[function(require,module,exports){ -module.exports = function(midpoint, node) { - return function(graph) { - graph = graph.replace(node.move(midpoint.loc)); - - var parents = _.intersection( - graph.parentWays(graph.entity(midpoint.edge[0])), - graph.parentWays(graph.entity(midpoint.edge[1]))); - - parents.forEach(function(way) { - for (var i = 0; i < way.nodes.length - 1; i++) { - if (iD.geo.edgeEqual([way.nodes[i], way.nodes[i + 1]], midpoint.edge)) { - graph = graph.replace(graph.entity(way.id).addNode(node.id, i + 1)); - - // Add only one midpoint on doubled-back segments, - // turning them into self-intersections. - return; - } - } - }); - - return graph; - }; -}; - -},{}],4:[function(require,module,exports){ -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/AddNodeToWayAction.as -module.exports = function(wayId, nodeId, index) { - return function(graph) { - return graph.replace(graph.entity(wayId).addNode(nodeId, index)); - }; -}; - -},{}],5:[function(require,module,exports){ -module.exports = function(relationId, member, memberIndex) { - return function(graph) { - return graph.replace(graph.entity(relationId).updateMember(member, memberIndex)); - }; -}; - -},{}],6:[function(require,module,exports){ -module.exports = function(entityId, oldPreset, newPreset) { - return function(graph) { - var entity = graph.entity(entityId), - geometry = entity.geometry(graph), - tags = entity.tags; - - if (oldPreset) tags = oldPreset.removeTags(tags, geometry); - if (newPreset) tags = newPreset.applyTags(tags, geometry); - - return graph.replace(entity.update({tags: tags})); - }; -}; - -},{}],7:[function(require,module,exports){ -module.exports = function(entityId, tags) { - return function(graph) { - var entity = graph.entity(entityId); - return graph.replace(entity.update({tags: tags})); - }; -}; - -},{}],8:[function(require,module,exports){ -module.exports = function(wayId, projection, maxAngle) { - maxAngle = (maxAngle || 20) * Math.PI / 180; - - var action = function(graph) { - var way = graph.entity(wayId); - - if (!way.isConvex(graph)) { - graph = action.makeConvex(graph); - } - - var nodes = _.uniq(graph.childNodes(way)), - keyNodes = nodes.filter(function(n) { return graph.parentWays(n).length !== 1; }), - points = nodes.map(function(n) { return projection(n.loc); }), - keyPoints = keyNodes.map(function(n) { return projection(n.loc); }), - centroid = (points.length === 2) ? iD.geo.interp(points[0], points[1], 0.5) : d3.geom.polygon(points).centroid(), - radius = d3.median(points, function(p) { return iD.geo.euclideanDistance(centroid, p); }), - sign = d3.geom.polygon(points).area() > 0 ? 1 : -1, - ids; - - // we need atleast two key nodes for the algorithm to work - if (!keyNodes.length) { - keyNodes = [nodes[0]]; - keyPoints = [points[0]]; - } - - if (keyNodes.length === 1) { - var index = nodes.indexOf(keyNodes[0]), - oppositeIndex = Math.floor((index + nodes.length / 2) % nodes.length); - - keyNodes.push(nodes[oppositeIndex]); - keyPoints.push(points[oppositeIndex]); - } - - // key points and nodes are those connected to the ways, - // they are projected onto the circle, inbetween nodes are moved - // to constant intervals between key nodes, extra inbetween nodes are - // added if necessary. - for (var i = 0; i < keyPoints.length; i++) { - var nextKeyNodeIndex = (i + 1) % keyNodes.length, - startNode = keyNodes[i], - endNode = keyNodes[nextKeyNodeIndex], - startNodeIndex = nodes.indexOf(startNode), - endNodeIndex = nodes.indexOf(endNode), - numberNewPoints = -1, - indexRange = endNodeIndex - startNodeIndex, - distance, totalAngle, eachAngle, startAngle, endAngle, - angle, loc, node, j, - inBetweenNodes = []; - - if (indexRange < 0) { - indexRange += nodes.length; - } - - // position this key node - distance = iD.geo.euclideanDistance(centroid, keyPoints[i]); - if (distance === 0) { distance = 1e-4; } - keyPoints[i] = [ - centroid[0] + (keyPoints[i][0] - centroid[0]) / distance * radius, - centroid[1] + (keyPoints[i][1] - centroid[1]) / distance * radius]; - graph = graph.replace(keyNodes[i].move(projection.invert(keyPoints[i]))); - - // figure out the between delta angle we want to match to - startAngle = Math.atan2(keyPoints[i][1] - centroid[1], keyPoints[i][0] - centroid[0]); - endAngle = Math.atan2(keyPoints[nextKeyNodeIndex][1] - centroid[1], keyPoints[nextKeyNodeIndex][0] - centroid[0]); - totalAngle = endAngle - startAngle; - - // detects looping around -pi/pi - if (totalAngle * sign > 0) { - totalAngle = -sign * (2 * Math.PI - Math.abs(totalAngle)); - } - - do { - numberNewPoints++; - eachAngle = totalAngle / (indexRange + numberNewPoints); - } while (Math.abs(eachAngle) > maxAngle); - - // move existing points - for (j = 1; j < indexRange; j++) { - angle = startAngle + j * eachAngle; - loc = projection.invert([ - centroid[0] + Math.cos(angle)*radius, - centroid[1] + Math.sin(angle)*radius]); - - node = nodes[(j + startNodeIndex) % nodes.length].move(loc); - graph = graph.replace(node); - } - - // add new inbetween nodes if necessary - for (j = 0; j < numberNewPoints; j++) { - angle = startAngle + (indexRange + j) * eachAngle; - loc = projection.invert([ - centroid[0] + Math.cos(angle) * radius, - centroid[1] + Math.sin(angle) * radius]); - - node = iD.Node({loc: loc}); - graph = graph.replace(node); - - nodes.splice(endNodeIndex + j, 0, node); - inBetweenNodes.push(node.id); - } - - // Check for other ways that share these keyNodes.. - // If keyNodes are adjacent in both ways, - // we can add inBetween nodes to that shared way too.. - if (indexRange === 1 && inBetweenNodes.length) { - var startIndex1 = way.nodes.lastIndexOf(startNode.id), - endIndex1 = way.nodes.lastIndexOf(endNode.id), - wayDirection1 = (endIndex1 - startIndex1); - if (wayDirection1 < -1) { wayDirection1 = 1; } - - /* eslint-disable no-loop-func */ - _.each(_.without(graph.parentWays(keyNodes[i]), way), function(sharedWay) { - if (sharedWay.areAdjacent(startNode.id, endNode.id)) { - var startIndex2 = sharedWay.nodes.lastIndexOf(startNode.id), - endIndex2 = sharedWay.nodes.lastIndexOf(endNode.id), - wayDirection2 = (endIndex2 - startIndex2), - insertAt = endIndex2; - if (wayDirection2 < -1) { wayDirection2 = 1; } - - if (wayDirection1 !== wayDirection2) { - inBetweenNodes.reverse(); - insertAt = startIndex2; - } - for (j = 0; j < inBetweenNodes.length; j++) { - sharedWay = sharedWay.addNode(inBetweenNodes[j], insertAt + j); - } - graph = graph.replace(sharedWay); - } - }); - /* eslint-enable no-loop-func */ - } - - } - - // update the way to have all the new nodes - ids = nodes.map(function(n) { return n.id; }); - ids.push(ids[0]); - - way = way.update({nodes: ids}); - graph = graph.replace(way); - - return graph; - }; - - action.makeConvex = function(graph) { - var way = graph.entity(wayId), - nodes = _.uniq(graph.childNodes(way)), - points = nodes.map(function(n) { return projection(n.loc); }), - sign = d3.geom.polygon(points).area() > 0 ? 1 : -1, - hull = d3.geom.hull(points); - - // D3 convex hulls go counterclockwise.. - if (sign === -1) { - nodes.reverse(); - points.reverse(); - } - - for (var i = 0; i < hull.length - 1; i++) { - var startIndex = points.indexOf(hull[i]), - endIndex = points.indexOf(hull[i+1]), - indexRange = (endIndex - startIndex); - - if (indexRange < 0) { - indexRange += nodes.length; - } - - // move interior nodes to the surface of the convex hull.. - for (var j = 1; j < indexRange; j++) { - var point = iD.geo.interp(hull[i], hull[i+1], j / indexRange), - node = nodes[(j + startIndex) % nodes.length].move(projection.invert(point)); - graph = graph.replace(node); - } - } - return graph; - }; - - action.disabled = function(graph) { - if (!graph.entity(wayId).isClosed()) - return 'not_closed'; - }; - - return action; -}; - -},{}],9:[function(require,module,exports){ -// Connect the ways at the given nodes. -// -// The last node will survive. All other nodes will be replaced with -// the surviving node in parent ways, and then removed. -// -// Tags and relation memberships of of non-surviving nodes are merged -// to the survivor. -// -// This is the inverse of `iD.actions.Disconnect`. -// -// Reference: -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MergeNodesAction.as -// https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/MergeNodesAction.java -// -module.exports = function(nodeIds) { - return function(graph) { - var survivor = graph.entity(_.last(nodeIds)); - - for (var i = 0; i < nodeIds.length - 1; i++) { - var node = graph.entity(nodeIds[i]); - - /* eslint-disable no-loop-func */ - graph.parentWays(node).forEach(function(parent) { - if (!parent.areAdjacent(node.id, survivor.id)) { - graph = graph.replace(parent.replaceNode(node.id, survivor.id)); - } - }); - - graph.parentRelations(node).forEach(function(parent) { - graph = graph.replace(parent.replaceMember(node, survivor)); - }); - /* eslint-enable no-loop-func */ - - survivor = survivor.mergeTags(node.tags); - graph = iD.actions.DeleteNode(node.id)(graph); - } - - graph = graph.replace(survivor); - - return graph; - }; -}; - -},{}],10:[function(require,module,exports){ -module.exports = function(ids, fromGraph) { - var copies = {}; - - var action = function(graph) { - ids.forEach(function(id) { - fromGraph.entity(id).copy(fromGraph, copies); - }); - - for (var id in copies) { - graph = graph.replace(copies[id]); - } - - return graph; - }; - - action.copies = function() { - return copies; - }; - - return action; -}; - -},{}],11:[function(require,module,exports){ -module.exports = function(relationId, memberIndex) { - return function(graph) { - var relation = graph.entity(relationId) - .removeMember(memberIndex); - - graph = graph.replace(relation); - - if (relation.isDegenerate()) - graph = iD.actions.DeleteRelation(relation.id)(graph); - - return graph; - }; -}; - -},{}],12:[function(require,module,exports){ -module.exports = function(ids) { - var actions = { - way: iD.actions.DeleteWay, - node: iD.actions.DeleteNode, - relation: iD.actions.DeleteRelation - }; - - var action = function(graph) { - ids.forEach(function(id) { - if (graph.hasEntity(id)) { // It may have been deleted aready. - graph = actions[graph.entity(id).type](id)(graph); - } - }); - - return graph; - }; - - action.disabled = function(graph) { - for (var i = 0; i < ids.length; i++) { - var id = ids[i], - disabled = actions[graph.entity(id).type](id).disabled(graph); - if (disabled) return disabled; - } - }; - - return action; -}; - -},{}],13:[function(require,module,exports){ -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteNodeAction.as -module.exports = function(nodeId) { - var action = function(graph) { - var node = graph.entity(nodeId); - - graph.parentWays(node) - .forEach(function(parent) { - parent = parent.removeNode(nodeId); - graph = graph.replace(parent); - - if (parent.isDegenerate()) { - graph = iD.actions.DeleteWay(parent.id)(graph); - } - }); - - graph.parentRelations(node) - .forEach(function(parent) { - parent = parent.removeMembersWithID(nodeId); - graph = graph.replace(parent); - - if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); - } - }); - - return graph.remove(node); - }; - - action.disabled = function() { - return false; - }; - - return action; -}; - -},{}],14:[function(require,module,exports){ -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteRelationAction.as -module.exports = function(relationId) { - function deleteEntity(entity, graph) { - return !graph.parentWays(entity).length && - !graph.parentRelations(entity).length && - !entity.hasInterestingTags(); - } - - var action = function(graph) { - var relation = graph.entity(relationId); - - graph.parentRelations(relation) - .forEach(function(parent) { - parent = parent.removeMembersWithID(relationId); - graph = graph.replace(parent); - - if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); - } - }); - - _.uniq(_.map(relation.members, 'id')).forEach(function(memberId) { - graph = graph.replace(relation.removeMembersWithID(memberId)); - - var entity = graph.entity(memberId); - if (deleteEntity(entity, graph)) { - graph = iD.actions.DeleteMultiple([memberId])(graph); - } - }); - - return graph.remove(relation); - }; - - action.disabled = function(graph) { - if (!graph.entity(relationId).isComplete(graph)) - return 'incomplete_relation'; - }; - - return action; -}; - -},{}],15:[function(require,module,exports){ -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteWayAction.as -module.exports = function(wayId) { - function deleteNode(node, graph) { - return !graph.parentWays(node).length && - !graph.parentRelations(node).length && - !node.hasInterestingTags(); - } - - var action = function(graph) { - var way = graph.entity(wayId); - - graph.parentRelations(way) - .forEach(function(parent) { - parent = parent.removeMembersWithID(wayId); - graph = graph.replace(parent); - - if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); - } - }); - - _.uniq(way.nodes).forEach(function(nodeId) { - graph = graph.replace(way.removeNode(nodeId)); - - var node = graph.entity(nodeId); - if (deleteNode(node, graph)) { - graph = graph.remove(node); - } - }); - - return graph.remove(way); - }; - - action.disabled = function(graph) { - var disabled = false; - - graph.parentRelations(graph.entity(wayId)).forEach(function(parent) { - var type = parent.tags.type, - role = parent.memberById(wayId).role || 'outer'; - if (type === 'route' || type === 'boundary' || (type === 'multipolygon' && role === 'outer')) { - disabled = 'part_of_relation'; - } - }); - - return disabled; - }; - - return action; -}; - -},{}],16:[function(require,module,exports){ -module.exports = function(entityId) { - return function(graph) { - var entity = graph.entity(entityId), - newtags = _.clone(entity.tags), - change = false, - rule; - - // This handles deprecated tags with a single condition - for (var i = 0; i < iD.data.deprecated.length; i++) { - - rule = iD.data.deprecated[i]; - var match = _.toPairs(rule.old)[0], - replacements = rule.replace ? _.toPairs(rule.replace) : null; - - if (entity.tags[match[0]] && match[1] === '*') { - - var value = entity.tags[match[0]]; - if (replacements && !newtags[replacements[0][0]]) { - newtags[replacements[0][0]] = value; - } - delete newtags[match[0]]; - change = true; - - } else if (entity.tags[match[0]] === match[1]) { - newtags = _.assign({}, rule.replace || {}, _.omit(newtags, match[0])); - change = true; - } - } - - if (change) { - return graph.replace(entity.update({tags: newtags})); - } else { - return graph; - } - }; -}; - -},{}],17:[function(require,module,exports){ -module.exports = function(difference) { - return function(graph) { - function discardTags(entity) { - if (!_.isEmpty(entity.tags)) { - var tags = {}; - _.each(entity.tags, function(v, k) { - if (v) tags[k] = v; - }); - - graph = graph.replace(entity.update({ - tags: _.omit(tags, iD.data.discarded) - })); - } - } - - difference.modified().forEach(discardTags); - difference.created().forEach(discardTags); - - return graph; - }; -}; - -},{}],18:[function(require,module,exports){ -// Disconect the ways at the given node. -// -// Optionally, disconnect only the given ways. -// -// For testing convenience, accepts an ID to assign to the (first) new node. -// Normally, this will be undefined and the way will automatically -// be assigned a new ID. -// -// This is the inverse of `iD.actions.Connect`. -// -// Reference: -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/UnjoinNodeAction.as -// https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/UnGlueAction.java -// -module.exports = function(nodeId, newNodeId) { - var wayIds; - - var action = function(graph) { - var node = graph.entity(nodeId), - connections = action.connections(graph); - - connections.forEach(function(connection) { - var way = graph.entity(connection.wayID), - newNode = iD.Node({id: newNodeId, loc: node.loc, tags: node.tags}); - - graph = graph.replace(newNode); - if (connection.index === 0 && way.isArea()) { - // replace shared node with shared node.. - graph = graph.replace(way.replaceNode(way.nodes[0], newNode.id)); - } else { - // replace shared node with multiple new nodes.. - graph = graph.replace(way.updateNode(newNode.id, connection.index)); - } - }); - - return graph; - }; - - action.connections = function(graph) { - var candidates = [], - keeping = false, - parentWays = graph.parentWays(graph.entity(nodeId)); - - parentWays.forEach(function(way) { - if (wayIds && wayIds.indexOf(way.id) === -1) { - keeping = true; - return; - } - if (way.isArea() && (way.nodes[0] === nodeId)) { - candidates.push({wayID: way.id, index: 0}); - } else { - way.nodes.forEach(function(waynode, index) { - if (waynode === nodeId) { - candidates.push({wayID: way.id, index: index}); - } - }); - } - }); - - return keeping ? candidates : candidates.slice(1); - }; - - action.disabled = function(graph) { - var connections = action.connections(graph); - if (connections.length === 0 || (wayIds && wayIds.length !== connections.length)) - return 'not_connected'; - - var parentWays = graph.parentWays(graph.entity(nodeId)), - seenRelationIds = {}, - sharedRelation; - - parentWays.forEach(function(way) { - if (wayIds && wayIds.indexOf(way.id) === -1) - return; - - var relations = graph.parentRelations(way); - relations.forEach(function(relation) { - if (relation.id in seenRelationIds) { - sharedRelation = relation; - } else { - seenRelationIds[relation.id] = true; - } - }); - }); - - if (sharedRelation) - return 'relation'; - }; - - action.limitWays = function(_) { - if (!arguments.length) return wayIds; - wayIds = _; - return action; - }; - - return action; -}; - -},{}],19:[function(require,module,exports){ -module.exports.AddEntity = require('./add_entity'); -module.exports.AddMember = require('./add_member'); -module.exports.AddMidpoint = require('./add_midpoint'); -module.exports.AddVertex = require('./add_vertex'); -module.exports.ChangeMember = require('./change_member'); -module.exports.ChangePreset = require('./change_preset'); -module.exports.ChangeTags = require('./change_tags'); -module.exports.Circularize = require('./circularize'); -module.exports.Connect = require('./connect'); -module.exports.CopyEntities = require('./copy_entities'); -module.exports.DeleteMember = require('./delete_member'); -module.exports.DeleteMultiple = require('./delete_multiple'); -module.exports.DeleteNode = require('./delete_node'); -module.exports.DeleteRelation = require('./delete_relation'); -module.exports.DeleteWay = require('./delete_way'); -module.exports.DeprecateTags = require('./deprecate_tags'); -module.exports.DiscardTags = require('./discard_tags'); -module.exports.Disconnect = require('./disconnect'); -module.exports.Join = require('./join'); -module.exports.Merge = require('./merge'); -module.exports.MergePolygon = require('./merge_polygon'); -module.exports.MergeRemoteChanges = require('./merge_remote_changes'); -module.exports.Move = require('./move'); -module.exports.MoveNode = require('./move_node'); -module.exports.Noop = require('./noop'); -module.exports.Orthogonalize = require('./orthogonalize'); -module.exports.RestrictTurn = require('./restrict_turn'); -module.exports.Reverse = require('./reverse'); -module.exports.Revert = require('./revert'); -module.exports.RotateWay = require('./rotate_way'); -module.exports.Split = require('./split'); -module.exports.Straighten = require('./straighten'); -module.exports.UnrestrictTurn = require('./unrestrict_turn'); - -},{"./add_entity":1,"./add_member":2,"./add_midpoint":3,"./add_vertex":4,"./change_member":5,"./change_preset":6,"./change_tags":7,"./circularize":8,"./connect":9,"./copy_entities":10,"./delete_member":11,"./delete_multiple":12,"./delete_node":13,"./delete_relation":14,"./delete_way":15,"./deprecate_tags":16,"./discard_tags":17,"./disconnect":18,"./join":20,"./merge":21,"./merge_polygon":22,"./merge_remote_changes":23,"./move":24,"./move_node":25,"./noop":26,"./orthogonalize":27,"./restrict_turn":28,"./reverse":29,"./revert":30,"./rotate_way":31,"./split":32,"./straighten":33,"./unrestrict_turn":34}],20:[function(require,module,exports){ -// Join ways at the end node they share. -// -// This is the inverse of `iD.actions.Split`. -// -// Reference: -// https://github.com/systemed/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MergeWaysAction.as -// https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/CombineWayAction.java -// -module.exports = function(ids) { - - function groupEntitiesByGeometry(graph) { - var entities = ids.map(function(id) { return graph.entity(id); }); - return _.extend({line: []}, _.groupBy(entities, function(entity) { return entity.geometry(graph); })); - } - - var action = function(graph) { - var ways = ids.map(graph.entity, graph), - survivor = ways[0]; - - // Prefer to keep an existing way. - for (var i = 0; i < ways.length; i++) { - if (!ways[i].isNew()) { - survivor = ways[i]; - break; - } - } - - var joined = iD.geo.joinWays(ways, graph)[0]; - - survivor = survivor.update({nodes: _.map(joined.nodes, 'id')}); - graph = graph.replace(survivor); - - joined.forEach(function(way) { - if (way.id === survivor.id) - return; - - graph.parentRelations(way).forEach(function(parent) { - graph = graph.replace(parent.replaceMember(way, survivor)); - }); - - survivor = survivor.mergeTags(way.tags); - - graph = graph.replace(survivor); - graph = iD.actions.DeleteWay(way.id)(graph); - }); - - return graph; - }; - - action.disabled = function(graph) { - var geometries = groupEntitiesByGeometry(graph); - if (ids.length < 2 || ids.length !== geometries.line.length) - return 'not_eligible'; - - var joined = iD.geo.joinWays(ids.map(graph.entity, graph), graph); - if (joined.length > 1) - return 'not_adjacent'; - - var nodeIds = _.map(joined[0].nodes, 'id').slice(1, -1), - relation, - tags = {}, - conflicting = false; - - joined[0].forEach(function(way) { - var parents = graph.parentRelations(way); - parents.forEach(function(parent) { - if (parent.isRestriction() && parent.members.some(function(m) { return nodeIds.indexOf(m.id) >= 0; })) - relation = parent; - }); - - for (var k in way.tags) { - if (!(k in tags)) { - tags[k] = way.tags[k]; - } else if (tags[k] && iD.interestingTag(k) && tags[k] !== way.tags[k]) { - conflicting = true; - } - } - }); - - if (relation) - return 'restriction'; - - if (conflicting) - return 'conflicting_tags'; - }; - - return action; -}; - -},{}],21:[function(require,module,exports){ -module.exports = function(ids) { - function groupEntitiesByGeometry(graph) { - var entities = ids.map(function(id) { return graph.entity(id); }); - return _.extend({point: [], area: [], line: [], relation: []}, - _.groupBy(entities, function(entity) { return entity.geometry(graph); })); - } - - var action = function(graph) { - var geometries = groupEntitiesByGeometry(graph), - target = geometries.area[0] || geometries.line[0], - points = geometries.point; - - points.forEach(function(point) { - target = target.mergeTags(point.tags); - - graph.parentRelations(point).forEach(function(parent) { - graph = graph.replace(parent.replaceMember(point, target)); - }); - - graph = graph.remove(point); - }); - - graph = graph.replace(target); - - return graph; - }; - - action.disabled = function(graph) { - var geometries = groupEntitiesByGeometry(graph); - if (geometries.point.length === 0 || - (geometries.area.length + geometries.line.length) !== 1 || - geometries.relation.length !== 0) - return 'not_eligible'; - }; - - return action; -}; - -},{}],22:[function(require,module,exports){ -module.exports = function(ids, newRelationId) { - - function groupEntities(graph) { - var entities = ids.map(function (id) { return graph.entity(id); }); - return _.extend({ - closedWay: [], - multipolygon: [], - other: [] - }, _.groupBy(entities, function(entity) { - if (entity.type === 'way' && entity.isClosed()) { - return 'closedWay'; - } else if (entity.type === 'relation' && entity.isMultipolygon()) { - return 'multipolygon'; - } else { - return 'other'; - } - })); - } - - var action = function(graph) { - var entities = groupEntities(graph); - - // An array representing all the polygons that are part of the multipolygon. - // - // Each element is itself an array of objects with an id property, and has a - // locs property which is an array of the locations forming the polygon. - var polygons = entities.multipolygon.reduce(function(polygons, m) { - return polygons.concat(iD.geo.joinWays(m.members, graph)); - }, []).concat(entities.closedWay.map(function(d) { - var member = [{id: d.id}]; - member.nodes = graph.childNodes(d); - return member; - })); - - // contained is an array of arrays of boolean values, - // where contained[j][k] is true iff the jth way is - // contained by the kth way. - var contained = polygons.map(function(w, i) { - return polygons.map(function(d, n) { - if (i === n) return null; - return iD.geo.polygonContainsPolygon( - _.map(d.nodes, 'loc'), - _.map(w.nodes, 'loc')); - }); - }); - - // Sort all polygons as either outer or inner ways - var members = [], - outer = true; - - while (polygons.length) { - extractUncontained(polygons); - polygons = polygons.filter(isContained); - contained = contained.filter(isContained).map(filterContained); - } - - function isContained(d, i) { - return _.some(contained[i]); - } - - function filterContained(d) { - return d.filter(isContained); - } - - function extractUncontained(polygons) { - polygons.forEach(function(d, i) { - if (!isContained(d, i)) { - d.forEach(function(member) { - members.push({ - type: 'way', - id: member.id, - role: outer ? 'outer' : 'inner' - }); - }); - } - }); - outer = !outer; - } - - // Move all tags to one relation - var relation = entities.multipolygon[0] || - iD.Relation({ id: newRelationId, tags: { type: 'multipolygon' }}); - - entities.multipolygon.slice(1).forEach(function(m) { - relation = relation.mergeTags(m.tags); - graph = graph.remove(m); - }); - - entities.closedWay.forEach(function(way) { - function isThisOuter(m) { - return m.id === way.id && m.role !== 'inner'; - } - if (members.some(isThisOuter)) { - relation = relation.mergeTags(way.tags); - graph = graph.replace(way.update({ tags: {} })); - } - }); - - return graph.replace(relation.update({ - members: members, - tags: _.omit(relation.tags, 'area') - })); - }; - - action.disabled = function(graph) { - var entities = groupEntities(graph); - if (entities.other.length > 0 || - entities.closedWay.length + entities.multipolygon.length < 2) - return 'not_eligible'; - if (!entities.multipolygon.every(function(r) { return r.isComplete(graph); })) - return 'incomplete_relation'; - }; - - return action; -}; - -},{}],23:[function(require,module,exports){ -module.exports = function(id, localGraph, remoteGraph, formatUser) { - var option = 'safe', // 'safe', 'force_local', 'force_remote' - conflicts = []; - - function user(d) { - return _.isFunction(formatUser) ? formatUser(d) : d; - } - - - function mergeLocation(remote, target) { - function pointEqual(a, b) { - var epsilon = 1e-6; - return (Math.abs(a[0] - b[0]) < epsilon) && (Math.abs(a[1] - b[1]) < epsilon); - } - - if (option === 'force_local' || pointEqual(target.loc, remote.loc)) { - return target; - } - if (option === 'force_remote') { - return target.update({loc: remote.loc}); - } - - conflicts.push(t('merge_remote_changes.conflict.location', { user: user(remote.user) })); - return target; - } - - - function mergeNodes(base, remote, target) { - if (option === 'force_local' || _.isEqual(target.nodes, remote.nodes)) { - return target; - } - if (option === 'force_remote') { - return target.update({nodes: remote.nodes}); - } - - var ccount = conflicts.length, - o = base.nodes || [], - a = target.nodes || [], - b = remote.nodes || [], - nodes = [], - hunks = Diff3.diff3_merge(a, o, b, true); - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i]; - if (hunk.ok) { - nodes.push.apply(nodes, hunk.ok); - } else { - // for all conflicts, we can assume c.a !== c.b - // because `diff3_merge` called with `true` option to exclude false conflicts.. - var c = hunk.conflict; - if (_.isEqual(c.o, c.a)) { // only changed remotely - nodes.push.apply(nodes, c.b); - } else if (_.isEqual(c.o, c.b)) { // only changed locally - nodes.push.apply(nodes, c.a); - } else { // changed both locally and remotely - conflicts.push(t('merge_remote_changes.conflict.nodelist', { user: user(remote.user) })); - break; - } - } - } - - return (conflicts.length === ccount) ? target.update({nodes: nodes}) : target; - } - - - function mergeChildren(targetWay, children, updates, graph) { - function isUsed(node, targetWay) { - var parentWays = _.map(graph.parentWays(node), 'id'); - return node.hasInterestingTags() || - _.without(parentWays, targetWay.id).length > 0 || - graph.parentRelations(node).length > 0; - } - - var ccount = conflicts.length; - - for (var i = 0; i < children.length; i++) { - var id = children[i], - node = graph.hasEntity(id); - - // remove unused childNodes.. - if (targetWay.nodes.indexOf(id) === -1) { - if (node && !isUsed(node, targetWay)) { - updates.removeIds.push(id); - } - continue; - } - - // restore used childNodes.. - var local = localGraph.hasEntity(id), - remote = remoteGraph.hasEntity(id), - target; - - if (option === 'force_remote' && remote && remote.visible) { - updates.replacements.push(remote); - - } else if (option === 'force_local' && local) { - target = iD.Entity(local); - if (remote) { - target = target.update({ version: remote.version }); - } - updates.replacements.push(target); - - } else if (option === 'safe' && local && remote && local.version !== remote.version) { - target = iD.Entity(local, { version: remote.version }); - if (remote.visible) { - target = mergeLocation(remote, target); - } else { - conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) })); - } - - if (conflicts.length !== ccount) break; - updates.replacements.push(target); - } - } - - return targetWay; - } - - - function updateChildren(updates, graph) { - for (var i = 0; i < updates.replacements.length; i++) { - graph = graph.replace(updates.replacements[i]); - } - if (updates.removeIds.length) { - graph = iD.actions.DeleteMultiple(updates.removeIds)(graph); - } - return graph; - } - - - function mergeMembers(remote, target) { - if (option === 'force_local' || _.isEqual(target.members, remote.members)) { - return target; - } - if (option === 'force_remote') { - return target.update({members: remote.members}); - } - - conflicts.push(t('merge_remote_changes.conflict.memberlist', { user: user(remote.user) })); - return target; - } - - - function mergeTags(base, remote, target) { - function ignoreKey(k) { - return _.includes(iD.data.discarded, k); - } - - if (option === 'force_local' || _.isEqual(target.tags, remote.tags)) { - return target; - } - if (option === 'force_remote') { - return target.update({tags: remote.tags}); - } - - var ccount = conflicts.length, - o = base.tags || {}, - a = target.tags || {}, - b = remote.tags || {}, - keys = _.reject(_.union(_.keys(o), _.keys(a), _.keys(b)), ignoreKey), - tags = _.clone(a), - changed = false; - - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - - if (o[k] !== b[k] && a[k] !== b[k]) { // changed remotely.. - if (o[k] !== a[k]) { // changed locally.. - conflicts.push(t('merge_remote_changes.conflict.tags', - { tag: k, local: a[k], remote: b[k], user: user(remote.user) })); - - } else { // unchanged locally, accept remote change.. - if (b.hasOwnProperty(k)) { - tags[k] = b[k]; - } else { - delete tags[k]; - } - changed = true; - } - } - } - - return (changed && conflicts.length === ccount) ? target.update({tags: tags}) : target; - } - - - // `graph.base()` is the common ancestor of the two graphs. - // `localGraph` contains user's edits up to saving - // `remoteGraph` contains remote edits to modified nodes - // `graph` must be a descendent of `localGraph` and may include - // some conflict resolution actions performed on it. - // - // --- ... --- `localGraph` -- ... -- `graph` - // / - // `graph.base()` --- ... --- `remoteGraph` - // - var action = function(graph) { - var updates = { replacements: [], removeIds: [] }, - base = graph.base().entities[id], - local = localGraph.entity(id), - remote = remoteGraph.entity(id), - target = iD.Entity(local, { version: remote.version }); - - // delete/undelete - if (!remote.visible) { - if (option === 'force_remote') { - return iD.actions.DeleteMultiple([id])(graph); - - } else if (option === 'force_local') { - if (target.type === 'way') { - target = mergeChildren(target, _.uniq(local.nodes), updates, graph); - graph = updateChildren(updates, graph); - } - return graph.replace(target); - - } else { - conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) })); - return graph; // do nothing - } - } - - // merge - if (target.type === 'node') { - target = mergeLocation(remote, target); - - } else if (target.type === 'way') { - // pull in any child nodes that may not be present locally.. - graph.rebase(remoteGraph.childNodes(remote), [graph], false); - target = mergeNodes(base, remote, target); - target = mergeChildren(target, _.union(local.nodes, remote.nodes), updates, graph); - - } else if (target.type === 'relation') { - target = mergeMembers(remote, target); - } - - target = mergeTags(base, remote, target); - - if (!conflicts.length) { - graph = updateChildren(updates, graph).replace(target); - } - - return graph; - }; - - action.withOption = function(opt) { - option = opt; - return action; - }; - - action.conflicts = function() { - return conflicts; - }; - - return action; -}; - -},{}],24:[function(require,module,exports){ -// https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/command/MoveCommand.java -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MoveNodeAction.as -module.exports = function(moveIds, tryDelta, projection, cache) { - var delta = tryDelta; - - function vecAdd(a, b) { return [a[0] + b[0], a[1] + b[1]]; } - function vecSub(a, b) { return [a[0] - b[0], a[1] - b[1]]; } - - function setupCache(graph) { - function canMove(nodeId) { - var parents = _.map(graph.parentWays(graph.entity(nodeId)), 'id'); - if (parents.length < 3) return true; - - // Don't move a vertex where >2 ways meet, unless all parentWays are moving too.. - var parentsMoving = _.all(parents, function(id) { return cache.moving[id]; }); - if (!parentsMoving) delete cache.moving[nodeId]; - - return parentsMoving; - } - - function cacheEntities(ids) { - _.each(ids, function(id) { - if (cache.moving[id]) return; - cache.moving[id] = true; - - var entity = graph.hasEntity(id); - if (!entity) return; - - if (entity.type === 'node') { - cache.nodes.push(id); - cache.startLoc[id] = entity.loc; - } else if (entity.type === 'way') { - cache.ways.push(id); - cacheEntities(entity.nodes); - } else { - cacheEntities(_.map(entity.members, 'id')); - } - }); - } - - function cacheIntersections(ids) { - function isEndpoint(way, id) { return !way.isClosed() && !!way.affix(id); } - - _.each(ids, function(id) { - // consider only intersections with 1 moved and 1 unmoved way. - _.each(graph.childNodes(graph.entity(id)), function(node) { - var parents = graph.parentWays(node); - if (parents.length !== 2) return; - - var moved = graph.entity(id), - unmoved = _.find(parents, function(way) { return !cache.moving[way.id]; }); - if (!unmoved) return; - - // exclude ways that are overly connected.. - if (_.intersection(moved.nodes, unmoved.nodes).length > 2) return; - - if (moved.isArea() || unmoved.isArea()) return; - - cache.intersection[node.id] = { - nodeId: node.id, - movedId: moved.id, - unmovedId: unmoved.id, - movedIsEP: isEndpoint(moved, node.id), - unmovedIsEP: isEndpoint(unmoved, node.id) - }; - }); - }); - } - - - if (!cache) { - cache = {}; - } - if (!cache.ok) { - cache.moving = {}; - cache.intersection = {}; - cache.replacedVertex = {}; - cache.startLoc = {}; - cache.nodes = []; - cache.ways = []; - - cacheEntities(moveIds); - cacheIntersections(cache.ways); - cache.nodes = _.filter(cache.nodes, canMove); - - cache.ok = true; - } - } - - - // Place a vertex where the moved vertex used to be, to preserve way shape.. - function replaceMovedVertex(nodeId, wayId, graph, delta) { - var way = graph.entity(wayId), - moved = graph.entity(nodeId), - movedIndex = way.nodes.indexOf(nodeId), - len, prevIndex, nextIndex; - - if (way.isClosed()) { - len = way.nodes.length - 1; - prevIndex = (movedIndex + len - 1) % len; - nextIndex = (movedIndex + len + 1) % len; - } else { - len = way.nodes.length; - prevIndex = movedIndex - 1; - nextIndex = movedIndex + 1; - } - - var prev = graph.hasEntity(way.nodes[prevIndex]), - next = graph.hasEntity(way.nodes[nextIndex]); - - // Don't add orig vertex at endpoint.. - if (!prev || !next) return graph; - - var key = wayId + '_' + nodeId, - orig = cache.replacedVertex[key]; - if (!orig) { - orig = iD.Node(); - cache.replacedVertex[key] = orig; - cache.startLoc[orig.id] = cache.startLoc[nodeId]; - } - - var start, end; - if (delta) { - start = projection(cache.startLoc[nodeId]); - end = projection.invert(vecAdd(start, delta)); - } else { - end = cache.startLoc[nodeId]; - } - orig = orig.move(end); - - var angle = Math.abs(iD.geo.angle(orig, prev, projection) - - iD.geo.angle(orig, next, projection)) * 180 / Math.PI; - - // Don't add orig vertex if it would just make a straight line.. - if (angle > 175 && angle < 185) return graph; - - // Don't add orig vertex if another point is already nearby (within 10m) - if (iD.geo.sphericalDistance(prev.loc, orig.loc) < 10 || - iD.geo.sphericalDistance(orig.loc, next.loc) < 10) return graph; - - // moving forward or backward along way? - var p1 = [prev.loc, orig.loc, moved.loc, next.loc].map(projection), - p2 = [prev.loc, moved.loc, orig.loc, next.loc].map(projection), - d1 = iD.geo.pathLength(p1), - d2 = iD.geo.pathLength(p2), - insertAt = (d1 < d2) ? movedIndex : nextIndex; - - // moving around closed loop? - if (way.isClosed() && insertAt === 0) insertAt = len; - - way = way.addNode(orig.id, insertAt); - return graph.replace(orig).replace(way); - } - - // Reorder nodes around intersections that have moved.. - function unZorroIntersection(intersection, graph) { - var vertex = graph.entity(intersection.nodeId), - way1 = graph.entity(intersection.movedId), - way2 = graph.entity(intersection.unmovedId), - isEP1 = intersection.movedIsEP, - isEP2 = intersection.unmovedIsEP; - - // don't move the vertex if it is the endpoint of both ways. - if (isEP1 && isEP2) return graph; - - var nodes1 = _.without(graph.childNodes(way1), vertex), - nodes2 = _.without(graph.childNodes(way2), vertex); - - if (way1.isClosed() && way1.first() === vertex.id) nodes1.push(nodes1[0]); - if (way2.isClosed() && way2.first() === vertex.id) nodes2.push(nodes2[0]); - - var edge1 = !isEP1 && iD.geo.chooseEdge(nodes1, projection(vertex.loc), projection), - edge2 = !isEP2 && iD.geo.chooseEdge(nodes2, projection(vertex.loc), projection), - loc; - - // snap vertex to nearest edge (or some point between them).. - if (!isEP1 && !isEP2) { - var epsilon = 1e-4, maxIter = 10; - for (var i = 0; i < maxIter; i++) { - loc = iD.geo.interp(edge1.loc, edge2.loc, 0.5); - edge1 = iD.geo.chooseEdge(nodes1, projection(loc), projection); - edge2 = iD.geo.chooseEdge(nodes2, projection(loc), projection); - if (Math.abs(edge1.distance - edge2.distance) < epsilon) break; - } - } else if (!isEP1) { - loc = edge1.loc; - } else { - loc = edge2.loc; - } - - graph = graph.replace(vertex.move(loc)); - - // if zorro happened, reorder nodes.. - if (!isEP1 && edge1.index !== way1.nodes.indexOf(vertex.id)) { - way1 = way1.removeNode(vertex.id).addNode(vertex.id, edge1.index); - graph = graph.replace(way1); - } - if (!isEP2 && edge2.index !== way2.nodes.indexOf(vertex.id)) { - way2 = way2.removeNode(vertex.id).addNode(vertex.id, edge2.index); - graph = graph.replace(way2); - } - - return graph; - } - - - function cleanupIntersections(graph) { - _.each(cache.intersection, function(obj) { - graph = replaceMovedVertex(obj.nodeId, obj.movedId, graph, delta); - graph = replaceMovedVertex(obj.nodeId, obj.unmovedId, graph, null); - graph = unZorroIntersection(obj, graph); - }); - - return graph; - } - - // check if moving way endpoint can cross an unmoved way, if so limit delta.. - function limitDelta(graph) { - _.each(cache.intersection, function(obj) { - if (!obj.movedIsEP) return; - - var node = graph.entity(obj.nodeId), - start = projection(node.loc), - end = vecAdd(start, delta), - movedNodes = graph.childNodes(graph.entity(obj.movedId)), - movedPath = _.map(_.map(movedNodes, 'loc'), - function(loc) { return vecAdd(projection(loc), delta); }), - unmovedNodes = graph.childNodes(graph.entity(obj.unmovedId)), - unmovedPath = _.map(_.map(unmovedNodes, 'loc'), projection), - hits = iD.geo.pathIntersections(movedPath, unmovedPath); - - for (var i = 0; i < hits.length; i++) { - if (_.isEqual(hits[i], end)) continue; - var edge = iD.geo.chooseEdge(unmovedNodes, end, projection); - delta = vecSub(projection(edge.loc), start); - } - }); - } - - - var action = function(graph) { - if (delta[0] === 0 && delta[1] === 0) return graph; - - setupCache(graph); - - if (!_.isEmpty(cache.intersection)) { - limitDelta(graph); - } - - _.each(cache.nodes, function(id) { - var node = graph.entity(id), - start = projection(node.loc), - end = vecAdd(start, delta); - graph = graph.replace(node.move(projection.invert(end))); - }); - - if (!_.isEmpty(cache.intersection)) { - graph = cleanupIntersections(graph); - } - - return graph; - }; - - action.disabled = function(graph) { - function incompleteRelation(id) { - var entity = graph.entity(id); - return entity.type === 'relation' && !entity.isComplete(graph); - } - - if (_.some(moveIds, incompleteRelation)) - return 'incomplete_relation'; - }; - - action.delta = function() { - return delta; - }; - - return action; -}; - -},{}],25:[function(require,module,exports){ -// https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/command/MoveCommand.java -// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MoveNodeAction.as -module.exports = function(nodeId, loc) { - return function(graph) { - return graph.replace(graph.entity(nodeId).move(loc)); - }; -}; - -},{}],26:[function(require,module,exports){ -module.exports = function() { - return function(graph) { - return graph; - }; -}; - -},{}],27:[function(require,module,exports){ -/* - * Based on https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/potlatch2/tools/Quadrilateralise.as - */ - -module.exports = function(wayId, projection) { - var threshold = 12, // degrees within right or straight to alter - lowerThreshold = Math.cos((90 - threshold) * Math.PI / 180), - upperThreshold = Math.cos(threshold * Math.PI / 180); - - var action = function(graph) { - var way = graph.entity(wayId), - nodes = graph.childNodes(way), - points = _.uniq(nodes).map(function(n) { return projection(n.loc); }), - corner = {i: 0, dotp: 1}, - epsilon = 1e-4, - i, j, score, motions; - - if (nodes.length === 4) { - for (i = 0; i < 1000; i++) { - motions = points.map(calcMotion); - points[corner.i] = addPoints(points[corner.i],motions[corner.i]); - score = corner.dotp; - if (score < epsilon) { - break; - } - } - - graph = graph.replace(graph.entity(nodes[corner.i].id) - .move(projection.invert(points[corner.i]))); - } else { - var best, - originalPoints = _.clone(points); - score = Infinity; - - for (i = 0; i < 1000; i++) { - motions = points.map(calcMotion); - for (j = 0; j < motions.length; j++) { - points[j] = addPoints(points[j],motions[j]); - } - var newScore = squareness(points); - if (newScore < score) { - best = _.clone(points); - score = newScore; - } - if (score < epsilon) { - break; - } - } - - points = best; - - for (i = 0; i < points.length; i++) { - // only move the points that actually moved - if (originalPoints[i][0] !== points[i][0] || originalPoints[i][1] !== points[i][1]) { - graph = graph.replace(graph.entity(nodes[i].id) - .move(projection.invert(points[i]))); - } - } - - // remove empty nodes on straight sections - for (i = 0; i < points.length; i++) { - var node = nodes[i]; - - if (graph.parentWays(node).length > 1 || - graph.parentRelations(node).length || - node.hasInterestingTags()) { - - continue; - } - - var dotp = normalizedDotProduct(i, points); - if (dotp < -1 + epsilon) { - graph = iD.actions.DeleteNode(nodes[i].id)(graph); - } - } - } - - return graph; - - function calcMotion(b, i, array) { - var a = array[(i - 1 + array.length) % array.length], - c = array[(i + 1) % array.length], - p = subtractPoints(a, b), - q = subtractPoints(c, b), - scale, dotp; - - scale = 2 * Math.min(iD.geo.euclideanDistance(p, [0, 0]), iD.geo.euclideanDistance(q, [0, 0])); - p = normalizePoint(p, 1.0); - q = normalizePoint(q, 1.0); - - dotp = filterDotProduct(p[0] * q[0] + p[1] * q[1]); - - // nasty hack to deal with almost-straight segments (angle is closer to 180 than to 90/270). - if (array.length > 3) { - if (dotp < -0.707106781186547) { - dotp += 1.0; - } - } else if (dotp && Math.abs(dotp) < corner.dotp) { - corner.i = i; - corner.dotp = Math.abs(dotp); - } - - return normalizePoint(addPoints(p, q), 0.1 * dotp * scale); - } - }; - - function squareness(points) { - return points.reduce(function(sum, val, i, array) { - var dotp = normalizedDotProduct(i, array); - - dotp = filterDotProduct(dotp); - return sum + 2.0 * Math.min(Math.abs(dotp - 1.0), Math.min(Math.abs(dotp), Math.abs(dotp + 1))); - }, 0); - } - - function normalizedDotProduct(i, points) { - var a = points[(i - 1 + points.length) % points.length], - b = points[i], - c = points[(i + 1) % points.length], - p = subtractPoints(a, b), - q = subtractPoints(c, b); - - p = normalizePoint(p, 1.0); - q = normalizePoint(q, 1.0); - - return p[0] * q[0] + p[1] * q[1]; - } - - function subtractPoints(a, b) { - return [a[0] - b[0], a[1] - b[1]]; - } - - function addPoints(a, b) { - return [a[0] + b[0], a[1] + b[1]]; - } - - function normalizePoint(point, scale) { - var vector = [0, 0]; - var length = Math.sqrt(point[0] * point[0] + point[1] * point[1]); - if (length !== 0) { - vector[0] = point[0] / length; - vector[1] = point[1] / length; - } - - vector[0] *= scale; - vector[1] *= scale; - - return vector; - } - - function filterDotProduct(dotp) { - if (lowerThreshold > Math.abs(dotp) || Math.abs(dotp) > upperThreshold) { - return dotp; - } - - return 0; - } - - action.disabled = function(graph) { - var way = graph.entity(wayId), - nodes = graph.childNodes(way), - points = _.uniq(nodes).map(function(n) { return projection(n.loc); }); - - if (squareness(points)) { - return false; - } - - return 'not_squarish'; - }; - - return action; -}; - -},{}],28:[function(require,module,exports){ -// Create a restriction relation for `turn`, which must have the following structure: -// -// { -// from: { node: , way: }, -// via: { node: }, -// to: { node: , way: }, -// restriction: <'no_right_turn', 'no_left_turn', etc.> -// } -// -// This specifies a restriction of type `restriction` when traveling from -// `from.node` in `from.way` toward `to.node` in `to.way` via `via.node`. -// (The action does not check that these entities form a valid intersection.) -// -// If `restriction` is not provided, it is automatically determined by -// iD.geo.inferRestriction. -// -// If necessary, the `from` and `to` ways are split. In these cases, `from.node` -// and `to.node` are used to determine which portion of the split ways become -// members of the restriction. -// -// For testing convenience, accepts an ID to assign to the new relation. -// Normally, this will be undefined and the relation will automatically -// be assigned a new ID. -// -module.exports = function(turn, projection, restrictionId) { - return function(graph) { - var from = graph.entity(turn.from.way), - via = graph.entity(turn.via.node), - to = graph.entity(turn.to.way); - - function isClosingNode(way, nodeId) { - return nodeId === way.first() && nodeId === way.last(); - } - - function split(toOrFrom) { - var newID = toOrFrom.newID || iD.Way().id; - graph = iD.actions.Split(via.id, [newID]) - .limitWays([toOrFrom.way])(graph); - - var a = graph.entity(newID), - b = graph.entity(toOrFrom.way); - - if (a.nodes.indexOf(toOrFrom.node) !== -1) { - return [a, b]; - } else { - return [b, a]; - } - } - - if (!from.affix(via.id) || isClosingNode(from, via.id)) { - if (turn.from.node === turn.to.node) { - // U-turn - from = to = split(turn.from)[0]; - } else if (turn.from.way === turn.to.way) { - // Straight-on or circular - var s = split(turn.from); - from = s[0]; - to = s[1]; - } else { - // Other - from = split(turn.from)[0]; - } - } - - if (!to.affix(via.id) || isClosingNode(to, via.id)) { - to = split(turn.to)[0]; - } - - return graph.replace(iD.Relation({ - id: restrictionId, - tags: { - type: 'restriction', - restriction: turn.restriction || - iD.geo.inferRestriction( - graph, - turn.from, - turn.via, - turn.to, - projection) - }, - members: [ - {id: from.id, type: 'way', role: 'from'}, - {id: via.id, type: 'node', role: 'via'}, - {id: to.id, type: 'way', role: 'to'} - ] - })); - }; -}; - -},{}],29:[function(require,module,exports){ -/* - Order the nodes of a way in reverse order and reverse any direction dependent tags - other than `oneway`. (We assume that correcting a backwards oneway is the primary - reason for reversing a way.) - - The following transforms are performed: - - Keys: - *:right=* ⟺ *:left=* - *:forward=* ⟺ *:backward=* - direction=up ⟺ direction=down - incline=up ⟺ incline=down - *=right ⟺ *=left - - Relation members: - role=forward ⟺ role=backward - role=north ⟺ role=south - role=east ⟺ role=west - - In addition, numeric-valued `incline` tags are negated. - - The JOSM implementation was used as a guide, but transformations that were of unclear benefit - or adjusted tags that don't seem to be used in practice were omitted. - - References: - http://wiki.openstreetmap.org/wiki/Forward_%26_backward,_left_%26_right - http://wiki.openstreetmap.org/wiki/Key:direction#Steps - http://wiki.openstreetmap.org/wiki/Key:incline - http://wiki.openstreetmap.org/wiki/Route#Members - http://josm.openstreetmap.de/browser/josm/trunk/src/org/openstreetmap/josm/corrector/ReverseWayTagCorrector.java - */ -module.exports = function(wayId, options) { - var replacements = [ - [/:right$/, ':left'], [/:left$/, ':right'], - [/:forward$/, ':backward'], [/:backward$/, ':forward'] - ], - numeric = /^([+\-]?)(?=[\d.])/, - roleReversals = { - forward: 'backward', - backward: 'forward', - north: 'south', - south: 'north', - east: 'west', - west: 'east' - }; - - function reverseKey(key) { - for (var i = 0; i < replacements.length; ++i) { - var replacement = replacements[i]; - if (replacement[0].test(key)) { - return key.replace(replacement[0], replacement[1]); - } - } - return key; - } - - function reverseValue(key, value) { - if (key === 'incline' && numeric.test(value)) { - return value.replace(numeric, function(_, sign) { return sign === '-' ? '' : '-'; }); - } else if (key === 'incline' || key === 'direction') { - return {up: 'down', down: 'up'}[value] || value; - } else if (options && options.reverseOneway && key === 'oneway') { - return {yes: '-1', '1': '-1', '-1': 'yes'}[value] || value; - } else { - return {left: 'right', right: 'left'}[value] || value; - } - } - - return function(graph) { - var way = graph.entity(wayId), - nodes = way.nodes.slice().reverse(), - tags = {}, key, role; - - for (key in way.tags) { - tags[reverseKey(key)] = reverseValue(key, way.tags[key]); - } - - graph.parentRelations(way).forEach(function(relation) { - relation.members.forEach(function(member, index) { - if (member.id === way.id && (role = roleReversals[member.role])) { - relation = relation.updateMember({role: role}, index); - graph = graph.replace(relation); - } - }); - }); - - return graph.replace(way.update({nodes: nodes, tags: tags})); - }; -}; - -},{}],30:[function(require,module,exports){ -module.exports = function(id) { - - var action = function(graph) { - var entity = graph.hasEntity(id), - base = graph.base().entities[id]; - - if (entity && !base) { // entity will be removed.. - if (entity.type === 'node') { - graph.parentWays(entity) - .forEach(function(parent) { - parent = parent.removeNode(id); - graph = graph.replace(parent); - - if (parent.isDegenerate()) { - graph = iD.actions.DeleteWay(parent.id)(graph); - } - }); - } - - graph.parentRelations(entity) - .forEach(function(parent) { - parent = parent.removeMembersWithID(id); - graph = graph.replace(parent); - - if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); - } - }); - } - - return graph.revert(id); - }; - - return action; -}; - -},{}],31:[function(require,module,exports){ -module.exports = function(wayId, pivot, angle, projection) { - return function(graph) { - return graph.update(function(graph) { - var way = graph.entity(wayId); - - _.uniq(way.nodes).forEach(function(id) { - - var node = graph.entity(id), - point = projection(node.loc), - radial = [0,0]; - - radial[0] = point[0] - pivot[0]; - radial[1] = point[1] - pivot[1]; - - point = [ - radial[0] * Math.cos(angle) - radial[1] * Math.sin(angle) + pivot[0], - radial[0] * Math.sin(angle) + radial[1] * Math.cos(angle) + pivot[1] - ]; - - graph = graph.replace(node.move(projection.invert(point))); - - }); - - }); - }; -}; - -},{}],32:[function(require,module,exports){ -// Split a way at the given node. -// -// Optionally, split only the given ways, if multiple ways share -// the given node. -// -// This is the inverse of `iD.actions.Join`. -// -// For testing convenience, accepts an ID to assign to the new way. -// Normally, this will be undefined and the way will automatically -// be assigned a new ID. -// -// Reference: -// https://github.com/systemed/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/SplitWayAction.as -// -module.exports = function(nodeId, newWayIds) { - var wayIds; - - // if the way is closed, we need to search for a partner node - // to split the way at. - // - // The following looks for a node that is both far away from - // the initial node in terms of way segment length and nearby - // in terms of beeline-distance. This assures that areas get - // split on the most "natural" points (independent of the number - // of nodes). - // For example: bone-shaped areas get split across their waist - // line, circles across the diameter. - function splitArea(nodes, idxA, graph) { - var lengths = new Array(nodes.length), - length, - i, - best = 0, - idxB; - - function wrap(index) { - return iD.util.wrap(index, nodes.length); - } - - function dist(nA, nB) { - return iD.geo.sphericalDistance(graph.entity(nA).loc, graph.entity(nB).loc); - } - - // calculate lengths - length = 0; - for (i = wrap(idxA+1); i !== idxA; i = wrap(i+1)) { - length += dist(nodes[i], nodes[wrap(i-1)]); - lengths[i] = length; - } - - length = 0; - for (i = wrap(idxA-1); i !== idxA; i = wrap(i-1)) { - length += dist(nodes[i], nodes[wrap(i+1)]); - if (length < lengths[i]) - lengths[i] = length; - } - - // determine best opposite node to split - for (i = 0; i < nodes.length; i++) { - var cost = lengths[i] / dist(nodes[idxA], nodes[i]); - if (cost > best) { - idxB = i; - best = cost; - } - } - - return idxB; - } - - function split(graph, wayA, newWayId) { - var wayB = iD.Way({id: newWayId, tags: wayA.tags}), - nodesA, - nodesB, - isArea = wayA.isArea(), - isOuter = iD.geo.isSimpleMultipolygonOuterMember(wayA, graph); - - if (wayA.isClosed()) { - var nodes = wayA.nodes.slice(0, -1), - idxA = _.indexOf(nodes, nodeId), - idxB = splitArea(nodes, idxA, graph); - - if (idxB < idxA) { - nodesA = nodes.slice(idxA).concat(nodes.slice(0, idxB + 1)); - nodesB = nodes.slice(idxB, idxA + 1); - } else { - nodesA = nodes.slice(idxA, idxB + 1); - nodesB = nodes.slice(idxB).concat(nodes.slice(0, idxA + 1)); - } - } else { - var idx = _.indexOf(wayA.nodes, nodeId, 1); - nodesA = wayA.nodes.slice(0, idx + 1); - nodesB = wayA.nodes.slice(idx); - } - - wayA = wayA.update({nodes: nodesA}); - wayB = wayB.update({nodes: nodesB}); - - graph = graph.replace(wayA); - graph = graph.replace(wayB); - - graph.parentRelations(wayA).forEach(function(relation) { - if (relation.isRestriction()) { - var via = relation.memberByRole('via'); - if (via && wayB.contains(via.id)) { - relation = relation.updateMember({id: wayB.id}, relation.memberById(wayA.id).index); - graph = graph.replace(relation); - } - } else { - if (relation === isOuter) { - graph = graph.replace(relation.mergeTags(wayA.tags)); - graph = graph.replace(wayA.update({tags: {}})); - graph = graph.replace(wayB.update({tags: {}})); - } - - var member = { - id: wayB.id, - type: 'way', - role: relation.memberById(wayA.id).role - }; - - graph = iD.actions.AddMember(relation.id, member)(graph); - } - }); - - if (!isOuter && isArea) { - var multipolygon = iD.Relation({ - tags: _.extend({}, wayA.tags, {type: 'multipolygon'}), - members: [ - {id: wayA.id, role: 'outer', type: 'way'}, - {id: wayB.id, role: 'outer', type: 'way'} - ]}); - - graph = graph.replace(multipolygon); - graph = graph.replace(wayA.update({tags: {}})); - graph = graph.replace(wayB.update({tags: {}})); - } - - return graph; - } - - var action = function(graph) { - var candidates = action.ways(graph); - for (var i = 0; i < candidates.length; i++) { - graph = split(graph, candidates[i], newWayIds && newWayIds[i]); - } - return graph; - }; - - action.ways = function(graph) { - var node = graph.entity(nodeId), - parents = graph.parentWays(node), - hasLines = _.some(parents, function(parent) { return parent.geometry(graph) === 'line'; }); - - return parents.filter(function(parent) { - if (wayIds && wayIds.indexOf(parent.id) === -1) - return false; - - if (!wayIds && hasLines && parent.geometry(graph) !== 'line') - return false; - - if (parent.isClosed()) { - return true; - } - - for (var i = 1; i < parent.nodes.length - 1; i++) { - if (parent.nodes[i] === nodeId) { - return true; - } - } - - return false; - }); - }; - - action.disabled = function(graph) { - var candidates = action.ways(graph); - if (candidates.length === 0 || (wayIds && wayIds.length !== candidates.length)) - return 'not_eligible'; - }; - - action.limitWays = function(_) { - if (!arguments.length) return wayIds; - wayIds = _; - return action; - }; - - return action; -}; - -},{}],33:[function(require,module,exports){ -/* - * Based on https://github.com/openstreetmap/potlatch2/net/systemeD/potlatch2/tools/Straighten.as - */ - -module.exports = function(wayId, projection) { - function positionAlongWay(n, s, e) { - return ((n[0] - s[0]) * (e[0] - s[0]) + (n[1] - s[1]) * (e[1] - s[1]))/ - (Math.pow(e[0] - s[0], 2) + Math.pow(e[1] - s[1], 2)); - } - - var action = function(graph) { - var way = graph.entity(wayId), - nodes = graph.childNodes(way), - points = nodes.map(function(n) { return projection(n.loc); }), - startPoint = points[0], - endPoint = points[points.length-1], - toDelete = [], - i; - - for (i = 1; i < points.length-1; i++) { - var node = nodes[i], - point = points[i]; - - if (graph.parentWays(node).length > 1 || - graph.parentRelations(node).length || - node.hasInterestingTags()) { - - var u = positionAlongWay(point, startPoint, endPoint), - p0 = startPoint[0] + u * (endPoint[0] - startPoint[0]), - p1 = startPoint[1] + u * (endPoint[1] - startPoint[1]); - - graph = graph.replace(graph.entity(node.id) - .move(projection.invert([p0, p1]))); - } else { - // safe to delete - if (toDelete.indexOf(node) === -1) { - toDelete.push(node); - } - } - } - - for (i = 0; i < toDelete.length; i++) { - graph = iD.actions.DeleteNode(toDelete[i].id)(graph); - } - - return graph; - }; - - action.disabled = function(graph) { - // check way isn't too bendy - var way = graph.entity(wayId), - nodes = graph.childNodes(way), - points = nodes.map(function(n) { return projection(n.loc); }), - startPoint = points[0], - endPoint = points[points.length-1], - threshold = 0.2 * Math.sqrt(Math.pow(startPoint[0] - endPoint[0], 2) + Math.pow(startPoint[1] - endPoint[1], 2)), - i; - - if (threshold === 0) { - return 'too_bendy'; - } - - for (i = 1; i < points.length-1; i++) { - var point = points[i], - u = positionAlongWay(point, startPoint, endPoint), - p0 = startPoint[0] + u * (endPoint[0] - startPoint[0]), - p1 = startPoint[1] + u * (endPoint[1] - startPoint[1]), - dist = Math.sqrt(Math.pow(p0 - point[0], 2) + Math.pow(p1 - point[1], 2)); - - // to bendy if point is off by 20% of total start/end distance in projected space - if (isNaN(dist) || dist > threshold) { - return 'too_bendy'; - } - } - }; - - return action; -}; - -},{}],34:[function(require,module,exports){ -// Remove the effects of `turn.restriction` on `turn`, which must have the -// following structure: -// -// { -// from: { node: , way: }, -// via: { node: }, -// to: { node: , way: }, -// restriction: -// } -// -// In the simple case, `restriction` is a reference to a `no_*` restriction -// on the turn itself. In this case, it is simply deleted. -// -// The more complex case is where `restriction` references an `only_*` -// restriction on a different turn in the same intersection. In that case, -// that restriction is also deleted, but at the same time restrictions on -// the turns other than the first two are created. -// -module.exports = function(turn) { - return function(graph) { - return iD.actions.DeleteRelation(turn.restriction)(graph); - }; -}; - -},{}]},{},[19])(19) -}); \ No newline at end of file +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.iD = global.iD || {}, global.iD.actions = global.iD.actions || {}))); +}(this, function (exports) { 'use strict'; + + function AddEntity(way) { + return function(graph) { + return graph.replace(way); + }; + }; + + function AddMember(relationId, member, memberIndex) { + return function(graph) { + var relation = graph.entity(relationId); + + if (isNaN(memberIndex) && member.type === 'way') { + var members = relation.indexedMembers(); + members.push(member); + + var joined = iD.geo.joinWays(members, graph); + for (var i = 0; i < joined.length; i++) { + var segment = joined[i]; + for (var j = 0; j < segment.length && segment.length >= 2; j++) { + if (segment[j] !== member) + continue; + + if (j === 0) { + memberIndex = segment[j + 1].index; + } else if (j === segment.length - 1) { + memberIndex = segment[j - 1].index + 1; + } else { + memberIndex = Math.min(segment[j - 1].index + 1, segment[j + 1].index + 1); + } + } + } + } + + return graph.replace(relation.addMember(member, memberIndex)); + }; + }; + + function AddMidpoint(midpoint, node) { + return function(graph) { + graph = graph.replace(node.move(midpoint.loc)); + + var parents = _.intersection( + graph.parentWays(graph.entity(midpoint.edge[0])), + graph.parentWays(graph.entity(midpoint.edge[1]))); + + parents.forEach(function(way) { + for (var i = 0; i < way.nodes.length - 1; i++) { + if (iD.geo.edgeEqual([way.nodes[i], way.nodes[i + 1]], midpoint.edge)) { + graph = graph.replace(graph.entity(way.id).addNode(node.id, i + 1)); + + // Add only one midpoint on doubled-back segments, + // turning them into self-intersections. + return; + } + } + }); + + return graph; + }; + }; + + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/AddNodeToWayAction.as + function AddVertex(wayId, nodeId, index) { + return function(graph) { + return graph.replace(graph.entity(wayId).addNode(nodeId, index)); + }; + }; + + function ChangeMember(relationId, member, memberIndex) { + return function(graph) { + return graph.replace(graph.entity(relationId).updateMember(member, memberIndex)); + }; + }; + + function ChangePreset(entityId, oldPreset, newPreset) { + return function(graph) { + var entity = graph.entity(entityId), + geometry = entity.geometry(graph), + tags = entity.tags; + + if (oldPreset) tags = oldPreset.removeTags(tags, geometry); + if (newPreset) tags = newPreset.applyTags(tags, geometry); + + return graph.replace(entity.update({tags: tags})); + }; + }; + + function ChangeTags(entityId, tags) { + return function(graph) { + var entity = graph.entity(entityId); + return graph.replace(entity.update({tags: tags})); + }; + }; + + function Circularize(wayId, projection, maxAngle) { + maxAngle = (maxAngle || 20) * Math.PI / 180; + + var action = function(graph) { + var way = graph.entity(wayId); + + if (!way.isConvex(graph)) { + graph = action.makeConvex(graph); + } + + var nodes = _.uniq(graph.childNodes(way)), + keyNodes = nodes.filter(function(n) { return graph.parentWays(n).length !== 1; }), + points = nodes.map(function(n) { return projection(n.loc); }), + keyPoints = keyNodes.map(function(n) { return projection(n.loc); }), + centroid = (points.length === 2) ? iD.geo.interp(points[0], points[1], 0.5) : d3.geom.polygon(points).centroid(), + radius = d3.median(points, function(p) { return iD.geo.euclideanDistance(centroid, p); }), + sign = d3.geom.polygon(points).area() > 0 ? 1 : -1, + ids; + + // we need atleast two key nodes for the algorithm to work + if (!keyNodes.length) { + keyNodes = [nodes[0]]; + keyPoints = [points[0]]; + } + + if (keyNodes.length === 1) { + var index = nodes.indexOf(keyNodes[0]), + oppositeIndex = Math.floor((index + nodes.length / 2) % nodes.length); + + keyNodes.push(nodes[oppositeIndex]); + keyPoints.push(points[oppositeIndex]); + } + + // key points and nodes are those connected to the ways, + // they are projected onto the circle, inbetween nodes are moved + // to constant intervals between key nodes, extra inbetween nodes are + // added if necessary. + for (var i = 0; i < keyPoints.length; i++) { + var nextKeyNodeIndex = (i + 1) % keyNodes.length, + startNode = keyNodes[i], + endNode = keyNodes[nextKeyNodeIndex], + startNodeIndex = nodes.indexOf(startNode), + endNodeIndex = nodes.indexOf(endNode), + numberNewPoints = -1, + indexRange = endNodeIndex - startNodeIndex, + distance, totalAngle, eachAngle, startAngle, endAngle, + angle, loc, node, j, + inBetweenNodes = []; + + if (indexRange < 0) { + indexRange += nodes.length; + } + + // position this key node + distance = iD.geo.euclideanDistance(centroid, keyPoints[i]); + if (distance === 0) { distance = 1e-4; } + keyPoints[i] = [ + centroid[0] + (keyPoints[i][0] - centroid[0]) / distance * radius, + centroid[1] + (keyPoints[i][1] - centroid[1]) / distance * radius]; + graph = graph.replace(keyNodes[i].move(projection.invert(keyPoints[i]))); + + // figure out the between delta angle we want to match to + startAngle = Math.atan2(keyPoints[i][1] - centroid[1], keyPoints[i][0] - centroid[0]); + endAngle = Math.atan2(keyPoints[nextKeyNodeIndex][1] - centroid[1], keyPoints[nextKeyNodeIndex][0] - centroid[0]); + totalAngle = endAngle - startAngle; + + // detects looping around -pi/pi + if (totalAngle * sign > 0) { + totalAngle = -sign * (2 * Math.PI - Math.abs(totalAngle)); + } + + do { + numberNewPoints++; + eachAngle = totalAngle / (indexRange + numberNewPoints); + } while (Math.abs(eachAngle) > maxAngle); + + // move existing points + for (j = 1; j < indexRange; j++) { + angle = startAngle + j * eachAngle; + loc = projection.invert([ + centroid[0] + Math.cos(angle)*radius, + centroid[1] + Math.sin(angle)*radius]); + + node = nodes[(j + startNodeIndex) % nodes.length].move(loc); + graph = graph.replace(node); + } + + // add new inbetween nodes if necessary + for (j = 0; j < numberNewPoints; j++) { + angle = startAngle + (indexRange + j) * eachAngle; + loc = projection.invert([ + centroid[0] + Math.cos(angle) * radius, + centroid[1] + Math.sin(angle) * radius]); + + node = iD.Node({loc: loc}); + graph = graph.replace(node); + + nodes.splice(endNodeIndex + j, 0, node); + inBetweenNodes.push(node.id); + } + + // Check for other ways that share these keyNodes.. + // If keyNodes are adjacent in both ways, + // we can add inBetween nodes to that shared way too.. + if (indexRange === 1 && inBetweenNodes.length) { + var startIndex1 = way.nodes.lastIndexOf(startNode.id), + endIndex1 = way.nodes.lastIndexOf(endNode.id), + wayDirection1 = (endIndex1 - startIndex1); + if (wayDirection1 < -1) { wayDirection1 = 1; } + + /* eslint-disable no-loop-func */ + _.each(_.without(graph.parentWays(keyNodes[i]), way), function(sharedWay) { + if (sharedWay.areAdjacent(startNode.id, endNode.id)) { + var startIndex2 = sharedWay.nodes.lastIndexOf(startNode.id), + endIndex2 = sharedWay.nodes.lastIndexOf(endNode.id), + wayDirection2 = (endIndex2 - startIndex2), + insertAt = endIndex2; + if (wayDirection2 < -1) { wayDirection2 = 1; } + + if (wayDirection1 !== wayDirection2) { + inBetweenNodes.reverse(); + insertAt = startIndex2; + } + for (j = 0; j < inBetweenNodes.length; j++) { + sharedWay = sharedWay.addNode(inBetweenNodes[j], insertAt + j); + } + graph = graph.replace(sharedWay); + } + }); + /* eslint-enable no-loop-func */ + } + + } + + // update the way to have all the new nodes + ids = nodes.map(function(n) { return n.id; }); + ids.push(ids[0]); + + way = way.update({nodes: ids}); + graph = graph.replace(way); + + return graph; + }; + + action.makeConvex = function(graph) { + var way = graph.entity(wayId), + nodes = _.uniq(graph.childNodes(way)), + points = nodes.map(function(n) { return projection(n.loc); }), + sign = d3.geom.polygon(points).area() > 0 ? 1 : -1, + hull = d3.geom.hull(points); + + // D3 convex hulls go counterclockwise.. + if (sign === -1) { + nodes.reverse(); + points.reverse(); + } + + for (var i = 0; i < hull.length - 1; i++) { + var startIndex = points.indexOf(hull[i]), + endIndex = points.indexOf(hull[i+1]), + indexRange = (endIndex - startIndex); + + if (indexRange < 0) { + indexRange += nodes.length; + } + + // move interior nodes to the surface of the convex hull.. + for (var j = 1; j < indexRange; j++) { + var point = iD.geo.interp(hull[i], hull[i+1], j / indexRange), + node = nodes[(j + startIndex) % nodes.length].move(projection.invert(point)); + graph = graph.replace(node); + } + } + return graph; + }; + + action.disabled = function(graph) { + if (!graph.entity(wayId).isClosed()) + return 'not_closed'; + }; + + return action; + }; + + function DeleteMultiple(ids) { + var actions = { + way: DeleteWay, + node: DeleteNode, + relation: DeleteRelation + }; + + var action = function(graph) { + ids.forEach(function(id) { + if (graph.hasEntity(id)) { // It may have been deleted aready. + graph = actions[graph.entity(id).type](id)(graph); + } + }); + + return graph; + }; + + action.disabled = function(graph) { + for (var i = 0; i < ids.length; i++) { + var id = ids[i], + disabled = actions[graph.entity(id).type](id).disabled(graph); + if (disabled) return disabled; + } + }; + + return action; + }; + + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteRelationAction.as + function DeleteRelation(relationId) { + function deleteEntity(entity, graph) { + return !graph.parentWays(entity).length && + !graph.parentRelations(entity).length && + !entity.hasInterestingTags(); + } + + var action = function(graph) { + var relation = graph.entity(relationId); + + graph.parentRelations(relation) + .forEach(function(parent) { + parent = parent.removeMembersWithID(relationId); + graph = graph.replace(parent); + + if (parent.isDegenerate()) { + graph = DeleteRelation(parent.id)(graph); + } + }); + + _.uniq(_.map(relation.members, 'id')).forEach(function(memberId) { + graph = graph.replace(relation.removeMembersWithID(memberId)); + + var entity = graph.entity(memberId); + if (deleteEntity(entity, graph)) { + graph = DeleteMultiple([memberId])(graph); + } + }); + + return graph.remove(relation); + }; + + action.disabled = function(graph) { + if (!graph.entity(relationId).isComplete(graph)) + return 'incomplete_relation'; + }; + + return action; + } + + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteWayAction.as + function DeleteWay(wayId) { + function deleteNode(node, graph) { + return !graph.parentWays(node).length && + !graph.parentRelations(node).length && + !node.hasInterestingTags(); + } + + var action = function(graph) { + var way = graph.entity(wayId); + + graph.parentRelations(way) + .forEach(function(parent) { + parent = parent.removeMembersWithID(wayId); + graph = graph.replace(parent); + + if (parent.isDegenerate()) { + graph = DeleteRelation(parent.id)(graph); + } + }); + + _.uniq(way.nodes).forEach(function(nodeId) { + graph = graph.replace(way.removeNode(nodeId)); + + var node = graph.entity(nodeId); + if (deleteNode(node, graph)) { + graph = graph.remove(node); + } + }); + + return graph.remove(way); + }; + + action.disabled = function(graph) { + var disabled = false; + + graph.parentRelations(graph.entity(wayId)).forEach(function(parent) { + var type = parent.tags.type, + role = parent.memberById(wayId).role || 'outer'; + if (type === 'route' || type === 'boundary' || (type === 'multipolygon' && role === 'outer')) { + disabled = 'part_of_relation'; + } + }); + + return disabled; + }; + + return action; + }; + + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteNodeAction.as + function DeleteNode(nodeId) { + var action = function(graph) { + var node = graph.entity(nodeId); + + graph.parentWays(node) + .forEach(function(parent) { + parent = parent.removeNode(nodeId); + graph = graph.replace(parent); + + if (parent.isDegenerate()) { + graph = DeleteWay(parent.id)(graph); + } + }); + + graph.parentRelations(node) + .forEach(function(parent) { + parent = parent.removeMembersWithID(nodeId); + graph = graph.replace(parent); + + if (parent.isDegenerate()) { + graph = DeleteRelation(parent.id)(graph); + } + }); + + return graph.remove(node); + }; + + action.disabled = function() { + return false; + }; + + return action; + }; + + // Connect the ways at the given nodes. + // + // The last node will survive. All other nodes will be replaced with + // the surviving node in parent ways, and then removed. + // + // Tags and relation memberships of of non-surviving nodes are merged + // to the survivor. + // + // This is the inverse of `iD.actions.Disconnect`. + // + // Reference: + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MergeNodesAction.as + // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/MergeNodesAction.java + // + function Connect(nodeIds) { + return function(graph) { + var survivor = graph.entity(_.last(nodeIds)); + + for (var i = 0; i < nodeIds.length - 1; i++) { + var node = graph.entity(nodeIds[i]); + + /* eslint-disable no-loop-func */ + graph.parentWays(node).forEach(function(parent) { + if (!parent.areAdjacent(node.id, survivor.id)) { + graph = graph.replace(parent.replaceNode(node.id, survivor.id)); + } + }); + + graph.parentRelations(node).forEach(function(parent) { + graph = graph.replace(parent.replaceMember(node, survivor)); + }); + /* eslint-enable no-loop-func */ + + survivor = survivor.mergeTags(node.tags); + graph = DeleteNode(node.id)(graph); + } + + graph = graph.replace(survivor); + + return graph; + }; + }; + + function CopyEntities(ids, fromGraph) { + var copies = {}; + + var action = function(graph) { + ids.forEach(function(id) { + fromGraph.entity(id).copy(fromGraph, copies); + }); + + for (var id in copies) { + graph = graph.replace(copies[id]); + } + + return graph; + }; + + action.copies = function() { + return copies; + }; + + return action; + }; + + function DeleteMember(relationId, memberIndex) { + return function(graph) { + var relation = graph.entity(relationId) + .removeMember(memberIndex); + + graph = graph.replace(relation); + + if (relation.isDegenerate()) + graph = DeleteRelation(relation.id)(graph); + + return graph; + }; + }; + + function DeprecateTags(entityId) { + return function(graph) { + var entity = graph.entity(entityId), + newtags = _.clone(entity.tags), + change = false, + rule; + + // This handles deprecated tags with a single condition + for (var i = 0; i < iD.data.deprecated.length; i++) { + + rule = iD.data.deprecated[i]; + var match = _.toPairs(rule.old)[0], + replacements = rule.replace ? _.toPairs(rule.replace) : null; + + if (entity.tags[match[0]] && match[1] === '*') { + + var value = entity.tags[match[0]]; + if (replacements && !newtags[replacements[0][0]]) { + newtags[replacements[0][0]] = value; + } + delete newtags[match[0]]; + change = true; + + } else if (entity.tags[match[0]] === match[1]) { + newtags = _.assign({}, rule.replace || {}, _.omit(newtags, match[0])); + change = true; + } + } + + if (change) { + return graph.replace(entity.update({tags: newtags})); + } else { + return graph; + } + }; + } + + function DiscardTags(difference) { + return function(graph) { + function discardTags(entity) { + if (!_.isEmpty(entity.tags)) { + var tags = {}; + _.each(entity.tags, function(v, k) { + if (v) tags[k] = v; + }); + + graph = graph.replace(entity.update({ + tags: _.omit(tags, iD.data.discarded) + })); + } + } + + difference.modified().forEach(discardTags); + difference.created().forEach(discardTags); + + return graph; + }; + } + + // Disconect the ways at the given node. + // + // Optionally, disconnect only the given ways. + // + // For testing convenience, accepts an ID to assign to the (first) new node. + // Normally, this will be undefined and the way will automatically + // be assigned a new ID. + // + // This is the inverse of `iD.actions.Connect`. + // + // Reference: + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/UnjoinNodeAction.as + // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/UnGlueAction.java + // + function Disconnect(nodeId, newNodeId) { + var wayIds; + + var action = function(graph) { + var node = graph.entity(nodeId), + connections = action.connections(graph); + + connections.forEach(function(connection) { + var way = graph.entity(connection.wayID), + newNode = iD.Node({id: newNodeId, loc: node.loc, tags: node.tags}); + + graph = graph.replace(newNode); + if (connection.index === 0 && way.isArea()) { + // replace shared node with shared node.. + graph = graph.replace(way.replaceNode(way.nodes[0], newNode.id)); + } else { + // replace shared node with multiple new nodes.. + graph = graph.replace(way.updateNode(newNode.id, connection.index)); + } + }); + + return graph; + }; + + action.connections = function(graph) { + var candidates = [], + keeping = false, + parentWays = graph.parentWays(graph.entity(nodeId)); + + parentWays.forEach(function(way) { + if (wayIds && wayIds.indexOf(way.id) === -1) { + keeping = true; + return; + } + if (way.isArea() && (way.nodes[0] === nodeId)) { + candidates.push({wayID: way.id, index: 0}); + } else { + way.nodes.forEach(function(waynode, index) { + if (waynode === nodeId) { + candidates.push({wayID: way.id, index: index}); + } + }); + } + }); + + return keeping ? candidates : candidates.slice(1); + }; + + action.disabled = function(graph) { + var connections = action.connections(graph); + if (connections.length === 0 || (wayIds && wayIds.length !== connections.length)) + return 'not_connected'; + + var parentWays = graph.parentWays(graph.entity(nodeId)), + seenRelationIds = {}, + sharedRelation; + + parentWays.forEach(function(way) { + if (wayIds && wayIds.indexOf(way.id) === -1) + return; + + var relations = graph.parentRelations(way); + relations.forEach(function(relation) { + if (relation.id in seenRelationIds) { + sharedRelation = relation; + } else { + seenRelationIds[relation.id] = true; + } + }); + }); + + if (sharedRelation) + return 'relation'; + }; + + action.limitWays = function(_) { + if (!arguments.length) return wayIds; + wayIds = _; + return action; + }; + + return action; + } + + // Join ways at the end node they share. + // + // This is the inverse of `iD.actions.Split`. + // + // Reference: + // https://github.com/systemed/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MergeWaysAction.as + // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/CombineWayAction.java + // + function Join(ids) { + + function groupEntitiesByGeometry(graph) { + var entities = ids.map(function(id) { return graph.entity(id); }); + return _.extend({line: []}, _.groupBy(entities, function(entity) { return entity.geometry(graph); })); + } + + var action = function(graph) { + var ways = ids.map(graph.entity, graph), + survivor = ways[0]; + + // Prefer to keep an existing way. + for (var i = 0; i < ways.length; i++) { + if (!ways[i].isNew()) { + survivor = ways[i]; + break; + } + } + + var joined = iD.geo.joinWays(ways, graph)[0]; + + survivor = survivor.update({nodes: _.map(joined.nodes, 'id')}); + graph = graph.replace(survivor); + + joined.forEach(function(way) { + if (way.id === survivor.id) + return; + + graph.parentRelations(way).forEach(function(parent) { + graph = graph.replace(parent.replaceMember(way, survivor)); + }); + + survivor = survivor.mergeTags(way.tags); + + graph = graph.replace(survivor); + graph = DeleteWay(way.id)(graph); + }); + + return graph; + }; + + action.disabled = function(graph) { + var geometries = groupEntitiesByGeometry(graph); + if (ids.length < 2 || ids.length !== geometries.line.length) + return 'not_eligible'; + + var joined = iD.geo.joinWays(ids.map(graph.entity, graph), graph); + if (joined.length > 1) + return 'not_adjacent'; + + var nodeIds = _.map(joined[0].nodes, 'id').slice(1, -1), + relation, + tags = {}, + conflicting = false; + + joined[0].forEach(function(way) { + var parents = graph.parentRelations(way); + parents.forEach(function(parent) { + if (parent.isRestriction() && parent.members.some(function(m) { return nodeIds.indexOf(m.id) >= 0; })) + relation = parent; + }); + + for (var k in way.tags) { + if (!(k in tags)) { + tags[k] = way.tags[k]; + } else if (tags[k] && iD.interestingTag(k) && tags[k] !== way.tags[k]) { + conflicting = true; + } + } + }); + + if (relation) + return 'restriction'; + + if (conflicting) + return 'conflicting_tags'; + }; + + return action; + } + + function Merge(ids) { + function groupEntitiesByGeometry(graph) { + var entities = ids.map(function(id) { return graph.entity(id); }); + return _.extend({point: [], area: [], line: [], relation: []}, + _.groupBy(entities, function(entity) { return entity.geometry(graph); })); + } + + var action = function(graph) { + var geometries = groupEntitiesByGeometry(graph), + target = geometries.area[0] || geometries.line[0], + points = geometries.point; + + points.forEach(function(point) { + target = target.mergeTags(point.tags); + + graph.parentRelations(point).forEach(function(parent) { + graph = graph.replace(parent.replaceMember(point, target)); + }); + + graph = graph.remove(point); + }); + + graph = graph.replace(target); + + return graph; + }; + + action.disabled = function(graph) { + var geometries = groupEntitiesByGeometry(graph); + if (geometries.point.length === 0 || + (geometries.area.length + geometries.line.length) !== 1 || + geometries.relation.length !== 0) + return 'not_eligible'; + }; + + return action; + } + + function MergePolygon(ids, newRelationId) { + + function groupEntities(graph) { + var entities = ids.map(function (id) { return graph.entity(id); }); + return _.extend({ + closedWay: [], + multipolygon: [], + other: [] + }, _.groupBy(entities, function(entity) { + if (entity.type === 'way' && entity.isClosed()) { + return 'closedWay'; + } else if (entity.type === 'relation' && entity.isMultipolygon()) { + return 'multipolygon'; + } else { + return 'other'; + } + })); + } + + var action = function(graph) { + var entities = groupEntities(graph); + + // An array representing all the polygons that are part of the multipolygon. + // + // Each element is itself an array of objects with an id property, and has a + // locs property which is an array of the locations forming the polygon. + var polygons = entities.multipolygon.reduce(function(polygons, m) { + return polygons.concat(iD.geo.joinWays(m.members, graph)); + }, []).concat(entities.closedWay.map(function(d) { + var member = [{id: d.id}]; + member.nodes = graph.childNodes(d); + return member; + })); + + // contained is an array of arrays of boolean values, + // where contained[j][k] is true iff the jth way is + // contained by the kth way. + var contained = polygons.map(function(w, i) { + return polygons.map(function(d, n) { + if (i === n) return null; + return iD.geo.polygonContainsPolygon( + _.map(d.nodes, 'loc'), + _.map(w.nodes, 'loc')); + }); + }); + + // Sort all polygons as either outer or inner ways + var members = [], + outer = true; + + while (polygons.length) { + extractUncontained(polygons); + polygons = polygons.filter(isContained); + contained = contained.filter(isContained).map(filterContained); + } + + function isContained(d, i) { + return _.some(contained[i]); + } + + function filterContained(d) { + return d.filter(isContained); + } + + function extractUncontained(polygons) { + polygons.forEach(function(d, i) { + if (!isContained(d, i)) { + d.forEach(function(member) { + members.push({ + type: 'way', + id: member.id, + role: outer ? 'outer' : 'inner' + }); + }); + } + }); + outer = !outer; + } + + // Move all tags to one relation + var relation = entities.multipolygon[0] || + iD.Relation({ id: newRelationId, tags: { type: 'multipolygon' }}); + + entities.multipolygon.slice(1).forEach(function(m) { + relation = relation.mergeTags(m.tags); + graph = graph.remove(m); + }); + + entities.closedWay.forEach(function(way) { + function isThisOuter(m) { + return m.id === way.id && m.role !== 'inner'; + } + if (members.some(isThisOuter)) { + relation = relation.mergeTags(way.tags); + graph = graph.replace(way.update({ tags: {} })); + } + }); + + return graph.replace(relation.update({ + members: members, + tags: _.omit(relation.tags, 'area') + })); + }; + + action.disabled = function(graph) { + var entities = groupEntities(graph); + if (entities.other.length > 0 || + entities.closedWay.length + entities.multipolygon.length < 2) + return 'not_eligible'; + if (!entities.multipolygon.every(function(r) { return r.isComplete(graph); })) + return 'incomplete_relation'; + }; + + return action; + } + + function MergeRemoteChanges(id, localGraph, remoteGraph, formatUser) { + var option = 'safe', // 'safe', 'force_local', 'force_remote' + conflicts = []; + + function user(d) { + return _.isFunction(formatUser) ? formatUser(d) : d; + } + + + function mergeLocation(remote, target) { + function pointEqual(a, b) { + var epsilon = 1e-6; + return (Math.abs(a[0] - b[0]) < epsilon) && (Math.abs(a[1] - b[1]) < epsilon); + } + + if (option === 'force_local' || pointEqual(target.loc, remote.loc)) { + return target; + } + if (option === 'force_remote') { + return target.update({loc: remote.loc}); + } + + conflicts.push(t('merge_remote_changes.conflict.location', { user: user(remote.user) })); + return target; + } + + + function mergeNodes(base, remote, target) { + if (option === 'force_local' || _.isEqual(target.nodes, remote.nodes)) { + return target; + } + if (option === 'force_remote') { + return target.update({nodes: remote.nodes}); + } + + var ccount = conflicts.length, + o = base.nodes || [], + a = target.nodes || [], + b = remote.nodes || [], + nodes = [], + hunks = Diff3.diff3_merge(a, o, b, true); + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i]; + if (hunk.ok) { + nodes.push.apply(nodes, hunk.ok); + } else { + // for all conflicts, we can assume c.a !== c.b + // because `diff3_merge` called with `true` option to exclude false conflicts.. + var c = hunk.conflict; + if (_.isEqual(c.o, c.a)) { // only changed remotely + nodes.push.apply(nodes, c.b); + } else if (_.isEqual(c.o, c.b)) { // only changed locally + nodes.push.apply(nodes, c.a); + } else { // changed both locally and remotely + conflicts.push(t('merge_remote_changes.conflict.nodelist', { user: user(remote.user) })); + break; + } + } + } + + return (conflicts.length === ccount) ? target.update({nodes: nodes}) : target; + } + + + function mergeChildren(targetWay, children, updates, graph) { + function isUsed(node, targetWay) { + var parentWays = _.map(graph.parentWays(node), 'id'); + return node.hasInterestingTags() || + _.without(parentWays, targetWay.id).length > 0 || + graph.parentRelations(node).length > 0; + } + + var ccount = conflicts.length; + + for (var i = 0; i < children.length; i++) { + var id = children[i], + node = graph.hasEntity(id); + + // remove unused childNodes.. + if (targetWay.nodes.indexOf(id) === -1) { + if (node && !isUsed(node, targetWay)) { + updates.removeIds.push(id); + } + continue; + } + + // restore used childNodes.. + var local = localGraph.hasEntity(id), + remote = remoteGraph.hasEntity(id), + target; + + if (option === 'force_remote' && remote && remote.visible) { + updates.replacements.push(remote); + + } else if (option === 'force_local' && local) { + target = iD.Entity(local); + if (remote) { + target = target.update({ version: remote.version }); + } + updates.replacements.push(target); + + } else if (option === 'safe' && local && remote && local.version !== remote.version) { + target = iD.Entity(local, { version: remote.version }); + if (remote.visible) { + target = mergeLocation(remote, target); + } else { + conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) })); + } + + if (conflicts.length !== ccount) break; + updates.replacements.push(target); + } + } + + return targetWay; + } + + + function updateChildren(updates, graph) { + for (var i = 0; i < updates.replacements.length; i++) { + graph = graph.replace(updates.replacements[i]); + } + if (updates.removeIds.length) { + graph = DeleteMultiple(updates.removeIds)(graph); + } + return graph; + } + + + function mergeMembers(remote, target) { + if (option === 'force_local' || _.isEqual(target.members, remote.members)) { + return target; + } + if (option === 'force_remote') { + return target.update({members: remote.members}); + } + + conflicts.push(t('merge_remote_changes.conflict.memberlist', { user: user(remote.user) })); + return target; + } + + + function mergeTags(base, remote, target) { + function ignoreKey(k) { + return _.includes(iD.data.discarded, k); + } + + if (option === 'force_local' || _.isEqual(target.tags, remote.tags)) { + return target; + } + if (option === 'force_remote') { + return target.update({tags: remote.tags}); + } + + var ccount = conflicts.length, + o = base.tags || {}, + a = target.tags || {}, + b = remote.tags || {}, + keys = _.reject(_.union(_.keys(o), _.keys(a), _.keys(b)), ignoreKey), + tags = _.clone(a), + changed = false; + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + + if (o[k] !== b[k] && a[k] !== b[k]) { // changed remotely.. + if (o[k] !== a[k]) { // changed locally.. + conflicts.push(t('merge_remote_changes.conflict.tags', + { tag: k, local: a[k], remote: b[k], user: user(remote.user) })); + + } else { // unchanged locally, accept remote change.. + if (b.hasOwnProperty(k)) { + tags[k] = b[k]; + } else { + delete tags[k]; + } + changed = true; + } + } + } + + return (changed && conflicts.length === ccount) ? target.update({tags: tags}) : target; + } + + + // `graph.base()` is the common ancestor of the two graphs. + // `localGraph` contains user's edits up to saving + // `remoteGraph` contains remote edits to modified nodes + // `graph` must be a descendent of `localGraph` and may include + // some conflict resolution actions performed on it. + // + // --- ... --- `localGraph` -- ... -- `graph` + // / + // `graph.base()` --- ... --- `remoteGraph` + // + var action = function(graph) { + var updates = { replacements: [], removeIds: [] }, + base = graph.base().entities[id], + local = localGraph.entity(id), + remote = remoteGraph.entity(id), + target = iD.Entity(local, { version: remote.version }); + + // delete/undelete + if (!remote.visible) { + if (option === 'force_remote') { + return DeleteMultiple([id])(graph); + + } else if (option === 'force_local') { + if (target.type === 'way') { + target = mergeChildren(target, _.uniq(local.nodes), updates, graph); + graph = updateChildren(updates, graph); + } + return graph.replace(target); + + } else { + conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) })); + return graph; // do nothing + } + } + + // merge + if (target.type === 'node') { + target = mergeLocation(remote, target); + + } else if (target.type === 'way') { + // pull in any child nodes that may not be present locally.. + graph.rebase(remoteGraph.childNodes(remote), [graph], false); + target = mergeNodes(base, remote, target); + target = mergeChildren(target, _.union(local.nodes, remote.nodes), updates, graph); + + } else if (target.type === 'relation') { + target = mergeMembers(remote, target); + } + + target = mergeTags(base, remote, target); + + if (!conflicts.length) { + graph = updateChildren(updates, graph).replace(target); + } + + return graph; + }; + + action.withOption = function(opt) { + option = opt; + return action; + }; + + action.conflicts = function() { + return conflicts; + }; + + return action; + }; + + // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/command/MoveCommand.java + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MoveNodeAction.as + function Move(moveIds, tryDelta, projection, cache) { + var delta = tryDelta; + + function vecAdd(a, b) { return [a[0] + b[0], a[1] + b[1]]; } + function vecSub(a, b) { return [a[0] - b[0], a[1] - b[1]]; } + + function setupCache(graph) { + function canMove(nodeId) { + var parents = _.map(graph.parentWays(graph.entity(nodeId)), 'id'); + if (parents.length < 3) return true; + + // Don't move a vertex where >2 ways meet, unless all parentWays are moving too.. + var parentsMoving = _.all(parents, function(id) { return cache.moving[id]; }); + if (!parentsMoving) delete cache.moving[nodeId]; + + return parentsMoving; + } + + function cacheEntities(ids) { + _.each(ids, function(id) { + if (cache.moving[id]) return; + cache.moving[id] = true; + + var entity = graph.hasEntity(id); + if (!entity) return; + + if (entity.type === 'node') { + cache.nodes.push(id); + cache.startLoc[id] = entity.loc; + } else if (entity.type === 'way') { + cache.ways.push(id); + cacheEntities(entity.nodes); + } else { + cacheEntities(_.map(entity.members, 'id')); + } + }); + } + + function cacheIntersections(ids) { + function isEndpoint(way, id) { return !way.isClosed() && !!way.affix(id); } + + _.each(ids, function(id) { + // consider only intersections with 1 moved and 1 unmoved way. + _.each(graph.childNodes(graph.entity(id)), function(node) { + var parents = graph.parentWays(node); + if (parents.length !== 2) return; + + var moved = graph.entity(id), + unmoved = _.find(parents, function(way) { return !cache.moving[way.id]; }); + if (!unmoved) return; + + // exclude ways that are overly connected.. + if (_.intersection(moved.nodes, unmoved.nodes).length > 2) return; + + if (moved.isArea() || unmoved.isArea()) return; + + cache.intersection[node.id] = { + nodeId: node.id, + movedId: moved.id, + unmovedId: unmoved.id, + movedIsEP: isEndpoint(moved, node.id), + unmovedIsEP: isEndpoint(unmoved, node.id) + }; + }); + }); + } + + + if (!cache) { + cache = {}; + } + if (!cache.ok) { + cache.moving = {}; + cache.intersection = {}; + cache.replacedVertex = {}; + cache.startLoc = {}; + cache.nodes = []; + cache.ways = []; + + cacheEntities(moveIds); + cacheIntersections(cache.ways); + cache.nodes = _.filter(cache.nodes, canMove); + + cache.ok = true; + } + } + + + // Place a vertex where the moved vertex used to be, to preserve way shape.. + function replaceMovedVertex(nodeId, wayId, graph, delta) { + var way = graph.entity(wayId), + moved = graph.entity(nodeId), + movedIndex = way.nodes.indexOf(nodeId), + len, prevIndex, nextIndex; + + if (way.isClosed()) { + len = way.nodes.length - 1; + prevIndex = (movedIndex + len - 1) % len; + nextIndex = (movedIndex + len + 1) % len; + } else { + len = way.nodes.length; + prevIndex = movedIndex - 1; + nextIndex = movedIndex + 1; + } + + var prev = graph.hasEntity(way.nodes[prevIndex]), + next = graph.hasEntity(way.nodes[nextIndex]); + + // Don't add orig vertex at endpoint.. + if (!prev || !next) return graph; + + var key = wayId + '_' + nodeId, + orig = cache.replacedVertex[key]; + if (!orig) { + orig = iD.Node(); + cache.replacedVertex[key] = orig; + cache.startLoc[orig.id] = cache.startLoc[nodeId]; + } + + var start, end; + if (delta) { + start = projection(cache.startLoc[nodeId]); + end = projection.invert(vecAdd(start, delta)); + } else { + end = cache.startLoc[nodeId]; + } + orig = orig.move(end); + + var angle = Math.abs(iD.geo.angle(orig, prev, projection) - + iD.geo.angle(orig, next, projection)) * 180 / Math.PI; + + // Don't add orig vertex if it would just make a straight line.. + if (angle > 175 && angle < 185) return graph; + + // Don't add orig vertex if another point is already nearby (within 10m) + if (iD.geo.sphericalDistance(prev.loc, orig.loc) < 10 || + iD.geo.sphericalDistance(orig.loc, next.loc) < 10) return graph; + + // moving forward or backward along way? + var p1 = [prev.loc, orig.loc, moved.loc, next.loc].map(projection), + p2 = [prev.loc, moved.loc, orig.loc, next.loc].map(projection), + d1 = iD.geo.pathLength(p1), + d2 = iD.geo.pathLength(p2), + insertAt = (d1 < d2) ? movedIndex : nextIndex; + + // moving around closed loop? + if (way.isClosed() && insertAt === 0) insertAt = len; + + way = way.addNode(orig.id, insertAt); + return graph.replace(orig).replace(way); + } + + // Reorder nodes around intersections that have moved.. + function unZorroIntersection(intersection, graph) { + var vertex = graph.entity(intersection.nodeId), + way1 = graph.entity(intersection.movedId), + way2 = graph.entity(intersection.unmovedId), + isEP1 = intersection.movedIsEP, + isEP2 = intersection.unmovedIsEP; + + // don't move the vertex if it is the endpoint of both ways. + if (isEP1 && isEP2) return graph; + + var nodes1 = _.without(graph.childNodes(way1), vertex), + nodes2 = _.without(graph.childNodes(way2), vertex); + + if (way1.isClosed() && way1.first() === vertex.id) nodes1.push(nodes1[0]); + if (way2.isClosed() && way2.first() === vertex.id) nodes2.push(nodes2[0]); + + var edge1 = !isEP1 && iD.geo.chooseEdge(nodes1, projection(vertex.loc), projection), + edge2 = !isEP2 && iD.geo.chooseEdge(nodes2, projection(vertex.loc), projection), + loc; + + // snap vertex to nearest edge (or some point between them).. + if (!isEP1 && !isEP2) { + var epsilon = 1e-4, maxIter = 10; + for (var i = 0; i < maxIter; i++) { + loc = iD.geo.interp(edge1.loc, edge2.loc, 0.5); + edge1 = iD.geo.chooseEdge(nodes1, projection(loc), projection); + edge2 = iD.geo.chooseEdge(nodes2, projection(loc), projection); + if (Math.abs(edge1.distance - edge2.distance) < epsilon) break; + } + } else if (!isEP1) { + loc = edge1.loc; + } else { + loc = edge2.loc; + } + + graph = graph.replace(vertex.move(loc)); + + // if zorro happened, reorder nodes.. + if (!isEP1 && edge1.index !== way1.nodes.indexOf(vertex.id)) { + way1 = way1.removeNode(vertex.id).addNode(vertex.id, edge1.index); + graph = graph.replace(way1); + } + if (!isEP2 && edge2.index !== way2.nodes.indexOf(vertex.id)) { + way2 = way2.removeNode(vertex.id).addNode(vertex.id, edge2.index); + graph = graph.replace(way2); + } + + return graph; + } + + + function cleanupIntersections(graph) { + _.each(cache.intersection, function(obj) { + graph = replaceMovedVertex(obj.nodeId, obj.movedId, graph, delta); + graph = replaceMovedVertex(obj.nodeId, obj.unmovedId, graph, null); + graph = unZorroIntersection(obj, graph); + }); + + return graph; + } + + // check if moving way endpoint can cross an unmoved way, if so limit delta.. + function limitDelta(graph) { + _.each(cache.intersection, function(obj) { + if (!obj.movedIsEP) return; + + var node = graph.entity(obj.nodeId), + start = projection(node.loc), + end = vecAdd(start, delta), + movedNodes = graph.childNodes(graph.entity(obj.movedId)), + movedPath = _.map(_.map(movedNodes, 'loc'), + function(loc) { return vecAdd(projection(loc), delta); }), + unmovedNodes = graph.childNodes(graph.entity(obj.unmovedId)), + unmovedPath = _.map(_.map(unmovedNodes, 'loc'), projection), + hits = iD.geo.pathIntersections(movedPath, unmovedPath); + + for (var i = 0; i < hits.length; i++) { + if (_.isEqual(hits[i], end)) continue; + var edge = iD.geo.chooseEdge(unmovedNodes, end, projection); + delta = vecSub(projection(edge.loc), start); + } + }); + } + + + var action = function(graph) { + if (delta[0] === 0 && delta[1] === 0) return graph; + + setupCache(graph); + + if (!_.isEmpty(cache.intersection)) { + limitDelta(graph); + } + + _.each(cache.nodes, function(id) { + var node = graph.entity(id), + start = projection(node.loc), + end = vecAdd(start, delta); + graph = graph.replace(node.move(projection.invert(end))); + }); + + if (!_.isEmpty(cache.intersection)) { + graph = cleanupIntersections(graph); + } + + return graph; + }; + + action.disabled = function(graph) { + function incompleteRelation(id) { + var entity = graph.entity(id); + return entity.type === 'relation' && !entity.isComplete(graph); + } + + if (_.some(moveIds, incompleteRelation)) + return 'incomplete_relation'; + }; + + action.delta = function() { + return delta; + }; + + return action; + }; + + // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/command/MoveCommand.java + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MoveNodeAction.as + function MoveNode(nodeId, loc) { + return function(graph) { + return graph.replace(graph.entity(nodeId).move(loc)); + }; + } + + function Noop() { + return function(graph) { + return graph; + }; + } + + /* + * Based on https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/potlatch2/tools/Quadrilateralise.as + */ + + function Orthogonalize(wayId, projection) { + var threshold = 12, // degrees within right or straight to alter + lowerThreshold = Math.cos((90 - threshold) * Math.PI / 180), + upperThreshold = Math.cos(threshold * Math.PI / 180); + + var action = function(graph) { + var way = graph.entity(wayId), + nodes = graph.childNodes(way), + points = _.uniq(nodes).map(function(n) { return projection(n.loc); }), + corner = {i: 0, dotp: 1}, + epsilon = 1e-4, + i, j, score, motions; + + if (nodes.length === 4) { + for (i = 0; i < 1000; i++) { + motions = points.map(calcMotion); + points[corner.i] = addPoints(points[corner.i],motions[corner.i]); + score = corner.dotp; + if (score < epsilon) { + break; + } + } + + graph = graph.replace(graph.entity(nodes[corner.i].id) + .move(projection.invert(points[corner.i]))); + } else { + var best, + originalPoints = _.clone(points); + score = Infinity; + + for (i = 0; i < 1000; i++) { + motions = points.map(calcMotion); + for (j = 0; j < motions.length; j++) { + points[j] = addPoints(points[j],motions[j]); + } + var newScore = squareness(points); + if (newScore < score) { + best = _.clone(points); + score = newScore; + } + if (score < epsilon) { + break; + } + } + + points = best; + + for (i = 0; i < points.length; i++) { + // only move the points that actually moved + if (originalPoints[i][0] !== points[i][0] || originalPoints[i][1] !== points[i][1]) { + graph = graph.replace(graph.entity(nodes[i].id) + .move(projection.invert(points[i]))); + } + } + + // remove empty nodes on straight sections + for (i = 0; i < points.length; i++) { + var node = nodes[i]; + + if (graph.parentWays(node).length > 1 || + graph.parentRelations(node).length || + node.hasInterestingTags()) { + + continue; + } + + var dotp = normalizedDotProduct(i, points); + if (dotp < -1 + epsilon) { + graph = DeleteNode(nodes[i].id)(graph); + } + } + } + + return graph; + + function calcMotion(b, i, array) { + var a = array[(i - 1 + array.length) % array.length], + c = array[(i + 1) % array.length], + p = subtractPoints(a, b), + q = subtractPoints(c, b), + scale, dotp; + + scale = 2 * Math.min(iD.geo.euclideanDistance(p, [0, 0]), iD.geo.euclideanDistance(q, [0, 0])); + p = normalizePoint(p, 1.0); + q = normalizePoint(q, 1.0); + + dotp = filterDotProduct(p[0] * q[0] + p[1] * q[1]); + + // nasty hack to deal with almost-straight segments (angle is closer to 180 than to 90/270). + if (array.length > 3) { + if (dotp < -0.707106781186547) { + dotp += 1.0; + } + } else if (dotp && Math.abs(dotp) < corner.dotp) { + corner.i = i; + corner.dotp = Math.abs(dotp); + } + + return normalizePoint(addPoints(p, q), 0.1 * dotp * scale); + } + }; + + function squareness(points) { + return points.reduce(function(sum, val, i, array) { + var dotp = normalizedDotProduct(i, array); + + dotp = filterDotProduct(dotp); + return sum + 2.0 * Math.min(Math.abs(dotp - 1.0), Math.min(Math.abs(dotp), Math.abs(dotp + 1))); + }, 0); + } + + function normalizedDotProduct(i, points) { + var a = points[(i - 1 + points.length) % points.length], + b = points[i], + c = points[(i + 1) % points.length], + p = subtractPoints(a, b), + q = subtractPoints(c, b); + + p = normalizePoint(p, 1.0); + q = normalizePoint(q, 1.0); + + return p[0] * q[0] + p[1] * q[1]; + } + + function subtractPoints(a, b) { + return [a[0] - b[0], a[1] - b[1]]; + } + + function addPoints(a, b) { + return [a[0] + b[0], a[1] + b[1]]; + } + + function normalizePoint(point, scale) { + var vector = [0, 0]; + var length = Math.sqrt(point[0] * point[0] + point[1] * point[1]); + if (length !== 0) { + vector[0] = point[0] / length; + vector[1] = point[1] / length; + } + + vector[0] *= scale; + vector[1] *= scale; + + return vector; + } + + function filterDotProduct(dotp) { + if (lowerThreshold > Math.abs(dotp) || Math.abs(dotp) > upperThreshold) { + return dotp; + } + + return 0; + } + + action.disabled = function(graph) { + var way = graph.entity(wayId), + nodes = graph.childNodes(way), + points = _.uniq(nodes).map(function(n) { return projection(n.loc); }); + + if (squareness(points)) { + return false; + } + + return 'not_squarish'; + }; + + return action; + } + + // Split a way at the given node. + // + // Optionally, split only the given ways, if multiple ways share + // the given node. + // + // This is the inverse of `iD.actions.Join`. + // + // For testing convenience, accepts an ID to assign to the new way. + // Normally, this will be undefined and the way will automatically + // be assigned a new ID. + // + // Reference: + // https://github.com/systemed/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/SplitWayAction.as + // + function Split(nodeId, newWayIds) { + var wayIds; + + // if the way is closed, we need to search for a partner node + // to split the way at. + // + // The following looks for a node that is both far away from + // the initial node in terms of way segment length and nearby + // in terms of beeline-distance. This assures that areas get + // split on the most "natural" points (independent of the number + // of nodes). + // For example: bone-shaped areas get split across their waist + // line, circles across the diameter. + function splitArea(nodes, idxA, graph) { + var lengths = new Array(nodes.length), + length, + i, + best = 0, + idxB; + + function wrap(index) { + return iD.util.wrap(index, nodes.length); + } + + function dist(nA, nB) { + return iD.geo.sphericalDistance(graph.entity(nA).loc, graph.entity(nB).loc); + } + + // calculate lengths + length = 0; + for (i = wrap(idxA+1); i !== idxA; i = wrap(i+1)) { + length += dist(nodes[i], nodes[wrap(i-1)]); + lengths[i] = length; + } + + length = 0; + for (i = wrap(idxA-1); i !== idxA; i = wrap(i-1)) { + length += dist(nodes[i], nodes[wrap(i+1)]); + if (length < lengths[i]) + lengths[i] = length; + } + + // determine best opposite node to split + for (i = 0; i < nodes.length; i++) { + var cost = lengths[i] / dist(nodes[idxA], nodes[i]); + if (cost > best) { + idxB = i; + best = cost; + } + } + + return idxB; + } + + function split(graph, wayA, newWayId) { + var wayB = iD.Way({id: newWayId, tags: wayA.tags}), + nodesA, + nodesB, + isArea = wayA.isArea(), + isOuter = iD.geo.isSimpleMultipolygonOuterMember(wayA, graph); + + if (wayA.isClosed()) { + var nodes = wayA.nodes.slice(0, -1), + idxA = _.indexOf(nodes, nodeId), + idxB = splitArea(nodes, idxA, graph); + + if (idxB < idxA) { + nodesA = nodes.slice(idxA).concat(nodes.slice(0, idxB + 1)); + nodesB = nodes.slice(idxB, idxA + 1); + } else { + nodesA = nodes.slice(idxA, idxB + 1); + nodesB = nodes.slice(idxB).concat(nodes.slice(0, idxA + 1)); + } + } else { + var idx = _.indexOf(wayA.nodes, nodeId, 1); + nodesA = wayA.nodes.slice(0, idx + 1); + nodesB = wayA.nodes.slice(idx); + } + + wayA = wayA.update({nodes: nodesA}); + wayB = wayB.update({nodes: nodesB}); + + graph = graph.replace(wayA); + graph = graph.replace(wayB); + + graph.parentRelations(wayA).forEach(function(relation) { + if (relation.isRestriction()) { + var via = relation.memberByRole('via'); + if (via && wayB.contains(via.id)) { + relation = relation.updateMember({id: wayB.id}, relation.memberById(wayA.id).index); + graph = graph.replace(relation); + } + } else { + if (relation === isOuter) { + graph = graph.replace(relation.mergeTags(wayA.tags)); + graph = graph.replace(wayA.update({tags: {}})); + graph = graph.replace(wayB.update({tags: {}})); + } + + var member = { + id: wayB.id, + type: 'way', + role: relation.memberById(wayA.id).role + }; + + graph = AddMember(relation.id, member)(graph); + } + }); + + if (!isOuter && isArea) { + var multipolygon = iD.Relation({ + tags: _.extend({}, wayA.tags, {type: 'multipolygon'}), + members: [ + {id: wayA.id, role: 'outer', type: 'way'}, + {id: wayB.id, role: 'outer', type: 'way'} + ]}); + + graph = graph.replace(multipolygon); + graph = graph.replace(wayA.update({tags: {}})); + graph = graph.replace(wayB.update({tags: {}})); + } + + return graph; + } + + var action = function(graph) { + var candidates = action.ways(graph); + for (var i = 0; i < candidates.length; i++) { + graph = split(graph, candidates[i], newWayIds && newWayIds[i]); + } + return graph; + }; + + action.ways = function(graph) { + var node = graph.entity(nodeId), + parents = graph.parentWays(node), + hasLines = _.some(parents, function(parent) { return parent.geometry(graph) === 'line'; }); + + return parents.filter(function(parent) { + if (wayIds && wayIds.indexOf(parent.id) === -1) + return false; + + if (!wayIds && hasLines && parent.geometry(graph) !== 'line') + return false; + + if (parent.isClosed()) { + return true; + } + + for (var i = 1; i < parent.nodes.length - 1; i++) { + if (parent.nodes[i] === nodeId) { + return true; + } + } + + return false; + }); + }; + + action.disabled = function(graph) { + var candidates = action.ways(graph); + if (candidates.length === 0 || (wayIds && wayIds.length !== candidates.length)) + return 'not_eligible'; + }; + + action.limitWays = function(_) { + if (!arguments.length) return wayIds; + wayIds = _; + return action; + }; + + return action; + } + + // Create a restriction relation for `turn`, which must have the following structure: + // + // { + // from: { node: , way: }, + // via: { node: }, + // to: { node: , way: }, + // restriction: <'no_right_turn', 'no_left_turn', etc.> + // } + // + // This specifies a restriction of type `restriction` when traveling from + // `from.node` in `from.way` toward `to.node` in `to.way` via `via.node`. + // (The action does not check that these entities form a valid intersection.) + // + // If `restriction` is not provided, it is automatically determined by + // iD.geo.inferRestriction. + // + // If necessary, the `from` and `to` ways are split. In these cases, `from.node` + // and `to.node` are used to determine which portion of the split ways become + // members of the restriction. + // + // For testing convenience, accepts an ID to assign to the new relation. + // Normally, this will be undefined and the relation will automatically + // be assigned a new ID. + // + function RestrictTurn(turn, projection, restrictionId) { + return function(graph) { + var from = graph.entity(turn.from.way), + via = graph.entity(turn.via.node), + to = graph.entity(turn.to.way); + + function isClosingNode(way, nodeId) { + return nodeId === way.first() && nodeId === way.last(); + } + + function split(toOrFrom) { + var newID = toOrFrom.newID || iD.Way().id; + graph = Split(via.id, [newID]) + .limitWays([toOrFrom.way])(graph); + + var a = graph.entity(newID), + b = graph.entity(toOrFrom.way); + + if (a.nodes.indexOf(toOrFrom.node) !== -1) { + return [a, b]; + } else { + return [b, a]; + } + } + + if (!from.affix(via.id) || isClosingNode(from, via.id)) { + if (turn.from.node === turn.to.node) { + // U-turn + from = to = split(turn.from)[0]; + } else if (turn.from.way === turn.to.way) { + // Straight-on or circular + var s = split(turn.from); + from = s[0]; + to = s[1]; + } else { + // Other + from = split(turn.from)[0]; + } + } + + if (!to.affix(via.id) || isClosingNode(to, via.id)) { + to = split(turn.to)[0]; + } + + return graph.replace(iD.Relation({ + id: restrictionId, + tags: { + type: 'restriction', + restriction: turn.restriction || + iD.geo.inferRestriction( + graph, + turn.from, + turn.via, + turn.to, + projection) + }, + members: [ + {id: from.id, type: 'way', role: 'from'}, + {id: via.id, type: 'node', role: 'via'}, + {id: to.id, type: 'way', role: 'to'} + ] + })); + }; + } + + /* + Order the nodes of a way in reverse order and reverse any direction dependent tags + other than `oneway`. (We assume that correcting a backwards oneway is the primary + reason for reversing a way.) + + The following transforms are performed: + + Keys: + *:right=* ⟺ *:left=* + *:forward=* ⟺ *:backward=* + direction=up ⟺ direction=down + incline=up ⟺ incline=down + *=right ⟺ *=left + + Relation members: + role=forward ⟺ role=backward + role=north ⟺ role=south + role=east ⟺ role=west + + In addition, numeric-valued `incline` tags are negated. + + The JOSM implementation was used as a guide, but transformations that were of unclear benefit + or adjusted tags that don't seem to be used in practice were omitted. + + References: + http://wiki.openstreetmap.org/wiki/Forward_%26_backward,_left_%26_right + http://wiki.openstreetmap.org/wiki/Key:direction#Steps + http://wiki.openstreetmap.org/wiki/Key:incline + http://wiki.openstreetmap.org/wiki/Route#Members + http://josm.openstreetmap.de/browser/josm/trunk/src/org/openstreetmap/josm/corrector/ReverseWayTagCorrector.java + */ + function Reverse(wayId, options) { + var replacements = [ + [/:right$/, ':left'], [/:left$/, ':right'], + [/:forward$/, ':backward'], [/:backward$/, ':forward'] + ], + numeric = /^([+\-]?)(?=[\d.])/, + roleReversals = { + forward: 'backward', + backward: 'forward', + north: 'south', + south: 'north', + east: 'west', + west: 'east' + }; + + function reverseKey(key) { + for (var i = 0; i < replacements.length; ++i) { + var replacement = replacements[i]; + if (replacement[0].test(key)) { + return key.replace(replacement[0], replacement[1]); + } + } + return key; + } + + function reverseValue(key, value) { + if (key === 'incline' && numeric.test(value)) { + return value.replace(numeric, function(_, sign) { return sign === '-' ? '' : '-'; }); + } else if (key === 'incline' || key === 'direction') { + return {up: 'down', down: 'up'}[value] || value; + } else if (options && options.reverseOneway && key === 'oneway') { + return {yes: '-1', '1': '-1', '-1': 'yes'}[value] || value; + } else { + return {left: 'right', right: 'left'}[value] || value; + } + } + + return function(graph) { + var way = graph.entity(wayId), + nodes = way.nodes.slice().reverse(), + tags = {}, key, role; + + for (key in way.tags) { + tags[reverseKey(key)] = reverseValue(key, way.tags[key]); + } + + graph.parentRelations(way).forEach(function(relation) { + relation.members.forEach(function(member, index) { + if (member.id === way.id && (role = roleReversals[member.role])) { + relation = relation.updateMember({role: role}, index); + graph = graph.replace(relation); + } + }); + }); + + return graph.replace(way.update({nodes: nodes, tags: tags})); + }; + } + + function Revert(id) { + + var action = function(graph) { + var entity = graph.hasEntity(id), + base = graph.base().entities[id]; + + if (entity && !base) { // entity will be removed.. + if (entity.type === 'node') { + graph.parentWays(entity) + .forEach(function(parent) { + parent = parent.removeNode(id); + graph = graph.replace(parent); + + if (parent.isDegenerate()) { + graph = DeleteWay(parent.id)(graph); + } + }); + } + + graph.parentRelations(entity) + .forEach(function(parent) { + parent = parent.removeMembersWithID(id); + graph = graph.replace(parent); + + if (parent.isDegenerate()) { + graph = DeleteRelation(parent.id)(graph); + } + }); + } + + return graph.revert(id); + }; + + return action; + } + + function RotateWay(wayId, pivot, angle, projection) { + return function(graph) { + return graph.update(function(graph) { + var way = graph.entity(wayId); + + _.uniq(way.nodes).forEach(function(id) { + + var node = graph.entity(id), + point = projection(node.loc), + radial = [0,0]; + + radial[0] = point[0] - pivot[0]; + radial[1] = point[1] - pivot[1]; + + point = [ + radial[0] * Math.cos(angle) - radial[1] * Math.sin(angle) + pivot[0], + radial[0] * Math.sin(angle) + radial[1] * Math.cos(angle) + pivot[1] + ]; + + graph = graph.replace(node.move(projection.invert(point))); + + }); + + }); + }; + } + + /* + * Based on https://github.com/openstreetmap/potlatch2/net/systemeD/potlatch2/tools/Straighten.as + */ + + function Straighten(wayId, projection) { + function positionAlongWay(n, s, e) { + return ((n[0] - s[0]) * (e[0] - s[0]) + (n[1] - s[1]) * (e[1] - s[1]))/ + (Math.pow(e[0] - s[0], 2) + Math.pow(e[1] - s[1], 2)); + } + + var action = function(graph) { + var way = graph.entity(wayId), + nodes = graph.childNodes(way), + points = nodes.map(function(n) { return projection(n.loc); }), + startPoint = points[0], + endPoint = points[points.length-1], + toDelete = [], + i; + + for (i = 1; i < points.length-1; i++) { + var node = nodes[i], + point = points[i]; + + if (graph.parentWays(node).length > 1 || + graph.parentRelations(node).length || + node.hasInterestingTags()) { + + var u = positionAlongWay(point, startPoint, endPoint), + p0 = startPoint[0] + u * (endPoint[0] - startPoint[0]), + p1 = startPoint[1] + u * (endPoint[1] - startPoint[1]); + + graph = graph.replace(graph.entity(node.id) + .move(projection.invert([p0, p1]))); + } else { + // safe to delete + if (toDelete.indexOf(node) === -1) { + toDelete.push(node); + } + } + } + + for (i = 0; i < toDelete.length; i++) { + graph = DeleteNode(toDelete[i].id)(graph); + } + + return graph; + }; + + action.disabled = function(graph) { + // check way isn't too bendy + var way = graph.entity(wayId), + nodes = graph.childNodes(way), + points = nodes.map(function(n) { return projection(n.loc); }), + startPoint = points[0], + endPoint = points[points.length-1], + threshold = 0.2 * Math.sqrt(Math.pow(startPoint[0] - endPoint[0], 2) + Math.pow(startPoint[1] - endPoint[1], 2)), + i; + + if (threshold === 0) { + return 'too_bendy'; + } + + for (i = 1; i < points.length-1; i++) { + var point = points[i], + u = positionAlongWay(point, startPoint, endPoint), + p0 = startPoint[0] + u * (endPoint[0] - startPoint[0]), + p1 = startPoint[1] + u * (endPoint[1] - startPoint[1]), + dist = Math.sqrt(Math.pow(p0 - point[0], 2) + Math.pow(p1 - point[1], 2)); + + // to bendy if point is off by 20% of total start/end distance in projected space + if (isNaN(dist) || dist > threshold) { + return 'too_bendy'; + } + } + }; + + return action; + } + + // Remove the effects of `turn.restriction` on `turn`, which must have the + // following structure: + // + // { + // from: { node: , way: }, + // via: { node: }, + // to: { node: , way: }, + // restriction: + // } + // + // In the simple case, `restriction` is a reference to a `no_*` restriction + // on the turn itself. In this case, it is simply deleted. + // + // The more complex case is where `restriction` references an `only_*` + // restriction on a different turn in the same intersection. In that case, + // that restriction is also deleted, but at the same time restrictions on + // the turns other than the first two are created. + // + function UnrestrictTurn(turn) { + return function(graph) { + return DeleteRelation(turn.restriction)(graph); + }; + } + + exports.AddEntity = AddEntity; + exports.AddMember = AddMember; + exports.AddMidpoint = AddMidpoint; + exports.AddVertex = AddVertex; + exports.ChangeMember = ChangeMember; + exports.ChangePreset = ChangePreset; + exports.ChangeTags = ChangeTags; + exports.Circularize = Circularize; + exports.Connect = Connect; + exports.CopyEntities = CopyEntities; + exports.DeleteMember = DeleteMember; + exports.DeleteMultiple = DeleteMultiple; + exports.DeleteNode = DeleteNode; + exports.DeleteRelation = DeleteRelation; + exports.DeleteWay = DeleteWay; + exports.DeprecateTags = DeprecateTags; + exports.DiscardTags = DiscardTags; + exports.Disconnect = Disconnect; + exports.Join = Join; + exports.Merge = Merge; + exports.MergePolygon = MergePolygon; + exports.MergeRemoteChanges = MergeRemoteChanges; + exports.Move = Move; + exports.MoveNode = MoveNode; + exports.Noop = Noop; + exports.Orthogonalize = Orthogonalize; + exports.RestrictTurn = RestrictTurn; + exports.Reverse = Reverse; + exports.Revert = Revert; + exports.RotateWay = RotateWay; + exports.Split = Split; + exports.Straighten = Straighten; + exports.UnrestrictTurn = UnrestrictTurn; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); \ No newline at end of file diff --git a/modules/.eslintrc b/modules/.eslintrc new file mode 100644 index 000000000..f482330f6 --- /dev/null +++ b/modules/.eslintrc @@ -0,0 +1,6 @@ +{ + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module" + } +} diff --git a/modules/actions/add_entity.js b/modules/actions/add_entity.js index 38a1e5f7d..2a802693d 100644 --- a/modules/actions/add_entity.js +++ b/modules/actions/add_entity.js @@ -1,5 +1,5 @@ -module.exports = function(way) { +export function AddEntity(way) { return function(graph) { return graph.replace(way); }; -}; +} diff --git a/modules/actions/add_member.js b/modules/actions/add_member.js index e8a4a7be8..6e7a1e688 100644 --- a/modules/actions/add_member.js +++ b/modules/actions/add_member.js @@ -1,4 +1,4 @@ -module.exports = function(relationId, member, memberIndex) { +export function AddMember(relationId, member, memberIndex) { return function(graph) { var relation = graph.entity(relationId); @@ -26,4 +26,4 @@ module.exports = function(relationId, member, memberIndex) { return graph.replace(relation.addMember(member, memberIndex)); }; -}; +} diff --git a/modules/actions/add_midpoint.js b/modules/actions/add_midpoint.js index be7c49453..94a458a8f 100644 --- a/modules/actions/add_midpoint.js +++ b/modules/actions/add_midpoint.js @@ -1,4 +1,4 @@ -module.exports = function(midpoint, node) { +export function AddMidpoint(midpoint, node) { return function(graph) { graph = graph.replace(node.move(midpoint.loc)); @@ -20,4 +20,4 @@ module.exports = function(midpoint, node) { return graph; }; -}; +} diff --git a/modules/actions/add_vertex.js b/modules/actions/add_vertex.js index ac7a9997e..29473c286 100644 --- a/modules/actions/add_vertex.js +++ b/modules/actions/add_vertex.js @@ -1,6 +1,6 @@ // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/AddNodeToWayAction.as -module.exports = function(wayId, nodeId, index) { +export function AddVertex(wayId, nodeId, index) { return function(graph) { return graph.replace(graph.entity(wayId).addNode(nodeId, index)); }; -}; +} diff --git a/modules/actions/change_member.js b/modules/actions/change_member.js index 8b374fc12..5c2df07c2 100644 --- a/modules/actions/change_member.js +++ b/modules/actions/change_member.js @@ -1,5 +1,5 @@ -module.exports = function(relationId, member, memberIndex) { +export function ChangeMember(relationId, member, memberIndex) { return function(graph) { return graph.replace(graph.entity(relationId).updateMember(member, memberIndex)); }; -}; +} diff --git a/modules/actions/change_preset.js b/modules/actions/change_preset.js index 79715cfc6..d35278d3d 100644 --- a/modules/actions/change_preset.js +++ b/modules/actions/change_preset.js @@ -1,4 +1,4 @@ -module.exports = function(entityId, oldPreset, newPreset) { +export function ChangePreset(entityId, oldPreset, newPreset) { return function(graph) { var entity = graph.entity(entityId), geometry = entity.geometry(graph), @@ -9,4 +9,4 @@ module.exports = function(entityId, oldPreset, newPreset) { return graph.replace(entity.update({tags: tags})); }; -}; +} diff --git a/modules/actions/change_tags.js b/modules/actions/change_tags.js index c054a99a6..703b5bdcb 100644 --- a/modules/actions/change_tags.js +++ b/modules/actions/change_tags.js @@ -1,6 +1,6 @@ -module.exports = function(entityId, tags) { +export function ChangeTags(entityId, tags) { return function(graph) { var entity = graph.entity(entityId); return graph.replace(entity.update({tags: tags})); }; -}; +} diff --git a/modules/actions/circularize.js b/modules/actions/circularize.js index d662d4875..076a5990b 100644 --- a/modules/actions/circularize.js +++ b/modules/actions/circularize.js @@ -1,4 +1,4 @@ -module.exports = function(wayId, projection, maxAngle) { +export function Circularize(wayId, projection, maxAngle) { maxAngle = (maxAngle || 20) * Math.PI / 180; var action = function(graph) { @@ -180,4 +180,4 @@ module.exports = function(wayId, projection, maxAngle) { }; return action; -}; +} diff --git a/modules/actions/connect.js b/modules/actions/connect.js index 6395d9509..9134c1ccb 100644 --- a/modules/actions/connect.js +++ b/modules/actions/connect.js @@ -1,3 +1,5 @@ +import { DeleteNode } from './delete_node'; + // Connect the ways at the given nodes. // // The last node will survive. All other nodes will be replaced with @@ -12,7 +14,7 @@ // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MergeNodesAction.as // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/MergeNodesAction.java // -module.exports = function(nodeIds) { +export function Connect(nodeIds) { return function(graph) { var survivor = graph.entity(_.last(nodeIds)); @@ -32,11 +34,11 @@ module.exports = function(nodeIds) { /* eslint-enable no-loop-func */ survivor = survivor.mergeTags(node.tags); - graph = iD.actions.DeleteNode(node.id)(graph); + graph = DeleteNode(node.id)(graph); } graph = graph.replace(survivor); return graph; }; -}; +} diff --git a/modules/actions/copy_entities.js b/modules/actions/copy_entities.js index 1f168fdf9..1e87404b9 100644 --- a/modules/actions/copy_entities.js +++ b/modules/actions/copy_entities.js @@ -1,4 +1,4 @@ -module.exports = function(ids, fromGraph) { +export function CopyEntities(ids, fromGraph) { var copies = {}; var action = function(graph) { @@ -18,4 +18,4 @@ module.exports = function(ids, fromGraph) { }; return action; -}; +} diff --git a/modules/actions/delete_member.js b/modules/actions/delete_member.js index 23842f613..a221615b7 100644 --- a/modules/actions/delete_member.js +++ b/modules/actions/delete_member.js @@ -1,4 +1,6 @@ -module.exports = function(relationId, memberIndex) { +import { DeleteRelation } from './delete_relation'; + +export function DeleteMember(relationId, memberIndex) { return function(graph) { var relation = graph.entity(relationId) .removeMember(memberIndex); @@ -6,8 +8,8 @@ module.exports = function(relationId, memberIndex) { graph = graph.replace(relation); if (relation.isDegenerate()) - graph = iD.actions.DeleteRelation(relation.id)(graph); + graph = DeleteRelation(relation.id)(graph); return graph; }; -}; +} diff --git a/modules/actions/delete_multiple.js b/modules/actions/delete_multiple.js index a9c50f88a..809bff189 100644 --- a/modules/actions/delete_multiple.js +++ b/modules/actions/delete_multiple.js @@ -1,8 +1,12 @@ -module.exports = function(ids) { +import { DeleteWay } from './delete_way'; +import { DeleteNode } from './delete_node'; +import { DeleteRelation } from './delete_relation'; + +export function DeleteMultiple(ids) { var actions = { - way: iD.actions.DeleteWay, - node: iD.actions.DeleteNode, - relation: iD.actions.DeleteRelation + way: DeleteWay, + node: DeleteNode, + relation: DeleteRelation }; var action = function(graph) { @@ -24,4 +28,4 @@ module.exports = function(ids) { }; return action; -}; +} diff --git a/modules/actions/delete_node.js b/modules/actions/delete_node.js index 95ebd824c..84a1d5481 100644 --- a/modules/actions/delete_node.js +++ b/modules/actions/delete_node.js @@ -1,5 +1,8 @@ +import { DeleteWay } from './delete_way'; +import { DeleteRelation } from './delete_relation'; + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteNodeAction.as -module.exports = function(nodeId) { +export function DeleteNode(nodeId) { var action = function(graph) { var node = graph.entity(nodeId); @@ -9,7 +12,7 @@ module.exports = function(nodeId) { graph = graph.replace(parent); if (parent.isDegenerate()) { - graph = iD.actions.DeleteWay(parent.id)(graph); + graph = DeleteWay(parent.id)(graph); } }); @@ -19,7 +22,7 @@ module.exports = function(nodeId) { graph = graph.replace(parent); if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); + graph = DeleteRelation(parent.id)(graph); } }); @@ -31,4 +34,4 @@ module.exports = function(nodeId) { }; return action; -}; +} diff --git a/modules/actions/delete_relation.js b/modules/actions/delete_relation.js index f656fca95..27a2a5053 100644 --- a/modules/actions/delete_relation.js +++ b/modules/actions/delete_relation.js @@ -1,5 +1,7 @@ +import { DeleteMultiple } from './delete_multiple'; + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteRelationAction.as -module.exports = function(relationId) { +export function DeleteRelation(relationId) { function deleteEntity(entity, graph) { return !graph.parentWays(entity).length && !graph.parentRelations(entity).length && @@ -15,7 +17,7 @@ module.exports = function(relationId) { graph = graph.replace(parent); if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); + graph = DeleteRelation(parent.id)(graph); } }); @@ -24,7 +26,7 @@ module.exports = function(relationId) { var entity = graph.entity(memberId); if (deleteEntity(entity, graph)) { - graph = iD.actions.DeleteMultiple([memberId])(graph); + graph = DeleteMultiple([memberId])(graph); } }); @@ -37,4 +39,4 @@ module.exports = function(relationId) { }; return action; -}; +} diff --git a/modules/actions/delete_way.js b/modules/actions/delete_way.js index 1ca876d5c..b6f256ebd 100644 --- a/modules/actions/delete_way.js +++ b/modules/actions/delete_way.js @@ -1,5 +1,7 @@ +import { DeleteRelation } from './delete_relation'; + // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteWayAction.as -module.exports = function(wayId) { +export function DeleteWay(wayId) { function deleteNode(node, graph) { return !graph.parentWays(node).length && !graph.parentRelations(node).length && @@ -15,7 +17,7 @@ module.exports = function(wayId) { graph = graph.replace(parent); if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); + graph = DeleteRelation(parent.id)(graph); } }); @@ -46,4 +48,4 @@ module.exports = function(wayId) { }; return action; -}; +} diff --git a/modules/actions/deprecate_tags.js b/modules/actions/deprecate_tags.js index 228227567..8dc1121fa 100644 --- a/modules/actions/deprecate_tags.js +++ b/modules/actions/deprecate_tags.js @@ -1,4 +1,4 @@ -module.exports = function(entityId) { +export function DeprecateTags(entityId) { return function(graph) { var entity = graph.entity(entityId), newtags = _.clone(entity.tags), @@ -33,4 +33,4 @@ module.exports = function(entityId) { return graph; } }; -}; +} diff --git a/modules/actions/discard_tags.js b/modules/actions/discard_tags.js index 662d79c07..3a305b2f2 100644 --- a/modules/actions/discard_tags.js +++ b/modules/actions/discard_tags.js @@ -1,4 +1,4 @@ -module.exports = function(difference) { +export function DiscardTags(difference) { return function(graph) { function discardTags(entity) { if (!_.isEmpty(entity.tags)) { @@ -18,4 +18,4 @@ module.exports = function(difference) { return graph; }; -}; +} diff --git a/modules/actions/disconnect.js b/modules/actions/disconnect.js index 888877db1..c4aced41e 100644 --- a/modules/actions/disconnect.js +++ b/modules/actions/disconnect.js @@ -12,7 +12,7 @@ // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/UnjoinNodeAction.as // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/UnGlueAction.java // -module.exports = function(nodeId, newNodeId) { +export function Disconnect(nodeId, newNodeId) { var wayIds; var action = function(graph) { @@ -94,4 +94,4 @@ module.exports = function(nodeId, newNodeId) { }; return action; -}; +} diff --git a/modules/actions/index.js b/modules/actions/index.js index 943a836df..10a772d0e 100644 --- a/modules/actions/index.js +++ b/modules/actions/index.js @@ -1,33 +1,33 @@ -module.exports.AddEntity = require('./add_entity'); -module.exports.AddMember = require('./add_member'); -module.exports.AddMidpoint = require('./add_midpoint'); -module.exports.AddVertex = require('./add_vertex'); -module.exports.ChangeMember = require('./change_member'); -module.exports.ChangePreset = require('./change_preset'); -module.exports.ChangeTags = require('./change_tags'); -module.exports.Circularize = require('./circularize'); -module.exports.Connect = require('./connect'); -module.exports.CopyEntities = require('./copy_entities'); -module.exports.DeleteMember = require('./delete_member'); -module.exports.DeleteMultiple = require('./delete_multiple'); -module.exports.DeleteNode = require('./delete_node'); -module.exports.DeleteRelation = require('./delete_relation'); -module.exports.DeleteWay = require('./delete_way'); -module.exports.DeprecateTags = require('./deprecate_tags'); -module.exports.DiscardTags = require('./discard_tags'); -module.exports.Disconnect = require('./disconnect'); -module.exports.Join = require('./join'); -module.exports.Merge = require('./merge'); -module.exports.MergePolygon = require('./merge_polygon'); -module.exports.MergeRemoteChanges = require('./merge_remote_changes'); -module.exports.Move = require('./move'); -module.exports.MoveNode = require('./move_node'); -module.exports.Noop = require('./noop'); -module.exports.Orthogonalize = require('./orthogonalize'); -module.exports.RestrictTurn = require('./restrict_turn'); -module.exports.Reverse = require('./reverse'); -module.exports.Revert = require('./revert'); -module.exports.RotateWay = require('./rotate_way'); -module.exports.Split = require('./split'); -module.exports.Straighten = require('./straighten'); -module.exports.UnrestrictTurn = require('./unrestrict_turn'); +export { AddEntity } from './add_entity'; +export { AddMember } from './add_member'; +export { AddMidpoint } from './add_midpoint'; +export { AddVertex } from './add_vertex'; +export { ChangeMember } from './change_member'; +export { ChangePreset } from './change_preset'; +export { ChangeTags } from './change_tags'; +export { Circularize } from './circularize'; +export { Connect } from './connect'; +export { CopyEntities } from './copy_entities'; +export { DeleteMember } from './delete_member'; +export { DeleteMultiple } from './delete_multiple'; +export { DeleteNode } from './delete_node'; +export { DeleteRelation } from './delete_relation'; +export { DeleteWay } from './delete_way'; +export { DeprecateTags } from './deprecate_tags'; +export { DiscardTags } from './discard_tags'; +export { Disconnect } from './disconnect'; +export { Join } from './join'; +export { Merge } from './merge'; +export { MergePolygon } from './merge_polygon'; +export { MergeRemoteChanges } from './merge_remote_changes'; +export { Move } from './move'; +export { MoveNode } from './move_node'; +export { Noop } from './noop'; +export { Orthogonalize } from './orthogonalize'; +export { RestrictTurn } from './restrict_turn'; +export { Reverse } from './reverse'; +export { Revert } from './revert'; +export { RotateWay } from './rotate_way'; +export { Split } from './split'; +export { Straighten } from './straighten'; +export { UnrestrictTurn } from './unrestrict_turn'; diff --git a/modules/actions/join.js b/modules/actions/join.js index 101d5ac0e..7f2b08b94 100644 --- a/modules/actions/join.js +++ b/modules/actions/join.js @@ -1,3 +1,5 @@ +import { DeleteWay } from './delete_way'; + // Join ways at the end node they share. // // This is the inverse of `iD.actions.Split`. @@ -6,7 +8,7 @@ // https://github.com/systemed/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MergeWaysAction.as // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/actions/CombineWayAction.java // -module.exports = function(ids) { +export function Join(ids) { function groupEntitiesByGeometry(graph) { var entities = ids.map(function(id) { return graph.entity(id); }); @@ -41,7 +43,7 @@ module.exports = function(ids) { survivor = survivor.mergeTags(way.tags); graph = graph.replace(survivor); - graph = iD.actions.DeleteWay(way.id)(graph); + graph = DeleteWay(way.id)(graph); }); return graph; @@ -85,4 +87,4 @@ module.exports = function(ids) { }; return action; -}; +} diff --git a/modules/actions/merge.js b/modules/actions/merge.js index 2ac02c76e..4c47ba6d5 100644 --- a/modules/actions/merge.js +++ b/modules/actions/merge.js @@ -1,4 +1,4 @@ -module.exports = function(ids) { +export function Merge(ids) { function groupEntitiesByGeometry(graph) { var entities = ids.map(function(id) { return graph.entity(id); }); return _.extend({point: [], area: [], line: [], relation: []}, @@ -34,4 +34,4 @@ module.exports = function(ids) { }; return action; -}; +} diff --git a/modules/actions/merge_polygon.js b/modules/actions/merge_polygon.js index aaccb99cf..666e2a76f 100644 --- a/modules/actions/merge_polygon.js +++ b/modules/actions/merge_polygon.js @@ -1,4 +1,4 @@ -module.exports = function(ids, newRelationId) { +export function MergePolygon(ids, newRelationId) { function groupEntities(graph) { var entities = ids.map(function (id) { return graph.entity(id); }); @@ -112,4 +112,4 @@ module.exports = function(ids, newRelationId) { }; return action; -}; +} diff --git a/modules/actions/merge_remote_changes.js b/modules/actions/merge_remote_changes.js index adb685fdc..6c2cb7012 100644 --- a/modules/actions/merge_remote_changes.js +++ b/modules/actions/merge_remote_changes.js @@ -1,4 +1,6 @@ -module.exports = function(id, localGraph, remoteGraph, formatUser) { +import { DeleteMultiple } from './delete_multiple'; + +export function MergeRemoteChanges(id, localGraph, remoteGraph, formatUser) { var option = 'safe', // 'safe', 'force_local', 'force_remote' conflicts = []; @@ -122,7 +124,7 @@ module.exports = function(id, localGraph, remoteGraph, formatUser) { graph = graph.replace(updates.replacements[i]); } if (updates.removeIds.length) { - graph = iD.actions.DeleteMultiple(updates.removeIds)(graph); + graph = DeleteMultiple(updates.removeIds)(graph); } return graph; } @@ -204,7 +206,7 @@ module.exports = function(id, localGraph, remoteGraph, formatUser) { // delete/undelete if (!remote.visible) { if (option === 'force_remote') { - return iD.actions.DeleteMultiple([id])(graph); + return DeleteMultiple([id])(graph); } else if (option === 'force_local') { if (target.type === 'way') { @@ -252,4 +254,4 @@ module.exports = function(id, localGraph, remoteGraph, formatUser) { }; return action; -}; +} diff --git a/modules/actions/move.js b/modules/actions/move.js index 48c311c44..93257e20e 100644 --- a/modules/actions/move.js +++ b/modules/actions/move.js @@ -1,6 +1,6 @@ // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/command/MoveCommand.java // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MoveNodeAction.as -module.exports = function(moveIds, tryDelta, projection, cache) { +export function Move(moveIds, tryDelta, projection, cache) { var delta = tryDelta; function vecAdd(a, b) { return [a[0] + b[0], a[1] + b[1]]; } @@ -276,4 +276,4 @@ module.exports = function(moveIds, tryDelta, projection, cache) { }; return action; -}; +} diff --git a/modules/actions/move_node.js b/modules/actions/move_node.js index 44b2a664a..0fa702d02 100644 --- a/modules/actions/move_node.js +++ b/modules/actions/move_node.js @@ -1,7 +1,7 @@ // https://github.com/openstreetmap/josm/blob/mirror/src/org/openstreetmap/josm/command/MoveCommand.java // https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/MoveNodeAction.as -module.exports = function(nodeId, loc) { +export function MoveNode(nodeId, loc) { return function(graph) { return graph.replace(graph.entity(nodeId).move(loc)); }; -}; +} diff --git a/modules/actions/noop.js b/modules/actions/noop.js index cf0f1cb3f..573cd535b 100644 --- a/modules/actions/noop.js +++ b/modules/actions/noop.js @@ -1,5 +1,5 @@ -module.exports = function() { +export function Noop() { return function(graph) { return graph; }; -}; +} diff --git a/modules/actions/orthogonalize.js b/modules/actions/orthogonalize.js index 1e8a9bc1a..c14ff50cc 100644 --- a/modules/actions/orthogonalize.js +++ b/modules/actions/orthogonalize.js @@ -1,8 +1,10 @@ +import { DeleteNode } from './delete_node'; + /* * Based on https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/potlatch2/tools/Quadrilateralise.as */ -module.exports = function(wayId, projection) { +export function Orthogonalize(wayId, projection) { var threshold = 12, // degrees within right or straight to alter lowerThreshold = Math.cos((90 - threshold) * Math.PI / 180), upperThreshold = Math.cos(threshold * Math.PI / 180); @@ -70,7 +72,7 @@ module.exports = function(wayId, projection) { var dotp = normalizedDotProduct(i, points); if (dotp < -1 + epsilon) { - graph = iD.actions.DeleteNode(nodes[i].id)(graph); + graph = DeleteNode(nodes[i].id)(graph); } } } @@ -169,4 +171,4 @@ module.exports = function(wayId, projection) { }; return action; -}; +} diff --git a/modules/actions/restrict_turn.js b/modules/actions/restrict_turn.js index 6d9260d99..49d9d7be3 100644 --- a/modules/actions/restrict_turn.js +++ b/modules/actions/restrict_turn.js @@ -1,3 +1,5 @@ +import { Split } from './split'; + // Create a restriction relation for `turn`, which must have the following structure: // // { @@ -22,7 +24,7 @@ // Normally, this will be undefined and the relation will automatically // be assigned a new ID. // -module.exports = function(turn, projection, restrictionId) { +export function RestrictTurn(turn, projection, restrictionId) { return function(graph) { var from = graph.entity(turn.from.way), via = graph.entity(turn.via.node), @@ -34,7 +36,7 @@ module.exports = function(turn, projection, restrictionId) { function split(toOrFrom) { var newID = toOrFrom.newID || iD.Way().id; - graph = iD.actions.Split(via.id, [newID]) + graph = Split(via.id, [newID]) .limitWays([toOrFrom.way])(graph); var a = graph.entity(newID), @@ -85,4 +87,4 @@ module.exports = function(turn, projection, restrictionId) { ] })); }; -}; +} diff --git a/modules/actions/reverse.js b/modules/actions/reverse.js index b811fb2d3..1fb18ad85 100644 --- a/modules/actions/reverse.js +++ b/modules/actions/reverse.js @@ -29,7 +29,7 @@ http://wiki.openstreetmap.org/wiki/Route#Members http://josm.openstreetmap.de/browser/josm/trunk/src/org/openstreetmap/josm/corrector/ReverseWayTagCorrector.java */ -module.exports = function(wayId, options) { +export function Reverse(wayId, options) { var replacements = [ [/:right$/, ':left'], [/:left$/, ':right'], [/:forward$/, ':backward'], [/:backward$/, ':forward'] @@ -86,4 +86,4 @@ module.exports = function(wayId, options) { return graph.replace(way.update({nodes: nodes, tags: tags})); }; -}; +} diff --git a/modules/actions/revert.js b/modules/actions/revert.js index 3667a6582..afb368b0c 100644 --- a/modules/actions/revert.js +++ b/modules/actions/revert.js @@ -1,4 +1,7 @@ -module.exports = function(id) { +import { DeleteWay } from './delete_way'; +import { DeleteRelation } from './delete_relation'; + +export function Revert(id) { var action = function(graph) { var entity = graph.hasEntity(id), @@ -12,7 +15,7 @@ module.exports = function(id) { graph = graph.replace(parent); if (parent.isDegenerate()) { - graph = iD.actions.DeleteWay(parent.id)(graph); + graph = DeleteWay(parent.id)(graph); } }); } @@ -23,7 +26,7 @@ module.exports = function(id) { graph = graph.replace(parent); if (parent.isDegenerate()) { - graph = iD.actions.DeleteRelation(parent.id)(graph); + graph = DeleteRelation(parent.id)(graph); } }); } @@ -32,4 +35,4 @@ module.exports = function(id) { }; return action; -}; +} diff --git a/modules/actions/rotate_way.js b/modules/actions/rotate_way.js index 6738913db..551909176 100644 --- a/modules/actions/rotate_way.js +++ b/modules/actions/rotate_way.js @@ -1,4 +1,4 @@ -module.exports = function(wayId, pivot, angle, projection) { +export function RotateWay(wayId, pivot, angle, projection) { return function(graph) { return graph.update(function(graph) { var way = graph.entity(wayId); @@ -23,4 +23,4 @@ module.exports = function(wayId, pivot, angle, projection) { }); }; -}; +} diff --git a/modules/actions/split.js b/modules/actions/split.js index 25829fcd4..5cae44bb5 100644 --- a/modules/actions/split.js +++ b/modules/actions/split.js @@ -1,3 +1,4 @@ +import { AddMember } from './add_member'; // Split a way at the given node. // // Optionally, split only the given ways, if multiple ways share @@ -12,7 +13,7 @@ // Reference: // https://github.com/systemed/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/SplitWayAction.as // -module.exports = function(nodeId, newWayIds) { +export function Split(nodeId, newWayIds) { var wayIds; // if the way is closed, we need to search for a partner node @@ -117,7 +118,7 @@ module.exports = function(nodeId, newWayIds) { role: relation.memberById(wayA.id).role }; - graph = iD.actions.AddMember(relation.id, member)(graph); + graph = AddMember(relation.id, member)(graph); } }); @@ -184,4 +185,4 @@ module.exports = function(nodeId, newWayIds) { }; return action; -}; +} diff --git a/modules/actions/straighten.js b/modules/actions/straighten.js index 9a898fa11..a3ef944e2 100644 --- a/modules/actions/straighten.js +++ b/modules/actions/straighten.js @@ -1,8 +1,10 @@ +import { DeleteNode } from './delete_node'; + /* * Based on https://github.com/openstreetmap/potlatch2/net/systemeD/potlatch2/tools/Straighten.as */ -module.exports = function(wayId, projection) { +export function Straighten(wayId, projection) { function positionAlongWay(n, s, e) { return ((n[0] - s[0]) * (e[0] - s[0]) + (n[1] - s[1]) * (e[1] - s[1]))/ (Math.pow(e[0] - s[0], 2) + Math.pow(e[1] - s[1], 2)); @@ -40,7 +42,7 @@ module.exports = function(wayId, projection) { } for (i = 0; i < toDelete.length; i++) { - graph = iD.actions.DeleteNode(toDelete[i].id)(graph); + graph = DeleteNode(toDelete[i].id)(graph); } return graph; @@ -75,4 +77,4 @@ module.exports = function(wayId, projection) { }; return action; -}; +} diff --git a/modules/actions/unrestrict_turn.js b/modules/actions/unrestrict_turn.js index 0809e4336..6535372b9 100644 --- a/modules/actions/unrestrict_turn.js +++ b/modules/actions/unrestrict_turn.js @@ -1,3 +1,5 @@ +import { DeleteRelation } from './delete_relation'; + // Remove the effects of `turn.restriction` on `turn`, which must have the // following structure: // @@ -16,8 +18,8 @@ // that restriction is also deleted, but at the same time restrictions on // the turns other than the first two are created. // -module.exports = function(turn) { +export function UnrestrictTurn(turn) { return function(graph) { - return iD.actions.DeleteRelation(turn.restriction)(graph); + return DeleteRelation(turn.restriction)(graph); }; -}; +} diff --git a/package.json b/package.json index 7e9864742..99d4e036c 100644 --- a/package.json +++ b/package.json @@ -8,10 +8,10 @@ "test": "test" }, "scripts": { - "postinstall": "rm -rf node_modules/.bin/phantomjs", "test": "npm run lint && phantomjs node_modules/mocha-phantomjs-core/mocha-phantomjs-core.js test/index.html dot && make && phantomjs node_modules/mocha-phantomjs-core/mocha-phantomjs-core.js test/index_packaged.html dot", "start": "http-server .", "lint": "eslint js/id && npm run lint:spec:actions", + "lint:modules": "eslint modules", "lint:spec:actions": "eslint test/spec/actions" }, "repository": { @@ -24,11 +24,10 @@ ], "license": "ISC", "devDependencies": { - "browserify": "13.0.1", "chai": "~1.9.2", "d3": "3.5.5", "editor-layer-index": "git://github.com/osmlab/editor-layer-index.git#gh-pages", - "eslint": "^1.10.3", + "eslint": "^2.12.0", "glob": "~3.1.21", "happen": "0.1.2", "http-server": "^0.9.0", @@ -37,17 +36,19 @@ "lodash-cli": "4.12.0", "maki": "0.5.0", "minimist": "~1.2.0", - "mocha": "~2.3.4", - "mocha-phantomjs-core": "^1.3.0", + "mocha": "~2.5.3", + "mocha-phantomjs-core": "^2.0.1", "name-suggestion-index": "0.1.1", "request": "~2.16.2", + "rollup": "0.31.2", "sinon": "~1.6", "sinon-chai": "~2.3.1", "smash": "0.0", "svg-sprite": "1.2.19", "uglify-js": "~2.4.16", "xml2js": "~0.4.13", - "xmlbuilder": "~4.2.0" + "xmlbuilder": "~4.2.0", + "phantomjs-prebuilt": "2.1.7" }, "engines": { "node": ">=0.10.0" diff --git a/test/index.html b/test/index.html index 206a4039a..f93b5e2b8 100644 --- a/test/index.html +++ b/test/index.html @@ -14,7 +14,6 @@ - -