X-Git-Url: https://git.openstreetmap.org./rails.git/blobdiff_plain/5c5695d9c1317a958f85fe85eefb1dc92bb68178..09f6b8348607e709729d9e3c8d2678a668ab50bb:/vendor/assets/iD/iD.js diff --git a/vendor/assets/iD/iD.js b/vendor/assets/iD/iD.js index 9fc95e2fc..0c6f719a4 100644 --- a/vendor/assets/iD/iD.js +++ b/vendor/assets/iD/iD.js @@ -1,32 +1,11 @@ (() => { var __create = Object.create; var __defProp = Object.defineProperty; - var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; - var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; - var __propIsEnum = Object.prototype.propertyIsEnumerable; - var __knownSymbol = (name, symbol) => { - if (symbol = Symbol[name]) - return symbol; - throw Error("Symbol." + name + " is not defined"); - }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues = (a2, b2) => { - for (var prop in b2 || (b2 = {})) - if (__hasOwnProp.call(b2, prop)) - __defNormalProp(a2, prop, b2[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b2)) { - if (__propIsEnum.call(b2, prop)) - __defNormalProp(a2, prop, b2[prop]); - } - return a2; - }; - var __spreadProps = (a2, b2) => __defProps(a2, __getOwnPropDescs(b2)); var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { get: (a2, b2) => (typeof require !== "undefined" ? require : a2)[b2] }) : x2)(function(x2) { @@ -74,43 +53,6 @@ __accessCheck(obj, member, "access private method"); return method; }; - var __await = function(promise, isYieldStar) { - this[0] = promise; - this[1] = isYieldStar; - }; - var __yieldStar = (value) => { - var obj = value[__knownSymbol("asyncIterator")]; - var isAwait = false; - var method; - var it = {}; - if (obj == null) { - obj = value[__knownSymbol("iterator")](); - method = (k2) => it[k2] = (x2) => obj[k2](x2); - } else { - obj = obj.call(value); - method = (k2) => it[k2] = (v2) => { - if (isAwait) { - isAwait = false; - if (k2 === "throw") - throw v2; - return v2; - } - isAwait = true; - return { - done: false, - value: new __await(new Promise((resolve) => { - var x2 = obj[k2](v2); - if (!(x2 instanceof Object)) - throw TypeError("Object expected"); - resolve(x2); - }), 1) - }; - }; - } - return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x2) => { - throw x2; - }, "return" in obj && method("return"), it; - }; // node_modules/diacritics/index.js var require_diacritics = __commonJS({ @@ -513,15 +455,15 @@ var diacriticsMap = {}; for (i3 = 0; i3 < replacementList.length; i3 += 1) { chars = replacementList[i3].chars; - for (j3 = 0; j3 < chars.length; j3 += 1) { - diacriticsMap[chars[j3]] = replacementList[i3].base; + for (j2 = 0; j2 < chars.length; j2 += 1) { + diacriticsMap[chars[j2]] = replacementList[i3].base; } } var chars; - var j3; + var j2; var i3; - function removeDiacritics2(str2) { - return str2.replace(/[^\u0000-\u007e]/g, function(c2) { + function removeDiacritics2(str) { + return str.replace(/[^\u0000-\u007e]/g, function(c2) { return diacriticsMap[c2] || c2; }); } @@ -2884,8 +2826,8 @@ let normalForm = reference_1.ligatureList[v2]; if (normalForm !== "words") { let ligForms = Object.keys(unicode_ligatures_1.default[normalForm]); - for (let f3 = 0; f3 < ligForms.length; f3++) { - if (unicode_ligatures_1.default[normalForm][ligForms[f3]] === letter) { + for (let f2 = 0; f2 < ligForms.length; f2++) { + if (unicode_ligatures_1.default[normalForm][ligForms[f2]] === letter) { returnable += normalForm; return; } @@ -3096,10 +3038,10 @@ v2.isEmpty = !v2.major && !v2.minor && !v2.patch && !v2.build; v2.parsed = [v2.major, v2.minor, v2.patch, v2.build]; v2.text = v2.parsed.join("."); - v2.compare = compare; + v2.compare = compare2; return v2; } - function compare(v2) { + function compare2(v2) { if (typeof v2 === "string") { v2 = parseVersion3(v2); } @@ -3126,10 +3068,10 @@ typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.quickselect = factory(); })(exports2, function() { "use strict"; - function quickselect2(arr, k2, left, right, compare) { - quickselectStep(arr, k2, left || 0, right || arr.length - 1, compare || defaultCompare); + function quickselect2(arr, k2, left, right, compare2) { + quickselectStep(arr, k2, left || 0, right || arr.length - 1, compare2 || defaultCompare); } - function quickselectStep(arr, k2, left, right, compare) { + function quickselectStep(arr, k2, left, right, compare2) { while (right > left) { if (right - left > 600) { var n3 = right - left + 1; @@ -3139,39 +3081,39 @@ var sd = 0.5 * Math.sqrt(z2 * s2 * (n3 - s2) / n3) * (m2 - n3 / 2 < 0 ? -1 : 1); var newLeft = Math.max(left, Math.floor(k2 - m2 * s2 / n3 + sd)); var newRight = Math.min(right, Math.floor(k2 + (n3 - m2) * s2 / n3 + sd)); - quickselectStep(arr, k2, newLeft, newRight, compare); + quickselectStep(arr, k2, newLeft, newRight, compare2); } var t2 = arr[k2]; var i3 = left; - var j3 = right; + var j2 = right; swap2(arr, left, k2); - if (compare(arr[right], t2) > 0) + if (compare2(arr[right], t2) > 0) swap2(arr, left, right); - while (i3 < j3) { - swap2(arr, i3, j3); + while (i3 < j2) { + swap2(arr, i3, j2); i3++; - j3--; - while (compare(arr[i3], t2) < 0) + j2--; + while (compare2(arr[i3], t2) < 0) i3++; - while (compare(arr[j3], t2) > 0) - j3--; + while (compare2(arr[j2], t2) > 0) + j2--; } - if (compare(arr[left], t2) === 0) - swap2(arr, left, j3); + if (compare2(arr[left], t2) === 0) + swap2(arr, left, j2); else { - j3++; - swap2(arr, j3, right); + j2++; + swap2(arr, j2, right); } - if (j3 <= k2) - left = j3 + 1; - if (k2 <= j3) - right = j3 - 1; + if (j2 <= k2) + left = j2 + 1; + if (k2 <= j2) + right = j2 - 1; } } - function swap2(arr, i3, j3) { + function swap2(arr, i3, j2) { var tmp = arr[i3]; - arr[i3] = arr[j3]; - arr[j3] = tmp; + arr[i3] = arr[j2]; + arr[j2] = tmp; } function defaultCompare(a2, b2) { return a2 < b2 ? -1 : a2 > b2 ? 1 : 0; @@ -3348,14 +3290,14 @@ node = createNode([]); node.leaf = false; node.height = height; - var N22 = Math.ceil(N2 / M2), N1 = N22 * Math.ceil(Math.sqrt(M2)), i3, j3, right2, right3; + var N22 = Math.ceil(N2 / M2), N1 = N22 * Math.ceil(Math.sqrt(M2)), i3, j2, right2, right3; multiSelect(items, left, right, N1, this.compareMinX); for (i3 = left; i3 <= right; i3 += N1) { right2 = Math.min(i3 + N1 - 1, right); multiSelect(items, i3, right2, N22, this.compareMinY); - for (j3 = i3; j3 <= right2; j3 += N22) { - right3 = Math.min(j3 + N22 - 1, right2); - node.children.push(this._build(items, j3, right3, height - 1)); + for (j2 = i3; j2 <= right2; j2 += N22) { + right3 = Math.min(j2 + N22 - 1, right2); + node.children.push(this._build(items, j2, right3, height - 1)); } } calcBBox(node, this.toBBox); @@ -3450,8 +3392,8 @@ node.children.sort(compareMinX); }, // total margin of all possible split distributions where each node is at least m full - _allDistMargin: function(node, m2, M2, compare) { - node.children.sort(compare); + _allDistMargin: function(node, m2, M2, compare2) { + node.children.sort(compare2); var toBBox = this.toBBox, leftBBox = distBBox(node, 0, m2, toBBox), rightBBox = distBBox(node, M2 - m2, M2, toBBox), margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), i3, child; for (i3 = m2; i3 < M2 - m2; i3++) { child = node.children[i3]; @@ -3560,7 +3502,7 @@ maxY: -Infinity }; } - function multiSelect(arr, left, right, n3, compare) { + function multiSelect(arr, left, right, n3, compare2) { var stack = [left, right], mid; while (stack.length) { right = stack.pop(); @@ -3568,7 +3510,7 @@ if (right - left <= n3) continue; mid = left + Math.ceil((right - left) / n3 / 2) * n3; - quickselect2(arr, mid, left, right, compare); + quickselect2(arr, mid, left, right, compare2); stack.push(left, mid, mid, right); } } @@ -3688,8 +3630,8 @@ if (feature3.geometry.type === "Polygon") { bboxes.push(treeItem(coords, feature3.properties)); } else if (feature3.geometry.type === "MultiPolygon") { - for (var j3 = 0; j3 < coords.length; j3++) { - bboxes.push(treeItem(coords[j3], feature3.properties)); + for (var j2 = 0; j2 < coords.length; j2++) { + bboxes.push(treeItem(coords[j2], feature3.properties)); } } } @@ -3746,8 +3688,8 @@ var inside = false; for (var i3 = 0, len = rings.length; i3 < len; i3++) { var ring = rings[i3]; - for (var j3 = 0, len2 = ring.length, k2 = len2 - 1; j3 < len2; k2 = j3++) { - if (rayIntersect(p2, ring[j3], ring[k2])) + for (var j2 = 0, len2 = ring.length, k2 = len2 - 1; j2 < len2; k2 = j2++) { + if (rayIntersect(p2, ring[j2], ring[k2])) inside = !inside; } } @@ -4051,2797 +3993,772 @@ } }); - // node_modules/polygon-clipping/dist/polygon-clipping.umd.js - var require_polygon_clipping_umd = __commonJS({ - "node_modules/polygon-clipping/dist/polygon-clipping.umd.js"(exports2, module2) { - (function(global2, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.polygonClipping = factory()); - })(exports2, function() { - "use strict"; - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); + // node_modules/geojson-precision/index.js + var require_geojson_precision = __commonJS({ + "node_modules/geojson-precision/index.js"(exports2, module2) { + (function() { + function parse(t2, coordinatePrecision, extrasPrecision) { + function point2(p2) { + return p2.map(function(e3, index) { + if (index < 2) { + return 1 * e3.toFixed(coordinatePrecision); + } else { + return 1 * e3.toFixed(extrasPrecision); + } + }); } - } - function _defineProperties(target, props) { - for (var i3 = 0; i3 < props.length; i3++) { - var descriptor = props[i3]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) - descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); + function multi(l2) { + return l2.map(point2); + } + function poly(p2) { + return p2.map(multi); + } + function multiPoly(m2) { + return m2.map(poly); + } + function geometry(obj) { + if (!obj) { + return {}; + } + switch (obj.type) { + case "Point": + obj.coordinates = point2(obj.coordinates); + return obj; + case "LineString": + case "MultiPoint": + obj.coordinates = multi(obj.coordinates); + return obj; + case "Polygon": + case "MultiLineString": + obj.coordinates = poly(obj.coordinates); + return obj; + case "MultiPolygon": + obj.coordinates = multiPoly(obj.coordinates); + return obj; + case "GeometryCollection": + obj.geometries = obj.geometries.map(geometry); + return obj; + default: + return {}; + } + } + function feature3(obj) { + obj.geometry = geometry(obj.geometry); + return obj; + } + function featureCollection(f2) { + f2.features = f2.features.map(feature3); + return f2; + } + function geometryCollection(g3) { + g3.geometries = g3.geometries.map(geometry); + return g3; + } + if (!t2) { + return t2; + } + switch (t2.type) { + case "Feature": + return feature3(t2); + case "GeometryCollection": + return geometryCollection(t2); + case "FeatureCollection": + return featureCollection(t2); + case "Point": + case "LineString": + case "Polygon": + case "MultiPoint": + case "MultiPolygon": + case "MultiLineString": + return geometry(t2); + default: + return t2; } } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) - _defineProperties(Constructor, staticProps); - return Constructor; + module2.exports = parse; + module2.exports.parse = parse; + })(); + } + }); + + // node_modules/@aitodotai/json-stringify-pretty-compact/index.js + var require_json_stringify_pretty_compact = __commonJS({ + "node_modules/@aitodotai/json-stringify-pretty-compact/index.js"(exports2, module2) { + function isObject3(obj) { + return typeof obj === "object" && obj !== null; + } + function forEach(obj, cb) { + if (Array.isArray(obj)) { + obj.forEach(cb); + } else if (isObject3(obj)) { + Object.keys(obj).forEach(function(key) { + var val = obj[key]; + cb(val, key); + }); } - var Node = ( - /** @class */ - function() { - function Node2(key, data) { - this.next = null; - this.key = key; - this.data = data; - this.left = null; - this.right = null; + } + function getTreeDepth(obj) { + var depth = 0; + if (Array.isArray(obj) || isObject3(obj)) { + forEach(obj, function(val) { + if (Array.isArray(val) || isObject3(val)) { + var tmpDepth = getTreeDepth(val); + if (tmpDepth > depth) { + depth = tmpDepth; + } } - return Node2; - }() - ); - function DEFAULT_COMPARE(a2, b2) { - return a2 > b2 ? 1 : a2 < b2 ? -1 : 0; + }); + return depth + 1; } - function splay(i3, t2, comparator) { - var N2 = new Node(null, null); - var l2 = N2; - var r2 = N2; - while (true) { - var cmp2 = comparator(i3, t2.key); - if (cmp2 < 0) { - if (t2.left === null) - break; - if (comparator(i3, t2.left.key) < 0) { - var y2 = t2.left; - t2.left = y2.right; - y2.right = t2; - t2 = y2; - if (t2.left === null) - break; - } - r2.left = t2; - r2 = t2; - t2 = t2.left; - } else if (cmp2 > 0) { - if (t2.right === null) - break; - if (comparator(i3, t2.right.key) > 0) { - var y2 = t2.right; - t2.right = y2.left; - y2.left = t2; - t2 = y2; - if (t2.right === null) - break; + return depth; + } + function stringify3(obj, options2) { + options2 = options2 || {}; + var indent = JSON.stringify([1], null, get4(options2, "indent", 2)).slice(2, -3); + var addMargin = get4(options2, "margins", false); + var addArrayMargin = get4(options2, "arrayMargins", false); + var addObjectMargin = get4(options2, "objectMargins", false); + var maxLength = indent === "" ? Infinity : get4(options2, "maxLength", 80); + var maxNesting = get4(options2, "maxNesting", Infinity); + return function _stringify(obj2, currentIndent, reserved) { + if (obj2 && typeof obj2.toJSON === "function") { + obj2 = obj2.toJSON(); + } + var string = JSON.stringify(obj2); + if (string === void 0) { + return string; + } + var length2 = maxLength - currentIndent.length - reserved; + var treeDepth = getTreeDepth(obj2); + if (treeDepth <= maxNesting && string.length <= length2) { + var prettified = prettify(string, { + addMargin, + addArrayMargin, + addObjectMargin + }); + if (prettified.length <= length2) { + return prettified; + } + } + if (isObject3(obj2)) { + var nextIndent = currentIndent + indent; + var items = []; + var delimiters; + var comma = function(array2, index2) { + return index2 === array2.length - 1 ? 0 : 1; + }; + if (Array.isArray(obj2)) { + for (var index = 0; index < obj2.length; index++) { + items.push( + _stringify(obj2[index], nextIndent, comma(obj2, index)) || "null" + ); } - l2.right = t2; - l2 = t2; - t2 = t2.right; - } else - break; + delimiters = "[]"; + } else { + Object.keys(obj2).forEach(function(key, index2, array2) { + var keyPart = JSON.stringify(key) + ": "; + var value = _stringify( + obj2[key], + nextIndent, + keyPart.length + comma(array2, index2) + ); + if (value !== void 0) { + items.push(keyPart + value); + } + }); + delimiters = "{}"; + } + if (items.length > 0) { + return [ + delimiters[0], + indent + items.join(",\n" + nextIndent), + delimiters[1] + ].join("\n" + currentIndent); + } } - l2.right = t2.left; - r2.left = t2.right; - t2.left = N2.right; - t2.right = N2.left; - return t2; + return string; + }(obj, "", 0); + } + var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,\][}{]/g; + function prettify(string, options2) { + options2 = options2 || {}; + var tokens = { + "{": "{", + "}": "}", + "[": "[", + "]": "]", + ",": ", ", + ":": ": " + }; + if (options2.addMargin || options2.addObjectMargin) { + tokens["{"] = "{ "; + tokens["}"] = " }"; } - function insert(i3, data, t2, comparator) { - var node = new Node(i3, data); - if (t2 === null) { - node.left = node.right = null; - return node; + if (options2.addMargin || options2.addArrayMargin) { + tokens["["] = "[ "; + tokens["]"] = " ]"; + } + return string.replace(stringOrChar, function(match, string2) { + return string2 ? match : tokens[match]; + }); + } + function get4(options2, name, defaultValue) { + return name in options2 ? options2[name] : defaultValue; + } + module2.exports = stringify3; + } + }); + + // node_modules/aes-js/index.js + var require_aes_js = __commonJS({ + "node_modules/aes-js/index.js"(exports2, module2) { + (function(root3) { + "use strict"; + function checkInt(value) { + return parseInt(value) === value; + } + function checkInts(arrayish) { + if (!checkInt(arrayish.length)) { + return false; } - t2 = splay(i3, t2, comparator); - var cmp2 = comparator(i3, t2.key); - if (cmp2 < 0) { - node.left = t2.left; - node.right = t2; - t2.left = null; - } else if (cmp2 >= 0) { - node.right = t2.right; - node.left = t2; - t2.right = null; + for (var i3 = 0; i3 < arrayish.length; i3++) { + if (!checkInt(arrayish[i3]) || arrayish[i3] < 0 || arrayish[i3] > 255) { + return false; + } } - return node; + return true; } - function split(key, v2, comparator) { - var left = null; - var right = null; - if (v2) { - v2 = splay(key, v2, comparator); - var cmp2 = comparator(v2.key, key); - if (cmp2 === 0) { - left = v2.left; - right = v2.right; - } else if (cmp2 < 0) { - right = v2.right; - v2.right = null; - left = v2; - } else { - left = v2.left; - v2.left = null; - right = v2; + function coerceArray(arg, copy2) { + if (arg.buffer && arg.name === "Uint8Array") { + if (copy2) { + if (arg.slice) { + arg = arg.slice(); + } else { + arg = Array.prototype.slice.call(arg); + } } + return arg; } - return { - left, - right - }; + if (Array.isArray(arg)) { + if (!checkInts(arg)) { + throw new Error("Array contains invalid value: " + arg); + } + return new Uint8Array(arg); + } + if (checkInt(arg.length) && checkInts(arg)) { + return new Uint8Array(arg); + } + throw new Error("unsupported array-like object"); } - function merge2(left, right, comparator) { - if (right === null) - return left; - if (left === null) - return right; - right = splay(left.key, right, comparator); - right.left = left; - return right; + function createArray(length2) { + return new Uint8Array(length2); } - function printRow(root3, prefix, isTail, out, printNode) { - if (root3) { - out("" + prefix + (isTail ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ") + printNode(root3) + "\n"); - var indent2 = prefix + (isTail ? " " : "\u2502 "); - if (root3.left) - printRow(root3.left, indent2, false, out, printNode); - if (root3.right) - printRow(root3.right, indent2, true, out, printNode); + function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) { + if (sourceStart != null || sourceEnd != null) { + if (sourceArray.slice) { + sourceArray = sourceArray.slice(sourceStart, sourceEnd); + } else { + sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd); + } } + targetArray.set(sourceArray, targetStart); } - var Tree = ( - /** @class */ - function() { - function Tree2(comparator) { - if (comparator === void 0) { - comparator = DEFAULT_COMPARE; + var convertUtf8 = /* @__PURE__ */ function() { + function toBytes(text) { + var result = [], i3 = 0; + text = encodeURI(text); + while (i3 < text.length) { + var c2 = text.charCodeAt(i3++); + if (c2 === 37) { + result.push(parseInt(text.substr(i3, 2), 16)); + i3 += 2; + } else { + result.push(c2); } - this._root = null; - this._size = 0; - this._comparator = comparator; } - Tree2.prototype.insert = function(key, data) { - this._size++; - return this._root = insert(key, data, this._root, this._comparator); - }; - Tree2.prototype.add = function(key, data) { - var node = new Node(key, data); - if (this._root === null) { - node.left = node.right = null; - this._size++; - this._root = node; + return coerceArray(result); + } + function fromBytes(bytes) { + var result = [], i3 = 0; + while (i3 < bytes.length) { + var c2 = bytes[i3]; + if (c2 < 128) { + result.push(String.fromCharCode(c2)); + i3++; + } else if (c2 > 191 && c2 < 224) { + result.push(String.fromCharCode((c2 & 31) << 6 | bytes[i3 + 1] & 63)); + i3 += 2; + } else { + result.push(String.fromCharCode((c2 & 15) << 12 | (bytes[i3 + 1] & 63) << 6 | bytes[i3 + 2] & 63)); + i3 += 3; } - var comparator = this._comparator; - var t2 = splay(key, this._root, comparator); - var cmp2 = comparator(key, t2.key); - if (cmp2 === 0) - this._root = t2; - else { - if (cmp2 < 0) { - node.left = t2.left; - node.right = t2; - t2.left = null; - } else if (cmp2 > 0) { - node.right = t2.right; - node.left = t2; - t2.right = null; - } - this._size++; - this._root = node; + } + return result.join(""); + } + return { + toBytes, + fromBytes + }; + }(); + var convertHex = /* @__PURE__ */ function() { + function toBytes(text) { + var result = []; + for (var i3 = 0; i3 < text.length; i3 += 2) { + result.push(parseInt(text.substr(i3, 2), 16)); + } + return result; + } + var Hex = "0123456789abcdef"; + function fromBytes(bytes) { + var result = []; + for (var i3 = 0; i3 < bytes.length; i3++) { + var v2 = bytes[i3]; + result.push(Hex[(v2 & 240) >> 4] + Hex[v2 & 15]); + } + return result.join(""); + } + return { + toBytes, + fromBytes + }; + }(); + var numberOfRounds = { 16: 10, 24: 12, 32: 14 }; + var rcon = [1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145]; + var S2 = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]; + var Si = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125]; + var T1 = [3328402341, 4168907908, 4000806809, 4135287693, 4294111757, 3597364157, 3731845041, 2445657428, 1613770832, 33620227, 3462883241, 1445669757, 3892248089, 3050821474, 1303096294, 3967186586, 2412431941, 528646813, 2311702848, 4202528135, 4026202645, 2992200171, 2387036105, 4226871307, 1101901292, 3017069671, 1604494077, 1169141738, 597466303, 1403299063, 3832705686, 2613100635, 1974974402, 3791519004, 1033081774, 1277568618, 1815492186, 2118074177, 4126668546, 2211236943, 1748251740, 1369810420, 3521504564, 4193382664, 3799085459, 2883115123, 1647391059, 706024767, 134480908, 2512897874, 1176707941, 2646852446, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, 3756188221, 3454790438, 1311188841, 2142417613, 3933566367, 302582043, 495158174, 1479289972, 874125870, 907746093, 3698224818, 3025820398, 1537253627, 2756858614, 1983593293, 3084310113, 2108928974, 1378429307, 3722699582, 1580150641, 327451799, 2790478837, 3117535592, 0, 3253595436, 1075847264, 3825007647, 2041688520, 3059440621, 3563743934, 2378943302, 1740553945, 1916352843, 2487896798, 2555137236, 2958579944, 2244988746, 3151024235, 3320835882, 1336584933, 3992714006, 2252555205, 2588757463, 1714631509, 293963156, 2319795663, 3925473552, 67240454, 4269768577, 2689618160, 2017213508, 631218106, 1269344483, 2723238387, 1571005438, 2151694528, 93294474, 1066570413, 563977660, 1882732616, 4059428100, 1673313503, 2008463041, 2950355573, 1109467491, 537923632, 3858759450, 4260623118, 3218264685, 2177748300, 403442708, 638784309, 3287084079, 3193921505, 899127202, 2286175436, 773265209, 2479146071, 1437050866, 4236148354, 2050833735, 3362022572, 3126681063, 840505643, 3866325909, 3227541664, 427917720, 2655997905, 2749160575, 1143087718, 1412049534, 999329963, 193497219, 2353415882, 3354324521, 1807268051, 672404540, 2816401017, 3160301282, 369822493, 2916866934, 3688947771, 1681011286, 1949973070, 336202270, 2454276571, 201721354, 1210328172, 3093060836, 2680341085, 3184776046, 1135389935, 3294782118, 965841320, 831886756, 3554993207, 4068047243, 3588745010, 2345191491, 1849112409, 3664604599, 26054028, 2983581028, 2622377682, 1235855840, 3630984372, 2891339514, 4092916743, 3488279077, 3395642799, 4101667470, 1202630377, 268961816, 1874508501, 4034427016, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, 2546386513, 3421038627, 2715671932, 3899946140, 1042226977, 2521517021, 1639824860, 227249030, 260737669, 3765465232, 2084453954, 1907733956, 3429263018, 2420656344, 100860677, 4160157185, 470683154, 3261161891, 1781871967, 2924959737, 1773779408, 394692241, 2579611992, 974986535, 664706745, 3655459128, 3958962195, 731420851, 571543859, 3530123707, 2849626480, 126783113, 865375399, 765172662, 1008606754, 361203602, 3387549984, 2278477385, 2857719295, 1344809080, 2782912378, 59542671, 1503764984, 160008576, 437062935, 1707065306, 3622233649, 2218934982, 3496503480, 2185314755, 697932208, 1512910199, 504303377, 2075177163, 2824099068, 1841019862, 739644986]; + var T2 = [2781242211, 2230877308, 2582542199, 2381740923, 234877682, 3184946027, 2984144751, 1418839493, 1348481072, 50462977, 2848876391, 2102799147, 434634494, 1656084439, 3863849899, 2599188086, 1167051466, 2636087938, 1082771913, 2281340285, 368048890, 3954334041, 3381544775, 201060592, 3963727277, 1739838676, 4250903202, 3930435503, 3206782108, 4149453988, 2531553906, 1536934080, 3262494647, 484572669, 2923271059, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, 4098991525, 886171109, 150598129, 2481090929, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, 2704774806, 252314885, 3039795866, 151914247, 908333586, 2602270848, 1038082786, 651029483, 1766729511, 3447698098, 2682942837, 454166793, 2652734339, 1951935532, 775166490, 758520603, 3000790638, 4004797018, 4217086112, 4137964114, 1299594043, 1639438038, 3464344499, 2068982057, 1054729187, 1901997871, 2534638724, 4121318227, 1757008337, 0, 750906861, 1614815264, 535035132, 3363418545, 3988151131, 3201591914, 1183697867, 3647454910, 1265776953, 3734260298, 3566750796, 3903871064, 1250283471, 1807470800, 717615087, 3847203498, 384695291, 3313910595, 3617213773, 1432761139, 2484176261, 3481945413, 283769337, 100925954, 2180939647, 4037038160, 1148730428, 3123027871, 3813386408, 4087501137, 4267549603, 3229630528, 2315620239, 2906624658, 3156319645, 1215313976, 82966005, 3747855548, 3245848246, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, 3787349855, 2721421207, 3431482436, 959321879, 1469301956, 4065699751, 2197585534, 1199193405, 2898814052, 3887750493, 724703513, 2514908019, 2696962144, 2551808385, 3516813135, 2141445340, 1715741218, 2119445034, 2872807568, 2198571144, 3398190662, 700968686, 3547052216, 1009259540, 2041044702, 3803995742, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, 3683797321, 168560134, 1816667172, 3837287516, 1570751170, 1857934291, 4014189740, 2797888098, 2822345105, 2754712981, 936633572, 2347923833, 852879335, 1133234376, 1500395319, 3084545389, 2348912013, 1689376213, 3533459022, 3762923945, 3034082412, 4205598294, 133428468, 634383082, 2949277029, 2398386810, 3913789102, 403703816, 3580869306, 2297460856, 1867130149, 1918643758, 607656988, 4049053350, 3346248884, 1368901318, 600565992, 2090982877, 2632479860, 557719327, 3717614411, 3697393085, 2249034635, 2232388234, 2430627952, 1115438654, 3295786421, 2865522278, 3633334344, 84280067, 33027830, 303828494, 2747425121, 1600795957, 4188952407, 3496589753, 2434238086, 1486471617, 658119965, 3106381470, 953803233, 334231800, 3005978776, 857870609, 3151128937, 1890179545, 2298973838, 2805175444, 3056442267, 574365214, 2450884487, 550103529, 1233637070, 4289353045, 2018519080, 2057691103, 2399374476, 4166623649, 2148108681, 387583245, 3664101311, 836232934, 3330556482, 3100665960, 3280093505, 2955516313, 2002398509, 287182607, 3413881008, 4238890068, 3597515707, 975967766]; + var T3 = [1671808611, 2089089148, 2006576759, 2072901243, 4061003762, 1807603307, 1873927791, 3310653893, 810573872, 16974337, 1739181671, 729634347, 4263110654, 3613570519, 2883997099, 1989864566, 3393556426, 2191335298, 3376449993, 2106063485, 4195741690, 1508618841, 1204391495, 4027317232, 2917941677, 3563566036, 2734514082, 2951366063, 2629772188, 2767672228, 1922491506, 3227229120, 3082974647, 4246528509, 2477669779, 644500518, 911895606, 1061256767, 4144166391, 3427763148, 878471220, 2784252325, 3845444069, 4043897329, 1905517169, 3631459288, 827548209, 356461077, 67897348, 3344078279, 593839651, 3277757891, 405286936, 2527147926, 84871685, 2595565466, 118033927, 305538066, 2157648768, 3795705826, 3945188843, 661212711, 2999812018, 1973414517, 152769033, 2208177539, 745822252, 439235610, 455947803, 1857215598, 1525593178, 2700827552, 1391895634, 994932283, 3596728278, 3016654259, 695947817, 3812548067, 795958831, 2224493444, 1408607827, 3513301457, 0, 3979133421, 543178784, 4229948412, 2982705585, 1542305371, 1790891114, 3410398667, 3201918910, 961245753, 1256100938, 1289001036, 1491644504, 3477767631, 3496721360, 4012557807, 2867154858, 4212583931, 1137018435, 1305975373, 861234739, 2241073541, 1171229253, 4178635257, 33948674, 2139225727, 1357946960, 1011120188, 2679776671, 2833468328, 1374921297, 2751356323, 1086357568, 2408187279, 2460827538, 2646352285, 944271416, 4110742005, 3168756668, 3066132406, 3665145818, 560153121, 271589392, 4279952895, 4077846003, 3530407890, 3444343245, 202643468, 322250259, 3962553324, 1608629855, 2543990167, 1154254916, 389623319, 3294073796, 2817676711, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, 2174228865, 1339137615, 3699352540, 577127458, 712922154, 2427141008, 2290289544, 1187679302, 3995715566, 3100863416, 339486740, 3732514782, 1591917662, 186455563, 3681988059, 3762019296, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, 3260915650, 3547250131, 2901361580, 1655096418, 2443721105, 2510565781, 3828863972, 2039214713, 3878868455, 3359869896, 928607799, 1840765549, 2374762893, 3580146133, 1322425422, 2850048425, 1823791212, 1459268694, 4094161908, 3928346602, 1706019429, 2056189050, 2934523822, 135794696, 3134549946, 2022240376, 628050469, 779246638, 472135708, 2800834470, 3032970164, 3327236038, 3894660072, 3715932637, 1956440180, 522272287, 1272813131, 3185336765, 2340818315, 2323976074, 1888542832, 1044544574, 3049550261, 1722469478, 1222152264, 50660867, 4127324150, 236067854, 1638122081, 895445557, 1475980887, 3117443513, 2257655686, 3243809217, 489110045, 2662934430, 3778599393, 4162055160, 2561878936, 288563729, 1773916777, 3648039385, 2391345038, 2493985684, 2612407707, 505560094, 2274497927, 3911240169, 3460925390, 1442818645, 678973480, 3749357023, 2358182796, 2717407649, 2306869641, 219617805, 3218761151, 3862026214, 1120306242, 1756942440, 1103331905, 2578459033, 762796589, 252780047, 2966125488, 1425844308, 3151392187, 372911126]; + var T4 = [1667474886, 2088535288, 2004326894, 2071694838, 4075949567, 1802223062, 1869591006, 3318043793, 808472672, 16843522, 1734846926, 724270422, 4278065639, 3621216949, 2880169549, 1987484396, 3402253711, 2189597983, 3385409673, 2105378810, 4210693615, 1499065266, 1195886990, 4042263547, 2913856577, 3570689971, 2728590687, 2947541573, 2627518243, 2762274643, 1920112356, 3233831835, 3082273397, 4261223649, 2475929149, 640051788, 909531756, 1061110142, 4160160501, 3435941763, 875846760, 2779116625, 3857003729, 4059105529, 1903268834, 3638064043, 825316194, 353713962, 67374088, 3351728789, 589522246, 3284360861, 404236336, 2526454071, 84217610, 2593830191, 117901582, 303183396, 2155911963, 3806477791, 3958056653, 656894286, 2998062463, 1970642922, 151591698, 2206440989, 741110872, 437923380, 454765878, 1852748508, 1515908788, 2694904667, 1381168804, 993742198, 3604373943, 3014905469, 690584402, 3823320797, 791638366, 2223281939, 1398011302, 3520161977, 0, 3991743681, 538992704, 4244381667, 2981218425, 1532751286, 1785380564, 3419096717, 3200178535, 960056178, 1246420628, 1280103576, 1482221744, 3486468741, 3503319995, 4025428677, 2863326543, 4227536621, 1128514950, 1296947098, 859002214, 2240123921, 1162203018, 4193849577, 33687044, 2139062782, 1347481760, 1010582648, 2678045221, 2829640523, 1364325282, 2745433693, 1077985408, 2408548869, 2459086143, 2644360225, 943212656, 4126475505, 3166494563, 3065430391, 3671750063, 555836226, 269496352, 4294908645, 4092792573, 3537006015, 3452783745, 202118168, 320025894, 3974901699, 1600119230, 2543297077, 1145359496, 387397934, 3301201811, 2812801621, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, 2172753945, 1330631070, 3705438115, 572679748, 707427924, 2425400123, 2290647819, 1179044492, 4008585671, 3099120491, 336870440, 3739122087, 1583276732, 185277718, 3688593069, 3772791771, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, 3267517855, 3553849021, 2897014595, 1650632388, 2442242105, 2509612081, 3840161747, 2038008818, 3890688725, 3368567691, 926374254, 1835907034, 2374863873, 3587531953, 1313788572, 2846482505, 1819063512, 1448540844, 4109633523, 3941213647, 1701162954, 2054852340, 2930698567, 134748176, 3132806511, 2021165296, 623210314, 774795868, 471606328, 2795958615, 3031746419, 3334885783, 3907527627, 3722280097, 1953799400, 522133822, 1263263126, 3183336545, 2341176845, 2324333839, 1886425312, 1044267644, 3048588401, 1718004428, 1212733584, 50529542, 4143317495, 235803164, 1633788866, 892690282, 1465383342, 3115962473, 2256965911, 3250673817, 488449850, 2661202215, 3789633753, 4177007595, 2560144171, 286339874, 1768537042, 3654906025, 2391705863, 2492770099, 2610673197, 505291324, 2273808917, 3924369609, 3469625735, 1431699370, 673740880, 3755965093, 2358021891, 2711746649, 2307489801, 218961690, 3217021541, 3873845719, 1111672452, 1751693520, 1094828930, 2576986153, 757954394, 252645662, 2964376443, 1414855848, 3149649517, 370555436]; + var T5 = [1374988112, 2118214995, 437757123, 975658646, 1001089995, 530400753, 2902087851, 1273168787, 540080725, 2910219766, 2295101073, 4110568485, 1340463100, 3307916247, 641025152, 3043140495, 3736164937, 632953703, 1172967064, 1576976609, 3274667266, 2169303058, 2370213795, 1809054150, 59727847, 361929877, 3211623147, 2505202138, 3569255213, 1484005843, 1239443753, 2395588676, 1975683434, 4102977912, 2572697195, 666464733, 3202437046, 4035489047, 3374361702, 2110667444, 1675577880, 3843699074, 2538681184, 1649639237, 2976151520, 3144396420, 4269907996, 4178062228, 1883793496, 2403728665, 2497604743, 1383856311, 2876494627, 1917518562, 3810496343, 1716890410, 3001755655, 800440835, 2261089178, 3543599269, 807962610, 599762354, 33778362, 3977675356, 2328828971, 2809771154, 4077384432, 1315562145, 1708848333, 101039829, 3509871135, 3299278474, 875451293, 2733856160, 92987698, 2767645557, 193195065, 1080094634, 1584504582, 3178106961, 1042385657, 2531067453, 3711829422, 1306967366, 2438237621, 1908694277, 67556463, 1615861247, 429456164, 3602770327, 2302690252, 1742315127, 2968011453, 126454664, 3877198648, 2043211483, 2709260871, 2084704233, 4169408201, 0, 159417987, 841739592, 504459436, 1817866830, 4245618683, 260388950, 1034867998, 908933415, 168810852, 1750902305, 2606453969, 607530554, 202008497, 2472011535, 3035535058, 463180190, 2160117071, 1641816226, 1517767529, 470948374, 3801332234, 3231722213, 1008918595, 303765277, 235474187, 4069246893, 766945465, 337553864, 1475418501, 2943682380, 4003061179, 2743034109, 4144047775, 1551037884, 1147550661, 1543208500, 2336434550, 3408119516, 3069049960, 3102011747, 3610369226, 1113818384, 328671808, 2227573024, 2236228733, 3535486456, 2935566865, 3341394285, 496906059, 3702665459, 226906860, 2009195472, 733156972, 2842737049, 294930682, 1206477858, 2835123396, 2700099354, 1451044056, 573804783, 2269728455, 3644379585, 2362090238, 2564033334, 2801107407, 2776292904, 3669462566, 1068351396, 742039012, 1350078989, 1784663195, 1417561698, 4136440770, 2430122216, 775550814, 2193862645, 2673705150, 1775276924, 1876241833, 3475313331, 3366754619, 270040487, 3902563182, 3678124923, 3441850377, 1851332852, 3969562369, 2203032232, 3868552805, 2868897406, 566021896, 4011190502, 3135740889, 1248802510, 3936291284, 699432150, 832877231, 708780849, 3332740144, 899835584, 1951317047, 4236429990, 3767586992, 866637845, 4043610186, 1106041591, 2144161806, 395441711, 1984812685, 1139781709, 3433712980, 3835036895, 2664543715, 1282050075, 3240894392, 1181045119, 2640243204, 25965917, 4203181171, 4211818798, 3009879386, 2463879762, 3910161971, 1842759443, 2597806476, 933301370, 1509430414, 3943906441, 3467192302, 3076639029, 3776767469, 2051518780, 2631065433, 1441952575, 404016761, 1942435775, 1408749034, 1610459739, 3745345300, 2017778566, 3400528769, 3110650942, 941896748, 3265478751, 371049330, 3168937228, 675039627, 4279080257, 967311729, 135050206, 3635733660, 1683407248, 2076935265, 3576870512, 1215061108, 3501741890]; + var T6 = [1347548327, 1400783205, 3273267108, 2520393566, 3409685355, 4045380933, 2880240216, 2471224067, 1428173050, 4138563181, 2441661558, 636813900, 4233094615, 3620022987, 2149987652, 2411029155, 1239331162, 1730525723, 2554718734, 3781033664, 46346101, 310463728, 2743944855, 3328955385, 3875770207, 2501218972, 3955191162, 3667219033, 768917123, 3545789473, 692707433, 1150208456, 1786102409, 2029293177, 1805211710, 3710368113, 3065962831, 401639597, 1724457132, 3028143674, 409198410, 2196052529, 1620529459, 1164071807, 3769721975, 2226875310, 486441376, 2499348523, 1483753576, 428819965, 2274680428, 3075636216, 598438867, 3799141122, 1474502543, 711349675, 129166120, 53458370, 2592523643, 2782082824, 4063242375, 2988687269, 3120694122, 1559041666, 730517276, 2460449204, 4042459122, 2706270690, 3446004468, 3573941694, 533804130, 2328143614, 2637442643, 2695033685, 839224033, 1973745387, 957055980, 2856345839, 106852767, 1371368976, 4181598602, 1033297158, 2933734917, 1179510461, 3046200461, 91341917, 1862534868, 4284502037, 605657339, 2547432937, 3431546947, 2003294622, 3182487618, 2282195339, 954669403, 3682191598, 1201765386, 3917234703, 3388507166, 0, 2198438022, 1211247597, 2887651696, 1315723890, 4227665663, 1443857720, 507358933, 657861945, 1678381017, 560487590, 3516619604, 975451694, 2970356327, 261314535, 3535072918, 2652609425, 1333838021, 2724322336, 1767536459, 370938394, 182621114, 3854606378, 1128014560, 487725847, 185469197, 2918353863, 3106780840, 3356761769, 2237133081, 1286567175, 3152976349, 4255350624, 2683765030, 3160175349, 3309594171, 878443390, 1988838185, 3704300486, 1756818940, 1673061617, 3403100636, 272786309, 1075025698, 545572369, 2105887268, 4174560061, 296679730, 1841768865, 1260232239, 4091327024, 3960309330, 3497509347, 1814803222, 2578018489, 4195456072, 575138148, 3299409036, 446754879, 3629546796, 4011996048, 3347532110, 3252238545, 4270639778, 915985419, 3483825537, 681933534, 651868046, 2755636671, 3828103837, 223377554, 2607439820, 1649704518, 3270937875, 3901806776, 1580087799, 4118987695, 3198115200, 2087309459, 2842678573, 3016697106, 1003007129, 2802849917, 1860738147, 2077965243, 164439672, 4100872472, 32283319, 2827177882, 1709610350, 2125135846, 136428751, 3874428392, 3652904859, 3460984630, 3572145929, 3593056380, 2939266226, 824852259, 818324884, 3224740454, 930369212, 2801566410, 2967507152, 355706840, 1257309336, 4148292826, 243256656, 790073846, 2373340630, 1296297904, 1422699085, 3756299780, 3818836405, 457992840, 3099667487, 2135319889, 77422314, 1560382517, 1945798516, 788204353, 1521706781, 1385356242, 870912086, 325965383, 2358957921, 2050466060, 2388260884, 2313884476, 4006521127, 901210569, 3990953189, 1014646705, 1503449823, 1062597235, 2031621326, 3212035895, 3931371469, 1533017514, 350174575, 2256028891, 2177544179, 1052338372, 741876788, 1606591296, 1914052035, 213705253, 2334669897, 1107234197, 1899603969, 3725069491, 2631447780, 2422494913, 1635502980, 1893020342, 1950903388, 1120974935]; + var T7 = [2807058932, 1699970625, 2764249623, 1586903591, 1808481195, 1173430173, 1487645946, 59984867, 4199882800, 1844882806, 1989249228, 1277555970, 3623636965, 3419915562, 1149249077, 2744104290, 1514790577, 459744698, 244860394, 3235995134, 1963115311, 4027744588, 2544078150, 4190530515, 1608975247, 2627016082, 2062270317, 1507497298, 2200818878, 567498868, 1764313568, 3359936201, 2305455554, 2037970062, 1047239e3, 1910319033, 1337376481, 2904027272, 2892417312, 984907214, 1243112415, 830661914, 861968209, 2135253587, 2011214180, 2927934315, 2686254721, 731183368, 1750626376, 4246310725, 1820824798, 4172763771, 3542330227, 48394827, 2404901663, 2871682645, 671593195, 3254988725, 2073724613, 145085239, 2280796200, 2779915199, 1790575107, 2187128086, 472615631, 3029510009, 4075877127, 3802222185, 4107101658, 3201631749, 1646252340, 4270507174, 1402811438, 1436590835, 3778151818, 3950355702, 3963161475, 4020912224, 2667994737, 273792366, 2331590177, 104699613, 95345982, 3175501286, 2377486676, 1560637892, 3564045318, 369057872, 4213447064, 3919042237, 1137477952, 2658625497, 1119727848, 2340947849, 1530455833, 4007360968, 172466556, 266959938, 516552836, 0, 2256734592, 3980931627, 1890328081, 1917742170, 4294704398, 945164165, 3575528878, 958871085, 3647212047, 2787207260, 1423022939, 775562294, 1739656202, 3876557655, 2530391278, 2443058075, 3310321856, 547512796, 1265195639, 437656594, 3121275539, 719700128, 3762502690, 387781147, 218828297, 3350065803, 2830708150, 2848461854, 428169201, 122466165, 3720081049, 1627235199, 648017665, 4122762354, 1002783846, 2117360635, 695634755, 3336358691, 4234721005, 4049844452, 3704280881, 2232435299, 574624663, 287343814, 612205898, 1039717051, 840019705, 2708326185, 793451934, 821288114, 1391201670, 3822090177, 376187827, 3113855344, 1224348052, 1679968233, 2361698556, 1058709744, 752375421, 2431590963, 1321699145, 3519142200, 2734591178, 188127444, 2177869557, 3727205754, 2384911031, 3215212461, 2648976442, 2450346104, 3432737375, 1180849278, 331544205, 3102249176, 4150144569, 2952102595, 2159976285, 2474404304, 766078933, 313773861, 2570832044, 2108100632, 1668212892, 3145456443, 2013908262, 418672217, 3070356634, 2594734927, 1852171925, 3867060991, 3473416636, 3907448597, 2614737639, 919489135, 164948639, 2094410160, 2997825956, 590424639, 2486224549, 1723872674, 3157750862, 3399941250, 3501252752, 3625268135, 2555048196, 3673637356, 1343127501, 4130281361, 3599595085, 2957853679, 1297403050, 81781910, 3051593425, 2283490410, 532201772, 1367295589, 3926170974, 895287692, 1953757831, 1093597963, 492483431, 3528626907, 1446242576, 1192455638, 1636604631, 209336225, 344873464, 1015671571, 669961897, 3375740769, 3857572124, 2973530695, 3747192018, 1933530610, 3464042516, 935293895, 3454686199, 2858115069, 1863638845, 3683022916, 4085369519, 3292445032, 875313188, 1080017571, 3279033885, 621591778, 1233856572, 2504130317, 24197544, 3017672716, 3835484340, 3247465558, 2220981195, 3060847922, 1551124588, 1463996600]; + var T8 = [4104605777, 1097159550, 396673818, 660510266, 2875968315, 2638606623, 4200115116, 3808662347, 821712160, 1986918061, 3430322568, 38544885, 3856137295, 718002117, 893681702, 1654886325, 2975484382, 3122358053, 3926825029, 4274053469, 796197571, 1290801793, 1184342925, 3556361835, 2405426947, 2459735317, 1836772287, 1381620373, 3196267988, 1948373848, 3764988233, 3385345166, 3263785589, 2390325492, 1480485785, 3111247143, 3780097726, 2293045232, 548169417, 3459953789, 3746175075, 439452389, 1362321559, 1400849762, 1685577905, 1806599355, 2174754046, 137073913, 1214797936, 1174215055, 3731654548, 2079897426, 1943217067, 1258480242, 529487843, 1437280870, 3945269170, 3049390895, 3313212038, 923313619, 679998e3, 3215307299, 57326082, 377642221, 3474729866, 2041877159, 133361907, 1776460110, 3673476453, 96392454, 878845905, 2801699524, 777231668, 4082475170, 2330014213, 4142626212, 2213296395, 1626319424, 1906247262, 1846563261, 562755902, 3708173718, 1040559837, 3871163981, 1418573201, 3294430577, 114585348, 1343618912, 2566595609, 3186202582, 1078185097, 3651041127, 3896688048, 2307622919, 425408743, 3371096953, 2081048481, 1108339068, 2216610296, 0, 2156299017, 736970802, 292596766, 1517440620, 251657213, 2235061775, 2933202493, 758720310, 265905162, 1554391400, 1532285339, 908999204, 174567692, 1474760595, 4002861748, 2610011675, 3234156416, 3693126241, 2001430874, 303699484, 2478443234, 2687165888, 585122620, 454499602, 151849742, 2345119218, 3064510765, 514443284, 4044981591, 1963412655, 2581445614, 2137062819, 19308535, 1928707164, 1715193156, 4219352155, 1126790795, 600235211, 3992742070, 3841024952, 836553431, 1669664834, 2535604243, 3323011204, 1243905413, 3141400786, 4180808110, 698445255, 2653899549, 2989552604, 2253581325, 3252932727, 3004591147, 1891211689, 2487810577, 3915653703, 4237083816, 4030667424, 2100090966, 865136418, 1229899655, 953270745, 3399679628, 3557504664, 4118925222, 2061379749, 3079546586, 2915017791, 983426092, 2022837584, 1607244650, 2118541908, 2366882550, 3635996816, 972512814, 3283088770, 1568718495, 3499326569, 3576539503, 621982671, 2895723464, 410887952, 2623762152, 1002142683, 645401037, 1494807662, 2595684844, 1335535747, 2507040230, 4293295786, 3167684641, 367585007, 3885750714, 1865862730, 2668221674, 2960971305, 2763173681, 1059270954, 2777952454, 2724642869, 1320957812, 2194319100, 2429595872, 2815956275, 77089521, 3973773121, 3444575871, 2448830231, 1305906550, 4021308739, 2857194700, 2516901860, 3518358430, 1787304780, 740276417, 1699839814, 1592394909, 2352307457, 2272556026, 188821243, 1729977011, 3687994002, 274084841, 3594982253, 3613494426, 2701949495, 4162096729, 322734571, 2837966542, 1640576439, 484830689, 1202797690, 3537852828, 4067639125, 349075736, 3342319475, 4157467219, 4255800159, 1030690015, 1155237496, 2951971274, 1757691577, 607398968, 2738905026, 499347990, 3794078908, 1011452712, 227885567, 2818666809, 213114376, 3034881240, 1455525988, 3414450555, 850817237, 1817998408, 3092726480]; + var U1 = [0, 235474187, 470948374, 303765277, 941896748, 908933415, 607530554, 708780849, 1883793496, 2118214995, 1817866830, 1649639237, 1215061108, 1181045119, 1417561698, 1517767529, 3767586992, 4003061179, 4236429990, 4069246893, 3635733660, 3602770327, 3299278474, 3400528769, 2430122216, 2664543715, 2362090238, 2193862645, 2835123396, 2801107407, 3035535058, 3135740889, 3678124923, 3576870512, 3341394285, 3374361702, 3810496343, 3977675356, 4279080257, 4043610186, 2876494627, 2776292904, 3076639029, 3110650942, 2472011535, 2640243204, 2403728665, 2169303058, 1001089995, 899835584, 666464733, 699432150, 59727847, 226906860, 530400753, 294930682, 1273168787, 1172967064, 1475418501, 1509430414, 1942435775, 2110667444, 1876241833, 1641816226, 2910219766, 2743034109, 2976151520, 3211623147, 2505202138, 2606453969, 2302690252, 2269728455, 3711829422, 3543599269, 3240894392, 3475313331, 3843699074, 3943906441, 4178062228, 4144047775, 1306967366, 1139781709, 1374988112, 1610459739, 1975683434, 2076935265, 1775276924, 1742315127, 1034867998, 866637845, 566021896, 800440835, 92987698, 193195065, 429456164, 395441711, 1984812685, 2017778566, 1784663195, 1683407248, 1315562145, 1080094634, 1383856311, 1551037884, 101039829, 135050206, 437757123, 337553864, 1042385657, 807962610, 573804783, 742039012, 2531067453, 2564033334, 2328828971, 2227573024, 2935566865, 2700099354, 3001755655, 3168937228, 3868552805, 3902563182, 4203181171, 4102977912, 3736164937, 3501741890, 3265478751, 3433712980, 1106041591, 1340463100, 1576976609, 1408749034, 2043211483, 2009195472, 1708848333, 1809054150, 832877231, 1068351396, 766945465, 599762354, 159417987, 126454664, 361929877, 463180190, 2709260871, 2943682380, 3178106961, 3009879386, 2572697195, 2538681184, 2236228733, 2336434550, 3509871135, 3745345300, 3441850377, 3274667266, 3910161971, 3877198648, 4110568485, 4211818798, 2597806476, 2497604743, 2261089178, 2295101073, 2733856160, 2902087851, 3202437046, 2968011453, 3936291284, 3835036895, 4136440770, 4169408201, 3535486456, 3702665459, 3467192302, 3231722213, 2051518780, 1951317047, 1716890410, 1750902305, 1113818384, 1282050075, 1584504582, 1350078989, 168810852, 67556463, 371049330, 404016761, 841739592, 1008918595, 775550814, 540080725, 3969562369, 3801332234, 4035489047, 4269907996, 3569255213, 3669462566, 3366754619, 3332740144, 2631065433, 2463879762, 2160117071, 2395588676, 2767645557, 2868897406, 3102011747, 3069049960, 202008497, 33778362, 270040487, 504459436, 875451293, 975658646, 675039627, 641025152, 2084704233, 1917518562, 1615861247, 1851332852, 1147550661, 1248802510, 1484005843, 1451044056, 933301370, 967311729, 733156972, 632953703, 260388950, 25965917, 328671808, 496906059, 1206477858, 1239443753, 1543208500, 1441952575, 2144161806, 1908694277, 1675577880, 1842759443, 3610369226, 3644379585, 3408119516, 3307916247, 4011190502, 3776767469, 4077384432, 4245618683, 2809771154, 2842737049, 3144396420, 3043140495, 2673705150, 2438237621, 2203032232, 2370213795]; + var U2 = [0, 185469197, 370938394, 487725847, 741876788, 657861945, 975451694, 824852259, 1483753576, 1400783205, 1315723890, 1164071807, 1950903388, 2135319889, 1649704518, 1767536459, 2967507152, 3152976349, 2801566410, 2918353863, 2631447780, 2547432937, 2328143614, 2177544179, 3901806776, 3818836405, 4270639778, 4118987695, 3299409036, 3483825537, 3535072918, 3652904859, 2077965243, 1893020342, 1841768865, 1724457132, 1474502543, 1559041666, 1107234197, 1257309336, 598438867, 681933534, 901210569, 1052338372, 261314535, 77422314, 428819965, 310463728, 3409685355, 3224740454, 3710368113, 3593056380, 3875770207, 3960309330, 4045380933, 4195456072, 2471224067, 2554718734, 2237133081, 2388260884, 3212035895, 3028143674, 2842678573, 2724322336, 4138563181, 4255350624, 3769721975, 3955191162, 3667219033, 3516619604, 3431546947, 3347532110, 2933734917, 2782082824, 3099667487, 3016697106, 2196052529, 2313884476, 2499348523, 2683765030, 1179510461, 1296297904, 1347548327, 1533017514, 1786102409, 1635502980, 2087309459, 2003294622, 507358933, 355706840, 136428751, 53458370, 839224033, 957055980, 605657339, 790073846, 2373340630, 2256028891, 2607439820, 2422494913, 2706270690, 2856345839, 3075636216, 3160175349, 3573941694, 3725069491, 3273267108, 3356761769, 4181598602, 4063242375, 4011996048, 3828103837, 1033297158, 915985419, 730517276, 545572369, 296679730, 446754879, 129166120, 213705253, 1709610350, 1860738147, 1945798516, 2029293177, 1239331162, 1120974935, 1606591296, 1422699085, 4148292826, 4233094615, 3781033664, 3931371469, 3682191598, 3497509347, 3446004468, 3328955385, 2939266226, 2755636671, 3106780840, 2988687269, 2198438022, 2282195339, 2501218972, 2652609425, 1201765386, 1286567175, 1371368976, 1521706781, 1805211710, 1620529459, 2105887268, 1988838185, 533804130, 350174575, 164439672, 46346101, 870912086, 954669403, 636813900, 788204353, 2358957921, 2274680428, 2592523643, 2441661558, 2695033685, 2880240216, 3065962831, 3182487618, 3572145929, 3756299780, 3270937875, 3388507166, 4174560061, 4091327024, 4006521127, 3854606378, 1014646705, 930369212, 711349675, 560487590, 272786309, 457992840, 106852767, 223377554, 1678381017, 1862534868, 1914052035, 2031621326, 1211247597, 1128014560, 1580087799, 1428173050, 32283319, 182621114, 401639597, 486441376, 768917123, 651868046, 1003007129, 818324884, 1503449823, 1385356242, 1333838021, 1150208456, 1973745387, 2125135846, 1673061617, 1756818940, 2970356327, 3120694122, 2802849917, 2887651696, 2637442643, 2520393566, 2334669897, 2149987652, 3917234703, 3799141122, 4284502037, 4100872472, 3309594171, 3460984630, 3545789473, 3629546796, 2050466060, 1899603969, 1814803222, 1730525723, 1443857720, 1560382517, 1075025698, 1260232239, 575138148, 692707433, 878443390, 1062597235, 243256656, 91341917, 409198410, 325965383, 3403100636, 3252238545, 3704300486, 3620022987, 3874428392, 3990953189, 4042459122, 4227665663, 2460449204, 2578018489, 2226875310, 2411029155, 3198115200, 3046200461, 2827177882, 2743944855]; + var U3 = [0, 218828297, 437656594, 387781147, 875313188, 958871085, 775562294, 590424639, 1750626376, 1699970625, 1917742170, 2135253587, 1551124588, 1367295589, 1180849278, 1265195639, 3501252752, 3720081049, 3399941250, 3350065803, 3835484340, 3919042237, 4270507174, 4085369519, 3102249176, 3051593425, 2734591178, 2952102595, 2361698556, 2177869557, 2530391278, 2614737639, 3145456443, 3060847922, 2708326185, 2892417312, 2404901663, 2187128086, 2504130317, 2555048196, 3542330227, 3727205754, 3375740769, 3292445032, 3876557655, 3926170974, 4246310725, 4027744588, 1808481195, 1723872674, 1910319033, 2094410160, 1608975247, 1391201670, 1173430173, 1224348052, 59984867, 244860394, 428169201, 344873464, 935293895, 984907214, 766078933, 547512796, 1844882806, 1627235199, 2011214180, 2062270317, 1507497298, 1423022939, 1137477952, 1321699145, 95345982, 145085239, 532201772, 313773861, 830661914, 1015671571, 731183368, 648017665, 3175501286, 2957853679, 2807058932, 2858115069, 2305455554, 2220981195, 2474404304, 2658625497, 3575528878, 3625268135, 3473416636, 3254988725, 3778151818, 3963161475, 4213447064, 4130281361, 3599595085, 3683022916, 3432737375, 3247465558, 3802222185, 4020912224, 4172763771, 4122762354, 3201631749, 3017672716, 2764249623, 2848461854, 2331590177, 2280796200, 2431590963, 2648976442, 104699613, 188127444, 472615631, 287343814, 840019705, 1058709744, 671593195, 621591778, 1852171925, 1668212892, 1953757831, 2037970062, 1514790577, 1463996600, 1080017571, 1297403050, 3673637356, 3623636965, 3235995134, 3454686199, 4007360968, 3822090177, 4107101658, 4190530515, 2997825956, 3215212461, 2830708150, 2779915199, 2256734592, 2340947849, 2627016082, 2443058075, 172466556, 122466165, 273792366, 492483431, 1047239e3, 861968209, 612205898, 695634755, 1646252340, 1863638845, 2013908262, 1963115311, 1446242576, 1530455833, 1277555970, 1093597963, 1636604631, 1820824798, 2073724613, 1989249228, 1436590835, 1487645946, 1337376481, 1119727848, 164948639, 81781910, 331544205, 516552836, 1039717051, 821288114, 669961897, 719700128, 2973530695, 3157750862, 2871682645, 2787207260, 2232435299, 2283490410, 2667994737, 2450346104, 3647212047, 3564045318, 3279033885, 3464042516, 3980931627, 3762502690, 4150144569, 4199882800, 3070356634, 3121275539, 2904027272, 2686254721, 2200818878, 2384911031, 2570832044, 2486224549, 3747192018, 3528626907, 3310321856, 3359936201, 3950355702, 3867060991, 4049844452, 4234721005, 1739656202, 1790575107, 2108100632, 1890328081, 1402811438, 1586903591, 1233856572, 1149249077, 266959938, 48394827, 369057872, 418672217, 1002783846, 919489135, 567498868, 752375421, 209336225, 24197544, 376187827, 459744698, 945164165, 895287692, 574624663, 793451934, 1679968233, 1764313568, 2117360635, 1933530610, 1343127501, 1560637892, 1243112415, 1192455638, 3704280881, 3519142200, 3336358691, 3419915562, 3907448597, 3857572124, 4075877127, 4294704398, 3029510009, 3113855344, 2927934315, 2744104290, 2159976285, 2377486676, 2594734927, 2544078150]; + var U4 = [0, 151849742, 303699484, 454499602, 607398968, 758720310, 908999204, 1059270954, 1214797936, 1097159550, 1517440620, 1400849762, 1817998408, 1699839814, 2118541908, 2001430874, 2429595872, 2581445614, 2194319100, 2345119218, 3034881240, 3186202582, 2801699524, 2951971274, 3635996816, 3518358430, 3399679628, 3283088770, 4237083816, 4118925222, 4002861748, 3885750714, 1002142683, 850817237, 698445255, 548169417, 529487843, 377642221, 227885567, 77089521, 1943217067, 2061379749, 1640576439, 1757691577, 1474760595, 1592394909, 1174215055, 1290801793, 2875968315, 2724642869, 3111247143, 2960971305, 2405426947, 2253581325, 2638606623, 2487810577, 3808662347, 3926825029, 4044981591, 4162096729, 3342319475, 3459953789, 3576539503, 3693126241, 1986918061, 2137062819, 1685577905, 1836772287, 1381620373, 1532285339, 1078185097, 1229899655, 1040559837, 923313619, 740276417, 621982671, 439452389, 322734571, 137073913, 19308535, 3871163981, 4021308739, 4104605777, 4255800159, 3263785589, 3414450555, 3499326569, 3651041127, 2933202493, 2815956275, 3167684641, 3049390895, 2330014213, 2213296395, 2566595609, 2448830231, 1305906550, 1155237496, 1607244650, 1455525988, 1776460110, 1626319424, 2079897426, 1928707164, 96392454, 213114376, 396673818, 514443284, 562755902, 679998e3, 865136418, 983426092, 3708173718, 3557504664, 3474729866, 3323011204, 4180808110, 4030667424, 3945269170, 3794078908, 2507040230, 2623762152, 2272556026, 2390325492, 2975484382, 3092726480, 2738905026, 2857194700, 3973773121, 3856137295, 4274053469, 4157467219, 3371096953, 3252932727, 3673476453, 3556361835, 2763173681, 2915017791, 3064510765, 3215307299, 2156299017, 2307622919, 2459735317, 2610011675, 2081048481, 1963412655, 1846563261, 1729977011, 1480485785, 1362321559, 1243905413, 1126790795, 878845905, 1030690015, 645401037, 796197571, 274084841, 425408743, 38544885, 188821243, 3613494426, 3731654548, 3313212038, 3430322568, 4082475170, 4200115116, 3780097726, 3896688048, 2668221674, 2516901860, 2366882550, 2216610296, 3141400786, 2989552604, 2837966542, 2687165888, 1202797690, 1320957812, 1437280870, 1554391400, 1669664834, 1787304780, 1906247262, 2022837584, 265905162, 114585348, 499347990, 349075736, 736970802, 585122620, 972512814, 821712160, 2595684844, 2478443234, 2293045232, 2174754046, 3196267988, 3079546586, 2895723464, 2777952454, 3537852828, 3687994002, 3234156416, 3385345166, 4142626212, 4293295786, 3841024952, 3992742070, 174567692, 57326082, 410887952, 292596766, 777231668, 660510266, 1011452712, 893681702, 1108339068, 1258480242, 1343618912, 1494807662, 1715193156, 1865862730, 1948373848, 2100090966, 2701949495, 2818666809, 3004591147, 3122358053, 2235061775, 2352307457, 2535604243, 2653899549, 3915653703, 3764988233, 4219352155, 4067639125, 3444575871, 3294430577, 3746175075, 3594982253, 836553431, 953270745, 600235211, 718002117, 367585007, 484830689, 133361907, 251657213, 2041877159, 1891211689, 1806599355, 1654886325, 1568718495, 1418573201, 1335535747, 1184342925]; + function convertToInt32(bytes) { + var result = []; + for (var i3 = 0; i3 < bytes.length; i3 += 4) { + result.push( + bytes[i3] << 24 | bytes[i3 + 1] << 16 | bytes[i3 + 2] << 8 | bytes[i3 + 3] + ); + } + return result; + } + var AES = function(key) { + if (!(this instanceof AES)) { + throw Error("AES must be instanitated with `new`"); + } + Object.defineProperty(this, "key", { + value: coerceArray(key, true) + }); + this._prepare(); + }; + AES.prototype._prepare = function() { + var rounds = numberOfRounds[this.key.length]; + if (rounds == null) { + throw new Error("invalid key size (must be 16, 24 or 32 bytes)"); + } + this._Ke = []; + this._Kd = []; + for (var i3 = 0; i3 <= rounds; i3++) { + this._Ke.push([0, 0, 0, 0]); + this._Kd.push([0, 0, 0, 0]); + } + var roundKeyCount = (rounds + 1) * 4; + var KC = this.key.length / 4; + var tk = convertToInt32(this.key); + var index; + for (var i3 = 0; i3 < KC; i3++) { + index = i3 >> 2; + this._Ke[index][i3 % 4] = tk[i3]; + this._Kd[rounds - index][i3 % 4] = tk[i3]; + } + var rconpointer = 0; + var t2 = KC, tt2; + while (t2 < roundKeyCount) { + tt2 = tk[KC - 1]; + tk[0] ^= S2[tt2 >> 16 & 255] << 24 ^ S2[tt2 >> 8 & 255] << 16 ^ S2[tt2 & 255] << 8 ^ S2[tt2 >> 24 & 255] ^ rcon[rconpointer] << 24; + rconpointer += 1; + if (KC != 8) { + for (var i3 = 1; i3 < KC; i3++) { + tk[i3] ^= tk[i3 - 1]; } - return this._root; - }; - Tree2.prototype.remove = function(key) { - this._root = this._remove(key, this._root, this._comparator); - }; - Tree2.prototype._remove = function(i3, t2, comparator) { - var x2; - if (t2 === null) - return null; - t2 = splay(i3, t2, comparator); - var cmp2 = comparator(i3, t2.key); - if (cmp2 === 0) { - if (t2.left === null) { - x2 = t2.right; - } else { - x2 = splay(i3, t2.left, comparator); - x2.right = t2.right; - } - this._size--; - return x2; - } - return t2; - }; - Tree2.prototype.pop = function() { - var node = this._root; - if (node) { - while (node.left) { - node = node.left; - } - this._root = splay(node.key, this._root, this._comparator); - this._root = this._remove(node.key, this._root, this._comparator); - return { - key: node.key, - data: node.data - }; - } - return null; - }; - Tree2.prototype.findStatic = function(key) { - var current = this._root; - var compare = this._comparator; - while (current) { - var cmp2 = compare(key, current.key); - if (cmp2 === 0) - return current; - else if (cmp2 < 0) - current = current.left; - else - current = current.right; - } - return null; - }; - Tree2.prototype.find = function(key) { - if (this._root) { - this._root = splay(key, this._root, this._comparator); - if (this._comparator(key, this._root.key) !== 0) - return null; - } - return this._root; - }; - Tree2.prototype.contains = function(key) { - var current = this._root; - var compare = this._comparator; - while (current) { - var cmp2 = compare(key, current.key); - if (cmp2 === 0) - return true; - else if (cmp2 < 0) - current = current.left; - else - current = current.right; - } - return false; - }; - Tree2.prototype.forEach = function(visitor, ctx) { - var current = this._root; - var Q2 = []; - var done = false; - while (!done) { - if (current !== null) { - Q2.push(current); - current = current.left; - } else { - if (Q2.length !== 0) { - current = Q2.pop(); - visitor.call(ctx, current); - current = current.right; - } else - done = true; - } - } - return this; - }; - Tree2.prototype.range = function(low, high, fn, ctx) { - var Q2 = []; - var compare = this._comparator; - var node = this._root; - var cmp2; - while (Q2.length !== 0 || node) { - if (node) { - Q2.push(node); - node = node.left; - } else { - node = Q2.pop(); - cmp2 = compare(node.key, high); - if (cmp2 > 0) { - break; - } else if (compare(node.key, low) >= 0) { - if (fn.call(ctx, node)) - return this; - } - node = node.right; - } - } - return this; - }; - Tree2.prototype.keys = function() { - var keys2 = []; - this.forEach(function(_a) { - var key = _a.key; - return keys2.push(key); - }); - return keys2; - }; - Tree2.prototype.values = function() { - var values = []; - this.forEach(function(_a) { - var data = _a.data; - return values.push(data); - }); - return values; - }; - Tree2.prototype.min = function() { - if (this._root) - return this.minNode(this._root).key; - return null; - }; - Tree2.prototype.max = function() { - if (this._root) - return this.maxNode(this._root).key; - return null; - }; - Tree2.prototype.minNode = function(t2) { - if (t2 === void 0) { - t2 = this._root; - } - if (t2) - while (t2.left) { - t2 = t2.left; - } - return t2; - }; - Tree2.prototype.maxNode = function(t2) { - if (t2 === void 0) { - t2 = this._root; - } - if (t2) - while (t2.right) { - t2 = t2.right; - } - return t2; - }; - Tree2.prototype.at = function(index2) { - var current = this._root; - var done = false; - var i3 = 0; - var Q2 = []; - while (!done) { - if (current) { - Q2.push(current); - current = current.left; - } else { - if (Q2.length > 0) { - current = Q2.pop(); - if (i3 === index2) - return current; - i3++; - current = current.right; - } else - done = true; - } - } - return null; - }; - Tree2.prototype.next = function(d2) { - var root3 = this._root; - var successor = null; - if (d2.right) { - successor = d2.right; - while (successor.left) { - successor = successor.left; - } - return successor; - } - var comparator = this._comparator; - while (root3) { - var cmp2 = comparator(d2.key, root3.key); - if (cmp2 === 0) - break; - else if (cmp2 < 0) { - successor = root3; - root3 = root3.left; - } else - root3 = root3.right; - } - return successor; - }; - Tree2.prototype.prev = function(d2) { - var root3 = this._root; - var predecessor = null; - if (d2.left !== null) { - predecessor = d2.left; - while (predecessor.right) { - predecessor = predecessor.right; - } - return predecessor; - } - var comparator = this._comparator; - while (root3) { - var cmp2 = comparator(d2.key, root3.key); - if (cmp2 === 0) - break; - else if (cmp2 < 0) - root3 = root3.left; - else { - predecessor = root3; - root3 = root3.right; - } - } - return predecessor; - }; - Tree2.prototype.clear = function() { - this._root = null; - this._size = 0; - return this; - }; - Tree2.prototype.toList = function() { - return toList(this._root); - }; - Tree2.prototype.load = function(keys2, values, presort) { - if (values === void 0) { - values = []; - } - if (presort === void 0) { - presort = false; - } - var size = keys2.length; - var comparator = this._comparator; - if (presort) - sort(keys2, values, 0, size - 1, comparator); - if (this._root === null) { - this._root = loadRecursive(keys2, values, 0, size); - this._size = size; - } else { - var mergedList = mergeLists(this.toList(), createList(keys2, values), comparator); - size = this._size + size; - this._root = sortedListToBST({ - head: mergedList - }, 0, size); - } - return this; - }; - Tree2.prototype.isEmpty = function() { - return this._root === null; - }; - Object.defineProperty(Tree2.prototype, "size", { - get: function get4() { - return this._size; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tree2.prototype, "root", { - get: function get4() { - return this._root; - }, - enumerable: true, - configurable: true - }); - Tree2.prototype.toString = function(printNode) { - if (printNode === void 0) { - printNode = function printNode2(n3) { - return String(n3.key); - }; + } else { + for (var i3 = 1; i3 < KC / 2; i3++) { + tk[i3] ^= tk[i3 - 1]; } - var out = []; - printRow(this._root, "", true, function(v2) { - return out.push(v2); - }, printNode); - return out.join(""); - }; - Tree2.prototype.update = function(key, newKey, newData) { - var comparator = this._comparator; - var _a = split(key, this._root, comparator), left = _a.left, right = _a.right; - if (comparator(key, newKey) < 0) { - right = insert(newKey, newData, right, comparator); - } else { - left = insert(newKey, newData, left, comparator); + tt2 = tk[KC / 2 - 1]; + tk[KC / 2] ^= S2[tt2 & 255] ^ S2[tt2 >> 8 & 255] << 8 ^ S2[tt2 >> 16 & 255] << 16 ^ S2[tt2 >> 24 & 255] << 24; + for (var i3 = KC / 2 + 1; i3 < KC; i3++) { + tk[i3] ^= tk[i3 - 1]; } - this._root = merge2(left, right, comparator); - }; - Tree2.prototype.split = function(key) { - return split(key, this._root, this._comparator); - }; - return Tree2; - }() - ); - function loadRecursive(keys2, values, start2, end) { - var size = end - start2; - if (size > 0) { - var middle = start2 + Math.floor(size / 2); - var key = keys2[middle]; - var data = values[middle]; - var node = new Node(key, data); - node.left = loadRecursive(keys2, values, start2, middle); - node.right = loadRecursive(keys2, values, middle + 1, end); - return node; - } - return null; - } - function createList(keys2, values) { - var head = new Node(null, null); - var p2 = head; - for (var i3 = 0; i3 < keys2.length; i3++) { - p2 = p2.next = new Node(keys2[i3], values[i3]); - } - p2.next = null; - return head.next; - } - function toList(root3) { - var current = root3; - var Q2 = []; - var done = false; - var head = new Node(null, null); - var p2 = head; - while (!done) { - if (current) { - Q2.push(current); - current = current.left; - } else { - if (Q2.length > 0) { - current = p2 = p2.next = Q2.pop(); - current = current.right; - } else - done = true; + } + var i3 = 0, r2, c2; + while (i3 < KC && t2 < roundKeyCount) { + r2 = t2 >> 2; + c2 = t2 % 4; + this._Ke[r2][c2] = tk[i3]; + this._Kd[rounds - r2][c2] = tk[i3++]; + t2++; } } - p2.next = null; - return head.next; - } - function sortedListToBST(list, start2, end) { - var size = end - start2; - if (size > 0) { - var middle = start2 + Math.floor(size / 2); - var left = sortedListToBST(list, start2, middle); - var root3 = list.head; - root3.left = left; - list.head = list.head.next; - root3.right = sortedListToBST(list, middle + 1, end); - return root3; - } - return null; - } - function mergeLists(l1, l2, compare) { - var head = new Node(null, null); - var p2 = head; - var p1 = l1; - var p22 = l2; - while (p1 !== null && p22 !== null) { - if (compare(p1.key, p22.key) < 0) { - p2.next = p1; - p1 = p1.next; - } else { - p2.next = p22; - p22 = p22.next; + for (var r2 = 1; r2 < rounds; r2++) { + for (var c2 = 0; c2 < 4; c2++) { + tt2 = this._Kd[r2][c2]; + this._Kd[r2][c2] = U1[tt2 >> 24 & 255] ^ U2[tt2 >> 16 & 255] ^ U3[tt2 >> 8 & 255] ^ U4[tt2 & 255]; } - p2 = p2.next; } - if (p1 !== null) { - p2.next = p1; - } else if (p22 !== null) { - p2.next = p22; + }; + AES.prototype.encrypt = function(plaintext) { + if (plaintext.length != 16) { + throw new Error("invalid plaintext size (must be 16 bytes)"); } - return head.next; - } - function sort(keys2, values, left, right, compare) { - if (left >= right) - return; - var pivot = keys2[left + right >> 1]; - var i3 = left - 1; - var j3 = right + 1; - while (true) { - do { - i3++; - } while (compare(keys2[i3], pivot) < 0); - do { - j3--; - } while (compare(keys2[j3], pivot) > 0); - if (i3 >= j3) - break; - var tmp = keys2[i3]; - keys2[i3] = keys2[j3]; - keys2[j3] = tmp; - tmp = values[i3]; - values[i3] = values[j3]; - values[j3] = tmp; + var rounds = this._Ke.length - 1; + var a2 = [0, 0, 0, 0]; + var t2 = convertToInt32(plaintext); + for (var i3 = 0; i3 < 4; i3++) { + t2[i3] ^= this._Ke[0][i3]; } - sort(keys2, values, left, j3, compare); - sort(keys2, values, j3 + 1, right, compare); - } - var isInBbox = function isInBbox2(bbox2, point2) { - return bbox2.ll.x <= point2.x && point2.x <= bbox2.ur.x && bbox2.ll.y <= point2.y && point2.y <= bbox2.ur.y; - }; - var getBboxOverlap = function getBboxOverlap2(b1, b2) { - if (b2.ur.x < b1.ll.x || b1.ur.x < b2.ll.x || b2.ur.y < b1.ll.y || b1.ur.y < b2.ll.y) - return null; - var lowerX = b1.ll.x < b2.ll.x ? b2.ll.x : b1.ll.x; - var upperX = b1.ur.x < b2.ur.x ? b1.ur.x : b2.ur.x; - var lowerY = b1.ll.y < b2.ll.y ? b2.ll.y : b1.ll.y; - var upperY = b1.ur.y < b2.ur.y ? b1.ur.y : b2.ur.y; - return { - ll: { - x: lowerX, - y: lowerY - }, - ur: { - x: upperX, - y: upperY - } - }; - }; - var epsilon3 = Number.EPSILON; - if (epsilon3 === void 0) - epsilon3 = Math.pow(2, -52); - var EPSILON_SQ = epsilon3 * epsilon3; - var cmp = function cmp2(a2, b2) { - if (-epsilon3 < a2 && a2 < epsilon3) { - if (-epsilon3 < b2 && b2 < epsilon3) { - return 0; + for (var r2 = 1; r2 < rounds; r2++) { + for (var i3 = 0; i3 < 4; i3++) { + a2[i3] = T1[t2[i3] >> 24 & 255] ^ T2[t2[(i3 + 1) % 4] >> 16 & 255] ^ T3[t2[(i3 + 2) % 4] >> 8 & 255] ^ T4[t2[(i3 + 3) % 4] & 255] ^ this._Ke[r2][i3]; } + t2 = a2.slice(); } - var ab = a2 - b2; - if (ab * ab < EPSILON_SQ * a2 * b2) { - return 0; + var result = createArray(16), tt2; + for (var i3 = 0; i3 < 4; i3++) { + tt2 = this._Ke[rounds][i3]; + result[4 * i3] = (S2[t2[i3] >> 24 & 255] ^ tt2 >> 24) & 255; + result[4 * i3 + 1] = (S2[t2[(i3 + 1) % 4] >> 16 & 255] ^ tt2 >> 16) & 255; + result[4 * i3 + 2] = (S2[t2[(i3 + 2) % 4] >> 8 & 255] ^ tt2 >> 8) & 255; + result[4 * i3 + 3] = (S2[t2[(i3 + 3) % 4] & 255] ^ tt2) & 255; } - return a2 < b2 ? -1 : 1; + return result; }; - var PtRounder = /* @__PURE__ */ function() { - function PtRounder2() { - _classCallCheck(this, PtRounder2); - this.reset(); + AES.prototype.decrypt = function(ciphertext) { + if (ciphertext.length != 16) { + throw new Error("invalid ciphertext size (must be 16 bytes)"); } - _createClass(PtRounder2, [{ - key: "reset", - value: function reset() { - this.xRounder = new CoordRounder(); - this.yRounder = new CoordRounder(); - } - }, { - key: "round", - value: function round(x2, y2) { - return { - x: this.xRounder.round(x2), - y: this.yRounder.round(y2) - }; - } - }]); - return PtRounder2; - }(); - var CoordRounder = /* @__PURE__ */ function() { - function CoordRounder2() { - _classCallCheck(this, CoordRounder2); - this.tree = new Tree(); - this.round(0); + var rounds = this._Kd.length - 1; + var a2 = [0, 0, 0, 0]; + var t2 = convertToInt32(ciphertext); + for (var i3 = 0; i3 < 4; i3++) { + t2[i3] ^= this._Kd[0][i3]; } - _createClass(CoordRounder2, [{ - key: "round", - value: function round(coord2) { - var node = this.tree.add(coord2); - var prevNode = this.tree.prev(node); - if (prevNode !== null && cmp(node.key, prevNode.key) === 0) { - this.tree.remove(coord2); - return prevNode.key; - } - var nextNode = this.tree.next(node); - if (nextNode !== null && cmp(node.key, nextNode.key) === 0) { - this.tree.remove(coord2); - return nextNode.key; - } - return coord2; + for (var r2 = 1; r2 < rounds; r2++) { + for (var i3 = 0; i3 < 4; i3++) { + a2[i3] = T5[t2[i3] >> 24 & 255] ^ T6[t2[(i3 + 3) % 4] >> 16 & 255] ^ T7[t2[(i3 + 2) % 4] >> 8 & 255] ^ T8[t2[(i3 + 1) % 4] & 255] ^ this._Kd[r2][i3]; } - }]); - return CoordRounder2; - }(); - var rounder = new PtRounder(); - var crossProduct = function crossProduct2(a2, b2) { - return a2.x * b2.y - a2.y * b2.x; + t2 = a2.slice(); + } + var result = createArray(16), tt2; + for (var i3 = 0; i3 < 4; i3++) { + tt2 = this._Kd[rounds][i3]; + result[4 * i3] = (Si[t2[i3] >> 24 & 255] ^ tt2 >> 24) & 255; + result[4 * i3 + 1] = (Si[t2[(i3 + 3) % 4] >> 16 & 255] ^ tt2 >> 16) & 255; + result[4 * i3 + 2] = (Si[t2[(i3 + 2) % 4] >> 8 & 255] ^ tt2 >> 8) & 255; + result[4 * i3 + 3] = (Si[t2[(i3 + 1) % 4] & 255] ^ tt2) & 255; + } + return result; }; - var dotProduct = function dotProduct2(a2, b2) { - return a2.x * b2.x + a2.y * b2.y; + var ModeOfOperationECB = function(key) { + if (!(this instanceof ModeOfOperationECB)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Electronic Code Block"; + this.name = "ecb"; + this._aes = new AES(key); }; - var compareVectorAngles = function compareVectorAngles2(basePt, endPt1, endPt2) { - var v1 = { - x: endPt1.x - basePt.x, - y: endPt1.y - basePt.y - }; - var v2 = { - x: endPt2.x - basePt.x, - y: endPt2.y - basePt.y - }; - var kross = crossProduct(v1, v2); - return cmp(kross, 0); + ModeOfOperationECB.prototype.encrypt = function(plaintext) { + plaintext = coerceArray(plaintext); + if (plaintext.length % 16 !== 0) { + throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); + } + var ciphertext = createArray(plaintext.length); + var block2 = createArray(16); + for (var i3 = 0; i3 < plaintext.length; i3 += 16) { + copyArray(plaintext, block2, 0, i3, i3 + 16); + block2 = this._aes.encrypt(block2); + copyArray(block2, ciphertext, i3); + } + return ciphertext; }; - var length = function length2(v2) { - return Math.sqrt(dotProduct(v2, v2)); + ModeOfOperationECB.prototype.decrypt = function(ciphertext) { + ciphertext = coerceArray(ciphertext); + if (ciphertext.length % 16 !== 0) { + throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); + } + var plaintext = createArray(ciphertext.length); + var block2 = createArray(16); + for (var i3 = 0; i3 < ciphertext.length; i3 += 16) { + copyArray(ciphertext, block2, 0, i3, i3 + 16); + block2 = this._aes.decrypt(block2); + copyArray(block2, plaintext, i3); + } + return plaintext; }; - var sineOfAngle = function sineOfAngle2(pShared, pBase, pAngle) { - var vBase = { - x: pBase.x - pShared.x, - y: pBase.y - pShared.y - }; - var vAngle = { - x: pAngle.x - pShared.x, - y: pAngle.y - pShared.y - }; - return crossProduct(vAngle, vBase) / length(vAngle) / length(vBase); + var ModeOfOperationCBC = function(key, iv) { + if (!(this instanceof ModeOfOperationCBC)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Cipher Block Chaining"; + this.name = "cbc"; + if (!iv) { + iv = createArray(16); + } else if (iv.length != 16) { + throw new Error("invalid initialation vector size (must be 16 bytes)"); + } + this._lastCipherblock = coerceArray(iv, true); + this._aes = new AES(key); }; - var cosineOfAngle = function cosineOfAngle2(pShared, pBase, pAngle) { - var vBase = { - x: pBase.x - pShared.x, - y: pBase.y - pShared.y - }; - var vAngle = { - x: pAngle.x - pShared.x, - y: pAngle.y - pShared.y - }; - return dotProduct(vAngle, vBase) / length(vAngle) / length(vBase); - }; - var horizontalIntersection = function horizontalIntersection2(pt2, v2, y2) { - if (v2.y === 0) - return null; - return { - x: pt2.x + v2.x / v2.y * (y2 - pt2.y), - y: y2 - }; - }; - var verticalIntersection = function verticalIntersection2(pt2, v2, x2) { - if (v2.x === 0) - return null; - return { - x: x2, - y: pt2.y + v2.y / v2.x * (x2 - pt2.x) - }; - }; - var intersection = function intersection2(pt1, v1, pt2, v2) { - if (v1.x === 0) - return verticalIntersection(pt2, v2, pt1.x); - if (v2.x === 0) - return verticalIntersection(pt1, v1, pt2.x); - if (v1.y === 0) - return horizontalIntersection(pt2, v2, pt1.y); - if (v2.y === 0) - return horizontalIntersection(pt1, v1, pt2.y); - var kross = crossProduct(v1, v2); - if (kross == 0) - return null; - var ve2 = { - x: pt2.x - pt1.x, - y: pt2.y - pt1.y - }; - var d1 = crossProduct(ve2, v1) / kross; - var d2 = crossProduct(ve2, v2) / kross; - var x12 = pt1.x + d2 * v1.x, x2 = pt2.x + d1 * v2.x; - var y12 = pt1.y + d2 * v1.y, y2 = pt2.y + d1 * v2.y; - var x3 = (x12 + x2) / 2; - var y3 = (y12 + y2) / 2; - return { - x: x3, - y: y3 - }; - }; - var SweepEvent = /* @__PURE__ */ function() { - _createClass(SweepEvent2, null, [{ - key: "compare", - // for ordering sweep events in the sweep event queue - value: function compare(a2, b2) { - var ptCmp = SweepEvent2.comparePoints(a2.point, b2.point); - if (ptCmp !== 0) - return ptCmp; - if (a2.point !== b2.point) - a2.link(b2); - if (a2.isLeft !== b2.isLeft) - return a2.isLeft ? 1 : -1; - return Segment.compare(a2.segment, b2.segment); - } - // for ordering points in sweep line order - }, { - key: "comparePoints", - value: function comparePoints(aPt, bPt) { - if (aPt.x < bPt.x) - return -1; - if (aPt.x > bPt.x) - return 1; - if (aPt.y < bPt.y) - return -1; - if (aPt.y > bPt.y) - return 1; - return 0; - } - // Warning: 'point' input will be modified and re-used (for performance) - }]); - function SweepEvent2(point2, isLeft) { - _classCallCheck(this, SweepEvent2); - if (point2.events === void 0) - point2.events = [this]; - else - point2.events.push(this); - this.point = point2; - this.isLeft = isLeft; + ModeOfOperationCBC.prototype.encrypt = function(plaintext) { + plaintext = coerceArray(plaintext); + if (plaintext.length % 16 !== 0) { + throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); } - _createClass(SweepEvent2, [{ - key: "link", - value: function link2(other) { - if (other.point === this.point) { - throw new Error("Tried to link already linked events"); - } - var otherEvents = other.point.events; - for (var i3 = 0, iMax = otherEvents.length; i3 < iMax; i3++) { - var evt = otherEvents[i3]; - this.point.events.push(evt); - evt.point = this.point; - } - this.checkForConsuming(); - } - /* Do a pass over our linked events and check to see if any pair - * of segments match, and should be consumed. */ - }, { - key: "checkForConsuming", - value: function checkForConsuming() { - var numEvents = this.point.events.length; - for (var i3 = 0; i3 < numEvents; i3++) { - var evt1 = this.point.events[i3]; - if (evt1.segment.consumedBy !== void 0) - continue; - for (var j3 = i3 + 1; j3 < numEvents; j3++) { - var evt2 = this.point.events[j3]; - if (evt2.consumedBy !== void 0) - continue; - if (evt1.otherSE.point.events !== evt2.otherSE.point.events) - continue; - evt1.segment.consume(evt2.segment); - } - } - } - }, { - key: "getAvailableLinkedEvents", - value: function getAvailableLinkedEvents() { - var events = []; - for (var i3 = 0, iMax = this.point.events.length; i3 < iMax; i3++) { - var evt = this.point.events[i3]; - if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) { - events.push(evt); - } - } - return events; - } - /** - * Returns a comparator function for sorting linked events that will - * favor the event that will give us the smallest left-side angle. - * All ring construction starts as low as possible heading to the right, - * so by always turning left as sharp as possible we'll get polygons - * without uncessary loops & holes. - * - * The comparator function has a compute cache such that it avoids - * re-computing already-computed values. - */ - }, { - key: "getLeftmostComparator", - value: function getLeftmostComparator(baseEvent) { - var _this = this; - var cache = /* @__PURE__ */ new Map(); - var fillCache = function fillCache2(linkedEvent) { - var nextEvent = linkedEvent.otherSE; - cache.set(linkedEvent, { - sine: sineOfAngle(_this.point, baseEvent.point, nextEvent.point), - cosine: cosineOfAngle(_this.point, baseEvent.point, nextEvent.point) - }); - }; - return function(a2, b2) { - if (!cache.has(a2)) - fillCache(a2); - if (!cache.has(b2)) - fillCache(b2); - var _cache$get = cache.get(a2), asine = _cache$get.sine, acosine = _cache$get.cosine; - var _cache$get2 = cache.get(b2), bsine = _cache$get2.sine, bcosine = _cache$get2.cosine; - if (asine >= 0 && bsine >= 0) { - if (acosine < bcosine) - return 1; - if (acosine > bcosine) - return -1; - return 0; - } - if (asine < 0 && bsine < 0) { - if (acosine < bcosine) - return -1; - if (acosine > bcosine) - return 1; - return 0; - } - if (bsine < asine) - return -1; - if (bsine > asine) - return 1; - return 0; - }; - } - }]); - return SweepEvent2; - }(); - var segmentId = 0; - var Segment = /* @__PURE__ */ function() { - _createClass(Segment2, null, [{ - key: "compare", - /* This compare() function is for ordering segments in the sweep - * line tree, and does so according to the following criteria: - * - * Consider the vertical line that lies an infinestimal step to the - * right of the right-more of the two left endpoints of the input - * segments. Imagine slowly moving a point up from negative infinity - * in the increasing y direction. Which of the two segments will that - * point intersect first? That segment comes 'before' the other one. - * - * If neither segment would be intersected by such a line, (if one - * or more of the segments are vertical) then the line to be considered - * is directly on the right-more of the two left inputs. - */ - value: function compare(a2, b2) { - var alx = a2.leftSE.point.x; - var blx = b2.leftSE.point.x; - var arx = a2.rightSE.point.x; - var brx = b2.rightSE.point.x; - if (brx < alx) - return 1; - if (arx < blx) - return -1; - var aly = a2.leftSE.point.y; - var bly = b2.leftSE.point.y; - var ary = a2.rightSE.point.y; - var bry = b2.rightSE.point.y; - if (alx < blx) { - if (bly < aly && bly < ary) - return 1; - if (bly > aly && bly > ary) - return -1; - var aCmpBLeft = a2.comparePoint(b2.leftSE.point); - if (aCmpBLeft < 0) - return 1; - if (aCmpBLeft > 0) - return -1; - var bCmpARight = b2.comparePoint(a2.rightSE.point); - if (bCmpARight !== 0) - return bCmpARight; - return -1; - } - if (alx > blx) { - if (aly < bly && aly < bry) - return -1; - if (aly > bly && aly > bry) - return 1; - var bCmpALeft = b2.comparePoint(a2.leftSE.point); - if (bCmpALeft !== 0) - return bCmpALeft; - var aCmpBRight = a2.comparePoint(b2.rightSE.point); - if (aCmpBRight < 0) - return 1; - if (aCmpBRight > 0) - return -1; - return 1; - } - if (aly < bly) - return -1; - if (aly > bly) - return 1; - if (arx < brx) { - var _bCmpARight = b2.comparePoint(a2.rightSE.point); - if (_bCmpARight !== 0) - return _bCmpARight; - } - if (arx > brx) { - var _aCmpBRight = a2.comparePoint(b2.rightSE.point); - if (_aCmpBRight < 0) - return 1; - if (_aCmpBRight > 0) - return -1; - } - if (arx !== brx) { - var ay = ary - aly; - var ax = arx - alx; - var by = bry - bly; - var bx = brx - blx; - if (ay > ax && by < bx) - return 1; - if (ay < ax && by > bx) - return -1; - } - if (arx > brx) - return 1; - if (arx < brx) - return -1; - if (ary < bry) - return -1; - if (ary > bry) - return 1; - if (a2.id < b2.id) - return -1; - if (a2.id > b2.id) - return 1; - return 0; + var ciphertext = createArray(plaintext.length); + var block2 = createArray(16); + for (var i3 = 0; i3 < plaintext.length; i3 += 16) { + copyArray(plaintext, block2, 0, i3, i3 + 16); + for (var j2 = 0; j2 < 16; j2++) { + block2[j2] ^= this._lastCipherblock[j2]; } - /* Warning: a reference to ringWindings input will be stored, - * and possibly will be later modified */ - }]); - function Segment2(leftSE, rightSE, rings, windings) { - _classCallCheck(this, Segment2); - this.id = ++segmentId; - this.leftSE = leftSE; - leftSE.segment = this; - leftSE.otherSE = rightSE; - this.rightSE = rightSE; - rightSE.segment = this; - rightSE.otherSE = leftSE; - this.rings = rings; - this.windings = windings; + this._lastCipherblock = this._aes.encrypt(block2); + copyArray(this._lastCipherblock, ciphertext, i3); } - _createClass(Segment2, [{ - key: "replaceRightSE", - /* When a segment is split, the rightSE is replaced with a new sweep event */ - value: function replaceRightSE(newRightSE) { - this.rightSE = newRightSE; - this.rightSE.segment = this; - this.rightSE.otherSE = this.leftSE; - this.leftSE.otherSE = this.rightSE; - } - }, { - key: "bbox", - value: function bbox2() { - var y12 = this.leftSE.point.y; - var y2 = this.rightSE.point.y; - return { - ll: { - x: this.leftSE.point.x, - y: y12 < y2 ? y12 : y2 - }, - ur: { - x: this.rightSE.point.x, - y: y12 > y2 ? y12 : y2 - } - }; - } - /* A vector from the left point to the right */ - }, { - key: "vector", - value: function vector() { - return { - x: this.rightSE.point.x - this.leftSE.point.x, - y: this.rightSE.point.y - this.leftSE.point.y - }; - } - }, { - key: "isAnEndpoint", - value: function isAnEndpoint(pt2) { - return pt2.x === this.leftSE.point.x && pt2.y === this.leftSE.point.y || pt2.x === this.rightSE.point.x && pt2.y === this.rightSE.point.y; - } - /* Compare this segment with a point. - * - * A point P is considered to be colinear to a segment if there - * exists a distance D such that if we travel along the segment - * from one * endpoint towards the other a distance D, we find - * ourselves at point P. - * - * Return value indicates: - * - * 1: point lies above the segment (to the left of vertical) - * 0: point is colinear to segment - * -1: point lies below the segment (to the right of vertical) - */ - }, { - key: "comparePoint", - value: function comparePoint(point2) { - if (this.isAnEndpoint(point2)) - return 0; - var lPt = this.leftSE.point; - var rPt = this.rightSE.point; - var v2 = this.vector(); - if (lPt.x === rPt.x) { - if (point2.x === lPt.x) - return 0; - return point2.x < lPt.x ? 1 : -1; - } - var yDist = (point2.y - lPt.y) / v2.y; - var xFromYDist = lPt.x + yDist * v2.x; - if (point2.x === xFromYDist) - return 0; - var xDist = (point2.x - lPt.x) / v2.x; - var yFromXDist = lPt.y + xDist * v2.y; - if (point2.y === yFromXDist) - return 0; - return point2.y < yFromXDist ? -1 : 1; - } - /** - * Given another segment, returns the first non-trivial intersection - * between the two segments (in terms of sweep line ordering), if it exists. - * - * A 'non-trivial' intersection is one that will cause one or both of the - * segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection: - * - * * endpoint of segA with endpoint of segB --> trivial - * * endpoint of segA with point along segB --> non-trivial - * * endpoint of segB with point along segA --> non-trivial - * * point along segA with point along segB --> non-trivial - * - * If no non-trivial intersection exists, return null - * Else, return null. - */ - }, { - key: "getIntersection", - value: function getIntersection(other) { - var tBbox = this.bbox(); - var oBbox = other.bbox(); - var bboxOverlap = getBboxOverlap(tBbox, oBbox); - if (bboxOverlap === null) - return null; - var tlp = this.leftSE.point; - var trp = this.rightSE.point; - var olp = other.leftSE.point; - var orp = other.rightSE.point; - var touchesOtherLSE = isInBbox(tBbox, olp) && this.comparePoint(olp) === 0; - var touchesThisLSE = isInBbox(oBbox, tlp) && other.comparePoint(tlp) === 0; - var touchesOtherRSE = isInBbox(tBbox, orp) && this.comparePoint(orp) === 0; - var touchesThisRSE = isInBbox(oBbox, trp) && other.comparePoint(trp) === 0; - if (touchesThisLSE && touchesOtherLSE) { - if (touchesThisRSE && !touchesOtherRSE) - return trp; - if (!touchesThisRSE && touchesOtherRSE) - return orp; - return null; - } - if (touchesThisLSE) { - if (touchesOtherRSE) { - if (tlp.x === orp.x && tlp.y === orp.y) - return null; - } - return tlp; - } - if (touchesOtherLSE) { - if (touchesThisRSE) { - if (trp.x === olp.x && trp.y === olp.y) - return null; - } - return olp; - } - if (touchesThisRSE && touchesOtherRSE) - return null; - if (touchesThisRSE) - return trp; - if (touchesOtherRSE) - return orp; - var pt2 = intersection(tlp, this.vector(), olp, other.vector()); - if (pt2 === null) - return null; - if (!isInBbox(bboxOverlap, pt2)) - return null; - return rounder.round(pt2.x, pt2.y); - } - /** - * Split the given segment into multiple segments on the given points. - * * Each existing segment will retain its leftSE and a new rightSE will be - * generated for it. - * * A new segment will be generated which will adopt the original segment's - * rightSE, and a new leftSE will be generated for it. - * * If there are more than two points given to split on, new segments - * in the middle will be generated with new leftSE and rightSE's. - * * An array of the newly generated SweepEvents will be returned. - * - * Warning: input array of points is modified - */ - }, { - key: "split", - value: function split2(point2) { - var newEvents = []; - var alreadyLinked = point2.events !== void 0; - var newLeftSE = new SweepEvent(point2, true); - var newRightSE = new SweepEvent(point2, false); - var oldRightSE = this.rightSE; - this.replaceRightSE(newRightSE); - newEvents.push(newRightSE); - newEvents.push(newLeftSE); - var newSeg = new Segment2(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice()); - if (SweepEvent.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) { - newSeg.swapEvents(); - } - if (SweepEvent.comparePoints(this.leftSE.point, this.rightSE.point) > 0) { - this.swapEvents(); - } - if (alreadyLinked) { - newLeftSE.checkForConsuming(); - newRightSE.checkForConsuming(); - } - return newEvents; - } - /* Swap which event is left and right */ - }, { - key: "swapEvents", - value: function swapEvents() { - var tmpEvt = this.rightSE; - this.rightSE = this.leftSE; - this.leftSE = tmpEvt; - this.leftSE.isLeft = true; - this.rightSE.isLeft = false; - for (var i3 = 0, iMax = this.windings.length; i3 < iMax; i3++) { - this.windings[i3] *= -1; - } - } - /* Consume another segment. We take their rings under our wing - * and mark them as consumed. Use for perfectly overlapping segments */ - }, { - key: "consume", - value: function consume(other) { - var consumer = this; - var consumee = other; - while (consumer.consumedBy) { - consumer = consumer.consumedBy; - } - while (consumee.consumedBy) { - consumee = consumee.consumedBy; - } - var cmp2 = Segment2.compare(consumer, consumee); - if (cmp2 === 0) - return; - if (cmp2 > 0) { - var tmp = consumer; - consumer = consumee; - consumee = tmp; - } - if (consumer.prev === consumee) { - var _tmp = consumer; - consumer = consumee; - consumee = _tmp; - } - for (var i3 = 0, iMax = consumee.rings.length; i3 < iMax; i3++) { - var ring = consumee.rings[i3]; - var winding = consumee.windings[i3]; - var index2 = consumer.rings.indexOf(ring); - if (index2 === -1) { - consumer.rings.push(ring); - consumer.windings.push(winding); - } else - consumer.windings[index2] += winding; - } - consumee.rings = null; - consumee.windings = null; - consumee.consumedBy = consumer; - consumee.leftSE.consumedBy = consumer.leftSE; - consumee.rightSE.consumedBy = consumer.rightSE; - } - /* The first segment previous segment chain that is in the result */ - }, { - key: "prevInResult", - value: function prevInResult() { - if (this._prevInResult !== void 0) - return this._prevInResult; - if (!this.prev) - this._prevInResult = null; - else if (this.prev.isInResult()) - this._prevInResult = this.prev; - else - this._prevInResult = this.prev.prevInResult(); - return this._prevInResult; - } - }, { - key: "beforeState", - value: function beforeState() { - if (this._beforeState !== void 0) - return this._beforeState; - if (!this.prev) - this._beforeState = { - rings: [], - windings: [], - multiPolys: [] - }; - else { - var seg = this.prev.consumedBy || this.prev; - this._beforeState = seg.afterState(); - } - return this._beforeState; - } - }, { - key: "afterState", - value: function afterState() { - if (this._afterState !== void 0) - return this._afterState; - var beforeState = this.beforeState(); - this._afterState = { - rings: beforeState.rings.slice(0), - windings: beforeState.windings.slice(0), - multiPolys: [] - }; - var ringsAfter = this._afterState.rings; - var windingsAfter = this._afterState.windings; - var mpsAfter = this._afterState.multiPolys; - for (var i3 = 0, iMax = this.rings.length; i3 < iMax; i3++) { - var ring = this.rings[i3]; - var winding = this.windings[i3]; - var index2 = ringsAfter.indexOf(ring); - if (index2 === -1) { - ringsAfter.push(ring); - windingsAfter.push(winding); - } else - windingsAfter[index2] += winding; - } - var polysAfter = []; - var polysExclude = []; - for (var _i = 0, _iMax = ringsAfter.length; _i < _iMax; _i++) { - if (windingsAfter[_i] === 0) - continue; - var _ring = ringsAfter[_i]; - var poly = _ring.poly; - if (polysExclude.indexOf(poly) !== -1) - continue; - if (_ring.isExterior) - polysAfter.push(poly); - else { - if (polysExclude.indexOf(poly) === -1) - polysExclude.push(poly); - var _index = polysAfter.indexOf(_ring.poly); - if (_index !== -1) - polysAfter.splice(_index, 1); - } - } - for (var _i2 = 0, _iMax2 = polysAfter.length; _i2 < _iMax2; _i2++) { - var mp = polysAfter[_i2].multiPoly; - if (mpsAfter.indexOf(mp) === -1) - mpsAfter.push(mp); - } - return this._afterState; - } - /* Is this segment part of the final result? */ - }, { - key: "isInResult", - value: function isInResult() { - if (this.consumedBy) - return false; - if (this._isInResult !== void 0) - return this._isInResult; - var mpsBefore = this.beforeState().multiPolys; - var mpsAfter = this.afterState().multiPolys; - switch (operation.type) { - case "union": { - var noBefores = mpsBefore.length === 0; - var noAfters = mpsAfter.length === 0; - this._isInResult = noBefores !== noAfters; - break; - } - case "intersection": { - var least; - var most; - if (mpsBefore.length < mpsAfter.length) { - least = mpsBefore.length; - most = mpsAfter.length; - } else { - least = mpsAfter.length; - most = mpsBefore.length; - } - this._isInResult = most === operation.numMultiPolys && least < most; - break; - } - case "xor": { - var diff = Math.abs(mpsBefore.length - mpsAfter.length); - this._isInResult = diff % 2 === 1; - break; - } - case "difference": { - var isJustSubject = function isJustSubject2(mps) { - return mps.length === 1 && mps[0].isSubject; - }; - this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter); - break; - } - default: - throw new Error("Unrecognized operation type found ".concat(operation.type)); - } - return this._isInResult; - } - }], [{ - key: "fromRing", - value: function fromRing(pt1, pt2, ring) { - var leftPt, rightPt, winding; - var cmpPts = SweepEvent.comparePoints(pt1, pt2); - if (cmpPts < 0) { - leftPt = pt1; - rightPt = pt2; - winding = 1; - } else if (cmpPts > 0) { - leftPt = pt2; - rightPt = pt1; - winding = -1; - } else - throw new Error("Tried to create degenerate segment at [".concat(pt1.x, ", ").concat(pt1.y, "]")); - var leftSE = new SweepEvent(leftPt, true); - var rightSE = new SweepEvent(rightPt, false); - return new Segment2(leftSE, rightSE, [ring], [winding]); - } - }]); - return Segment2; - }(); - var RingIn = /* @__PURE__ */ function() { - function RingIn2(geomRing, poly, isExterior) { - _classCallCheck(this, RingIn2); - if (!Array.isArray(geomRing) || geomRing.length === 0) { - throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); - } - this.poly = poly; - this.isExterior = isExterior; - this.segments = []; - if (typeof geomRing[0][0] !== "number" || typeof geomRing[0][1] !== "number") { - throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); - } - var firstPoint = rounder.round(geomRing[0][0], geomRing[0][1]); - this.bbox = { - ll: { - x: firstPoint.x, - y: firstPoint.y - }, - ur: { - x: firstPoint.x, - y: firstPoint.y - } - }; - var prevPoint = firstPoint; - for (var i3 = 1, iMax = geomRing.length; i3 < iMax; i3++) { - if (typeof geomRing[i3][0] !== "number" || typeof geomRing[i3][1] !== "number") { - throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); - } - var point2 = rounder.round(geomRing[i3][0], geomRing[i3][1]); - if (point2.x === prevPoint.x && point2.y === prevPoint.y) - continue; - this.segments.push(Segment.fromRing(prevPoint, point2, this)); - if (point2.x < this.bbox.ll.x) - this.bbox.ll.x = point2.x; - if (point2.y < this.bbox.ll.y) - this.bbox.ll.y = point2.y; - if (point2.x > this.bbox.ur.x) - this.bbox.ur.x = point2.x; - if (point2.y > this.bbox.ur.y) - this.bbox.ur.y = point2.y; - prevPoint = point2; - } - if (firstPoint.x !== prevPoint.x || firstPoint.y !== prevPoint.y) { - this.segments.push(Segment.fromRing(prevPoint, firstPoint, this)); - } + return ciphertext; + }; + ModeOfOperationCBC.prototype.decrypt = function(ciphertext) { + ciphertext = coerceArray(ciphertext); + if (ciphertext.length % 16 !== 0) { + throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); } - _createClass(RingIn2, [{ - key: "getSweepEvents", - value: function getSweepEvents() { - var sweepEvents = []; - for (var i3 = 0, iMax = this.segments.length; i3 < iMax; i3++) { - var segment = this.segments[i3]; - sweepEvents.push(segment.leftSE); - sweepEvents.push(segment.rightSE); - } - return sweepEvents; - } - }]); - return RingIn2; - }(); - var PolyIn = /* @__PURE__ */ function() { - function PolyIn2(geomPoly, multiPoly) { - _classCallCheck(this, PolyIn2); - if (!Array.isArray(geomPoly)) { - throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); - } - this.exteriorRing = new RingIn(geomPoly[0], this, true); - this.bbox = { - ll: { - x: this.exteriorRing.bbox.ll.x, - y: this.exteriorRing.bbox.ll.y - }, - ur: { - x: this.exteriorRing.bbox.ur.x, - y: this.exteriorRing.bbox.ur.y - } - }; - this.interiorRings = []; - for (var i3 = 1, iMax = geomPoly.length; i3 < iMax; i3++) { - var ring = new RingIn(geomPoly[i3], this, false); - if (ring.bbox.ll.x < this.bbox.ll.x) - this.bbox.ll.x = ring.bbox.ll.x; - if (ring.bbox.ll.y < this.bbox.ll.y) - this.bbox.ll.y = ring.bbox.ll.y; - if (ring.bbox.ur.x > this.bbox.ur.x) - this.bbox.ur.x = ring.bbox.ur.x; - if (ring.bbox.ur.y > this.bbox.ur.y) - this.bbox.ur.y = ring.bbox.ur.y; - this.interiorRings.push(ring); + var plaintext = createArray(ciphertext.length); + var block2 = createArray(16); + for (var i3 = 0; i3 < ciphertext.length; i3 += 16) { + copyArray(ciphertext, block2, 0, i3, i3 + 16); + block2 = this._aes.decrypt(block2); + for (var j2 = 0; j2 < 16; j2++) { + plaintext[i3 + j2] = block2[j2] ^ this._lastCipherblock[j2]; } - this.multiPoly = multiPoly; + copyArray(ciphertext, this._lastCipherblock, 0, i3, i3 + 16); } - _createClass(PolyIn2, [{ - key: "getSweepEvents", - value: function getSweepEvents() { - var sweepEvents = this.exteriorRing.getSweepEvents(); - for (var i3 = 0, iMax = this.interiorRings.length; i3 < iMax; i3++) { - var ringSweepEvents = this.interiorRings[i3].getSweepEvents(); - for (var j3 = 0, jMax = ringSweepEvents.length; j3 < jMax; j3++) { - sweepEvents.push(ringSweepEvents[j3]); - } - } - return sweepEvents; - } - }]); - return PolyIn2; - }(); - var MultiPolyIn = /* @__PURE__ */ function() { - function MultiPolyIn2(geom, isSubject) { - _classCallCheck(this, MultiPolyIn2); - if (!Array.isArray(geom)) { - throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); - } - try { - if (typeof geom[0][0][0] === "number") - geom = [geom]; - } catch (ex) { - } - this.polys = []; - this.bbox = { - ll: { - x: Number.POSITIVE_INFINITY, - y: Number.POSITIVE_INFINITY - }, - ur: { - x: Number.NEGATIVE_INFINITY, - y: Number.NEGATIVE_INFINITY - } - }; - for (var i3 = 0, iMax = geom.length; i3 < iMax; i3++) { - var poly = new PolyIn(geom[i3], this); - if (poly.bbox.ll.x < this.bbox.ll.x) - this.bbox.ll.x = poly.bbox.ll.x; - if (poly.bbox.ll.y < this.bbox.ll.y) - this.bbox.ll.y = poly.bbox.ll.y; - if (poly.bbox.ur.x > this.bbox.ur.x) - this.bbox.ur.x = poly.bbox.ur.x; - if (poly.bbox.ur.y > this.bbox.ur.y) - this.bbox.ur.y = poly.bbox.ur.y; - this.polys.push(poly); - } - this.isSubject = isSubject; + return plaintext; + }; + var ModeOfOperationCFB = function(key, iv, segmentSize) { + if (!(this instanceof ModeOfOperationCFB)) { + throw Error("AES must be instanitated with `new`"); } - _createClass(MultiPolyIn2, [{ - key: "getSweepEvents", - value: function getSweepEvents() { - var sweepEvents = []; - for (var i3 = 0, iMax = this.polys.length; i3 < iMax; i3++) { - var polySweepEvents = this.polys[i3].getSweepEvents(); - for (var j3 = 0, jMax = polySweepEvents.length; j3 < jMax; j3++) { - sweepEvents.push(polySweepEvents[j3]); - } - } - return sweepEvents; - } - }]); - return MultiPolyIn2; - }(); - var RingOut = /* @__PURE__ */ function() { - _createClass(RingOut2, null, [{ - key: "factory", - /* Given the segments from the sweep line pass, compute & return a series - * of closed rings from all the segments marked to be part of the result */ - value: function factory(allSegments) { - var ringsOut = []; - for (var i3 = 0, iMax = allSegments.length; i3 < iMax; i3++) { - var segment = allSegments[i3]; - if (!segment.isInResult() || segment.ringOut) - continue; - var prevEvent = null; - var event = segment.leftSE; - var nextEvent = segment.rightSE; - var events = [event]; - var startingPoint = event.point; - var intersectionLEs = []; - while (true) { - prevEvent = event; - event = nextEvent; - events.push(event); - if (event.point === startingPoint) - break; - while (true) { - var availableLEs = event.getAvailableLinkedEvents(); - if (availableLEs.length === 0) { - var firstPt = events[0].point; - var lastPt = events[events.length - 1].point; - throw new Error("Unable to complete output ring starting at [".concat(firstPt.x, ",") + " ".concat(firstPt.y, "]. Last matching segment found ends at") + " [".concat(lastPt.x, ", ").concat(lastPt.y, "].")); - } - if (availableLEs.length === 1) { - nextEvent = availableLEs[0].otherSE; - break; - } - var indexLE = null; - for (var j3 = 0, jMax = intersectionLEs.length; j3 < jMax; j3++) { - if (intersectionLEs[j3].point === event.point) { - indexLE = j3; - break; - } - } - if (indexLE !== null) { - var intersectionLE = intersectionLEs.splice(indexLE)[0]; - var ringEvents = events.splice(intersectionLE.index); - ringEvents.unshift(ringEvents[0].otherSE); - ringsOut.push(new RingOut2(ringEvents.reverse())); - continue; - } - intersectionLEs.push({ - index: events.length, - point: event.point - }); - var comparator = event.getLeftmostComparator(prevEvent); - nextEvent = availableLEs.sort(comparator)[0].otherSE; - break; - } - } - ringsOut.push(new RingOut2(events)); - } - return ringsOut; - } - }]); - function RingOut2(events) { - _classCallCheck(this, RingOut2); - this.events = events; - for (var i3 = 0, iMax = events.length; i3 < iMax; i3++) { - events[i3].segment.ringOut = this; - } - this.poly = null; + this.description = "Cipher Feedback"; + this.name = "cfb"; + if (!iv) { + iv = createArray(16); + } else if (iv.length != 16) { + throw new Error("invalid initialation vector size (must be 16 size)"); } - _createClass(RingOut2, [{ - key: "getGeom", - value: function getGeom2() { - var prevPt = this.events[0].point; - var points = [prevPt]; - for (var i3 = 1, iMax = this.events.length - 1; i3 < iMax; i3++) { - var _pt = this.events[i3].point; - var _nextPt = this.events[i3 + 1].point; - if (compareVectorAngles(_pt, prevPt, _nextPt) === 0) - continue; - points.push(_pt); - prevPt = _pt; - } - if (points.length === 1) - return null; - var pt2 = points[0]; - var nextPt = points[1]; - if (compareVectorAngles(pt2, prevPt, nextPt) === 0) - points.shift(); - points.push(points[0]); - var step = this.isExteriorRing() ? 1 : -1; - var iStart = this.isExteriorRing() ? 0 : points.length - 1; - var iEnd = this.isExteriorRing() ? points.length : -1; - var orderedPoints = []; - for (var _i = iStart; _i != iEnd; _i += step) { - orderedPoints.push([points[_i].x, points[_i].y]); - } - return orderedPoints; - } - }, { - key: "isExteriorRing", - value: function isExteriorRing() { - if (this._isExteriorRing === void 0) { - var enclosing = this.enclosingRing(); - this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true; - } - return this._isExteriorRing; - } - }, { - key: "enclosingRing", - value: function enclosingRing() { - if (this._enclosingRing === void 0) { - this._enclosingRing = this._calcEnclosingRing(); - } - return this._enclosingRing; - } - /* Returns the ring that encloses this one, if any */ - }, { - key: "_calcEnclosingRing", - value: function _calcEnclosingRing() { - var leftMostEvt = this.events[0]; - for (var i3 = 1, iMax = this.events.length; i3 < iMax; i3++) { - var evt = this.events[i3]; - if (SweepEvent.compare(leftMostEvt, evt) > 0) - leftMostEvt = evt; - } - var prevSeg = leftMostEvt.segment.prevInResult(); - var prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null; - while (true) { - if (!prevSeg) - return null; - if (!prevPrevSeg) - return prevSeg.ringOut; - if (prevPrevSeg.ringOut !== prevSeg.ringOut) { - if (prevPrevSeg.ringOut.enclosingRing() !== prevSeg.ringOut) { - return prevSeg.ringOut; - } else - return prevSeg.ringOut.enclosingRing(); - } - prevSeg = prevPrevSeg.prevInResult(); - prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null; - } - } - }]); - return RingOut2; - }(); - var PolyOut = /* @__PURE__ */ function() { - function PolyOut2(exteriorRing) { - _classCallCheck(this, PolyOut2); - this.exteriorRing = exteriorRing; - exteriorRing.poly = this; - this.interiorRings = []; + if (!segmentSize) { + segmentSize = 1; } - _createClass(PolyOut2, [{ - key: "addInterior", - value: function addInterior(ring) { - this.interiorRings.push(ring); - ring.poly = this; - } - }, { - key: "getGeom", - value: function getGeom2() { - var geom = [this.exteriorRing.getGeom()]; - if (geom[0] === null) - return null; - for (var i3 = 0, iMax = this.interiorRings.length; i3 < iMax; i3++) { - var ringGeom = this.interiorRings[i3].getGeom(); - if (ringGeom === null) - continue; - geom.push(ringGeom); - } - return geom; - } - }]); - return PolyOut2; - }(); - var MultiPolyOut = /* @__PURE__ */ function() { - function MultiPolyOut2(rings) { - _classCallCheck(this, MultiPolyOut2); - this.rings = rings; - this.polys = this._composePolys(rings); + this.segmentSize = segmentSize; + this._shiftRegister = coerceArray(iv, true); + this._aes = new AES(key); + }; + ModeOfOperationCFB.prototype.encrypt = function(plaintext) { + if (plaintext.length % this.segmentSize != 0) { + throw new Error("invalid plaintext size (must be segmentSize bytes)"); } - _createClass(MultiPolyOut2, [{ - key: "getGeom", - value: function getGeom2() { - var geom = []; - for (var i3 = 0, iMax = this.polys.length; i3 < iMax; i3++) { - var polyGeom = this.polys[i3].getGeom(); - if (polyGeom === null) - continue; - geom.push(polyGeom); - } - return geom; - } - }, { - key: "_composePolys", - value: function _composePolys(rings) { - var polys = []; - for (var i3 = 0, iMax = rings.length; i3 < iMax; i3++) { - var ring = rings[i3]; - if (ring.poly) - continue; - if (ring.isExteriorRing()) - polys.push(new PolyOut(ring)); - else { - var enclosingRing = ring.enclosingRing(); - if (!enclosingRing.poly) - polys.push(new PolyOut(enclosingRing)); - enclosingRing.poly.addInterior(ring); - } - } - return polys; + var encrypted = coerceArray(plaintext, true); + var xorSegment; + for (var i3 = 0; i3 < encrypted.length; i3 += this.segmentSize) { + xorSegment = this._aes.encrypt(this._shiftRegister); + for (var j2 = 0; j2 < this.segmentSize; j2++) { + encrypted[i3 + j2] ^= xorSegment[j2]; } - }]); - return MultiPolyOut2; - }(); - var SweepLine = /* @__PURE__ */ function() { - function SweepLine2(queue) { - var comparator = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : Segment.compare; - _classCallCheck(this, SweepLine2); - this.queue = queue; - this.tree = new Tree(comparator); - this.segments = []; + copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); + copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i3, i3 + this.segmentSize); } - _createClass(SweepLine2, [{ - key: "process", - value: function process2(event) { - var segment = event.segment; - var newEvents = []; - if (event.consumedBy) { - if (event.isLeft) - this.queue.remove(event.otherSE); - else - this.tree.remove(segment); - return newEvents; - } - var node = event.isLeft ? this.tree.insert(segment) : this.tree.find(segment); - if (!node) - throw new Error("Unable to find segment #".concat(segment.id, " ") + "[".concat(segment.leftSE.point.x, ", ").concat(segment.leftSE.point.y, "] -> ") + "[".concat(segment.rightSE.point.x, ", ").concat(segment.rightSE.point.y, "] ") + "in SweepLine tree. Please submit a bug report."); - var prevNode = node; - var nextNode = node; - var prevSeg = void 0; - var nextSeg = void 0; - while (prevSeg === void 0) { - prevNode = this.tree.prev(prevNode); - if (prevNode === null) - prevSeg = null; - else if (prevNode.key.consumedBy === void 0) - prevSeg = prevNode.key; - } - while (nextSeg === void 0) { - nextNode = this.tree.next(nextNode); - if (nextNode === null) - nextSeg = null; - else if (nextNode.key.consumedBy === void 0) - nextSeg = nextNode.key; - } - if (event.isLeft) { - var prevMySplitter = null; - if (prevSeg) { - var prevInter = prevSeg.getIntersection(segment); - if (prevInter !== null) { - if (!segment.isAnEndpoint(prevInter)) - prevMySplitter = prevInter; - if (!prevSeg.isAnEndpoint(prevInter)) { - var newEventsFromSplit = this._splitSafely(prevSeg, prevInter); - for (var i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { - newEvents.push(newEventsFromSplit[i3]); - } - } - } - } - var nextMySplitter = null; - if (nextSeg) { - var nextInter = nextSeg.getIntersection(segment); - if (nextInter !== null) { - if (!segment.isAnEndpoint(nextInter)) - nextMySplitter = nextInter; - if (!nextSeg.isAnEndpoint(nextInter)) { - var _newEventsFromSplit = this._splitSafely(nextSeg, nextInter); - for (var _i = 0, _iMax = _newEventsFromSplit.length; _i < _iMax; _i++) { - newEvents.push(_newEventsFromSplit[_i]); - } - } - } - } - if (prevMySplitter !== null || nextMySplitter !== null) { - var mySplitter = null; - if (prevMySplitter === null) - mySplitter = nextMySplitter; - else if (nextMySplitter === null) - mySplitter = prevMySplitter; - else { - var cmpSplitters = SweepEvent.comparePoints(prevMySplitter, nextMySplitter); - mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter; - } - this.queue.remove(segment.rightSE); - newEvents.push(segment.rightSE); - var _newEventsFromSplit2 = segment.split(mySplitter); - for (var _i2 = 0, _iMax2 = _newEventsFromSplit2.length; _i2 < _iMax2; _i2++) { - newEvents.push(_newEventsFromSplit2[_i2]); - } - } - if (newEvents.length > 0) { - this.tree.remove(segment); - newEvents.push(event); - } else { - this.segments.push(segment); - segment.prev = prevSeg; - } - } else { - if (prevSeg && nextSeg) { - var inter = prevSeg.getIntersection(nextSeg); - if (inter !== null) { - if (!prevSeg.isAnEndpoint(inter)) { - var _newEventsFromSplit3 = this._splitSafely(prevSeg, inter); - for (var _i3 = 0, _iMax3 = _newEventsFromSplit3.length; _i3 < _iMax3; _i3++) { - newEvents.push(_newEventsFromSplit3[_i3]); - } - } - if (!nextSeg.isAnEndpoint(inter)) { - var _newEventsFromSplit4 = this._splitSafely(nextSeg, inter); - for (var _i4 = 0, _iMax4 = _newEventsFromSplit4.length; _i4 < _iMax4; _i4++) { - newEvents.push(_newEventsFromSplit4[_i4]); - } - } - } - } - this.tree.remove(segment); - } - return newEvents; - } - /* Safely split a segment that is currently in the datastructures - * IE - a segment other than the one that is currently being processed. */ - }, { - key: "_splitSafely", - value: function _splitSafely(seg, pt2) { - this.tree.remove(seg); - var rightSE = seg.rightSE; - this.queue.remove(rightSE); - var newEvents = seg.split(pt2); - newEvents.push(rightSE); - if (seg.consumedBy === void 0) - this.tree.insert(seg); - return newEvents; - } - }]); - return SweepLine2; - }(); - var POLYGON_CLIPPING_MAX_QUEUE_SIZE = typeof process !== "undefined" && process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE || 1e6; - var POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS = typeof process !== "undefined" && process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS || 1e6; - var Operation = /* @__PURE__ */ function() { - function Operation2() { - _classCallCheck(this, Operation2); - } - _createClass(Operation2, [{ - key: "run", - value: function run(type2, geom, moreGeoms) { - operation.type = type2; - rounder.reset(); - var multipolys = [new MultiPolyIn(geom, true)]; - for (var i3 = 0, iMax = moreGeoms.length; i3 < iMax; i3++) { - multipolys.push(new MultiPolyIn(moreGeoms[i3], false)); - } - operation.numMultiPolys = multipolys.length; - if (operation.type === "difference") { - var subject = multipolys[0]; - var _i = 1; - while (_i < multipolys.length) { - if (getBboxOverlap(multipolys[_i].bbox, subject.bbox) !== null) - _i++; - else - multipolys.splice(_i, 1); - } - } - if (operation.type === "intersection") { - for (var _i2 = 0, _iMax = multipolys.length; _i2 < _iMax; _i2++) { - var mpA = multipolys[_i2]; - for (var j3 = _i2 + 1, jMax = multipolys.length; j3 < jMax; j3++) { - if (getBboxOverlap(mpA.bbox, multipolys[j3].bbox) === null) - return []; - } - } - } - var queue = new Tree(SweepEvent.compare); - for (var _i3 = 0, _iMax2 = multipolys.length; _i3 < _iMax2; _i3++) { - var sweepEvents = multipolys[_i3].getSweepEvents(); - for (var _j = 0, _jMax = sweepEvents.length; _j < _jMax; _j++) { - queue.insert(sweepEvents[_j]); - if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) { - throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big). Please file a bug report."); - } - } - } - var sweepLine = new SweepLine(queue); - var prevQueueSize = queue.size; - var node = queue.pop(); - while (node) { - var evt = node.key; - if (queue.size === prevQueueSize) { - var seg = evt.segment; - throw new Error("Unable to pop() ".concat(evt.isLeft ? "left" : "right", " SweepEvent ") + "[".concat(evt.point.x, ", ").concat(evt.point.y, "] from segment #").concat(seg.id, " ") + "[".concat(seg.leftSE.point.x, ", ").concat(seg.leftSE.point.y, "] -> ") + "[".concat(seg.rightSE.point.x, ", ").concat(seg.rightSE.point.y, "] from queue. ") + "Please file a bug report."); - } - if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) { - throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big). Please file a bug report."); - } - if (sweepLine.segments.length > POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS) { - throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments). Please file a bug report."); - } - var newEvents = sweepLine.process(evt); - for (var _i4 = 0, _iMax3 = newEvents.length; _i4 < _iMax3; _i4++) { - var _evt = newEvents[_i4]; - if (_evt.consumedBy === void 0) - queue.insert(_evt); - } - prevQueueSize = queue.size; - node = queue.pop(); - } - rounder.reset(); - var ringsOut = RingOut.factory(sweepLine.segments); - var result = new MultiPolyOut(ringsOut); - return result.getGeom(); + return encrypted; + }; + ModeOfOperationCFB.prototype.decrypt = function(ciphertext) { + if (ciphertext.length % this.segmentSize != 0) { + throw new Error("invalid ciphertext size (must be segmentSize bytes)"); + } + var plaintext = coerceArray(ciphertext, true); + var xorSegment; + for (var i3 = 0; i3 < plaintext.length; i3 += this.segmentSize) { + xorSegment = this._aes.encrypt(this._shiftRegister); + for (var j2 = 0; j2 < this.segmentSize; j2++) { + plaintext[i3 + j2] ^= xorSegment[j2]; } - }]); - return Operation2; - }(); - var operation = new Operation(); - var union = function union2(geom) { - for (var _len = arguments.length, moreGeoms = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - moreGeoms[_key - 1] = arguments[_key]; + copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); + copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i3, i3 + this.segmentSize); } - return operation.run("union", geom, moreGeoms); + return plaintext; }; - var intersection$1 = function intersection2(geom) { - for (var _len2 = arguments.length, moreGeoms = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - moreGeoms[_key2 - 1] = arguments[_key2]; + var ModeOfOperationOFB = function(key, iv) { + if (!(this instanceof ModeOfOperationOFB)) { + throw Error("AES must be instanitated with `new`"); } - return operation.run("intersection", geom, moreGeoms); - }; - var xor = function xor2(geom) { - for (var _len3 = arguments.length, moreGeoms = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - moreGeoms[_key3 - 1] = arguments[_key3]; + this.description = "Output Feedback"; + this.name = "ofb"; + if (!iv) { + iv = createArray(16); + } else if (iv.length != 16) { + throw new Error("invalid initialation vector size (must be 16 bytes)"); } - return operation.run("xor", geom, moreGeoms); + this._lastPrecipher = coerceArray(iv, true); + this._lastPrecipherIndex = 16; + this._aes = new AES(key); }; - var difference = function difference2(subjectGeom) { - for (var _len4 = arguments.length, clippingGeoms = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - clippingGeoms[_key4 - 1] = arguments[_key4]; + ModeOfOperationOFB.prototype.encrypt = function(plaintext) { + var encrypted = coerceArray(plaintext, true); + for (var i3 = 0; i3 < encrypted.length; i3++) { + if (this._lastPrecipherIndex === 16) { + this._lastPrecipher = this._aes.encrypt(this._lastPrecipher); + this._lastPrecipherIndex = 0; + } + encrypted[i3] ^= this._lastPrecipher[this._lastPrecipherIndex++]; } - return operation.run("difference", subjectGeom, clippingGeoms); + return encrypted; }; - var index = { - union, - intersection: intersection$1, - xor, - difference + ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt; + var Counter = function(initialValue) { + if (!(this instanceof Counter)) { + throw Error("Counter must be instanitated with `new`"); + } + if (initialValue !== 0 && !initialValue) { + initialValue = 1; + } + if (typeof initialValue === "number") { + this._counter = createArray(16); + this.setValue(initialValue); + } else { + this.setBytes(initialValue); + } }; - return index; - }); - } - }); - - // node_modules/geojson-precision/index.js - var require_geojson_precision = __commonJS({ - "node_modules/geojson-precision/index.js"(exports2, module2) { - (function() { - function parse(t2, coordinatePrecision, extrasPrecision) { - function point2(p2) { - return p2.map(function(e3, index) { - if (index < 2) { - return 1 * e3.toFixed(coordinatePrecision); - } else { - return 1 * e3.toFixed(extrasPrecision); - } - }); - } - function multi(l2) { - return l2.map(point2); - } - function poly(p2) { - return p2.map(multi); - } - function multiPoly(m2) { - return m2.map(poly); - } - function geometry(obj) { - if (!obj) { - return {}; - } - switch (obj.type) { - case "Point": - obj.coordinates = point2(obj.coordinates); - return obj; - case "LineString": - case "MultiPoint": - obj.coordinates = multi(obj.coordinates); - return obj; - case "Polygon": - case "MultiLineString": - obj.coordinates = poly(obj.coordinates); - return obj; - case "MultiPolygon": - obj.coordinates = multiPoly(obj.coordinates); - return obj; - case "GeometryCollection": - obj.geometries = obj.geometries.map(geometry); - return obj; - default: - return {}; - } - } - function feature3(obj) { - obj.geometry = geometry(obj.geometry); - return obj; - } - function featureCollection(f3) { - f3.features = f3.features.map(feature3); - return f3; - } - function geometryCollection(g3) { - g3.geometries = g3.geometries.map(geometry); - return g3; - } - if (!t2) { - return t2; - } - switch (t2.type) { - case "Feature": - return feature3(t2); - case "GeometryCollection": - return geometryCollection(t2); - case "FeatureCollection": - return featureCollection(t2); - case "Point": - case "LineString": - case "Polygon": - case "MultiPoint": - case "MultiPolygon": - case "MultiLineString": - return geometry(t2); - default: - return t2; + Counter.prototype.setValue = function(value) { + if (typeof value !== "number" || parseInt(value) != value) { + throw new Error("invalid counter value (must be an integer)"); } - } - module2.exports = parse; - module2.exports.parse = parse; - })(); - } - }); - - // node_modules/@aitodotai/json-stringify-pretty-compact/index.js - var require_json_stringify_pretty_compact = __commonJS({ - "node_modules/@aitodotai/json-stringify-pretty-compact/index.js"(exports2, module2) { - function isObject3(obj) { - return typeof obj === "object" && obj !== null; - } - function forEach(obj, cb) { - if (Array.isArray(obj)) { - obj.forEach(cb); - } else if (isObject3(obj)) { - Object.keys(obj).forEach(function(key) { - var val = obj[key]; - cb(val, key); - }); - } - } - function getTreeDepth(obj) { - var depth = 0; - if (Array.isArray(obj) || isObject3(obj)) { - forEach(obj, function(val) { - if (Array.isArray(val) || isObject3(val)) { - var tmpDepth = getTreeDepth(val); - if (tmpDepth > depth) { - depth = tmpDepth; - } - } - }); - return depth + 1; - } - return depth; - } - function stringify3(obj, options2) { - options2 = options2 || {}; - var indent2 = JSON.stringify([1], null, get4(options2, "indent", 2)).slice(2, -3); - var addMargin = get4(options2, "margins", false); - var addArrayMargin = get4(options2, "arrayMargins", false); - var addObjectMargin = get4(options2, "objectMargins", false); - var maxLength = indent2 === "" ? Infinity : get4(options2, "maxLength", 80); - var maxNesting = get4(options2, "maxNesting", Infinity); - return function _stringify(obj2, currentIndent, reserved) { - if (obj2 && typeof obj2.toJSON === "function") { - obj2 = obj2.toJSON(); + if (value > Number.MAX_SAFE_INTEGER) { + throw new Error("integer value out of safe range"); } - var string = JSON.stringify(obj2); - if (string === void 0) { - return string; + for (var index = 15; index >= 0; --index) { + this._counter[index] = value % 256; + value = parseInt(value / 256); } - var length = maxLength - currentIndent.length - reserved; - var treeDepth = getTreeDepth(obj2); - if (treeDepth <= maxNesting && string.length <= length) { - var prettified = prettify(string, { - addMargin, - addArrayMargin, - addObjectMargin - }); - if (prettified.length <= length) { - return prettified; - } + }; + Counter.prototype.setBytes = function(bytes) { + bytes = coerceArray(bytes, true); + if (bytes.length != 16) { + throw new Error("invalid counter bytes size (must be 16 bytes)"); } - if (isObject3(obj2)) { - var nextIndent = currentIndent + indent2; - var items = []; - var delimiters; - var comma = function(array2, index2) { - return index2 === array2.length - 1 ? 0 : 1; - }; - if (Array.isArray(obj2)) { - for (var index = 0; index < obj2.length; index++) { - items.push( - _stringify(obj2[index], nextIndent, comma(obj2, index)) || "null" - ); - } - delimiters = "[]"; + this._counter = bytes; + }; + Counter.prototype.increment = function() { + for (var i3 = 15; i3 >= 0; i3--) { + if (this._counter[i3] === 255) { + this._counter[i3] = 0; } else { - Object.keys(obj2).forEach(function(key, index2, array2) { - var keyPart = JSON.stringify(key) + ": "; - var value = _stringify( - obj2[key], - nextIndent, - keyPart.length + comma(array2, index2) - ); - if (value !== void 0) { - items.push(keyPart + value); - } - }); - delimiters = "{}"; - } - if (items.length > 0) { - return [ - delimiters[0], - indent2 + items.join(",\n" + nextIndent), - delimiters[1] - ].join("\n" + currentIndent); + this._counter[i3]++; + break; } } - return string; - }(obj, "", 0); - } - var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,\][}{]/g; - function prettify(string, options2) { - options2 = options2 || {}; - var tokens = { - "{": "{", - "}": "}", - "[": "[", - "]": "]", - ",": ", ", - ":": ": " }; - if (options2.addMargin || options2.addObjectMargin) { - tokens["{"] = "{ "; - tokens["}"] = " }"; - } - if (options2.addMargin || options2.addArrayMargin) { - tokens["["] = "[ "; - tokens["]"] = " ]"; - } - return string.replace(stringOrChar, function(match, string2) { - return string2 ? match : tokens[match]; - }); - } - function get4(options2, name, defaultValue) { - return name in options2 ? options2[name] : defaultValue; - } - module2.exports = stringify3; - } - }); - - // node_modules/aes-js/index.js - var require_aes_js = __commonJS({ - "node_modules/aes-js/index.js"(exports2, module2) { - (function(root3) { - "use strict"; - function checkInt(value) { - return parseInt(value) === value; - } - function checkInts(arrayish) { - if (!checkInt(arrayish.length)) { - return false; - } - for (var i3 = 0; i3 < arrayish.length; i3++) { - if (!checkInt(arrayish[i3]) || arrayish[i3] < 0 || arrayish[i3] > 255) { - return false; - } + var ModeOfOperationCTR = function(key, counter) { + if (!(this instanceof ModeOfOperationCTR)) { + throw Error("AES must be instanitated with `new`"); } - return true; - } - function coerceArray(arg, copy2) { - if (arg.buffer && arg.name === "Uint8Array") { - if (copy2) { - if (arg.slice) { - arg = arg.slice(); - } else { - arg = Array.prototype.slice.call(arg); - } - } - return arg; + this.description = "Counter"; + this.name = "ctr"; + if (!(counter instanceof Counter)) { + counter = new Counter(counter); } - if (Array.isArray(arg)) { - if (!checkInts(arg)) { - throw new Error("Array contains invalid value: " + arg); + this._counter = counter; + this._remainingCounter = null; + this._remainingCounterIndex = 16; + this._aes = new AES(key); + }; + ModeOfOperationCTR.prototype.encrypt = function(plaintext) { + var encrypted = coerceArray(plaintext, true); + for (var i3 = 0; i3 < encrypted.length; i3++) { + if (this._remainingCounterIndex === 16) { + this._remainingCounter = this._aes.encrypt(this._counter._counter); + this._remainingCounterIndex = 0; + this._counter.increment(); } - return new Uint8Array(arg); - } - if (checkInt(arg.length) && checkInts(arg)) { - return new Uint8Array(arg); + encrypted[i3] ^= this._remainingCounter[this._remainingCounterIndex++]; } - throw new Error("unsupported array-like object"); - } - function createArray(length) { - return new Uint8Array(length); - } - function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) { - if (sourceStart != null || sourceEnd != null) { - if (sourceArray.slice) { - sourceArray = sourceArray.slice(sourceStart, sourceEnd); - } else { - sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd); - } + return encrypted; + }; + ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt; + function pkcs7pad(data) { + data = coerceArray(data, true); + var padder = 16 - data.length % 16; + var result = createArray(data.length + padder); + copyArray(data, result); + for (var i3 = data.length; i3 < result.length; i3++) { + result[i3] = padder; } - targetArray.set(sourceArray, targetStart); + return result; } - var convertUtf8 = function() { - function toBytes(text2) { - var result = [], i3 = 0; - text2 = encodeURI(text2); - while (i3 < text2.length) { - var c2 = text2.charCodeAt(i3++); - if (c2 === 37) { - result.push(parseInt(text2.substr(i3, 2), 16)); - i3 += 2; - } else { - result.push(c2); - } - } - return coerceArray(result); - } - function fromBytes(bytes) { - var result = [], i3 = 0; - while (i3 < bytes.length) { - var c2 = bytes[i3]; - if (c2 < 128) { - result.push(String.fromCharCode(c2)); - i3++; - } else if (c2 > 191 && c2 < 224) { - result.push(String.fromCharCode((c2 & 31) << 6 | bytes[i3 + 1] & 63)); - i3 += 2; - } else { - result.push(String.fromCharCode((c2 & 15) << 12 | (bytes[i3 + 1] & 63) << 6 | bytes[i3 + 2] & 63)); - i3 += 3; - } - } - return result.join(""); + function pkcs7strip(data) { + data = coerceArray(data, true); + if (data.length < 16) { + throw new Error("PKCS#7 invalid length"); } - return { - toBytes, - fromBytes - }; - }(); - var convertHex = function() { - function toBytes(text2) { - var result = []; - for (var i3 = 0; i3 < text2.length; i3 += 2) { - result.push(parseInt(text2.substr(i3, 2), 16)); - } - return result; + var padder = data[data.length - 1]; + if (padder > 16) { + throw new Error("PKCS#7 padding byte out of range"); } - var Hex = "0123456789abcdef"; - function fromBytes(bytes) { - var result = []; - for (var i3 = 0; i3 < bytes.length; i3++) { - var v2 = bytes[i3]; - result.push(Hex[(v2 & 240) >> 4] + Hex[v2 & 15]); + var length2 = data.length - padder; + for (var i3 = 0; i3 < padder; i3++) { + if (data[length2 + i3] !== padder) { + throw new Error("PKCS#7 invalid padding byte"); } - return result.join(""); - } - return { - toBytes, - fromBytes - }; - }(); - var numberOfRounds = { 16: 10, 24: 12, 32: 14 }; - var rcon = [1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145]; - var S2 = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]; - var Si = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125]; - var T1 = [3328402341, 4168907908, 4000806809, 4135287693, 4294111757, 3597364157, 3731845041, 2445657428, 1613770832, 33620227, 3462883241, 1445669757, 3892248089, 3050821474, 1303096294, 3967186586, 2412431941, 528646813, 2311702848, 4202528135, 4026202645, 2992200171, 2387036105, 4226871307, 1101901292, 3017069671, 1604494077, 1169141738, 597466303, 1403299063, 3832705686, 2613100635, 1974974402, 3791519004, 1033081774, 1277568618, 1815492186, 2118074177, 4126668546, 2211236943, 1748251740, 1369810420, 3521504564, 4193382664, 3799085459, 2883115123, 1647391059, 706024767, 134480908, 2512897874, 1176707941, 2646852446, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, 3756188221, 3454790438, 1311188841, 2142417613, 3933566367, 302582043, 495158174, 1479289972, 874125870, 907746093, 3698224818, 3025820398, 1537253627, 2756858614, 1983593293, 3084310113, 2108928974, 1378429307, 3722699582, 1580150641, 327451799, 2790478837, 3117535592, 0, 3253595436, 1075847264, 3825007647, 2041688520, 3059440621, 3563743934, 2378943302, 1740553945, 1916352843, 2487896798, 2555137236, 2958579944, 2244988746, 3151024235, 3320835882, 1336584933, 3992714006, 2252555205, 2588757463, 1714631509, 293963156, 2319795663, 3925473552, 67240454, 4269768577, 2689618160, 2017213508, 631218106, 1269344483, 2723238387, 1571005438, 2151694528, 93294474, 1066570413, 563977660, 1882732616, 4059428100, 1673313503, 2008463041, 2950355573, 1109467491, 537923632, 3858759450, 4260623118, 3218264685, 2177748300, 403442708, 638784309, 3287084079, 3193921505, 899127202, 2286175436, 773265209, 2479146071, 1437050866, 4236148354, 2050833735, 3362022572, 3126681063, 840505643, 3866325909, 3227541664, 427917720, 2655997905, 2749160575, 1143087718, 1412049534, 999329963, 193497219, 2353415882, 3354324521, 1807268051, 672404540, 2816401017, 3160301282, 369822493, 2916866934, 3688947771, 1681011286, 1949973070, 336202270, 2454276571, 201721354, 1210328172, 3093060836, 2680341085, 3184776046, 1135389935, 3294782118, 965841320, 831886756, 3554993207, 4068047243, 3588745010, 2345191491, 1849112409, 3664604599, 26054028, 2983581028, 2622377682, 1235855840, 3630984372, 2891339514, 4092916743, 3488279077, 3395642799, 4101667470, 1202630377, 268961816, 1874508501, 4034427016, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, 2546386513, 3421038627, 2715671932, 3899946140, 1042226977, 2521517021, 1639824860, 227249030, 260737669, 3765465232, 2084453954, 1907733956, 3429263018, 2420656344, 100860677, 4160157185, 470683154, 3261161891, 1781871967, 2924959737, 1773779408, 394692241, 2579611992, 974986535, 664706745, 3655459128, 3958962195, 731420851, 571543859, 3530123707, 2849626480, 126783113, 865375399, 765172662, 1008606754, 361203602, 3387549984, 2278477385, 2857719295, 1344809080, 2782912378, 59542671, 1503764984, 160008576, 437062935, 1707065306, 3622233649, 2218934982, 3496503480, 2185314755, 697932208, 1512910199, 504303377, 2075177163, 2824099068, 1841019862, 739644986]; - var T2 = [2781242211, 2230877308, 2582542199, 2381740923, 234877682, 3184946027, 2984144751, 1418839493, 1348481072, 50462977, 2848876391, 2102799147, 434634494, 1656084439, 3863849899, 2599188086, 1167051466, 2636087938, 1082771913, 2281340285, 368048890, 3954334041, 3381544775, 201060592, 3963727277, 1739838676, 4250903202, 3930435503, 3206782108, 4149453988, 2531553906, 1536934080, 3262494647, 484572669, 2923271059, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, 4098991525, 886171109, 150598129, 2481090929, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, 2704774806, 252314885, 3039795866, 151914247, 908333586, 2602270848, 1038082786, 651029483, 1766729511, 3447698098, 2682942837, 454166793, 2652734339, 1951935532, 775166490, 758520603, 3000790638, 4004797018, 4217086112, 4137964114, 1299594043, 1639438038, 3464344499, 2068982057, 1054729187, 1901997871, 2534638724, 4121318227, 1757008337, 0, 750906861, 1614815264, 535035132, 3363418545, 3988151131, 3201591914, 1183697867, 3647454910, 1265776953, 3734260298, 3566750796, 3903871064, 1250283471, 1807470800, 717615087, 3847203498, 384695291, 3313910595, 3617213773, 1432761139, 2484176261, 3481945413, 283769337, 100925954, 2180939647, 4037038160, 1148730428, 3123027871, 3813386408, 4087501137, 4267549603, 3229630528, 2315620239, 2906624658, 3156319645, 1215313976, 82966005, 3747855548, 3245848246, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, 3787349855, 2721421207, 3431482436, 959321879, 1469301956, 4065699751, 2197585534, 1199193405, 2898814052, 3887750493, 724703513, 2514908019, 2696962144, 2551808385, 3516813135, 2141445340, 1715741218, 2119445034, 2872807568, 2198571144, 3398190662, 700968686, 3547052216, 1009259540, 2041044702, 3803995742, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, 3683797321, 168560134, 1816667172, 3837287516, 1570751170, 1857934291, 4014189740, 2797888098, 2822345105, 2754712981, 936633572, 2347923833, 852879335, 1133234376, 1500395319, 3084545389, 2348912013, 1689376213, 3533459022, 3762923945, 3034082412, 4205598294, 133428468, 634383082, 2949277029, 2398386810, 3913789102, 403703816, 3580869306, 2297460856, 1867130149, 1918643758, 607656988, 4049053350, 3346248884, 1368901318, 600565992, 2090982877, 2632479860, 557719327, 3717614411, 3697393085, 2249034635, 2232388234, 2430627952, 1115438654, 3295786421, 2865522278, 3633334344, 84280067, 33027830, 303828494, 2747425121, 1600795957, 4188952407, 3496589753, 2434238086, 1486471617, 658119965, 3106381470, 953803233, 334231800, 3005978776, 857870609, 3151128937, 1890179545, 2298973838, 2805175444, 3056442267, 574365214, 2450884487, 550103529, 1233637070, 4289353045, 2018519080, 2057691103, 2399374476, 4166623649, 2148108681, 387583245, 3664101311, 836232934, 3330556482, 3100665960, 3280093505, 2955516313, 2002398509, 287182607, 3413881008, 4238890068, 3597515707, 975967766]; - var T3 = [1671808611, 2089089148, 2006576759, 2072901243, 4061003762, 1807603307, 1873927791, 3310653893, 810573872, 16974337, 1739181671, 729634347, 4263110654, 3613570519, 2883997099, 1989864566, 3393556426, 2191335298, 3376449993, 2106063485, 4195741690, 1508618841, 1204391495, 4027317232, 2917941677, 3563566036, 2734514082, 2951366063, 2629772188, 2767672228, 1922491506, 3227229120, 3082974647, 4246528509, 2477669779, 644500518, 911895606, 1061256767, 4144166391, 3427763148, 878471220, 2784252325, 3845444069, 4043897329, 1905517169, 3631459288, 827548209, 356461077, 67897348, 3344078279, 593839651, 3277757891, 405286936, 2527147926, 84871685, 2595565466, 118033927, 305538066, 2157648768, 3795705826, 3945188843, 661212711, 2999812018, 1973414517, 152769033, 2208177539, 745822252, 439235610, 455947803, 1857215598, 1525593178, 2700827552, 1391895634, 994932283, 3596728278, 3016654259, 695947817, 3812548067, 795958831, 2224493444, 1408607827, 3513301457, 0, 3979133421, 543178784, 4229948412, 2982705585, 1542305371, 1790891114, 3410398667, 3201918910, 961245753, 1256100938, 1289001036, 1491644504, 3477767631, 3496721360, 4012557807, 2867154858, 4212583931, 1137018435, 1305975373, 861234739, 2241073541, 1171229253, 4178635257, 33948674, 2139225727, 1357946960, 1011120188, 2679776671, 2833468328, 1374921297, 2751356323, 1086357568, 2408187279, 2460827538, 2646352285, 944271416, 4110742005, 3168756668, 3066132406, 3665145818, 560153121, 271589392, 4279952895, 4077846003, 3530407890, 3444343245, 202643468, 322250259, 3962553324, 1608629855, 2543990167, 1154254916, 389623319, 3294073796, 2817676711, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, 2174228865, 1339137615, 3699352540, 577127458, 712922154, 2427141008, 2290289544, 1187679302, 3995715566, 3100863416, 339486740, 3732514782, 1591917662, 186455563, 3681988059, 3762019296, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, 3260915650, 3547250131, 2901361580, 1655096418, 2443721105, 2510565781, 3828863972, 2039214713, 3878868455, 3359869896, 928607799, 1840765549, 2374762893, 3580146133, 1322425422, 2850048425, 1823791212, 1459268694, 4094161908, 3928346602, 1706019429, 2056189050, 2934523822, 135794696, 3134549946, 2022240376, 628050469, 779246638, 472135708, 2800834470, 3032970164, 3327236038, 3894660072, 3715932637, 1956440180, 522272287, 1272813131, 3185336765, 2340818315, 2323976074, 1888542832, 1044544574, 3049550261, 1722469478, 1222152264, 50660867, 4127324150, 236067854, 1638122081, 895445557, 1475980887, 3117443513, 2257655686, 3243809217, 489110045, 2662934430, 3778599393, 4162055160, 2561878936, 288563729, 1773916777, 3648039385, 2391345038, 2493985684, 2612407707, 505560094, 2274497927, 3911240169, 3460925390, 1442818645, 678973480, 3749357023, 2358182796, 2717407649, 2306869641, 219617805, 3218761151, 3862026214, 1120306242, 1756942440, 1103331905, 2578459033, 762796589, 252780047, 2966125488, 1425844308, 3151392187, 372911126]; - var T4 = [1667474886, 2088535288, 2004326894, 2071694838, 4075949567, 1802223062, 1869591006, 3318043793, 808472672, 16843522, 1734846926, 724270422, 4278065639, 3621216949, 2880169549, 1987484396, 3402253711, 2189597983, 3385409673, 2105378810, 4210693615, 1499065266, 1195886990, 4042263547, 2913856577, 3570689971, 2728590687, 2947541573, 2627518243, 2762274643, 1920112356, 3233831835, 3082273397, 4261223649, 2475929149, 640051788, 909531756, 1061110142, 4160160501, 3435941763, 875846760, 2779116625, 3857003729, 4059105529, 1903268834, 3638064043, 825316194, 353713962, 67374088, 3351728789, 589522246, 3284360861, 404236336, 2526454071, 84217610, 2593830191, 117901582, 303183396, 2155911963, 3806477791, 3958056653, 656894286, 2998062463, 1970642922, 151591698, 2206440989, 741110872, 437923380, 454765878, 1852748508, 1515908788, 2694904667, 1381168804, 993742198, 3604373943, 3014905469, 690584402, 3823320797, 791638366, 2223281939, 1398011302, 3520161977, 0, 3991743681, 538992704, 4244381667, 2981218425, 1532751286, 1785380564, 3419096717, 3200178535, 960056178, 1246420628, 1280103576, 1482221744, 3486468741, 3503319995, 4025428677, 2863326543, 4227536621, 1128514950, 1296947098, 859002214, 2240123921, 1162203018, 4193849577, 33687044, 2139062782, 1347481760, 1010582648, 2678045221, 2829640523, 1364325282, 2745433693, 1077985408, 2408548869, 2459086143, 2644360225, 943212656, 4126475505, 3166494563, 3065430391, 3671750063, 555836226, 269496352, 4294908645, 4092792573, 3537006015, 3452783745, 202118168, 320025894, 3974901699, 1600119230, 2543297077, 1145359496, 387397934, 3301201811, 2812801621, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, 2172753945, 1330631070, 3705438115, 572679748, 707427924, 2425400123, 2290647819, 1179044492, 4008585671, 3099120491, 336870440, 3739122087, 1583276732, 185277718, 3688593069, 3772791771, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, 3267517855, 3553849021, 2897014595, 1650632388, 2442242105, 2509612081, 3840161747, 2038008818, 3890688725, 3368567691, 926374254, 1835907034, 2374863873, 3587531953, 1313788572, 2846482505, 1819063512, 1448540844, 4109633523, 3941213647, 1701162954, 2054852340, 2930698567, 134748176, 3132806511, 2021165296, 623210314, 774795868, 471606328, 2795958615, 3031746419, 3334885783, 3907527627, 3722280097, 1953799400, 522133822, 1263263126, 3183336545, 2341176845, 2324333839, 1886425312, 1044267644, 3048588401, 1718004428, 1212733584, 50529542, 4143317495, 235803164, 1633788866, 892690282, 1465383342, 3115962473, 2256965911, 3250673817, 488449850, 2661202215, 3789633753, 4177007595, 2560144171, 286339874, 1768537042, 3654906025, 2391705863, 2492770099, 2610673197, 505291324, 2273808917, 3924369609, 3469625735, 1431699370, 673740880, 3755965093, 2358021891, 2711746649, 2307489801, 218961690, 3217021541, 3873845719, 1111672452, 1751693520, 1094828930, 2576986153, 757954394, 252645662, 2964376443, 1414855848, 3149649517, 370555436]; - var T5 = [1374988112, 2118214995, 437757123, 975658646, 1001089995, 530400753, 2902087851, 1273168787, 540080725, 2910219766, 2295101073, 4110568485, 1340463100, 3307916247, 641025152, 3043140495, 3736164937, 632953703, 1172967064, 1576976609, 3274667266, 2169303058, 2370213795, 1809054150, 59727847, 361929877, 3211623147, 2505202138, 3569255213, 1484005843, 1239443753, 2395588676, 1975683434, 4102977912, 2572697195, 666464733, 3202437046, 4035489047, 3374361702, 2110667444, 1675577880, 3843699074, 2538681184, 1649639237, 2976151520, 3144396420, 4269907996, 4178062228, 1883793496, 2403728665, 2497604743, 1383856311, 2876494627, 1917518562, 3810496343, 1716890410, 3001755655, 800440835, 2261089178, 3543599269, 807962610, 599762354, 33778362, 3977675356, 2328828971, 2809771154, 4077384432, 1315562145, 1708848333, 101039829, 3509871135, 3299278474, 875451293, 2733856160, 92987698, 2767645557, 193195065, 1080094634, 1584504582, 3178106961, 1042385657, 2531067453, 3711829422, 1306967366, 2438237621, 1908694277, 67556463, 1615861247, 429456164, 3602770327, 2302690252, 1742315127, 2968011453, 126454664, 3877198648, 2043211483, 2709260871, 2084704233, 4169408201, 0, 159417987, 841739592, 504459436, 1817866830, 4245618683, 260388950, 1034867998, 908933415, 168810852, 1750902305, 2606453969, 607530554, 202008497, 2472011535, 3035535058, 463180190, 2160117071, 1641816226, 1517767529, 470948374, 3801332234, 3231722213, 1008918595, 303765277, 235474187, 4069246893, 766945465, 337553864, 1475418501, 2943682380, 4003061179, 2743034109, 4144047775, 1551037884, 1147550661, 1543208500, 2336434550, 3408119516, 3069049960, 3102011747, 3610369226, 1113818384, 328671808, 2227573024, 2236228733, 3535486456, 2935566865, 3341394285, 496906059, 3702665459, 226906860, 2009195472, 733156972, 2842737049, 294930682, 1206477858, 2835123396, 2700099354, 1451044056, 573804783, 2269728455, 3644379585, 2362090238, 2564033334, 2801107407, 2776292904, 3669462566, 1068351396, 742039012, 1350078989, 1784663195, 1417561698, 4136440770, 2430122216, 775550814, 2193862645, 2673705150, 1775276924, 1876241833, 3475313331, 3366754619, 270040487, 3902563182, 3678124923, 3441850377, 1851332852, 3969562369, 2203032232, 3868552805, 2868897406, 566021896, 4011190502, 3135740889, 1248802510, 3936291284, 699432150, 832877231, 708780849, 3332740144, 899835584, 1951317047, 4236429990, 3767586992, 866637845, 4043610186, 1106041591, 2144161806, 395441711, 1984812685, 1139781709, 3433712980, 3835036895, 2664543715, 1282050075, 3240894392, 1181045119, 2640243204, 25965917, 4203181171, 4211818798, 3009879386, 2463879762, 3910161971, 1842759443, 2597806476, 933301370, 1509430414, 3943906441, 3467192302, 3076639029, 3776767469, 2051518780, 2631065433, 1441952575, 404016761, 1942435775, 1408749034, 1610459739, 3745345300, 2017778566, 3400528769, 3110650942, 941896748, 3265478751, 371049330, 3168937228, 675039627, 4279080257, 967311729, 135050206, 3635733660, 1683407248, 2076935265, 3576870512, 1215061108, 3501741890]; - var T6 = [1347548327, 1400783205, 3273267108, 2520393566, 3409685355, 4045380933, 2880240216, 2471224067, 1428173050, 4138563181, 2441661558, 636813900, 4233094615, 3620022987, 2149987652, 2411029155, 1239331162, 1730525723, 2554718734, 3781033664, 46346101, 310463728, 2743944855, 3328955385, 3875770207, 2501218972, 3955191162, 3667219033, 768917123, 3545789473, 692707433, 1150208456, 1786102409, 2029293177, 1805211710, 3710368113, 3065962831, 401639597, 1724457132, 3028143674, 409198410, 2196052529, 1620529459, 1164071807, 3769721975, 2226875310, 486441376, 2499348523, 1483753576, 428819965, 2274680428, 3075636216, 598438867, 3799141122, 1474502543, 711349675, 129166120, 53458370, 2592523643, 2782082824, 4063242375, 2988687269, 3120694122, 1559041666, 730517276, 2460449204, 4042459122, 2706270690, 3446004468, 3573941694, 533804130, 2328143614, 2637442643, 2695033685, 839224033, 1973745387, 957055980, 2856345839, 106852767, 1371368976, 4181598602, 1033297158, 2933734917, 1179510461, 3046200461, 91341917, 1862534868, 4284502037, 605657339, 2547432937, 3431546947, 2003294622, 3182487618, 2282195339, 954669403, 3682191598, 1201765386, 3917234703, 3388507166, 0, 2198438022, 1211247597, 2887651696, 1315723890, 4227665663, 1443857720, 507358933, 657861945, 1678381017, 560487590, 3516619604, 975451694, 2970356327, 261314535, 3535072918, 2652609425, 1333838021, 2724322336, 1767536459, 370938394, 182621114, 3854606378, 1128014560, 487725847, 185469197, 2918353863, 3106780840, 3356761769, 2237133081, 1286567175, 3152976349, 4255350624, 2683765030, 3160175349, 3309594171, 878443390, 1988838185, 3704300486, 1756818940, 1673061617, 3403100636, 272786309, 1075025698, 545572369, 2105887268, 4174560061, 296679730, 1841768865, 1260232239, 4091327024, 3960309330, 3497509347, 1814803222, 2578018489, 4195456072, 575138148, 3299409036, 446754879, 3629546796, 4011996048, 3347532110, 3252238545, 4270639778, 915985419, 3483825537, 681933534, 651868046, 2755636671, 3828103837, 223377554, 2607439820, 1649704518, 3270937875, 3901806776, 1580087799, 4118987695, 3198115200, 2087309459, 2842678573, 3016697106, 1003007129, 2802849917, 1860738147, 2077965243, 164439672, 4100872472, 32283319, 2827177882, 1709610350, 2125135846, 136428751, 3874428392, 3652904859, 3460984630, 3572145929, 3593056380, 2939266226, 824852259, 818324884, 3224740454, 930369212, 2801566410, 2967507152, 355706840, 1257309336, 4148292826, 243256656, 790073846, 2373340630, 1296297904, 1422699085, 3756299780, 3818836405, 457992840, 3099667487, 2135319889, 77422314, 1560382517, 1945798516, 788204353, 1521706781, 1385356242, 870912086, 325965383, 2358957921, 2050466060, 2388260884, 2313884476, 4006521127, 901210569, 3990953189, 1014646705, 1503449823, 1062597235, 2031621326, 3212035895, 3931371469, 1533017514, 350174575, 2256028891, 2177544179, 1052338372, 741876788, 1606591296, 1914052035, 213705253, 2334669897, 1107234197, 1899603969, 3725069491, 2631447780, 2422494913, 1635502980, 1893020342, 1950903388, 1120974935]; - var T7 = [2807058932, 1699970625, 2764249623, 1586903591, 1808481195, 1173430173, 1487645946, 59984867, 4199882800, 1844882806, 1989249228, 1277555970, 3623636965, 3419915562, 1149249077, 2744104290, 1514790577, 459744698, 244860394, 3235995134, 1963115311, 4027744588, 2544078150, 4190530515, 1608975247, 2627016082, 2062270317, 1507497298, 2200818878, 567498868, 1764313568, 3359936201, 2305455554, 2037970062, 1047239e3, 1910319033, 1337376481, 2904027272, 2892417312, 984907214, 1243112415, 830661914, 861968209, 2135253587, 2011214180, 2927934315, 2686254721, 731183368, 1750626376, 4246310725, 1820824798, 4172763771, 3542330227, 48394827, 2404901663, 2871682645, 671593195, 3254988725, 2073724613, 145085239, 2280796200, 2779915199, 1790575107, 2187128086, 472615631, 3029510009, 4075877127, 3802222185, 4107101658, 3201631749, 1646252340, 4270507174, 1402811438, 1436590835, 3778151818, 3950355702, 3963161475, 4020912224, 2667994737, 273792366, 2331590177, 104699613, 95345982, 3175501286, 2377486676, 1560637892, 3564045318, 369057872, 4213447064, 3919042237, 1137477952, 2658625497, 1119727848, 2340947849, 1530455833, 4007360968, 172466556, 266959938, 516552836, 0, 2256734592, 3980931627, 1890328081, 1917742170, 4294704398, 945164165, 3575528878, 958871085, 3647212047, 2787207260, 1423022939, 775562294, 1739656202, 3876557655, 2530391278, 2443058075, 3310321856, 547512796, 1265195639, 437656594, 3121275539, 719700128, 3762502690, 387781147, 218828297, 3350065803, 2830708150, 2848461854, 428169201, 122466165, 3720081049, 1627235199, 648017665, 4122762354, 1002783846, 2117360635, 695634755, 3336358691, 4234721005, 4049844452, 3704280881, 2232435299, 574624663, 287343814, 612205898, 1039717051, 840019705, 2708326185, 793451934, 821288114, 1391201670, 3822090177, 376187827, 3113855344, 1224348052, 1679968233, 2361698556, 1058709744, 752375421, 2431590963, 1321699145, 3519142200, 2734591178, 188127444, 2177869557, 3727205754, 2384911031, 3215212461, 2648976442, 2450346104, 3432737375, 1180849278, 331544205, 3102249176, 4150144569, 2952102595, 2159976285, 2474404304, 766078933, 313773861, 2570832044, 2108100632, 1668212892, 3145456443, 2013908262, 418672217, 3070356634, 2594734927, 1852171925, 3867060991, 3473416636, 3907448597, 2614737639, 919489135, 164948639, 2094410160, 2997825956, 590424639, 2486224549, 1723872674, 3157750862, 3399941250, 3501252752, 3625268135, 2555048196, 3673637356, 1343127501, 4130281361, 3599595085, 2957853679, 1297403050, 81781910, 3051593425, 2283490410, 532201772, 1367295589, 3926170974, 895287692, 1953757831, 1093597963, 492483431, 3528626907, 1446242576, 1192455638, 1636604631, 209336225, 344873464, 1015671571, 669961897, 3375740769, 3857572124, 2973530695, 3747192018, 1933530610, 3464042516, 935293895, 3454686199, 2858115069, 1863638845, 3683022916, 4085369519, 3292445032, 875313188, 1080017571, 3279033885, 621591778, 1233856572, 2504130317, 24197544, 3017672716, 3835484340, 3247465558, 2220981195, 3060847922, 1551124588, 1463996600]; - var T8 = [4104605777, 1097159550, 396673818, 660510266, 2875968315, 2638606623, 4200115116, 3808662347, 821712160, 1986918061, 3430322568, 38544885, 3856137295, 718002117, 893681702, 1654886325, 2975484382, 3122358053, 3926825029, 4274053469, 796197571, 1290801793, 1184342925, 3556361835, 2405426947, 2459735317, 1836772287, 1381620373, 3196267988, 1948373848, 3764988233, 3385345166, 3263785589, 2390325492, 1480485785, 3111247143, 3780097726, 2293045232, 548169417, 3459953789, 3746175075, 439452389, 1362321559, 1400849762, 1685577905, 1806599355, 2174754046, 137073913, 1214797936, 1174215055, 3731654548, 2079897426, 1943217067, 1258480242, 529487843, 1437280870, 3945269170, 3049390895, 3313212038, 923313619, 679998e3, 3215307299, 57326082, 377642221, 3474729866, 2041877159, 133361907, 1776460110, 3673476453, 96392454, 878845905, 2801699524, 777231668, 4082475170, 2330014213, 4142626212, 2213296395, 1626319424, 1906247262, 1846563261, 562755902, 3708173718, 1040559837, 3871163981, 1418573201, 3294430577, 114585348, 1343618912, 2566595609, 3186202582, 1078185097, 3651041127, 3896688048, 2307622919, 425408743, 3371096953, 2081048481, 1108339068, 2216610296, 0, 2156299017, 736970802, 292596766, 1517440620, 251657213, 2235061775, 2933202493, 758720310, 265905162, 1554391400, 1532285339, 908999204, 174567692, 1474760595, 4002861748, 2610011675, 3234156416, 3693126241, 2001430874, 303699484, 2478443234, 2687165888, 585122620, 454499602, 151849742, 2345119218, 3064510765, 514443284, 4044981591, 1963412655, 2581445614, 2137062819, 19308535, 1928707164, 1715193156, 4219352155, 1126790795, 600235211, 3992742070, 3841024952, 836553431, 1669664834, 2535604243, 3323011204, 1243905413, 3141400786, 4180808110, 698445255, 2653899549, 2989552604, 2253581325, 3252932727, 3004591147, 1891211689, 2487810577, 3915653703, 4237083816, 4030667424, 2100090966, 865136418, 1229899655, 953270745, 3399679628, 3557504664, 4118925222, 2061379749, 3079546586, 2915017791, 983426092, 2022837584, 1607244650, 2118541908, 2366882550, 3635996816, 972512814, 3283088770, 1568718495, 3499326569, 3576539503, 621982671, 2895723464, 410887952, 2623762152, 1002142683, 645401037, 1494807662, 2595684844, 1335535747, 2507040230, 4293295786, 3167684641, 367585007, 3885750714, 1865862730, 2668221674, 2960971305, 2763173681, 1059270954, 2777952454, 2724642869, 1320957812, 2194319100, 2429595872, 2815956275, 77089521, 3973773121, 3444575871, 2448830231, 1305906550, 4021308739, 2857194700, 2516901860, 3518358430, 1787304780, 740276417, 1699839814, 1592394909, 2352307457, 2272556026, 188821243, 1729977011, 3687994002, 274084841, 3594982253, 3613494426, 2701949495, 4162096729, 322734571, 2837966542, 1640576439, 484830689, 1202797690, 3537852828, 4067639125, 349075736, 3342319475, 4157467219, 4255800159, 1030690015, 1155237496, 2951971274, 1757691577, 607398968, 2738905026, 499347990, 3794078908, 1011452712, 227885567, 2818666809, 213114376, 3034881240, 1455525988, 3414450555, 850817237, 1817998408, 3092726480]; - var U1 = [0, 235474187, 470948374, 303765277, 941896748, 908933415, 607530554, 708780849, 1883793496, 2118214995, 1817866830, 1649639237, 1215061108, 1181045119, 1417561698, 1517767529, 3767586992, 4003061179, 4236429990, 4069246893, 3635733660, 3602770327, 3299278474, 3400528769, 2430122216, 2664543715, 2362090238, 2193862645, 2835123396, 2801107407, 3035535058, 3135740889, 3678124923, 3576870512, 3341394285, 3374361702, 3810496343, 3977675356, 4279080257, 4043610186, 2876494627, 2776292904, 3076639029, 3110650942, 2472011535, 2640243204, 2403728665, 2169303058, 1001089995, 899835584, 666464733, 699432150, 59727847, 226906860, 530400753, 294930682, 1273168787, 1172967064, 1475418501, 1509430414, 1942435775, 2110667444, 1876241833, 1641816226, 2910219766, 2743034109, 2976151520, 3211623147, 2505202138, 2606453969, 2302690252, 2269728455, 3711829422, 3543599269, 3240894392, 3475313331, 3843699074, 3943906441, 4178062228, 4144047775, 1306967366, 1139781709, 1374988112, 1610459739, 1975683434, 2076935265, 1775276924, 1742315127, 1034867998, 866637845, 566021896, 800440835, 92987698, 193195065, 429456164, 395441711, 1984812685, 2017778566, 1784663195, 1683407248, 1315562145, 1080094634, 1383856311, 1551037884, 101039829, 135050206, 437757123, 337553864, 1042385657, 807962610, 573804783, 742039012, 2531067453, 2564033334, 2328828971, 2227573024, 2935566865, 2700099354, 3001755655, 3168937228, 3868552805, 3902563182, 4203181171, 4102977912, 3736164937, 3501741890, 3265478751, 3433712980, 1106041591, 1340463100, 1576976609, 1408749034, 2043211483, 2009195472, 1708848333, 1809054150, 832877231, 1068351396, 766945465, 599762354, 159417987, 126454664, 361929877, 463180190, 2709260871, 2943682380, 3178106961, 3009879386, 2572697195, 2538681184, 2236228733, 2336434550, 3509871135, 3745345300, 3441850377, 3274667266, 3910161971, 3877198648, 4110568485, 4211818798, 2597806476, 2497604743, 2261089178, 2295101073, 2733856160, 2902087851, 3202437046, 2968011453, 3936291284, 3835036895, 4136440770, 4169408201, 3535486456, 3702665459, 3467192302, 3231722213, 2051518780, 1951317047, 1716890410, 1750902305, 1113818384, 1282050075, 1584504582, 1350078989, 168810852, 67556463, 371049330, 404016761, 841739592, 1008918595, 775550814, 540080725, 3969562369, 3801332234, 4035489047, 4269907996, 3569255213, 3669462566, 3366754619, 3332740144, 2631065433, 2463879762, 2160117071, 2395588676, 2767645557, 2868897406, 3102011747, 3069049960, 202008497, 33778362, 270040487, 504459436, 875451293, 975658646, 675039627, 641025152, 2084704233, 1917518562, 1615861247, 1851332852, 1147550661, 1248802510, 1484005843, 1451044056, 933301370, 967311729, 733156972, 632953703, 260388950, 25965917, 328671808, 496906059, 1206477858, 1239443753, 1543208500, 1441952575, 2144161806, 1908694277, 1675577880, 1842759443, 3610369226, 3644379585, 3408119516, 3307916247, 4011190502, 3776767469, 4077384432, 4245618683, 2809771154, 2842737049, 3144396420, 3043140495, 2673705150, 2438237621, 2203032232, 2370213795]; - var U2 = [0, 185469197, 370938394, 487725847, 741876788, 657861945, 975451694, 824852259, 1483753576, 1400783205, 1315723890, 1164071807, 1950903388, 2135319889, 1649704518, 1767536459, 2967507152, 3152976349, 2801566410, 2918353863, 2631447780, 2547432937, 2328143614, 2177544179, 3901806776, 3818836405, 4270639778, 4118987695, 3299409036, 3483825537, 3535072918, 3652904859, 2077965243, 1893020342, 1841768865, 1724457132, 1474502543, 1559041666, 1107234197, 1257309336, 598438867, 681933534, 901210569, 1052338372, 261314535, 77422314, 428819965, 310463728, 3409685355, 3224740454, 3710368113, 3593056380, 3875770207, 3960309330, 4045380933, 4195456072, 2471224067, 2554718734, 2237133081, 2388260884, 3212035895, 3028143674, 2842678573, 2724322336, 4138563181, 4255350624, 3769721975, 3955191162, 3667219033, 3516619604, 3431546947, 3347532110, 2933734917, 2782082824, 3099667487, 3016697106, 2196052529, 2313884476, 2499348523, 2683765030, 1179510461, 1296297904, 1347548327, 1533017514, 1786102409, 1635502980, 2087309459, 2003294622, 507358933, 355706840, 136428751, 53458370, 839224033, 957055980, 605657339, 790073846, 2373340630, 2256028891, 2607439820, 2422494913, 2706270690, 2856345839, 3075636216, 3160175349, 3573941694, 3725069491, 3273267108, 3356761769, 4181598602, 4063242375, 4011996048, 3828103837, 1033297158, 915985419, 730517276, 545572369, 296679730, 446754879, 129166120, 213705253, 1709610350, 1860738147, 1945798516, 2029293177, 1239331162, 1120974935, 1606591296, 1422699085, 4148292826, 4233094615, 3781033664, 3931371469, 3682191598, 3497509347, 3446004468, 3328955385, 2939266226, 2755636671, 3106780840, 2988687269, 2198438022, 2282195339, 2501218972, 2652609425, 1201765386, 1286567175, 1371368976, 1521706781, 1805211710, 1620529459, 2105887268, 1988838185, 533804130, 350174575, 164439672, 46346101, 870912086, 954669403, 636813900, 788204353, 2358957921, 2274680428, 2592523643, 2441661558, 2695033685, 2880240216, 3065962831, 3182487618, 3572145929, 3756299780, 3270937875, 3388507166, 4174560061, 4091327024, 4006521127, 3854606378, 1014646705, 930369212, 711349675, 560487590, 272786309, 457992840, 106852767, 223377554, 1678381017, 1862534868, 1914052035, 2031621326, 1211247597, 1128014560, 1580087799, 1428173050, 32283319, 182621114, 401639597, 486441376, 768917123, 651868046, 1003007129, 818324884, 1503449823, 1385356242, 1333838021, 1150208456, 1973745387, 2125135846, 1673061617, 1756818940, 2970356327, 3120694122, 2802849917, 2887651696, 2637442643, 2520393566, 2334669897, 2149987652, 3917234703, 3799141122, 4284502037, 4100872472, 3309594171, 3460984630, 3545789473, 3629546796, 2050466060, 1899603969, 1814803222, 1730525723, 1443857720, 1560382517, 1075025698, 1260232239, 575138148, 692707433, 878443390, 1062597235, 243256656, 91341917, 409198410, 325965383, 3403100636, 3252238545, 3704300486, 3620022987, 3874428392, 3990953189, 4042459122, 4227665663, 2460449204, 2578018489, 2226875310, 2411029155, 3198115200, 3046200461, 2827177882, 2743944855]; - var U3 = [0, 218828297, 437656594, 387781147, 875313188, 958871085, 775562294, 590424639, 1750626376, 1699970625, 1917742170, 2135253587, 1551124588, 1367295589, 1180849278, 1265195639, 3501252752, 3720081049, 3399941250, 3350065803, 3835484340, 3919042237, 4270507174, 4085369519, 3102249176, 3051593425, 2734591178, 2952102595, 2361698556, 2177869557, 2530391278, 2614737639, 3145456443, 3060847922, 2708326185, 2892417312, 2404901663, 2187128086, 2504130317, 2555048196, 3542330227, 3727205754, 3375740769, 3292445032, 3876557655, 3926170974, 4246310725, 4027744588, 1808481195, 1723872674, 1910319033, 2094410160, 1608975247, 1391201670, 1173430173, 1224348052, 59984867, 244860394, 428169201, 344873464, 935293895, 984907214, 766078933, 547512796, 1844882806, 1627235199, 2011214180, 2062270317, 1507497298, 1423022939, 1137477952, 1321699145, 95345982, 145085239, 532201772, 313773861, 830661914, 1015671571, 731183368, 648017665, 3175501286, 2957853679, 2807058932, 2858115069, 2305455554, 2220981195, 2474404304, 2658625497, 3575528878, 3625268135, 3473416636, 3254988725, 3778151818, 3963161475, 4213447064, 4130281361, 3599595085, 3683022916, 3432737375, 3247465558, 3802222185, 4020912224, 4172763771, 4122762354, 3201631749, 3017672716, 2764249623, 2848461854, 2331590177, 2280796200, 2431590963, 2648976442, 104699613, 188127444, 472615631, 287343814, 840019705, 1058709744, 671593195, 621591778, 1852171925, 1668212892, 1953757831, 2037970062, 1514790577, 1463996600, 1080017571, 1297403050, 3673637356, 3623636965, 3235995134, 3454686199, 4007360968, 3822090177, 4107101658, 4190530515, 2997825956, 3215212461, 2830708150, 2779915199, 2256734592, 2340947849, 2627016082, 2443058075, 172466556, 122466165, 273792366, 492483431, 1047239e3, 861968209, 612205898, 695634755, 1646252340, 1863638845, 2013908262, 1963115311, 1446242576, 1530455833, 1277555970, 1093597963, 1636604631, 1820824798, 2073724613, 1989249228, 1436590835, 1487645946, 1337376481, 1119727848, 164948639, 81781910, 331544205, 516552836, 1039717051, 821288114, 669961897, 719700128, 2973530695, 3157750862, 2871682645, 2787207260, 2232435299, 2283490410, 2667994737, 2450346104, 3647212047, 3564045318, 3279033885, 3464042516, 3980931627, 3762502690, 4150144569, 4199882800, 3070356634, 3121275539, 2904027272, 2686254721, 2200818878, 2384911031, 2570832044, 2486224549, 3747192018, 3528626907, 3310321856, 3359936201, 3950355702, 3867060991, 4049844452, 4234721005, 1739656202, 1790575107, 2108100632, 1890328081, 1402811438, 1586903591, 1233856572, 1149249077, 266959938, 48394827, 369057872, 418672217, 1002783846, 919489135, 567498868, 752375421, 209336225, 24197544, 376187827, 459744698, 945164165, 895287692, 574624663, 793451934, 1679968233, 1764313568, 2117360635, 1933530610, 1343127501, 1560637892, 1243112415, 1192455638, 3704280881, 3519142200, 3336358691, 3419915562, 3907448597, 3857572124, 4075877127, 4294704398, 3029510009, 3113855344, 2927934315, 2744104290, 2159976285, 2377486676, 2594734927, 2544078150]; - var U4 = [0, 151849742, 303699484, 454499602, 607398968, 758720310, 908999204, 1059270954, 1214797936, 1097159550, 1517440620, 1400849762, 1817998408, 1699839814, 2118541908, 2001430874, 2429595872, 2581445614, 2194319100, 2345119218, 3034881240, 3186202582, 2801699524, 2951971274, 3635996816, 3518358430, 3399679628, 3283088770, 4237083816, 4118925222, 4002861748, 3885750714, 1002142683, 850817237, 698445255, 548169417, 529487843, 377642221, 227885567, 77089521, 1943217067, 2061379749, 1640576439, 1757691577, 1474760595, 1592394909, 1174215055, 1290801793, 2875968315, 2724642869, 3111247143, 2960971305, 2405426947, 2253581325, 2638606623, 2487810577, 3808662347, 3926825029, 4044981591, 4162096729, 3342319475, 3459953789, 3576539503, 3693126241, 1986918061, 2137062819, 1685577905, 1836772287, 1381620373, 1532285339, 1078185097, 1229899655, 1040559837, 923313619, 740276417, 621982671, 439452389, 322734571, 137073913, 19308535, 3871163981, 4021308739, 4104605777, 4255800159, 3263785589, 3414450555, 3499326569, 3651041127, 2933202493, 2815956275, 3167684641, 3049390895, 2330014213, 2213296395, 2566595609, 2448830231, 1305906550, 1155237496, 1607244650, 1455525988, 1776460110, 1626319424, 2079897426, 1928707164, 96392454, 213114376, 396673818, 514443284, 562755902, 679998e3, 865136418, 983426092, 3708173718, 3557504664, 3474729866, 3323011204, 4180808110, 4030667424, 3945269170, 3794078908, 2507040230, 2623762152, 2272556026, 2390325492, 2975484382, 3092726480, 2738905026, 2857194700, 3973773121, 3856137295, 4274053469, 4157467219, 3371096953, 3252932727, 3673476453, 3556361835, 2763173681, 2915017791, 3064510765, 3215307299, 2156299017, 2307622919, 2459735317, 2610011675, 2081048481, 1963412655, 1846563261, 1729977011, 1480485785, 1362321559, 1243905413, 1126790795, 878845905, 1030690015, 645401037, 796197571, 274084841, 425408743, 38544885, 188821243, 3613494426, 3731654548, 3313212038, 3430322568, 4082475170, 4200115116, 3780097726, 3896688048, 2668221674, 2516901860, 2366882550, 2216610296, 3141400786, 2989552604, 2837966542, 2687165888, 1202797690, 1320957812, 1437280870, 1554391400, 1669664834, 1787304780, 1906247262, 2022837584, 265905162, 114585348, 499347990, 349075736, 736970802, 585122620, 972512814, 821712160, 2595684844, 2478443234, 2293045232, 2174754046, 3196267988, 3079546586, 2895723464, 2777952454, 3537852828, 3687994002, 3234156416, 3385345166, 4142626212, 4293295786, 3841024952, 3992742070, 174567692, 57326082, 410887952, 292596766, 777231668, 660510266, 1011452712, 893681702, 1108339068, 1258480242, 1343618912, 1494807662, 1715193156, 1865862730, 1948373848, 2100090966, 2701949495, 2818666809, 3004591147, 3122358053, 2235061775, 2352307457, 2535604243, 2653899549, 3915653703, 3764988233, 4219352155, 4067639125, 3444575871, 3294430577, 3746175075, 3594982253, 836553431, 953270745, 600235211, 718002117, 367585007, 484830689, 133361907, 251657213, 2041877159, 1891211689, 1806599355, 1654886325, 1568718495, 1418573201, 1335535747, 1184342925]; - function convertToInt32(bytes) { - var result = []; - for (var i3 = 0; i3 < bytes.length; i3 += 4) { - result.push( - bytes[i3] << 24 | bytes[i3 + 1] << 16 | bytes[i3 + 2] << 8 | bytes[i3 + 3] - ); } + var result = createArray(length2); + copyArray(data, result, 0, 0, length2); return result; } - var AES = function(key) { - if (!(this instanceof AES)) { - throw Error("AES must be instanitated with `new`"); - } - Object.defineProperty(this, "key", { - value: coerceArray(key, true) - }); - this._prepare(); - }; - AES.prototype._prepare = function() { - var rounds = numberOfRounds[this.key.length]; - if (rounds == null) { - throw new Error("invalid key size (must be 16, 24 or 32 bytes)"); - } - this._Ke = []; - this._Kd = []; - for (var i3 = 0; i3 <= rounds; i3++) { - this._Ke.push([0, 0, 0, 0]); - this._Kd.push([0, 0, 0, 0]); - } - var roundKeyCount = (rounds + 1) * 4; - var KC = this.key.length / 4; - var tk = convertToInt32(this.key); - var index; - for (var i3 = 0; i3 < KC; i3++) { - index = i3 >> 2; - this._Ke[index][i3 % 4] = tk[i3]; - this._Kd[rounds - index][i3 % 4] = tk[i3]; - } - var rconpointer = 0; - var t2 = KC, tt2; - while (t2 < roundKeyCount) { - tt2 = tk[KC - 1]; - tk[0] ^= S2[tt2 >> 16 & 255] << 24 ^ S2[tt2 >> 8 & 255] << 16 ^ S2[tt2 & 255] << 8 ^ S2[tt2 >> 24 & 255] ^ rcon[rconpointer] << 24; - rconpointer += 1; - if (KC != 8) { - for (var i3 = 1; i3 < KC; i3++) { - tk[i3] ^= tk[i3 - 1]; - } - } else { - for (var i3 = 1; i3 < KC / 2; i3++) { - tk[i3] ^= tk[i3 - 1]; - } - tt2 = tk[KC / 2 - 1]; - tk[KC / 2] ^= S2[tt2 & 255] ^ S2[tt2 >> 8 & 255] << 8 ^ S2[tt2 >> 16 & 255] << 16 ^ S2[tt2 >> 24 & 255] << 24; - for (var i3 = KC / 2 + 1; i3 < KC; i3++) { - tk[i3] ^= tk[i3 - 1]; - } - } - var i3 = 0, r2, c2; - while (i3 < KC && t2 < roundKeyCount) { - r2 = t2 >> 2; - c2 = t2 % 4; - this._Ke[r2][c2] = tk[i3]; - this._Kd[rounds - r2][c2] = tk[i3++]; - t2++; - } - } - for (var r2 = 1; r2 < rounds; r2++) { - for (var c2 = 0; c2 < 4; c2++) { - tt2 = this._Kd[r2][c2]; - this._Kd[r2][c2] = U1[tt2 >> 24 & 255] ^ U2[tt2 >> 16 & 255] ^ U3[tt2 >> 8 & 255] ^ U4[tt2 & 255]; - } - } - }; - AES.prototype.encrypt = function(plaintext) { - if (plaintext.length != 16) { - throw new Error("invalid plaintext size (must be 16 bytes)"); - } - var rounds = this._Ke.length - 1; - var a2 = [0, 0, 0, 0]; - var t2 = convertToInt32(plaintext); - for (var i3 = 0; i3 < 4; i3++) { - t2[i3] ^= this._Ke[0][i3]; - } - for (var r2 = 1; r2 < rounds; r2++) { - for (var i3 = 0; i3 < 4; i3++) { - a2[i3] = T1[t2[i3] >> 24 & 255] ^ T2[t2[(i3 + 1) % 4] >> 16 & 255] ^ T3[t2[(i3 + 2) % 4] >> 8 & 255] ^ T4[t2[(i3 + 3) % 4] & 255] ^ this._Ke[r2][i3]; + var aesjs2 = { + AES, + Counter, + ModeOfOperation: { + ecb: ModeOfOperationECB, + cbc: ModeOfOperationCBC, + cfb: ModeOfOperationCFB, + ofb: ModeOfOperationOFB, + ctr: ModeOfOperationCTR + }, + utils: { + hex: convertHex, + utf8: convertUtf8 + }, + padding: { + pkcs7: { + pad: pkcs7pad, + strip: pkcs7strip } - t2 = a2.slice(); - } - var result = createArray(16), tt2; - for (var i3 = 0; i3 < 4; i3++) { - tt2 = this._Ke[rounds][i3]; - result[4 * i3] = (S2[t2[i3] >> 24 & 255] ^ tt2 >> 24) & 255; - result[4 * i3 + 1] = (S2[t2[(i3 + 1) % 4] >> 16 & 255] ^ tt2 >> 16) & 255; - result[4 * i3 + 2] = (S2[t2[(i3 + 2) % 4] >> 8 & 255] ^ tt2 >> 8) & 255; - result[4 * i3 + 3] = (S2[t2[(i3 + 3) % 4] & 255] ^ tt2) & 255; + }, + _arrayTest: { + coerceArray, + createArray, + copyArray } - return result; }; - AES.prototype.decrypt = function(ciphertext) { - if (ciphertext.length != 16) { - throw new Error("invalid ciphertext size (must be 16 bytes)"); - } - var rounds = this._Kd.length - 1; - var a2 = [0, 0, 0, 0]; - var t2 = convertToInt32(ciphertext); - for (var i3 = 0; i3 < 4; i3++) { - t2[i3] ^= this._Kd[0][i3]; - } - for (var r2 = 1; r2 < rounds; r2++) { - for (var i3 = 0; i3 < 4; i3++) { - a2[i3] = T5[t2[i3] >> 24 & 255] ^ T6[t2[(i3 + 3) % 4] >> 16 & 255] ^ T7[t2[(i3 + 2) % 4] >> 8 & 255] ^ T8[t2[(i3 + 1) % 4] & 255] ^ this._Kd[r2][i3]; - } - t2 = a2.slice(); - } - var result = createArray(16), tt2; - for (var i3 = 0; i3 < 4; i3++) { - tt2 = this._Kd[rounds][i3]; - result[4 * i3] = (Si[t2[i3] >> 24 & 255] ^ tt2 >> 24) & 255; - result[4 * i3 + 1] = (Si[t2[(i3 + 3) % 4] >> 16 & 255] ^ tt2 >> 16) & 255; - result[4 * i3 + 2] = (Si[t2[(i3 + 2) % 4] >> 8 & 255] ^ tt2 >> 8) & 255; - result[4 * i3 + 3] = (Si[t2[(i3 + 1) % 4] & 255] ^ tt2) & 255; - } - return result; - }; - var ModeOfOperationECB = function(key) { - if (!(this instanceof ModeOfOperationECB)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Electronic Code Block"; - this.name = "ecb"; - this._aes = new AES(key); - }; - ModeOfOperationECB.prototype.encrypt = function(plaintext) { - plaintext = coerceArray(plaintext); - if (plaintext.length % 16 !== 0) { - throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); - } - var ciphertext = createArray(plaintext.length); - var block2 = createArray(16); - for (var i3 = 0; i3 < plaintext.length; i3 += 16) { - copyArray(plaintext, block2, 0, i3, i3 + 16); - block2 = this._aes.encrypt(block2); - copyArray(block2, ciphertext, i3); - } - return ciphertext; - }; - ModeOfOperationECB.prototype.decrypt = function(ciphertext) { - ciphertext = coerceArray(ciphertext); - if (ciphertext.length % 16 !== 0) { - throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); - } - var plaintext = createArray(ciphertext.length); - var block2 = createArray(16); - for (var i3 = 0; i3 < ciphertext.length; i3 += 16) { - copyArray(ciphertext, block2, 0, i3, i3 + 16); - block2 = this._aes.decrypt(block2); - copyArray(block2, plaintext, i3); - } - return plaintext; - }; - var ModeOfOperationCBC = function(key, iv) { - if (!(this instanceof ModeOfOperationCBC)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Cipher Block Chaining"; - this.name = "cbc"; - if (!iv) { - iv = createArray(16); - } else if (iv.length != 16) { - throw new Error("invalid initialation vector size (must be 16 bytes)"); - } - this._lastCipherblock = coerceArray(iv, true); - this._aes = new AES(key); - }; - ModeOfOperationCBC.prototype.encrypt = function(plaintext) { - plaintext = coerceArray(plaintext); - if (plaintext.length % 16 !== 0) { - throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); - } - var ciphertext = createArray(plaintext.length); - var block2 = createArray(16); - for (var i3 = 0; i3 < plaintext.length; i3 += 16) { - copyArray(plaintext, block2, 0, i3, i3 + 16); - for (var j3 = 0; j3 < 16; j3++) { - block2[j3] ^= this._lastCipherblock[j3]; - } - this._lastCipherblock = this._aes.encrypt(block2); - copyArray(this._lastCipherblock, ciphertext, i3); - } - return ciphertext; - }; - ModeOfOperationCBC.prototype.decrypt = function(ciphertext) { - ciphertext = coerceArray(ciphertext); - if (ciphertext.length % 16 !== 0) { - throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); - } - var plaintext = createArray(ciphertext.length); - var block2 = createArray(16); - for (var i3 = 0; i3 < ciphertext.length; i3 += 16) { - copyArray(ciphertext, block2, 0, i3, i3 + 16); - block2 = this._aes.decrypt(block2); - for (var j3 = 0; j3 < 16; j3++) { - plaintext[i3 + j3] = block2[j3] ^ this._lastCipherblock[j3]; - } - copyArray(ciphertext, this._lastCipherblock, 0, i3, i3 + 16); - } - return plaintext; - }; - var ModeOfOperationCFB = function(key, iv, segmentSize) { - if (!(this instanceof ModeOfOperationCFB)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Cipher Feedback"; - this.name = "cfb"; - if (!iv) { - iv = createArray(16); - } else if (iv.length != 16) { - throw new Error("invalid initialation vector size (must be 16 size)"); - } - if (!segmentSize) { - segmentSize = 1; - } - this.segmentSize = segmentSize; - this._shiftRegister = coerceArray(iv, true); - this._aes = new AES(key); - }; - ModeOfOperationCFB.prototype.encrypt = function(plaintext) { - if (plaintext.length % this.segmentSize != 0) { - throw new Error("invalid plaintext size (must be segmentSize bytes)"); - } - var encrypted = coerceArray(plaintext, true); - var xorSegment; - for (var i3 = 0; i3 < encrypted.length; i3 += this.segmentSize) { - xorSegment = this._aes.encrypt(this._shiftRegister); - for (var j3 = 0; j3 < this.segmentSize; j3++) { - encrypted[i3 + j3] ^= xorSegment[j3]; - } - copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); - copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i3, i3 + this.segmentSize); - } - return encrypted; - }; - ModeOfOperationCFB.prototype.decrypt = function(ciphertext) { - if (ciphertext.length % this.segmentSize != 0) { - throw new Error("invalid ciphertext size (must be segmentSize bytes)"); - } - var plaintext = coerceArray(ciphertext, true); - var xorSegment; - for (var i3 = 0; i3 < plaintext.length; i3 += this.segmentSize) { - xorSegment = this._aes.encrypt(this._shiftRegister); - for (var j3 = 0; j3 < this.segmentSize; j3++) { - plaintext[i3 + j3] ^= xorSegment[j3]; - } - copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); - copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i3, i3 + this.segmentSize); - } - return plaintext; - }; - var ModeOfOperationOFB = function(key, iv) { - if (!(this instanceof ModeOfOperationOFB)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Output Feedback"; - this.name = "ofb"; - if (!iv) { - iv = createArray(16); - } else if (iv.length != 16) { - throw new Error("invalid initialation vector size (must be 16 bytes)"); - } - this._lastPrecipher = coerceArray(iv, true); - this._lastPrecipherIndex = 16; - this._aes = new AES(key); - }; - ModeOfOperationOFB.prototype.encrypt = function(plaintext) { - var encrypted = coerceArray(plaintext, true); - for (var i3 = 0; i3 < encrypted.length; i3++) { - if (this._lastPrecipherIndex === 16) { - this._lastPrecipher = this._aes.encrypt(this._lastPrecipher); - this._lastPrecipherIndex = 0; - } - encrypted[i3] ^= this._lastPrecipher[this._lastPrecipherIndex++]; - } - return encrypted; - }; - ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt; - var Counter = function(initialValue) { - if (!(this instanceof Counter)) { - throw Error("Counter must be instanitated with `new`"); - } - if (initialValue !== 0 && !initialValue) { - initialValue = 1; - } - if (typeof initialValue === "number") { - this._counter = createArray(16); - this.setValue(initialValue); - } else { - this.setBytes(initialValue); - } - }; - Counter.prototype.setValue = function(value) { - if (typeof value !== "number" || parseInt(value) != value) { - throw new Error("invalid counter value (must be an integer)"); - } - if (value > Number.MAX_SAFE_INTEGER) { - throw new Error("integer value out of safe range"); - } - for (var index = 15; index >= 0; --index) { - this._counter[index] = value % 256; - value = parseInt(value / 256); - } - }; - Counter.prototype.setBytes = function(bytes) { - bytes = coerceArray(bytes, true); - if (bytes.length != 16) { - throw new Error("invalid counter bytes size (must be 16 bytes)"); - } - this._counter = bytes; - }; - Counter.prototype.increment = function() { - for (var i3 = 15; i3 >= 0; i3--) { - if (this._counter[i3] === 255) { - this._counter[i3] = 0; - } else { - this._counter[i3]++; - break; - } - } - }; - var ModeOfOperationCTR = function(key, counter) { - if (!(this instanceof ModeOfOperationCTR)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Counter"; - this.name = "ctr"; - if (!(counter instanceof Counter)) { - counter = new Counter(counter); - } - this._counter = counter; - this._remainingCounter = null; - this._remainingCounterIndex = 16; - this._aes = new AES(key); - }; - ModeOfOperationCTR.prototype.encrypt = function(plaintext) { - var encrypted = coerceArray(plaintext, true); - for (var i3 = 0; i3 < encrypted.length; i3++) { - if (this._remainingCounterIndex === 16) { - this._remainingCounter = this._aes.encrypt(this._counter._counter); - this._remainingCounterIndex = 0; - this._counter.increment(); - } - encrypted[i3] ^= this._remainingCounter[this._remainingCounterIndex++]; - } - return encrypted; - }; - ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt; - function pkcs7pad(data) { - data = coerceArray(data, true); - var padder = 16 - data.length % 16; - var result = createArray(data.length + padder); - copyArray(data, result); - for (var i3 = data.length; i3 < result.length; i3++) { - result[i3] = padder; - } - return result; - } - function pkcs7strip(data) { - data = coerceArray(data, true); - if (data.length < 16) { - throw new Error("PKCS#7 invalid length"); - } - var padder = data[data.length - 1]; - if (padder > 16) { - throw new Error("PKCS#7 padding byte out of range"); - } - var length = data.length - padder; - for (var i3 = 0; i3 < padder; i3++) { - if (data[length + i3] !== padder) { - throw new Error("PKCS#7 invalid padding byte"); - } - } - var result = createArray(length); - copyArray(data, result, 0, 0, length); - return result; - } - var aesjs2 = { - AES, - Counter, - ModeOfOperation: { - ecb: ModeOfOperationECB, - cbc: ModeOfOperationCBC, - cfb: ModeOfOperationCFB, - ofb: ModeOfOperationOFB, - ctr: ModeOfOperationCTR - }, - utils: { - hex: convertHex, - utf8: convertUtf8 - }, - padding: { - pkcs7: { - pad: pkcs7pad, - strip: pkcs7strip - } - }, - _arrayTest: { - coerceArray, - createArray, - copyArray - } - }; - if (typeof exports2 !== "undefined") { - module2.exports = aesjs2; - } else if (typeof define === "function" && define.amd) { - define([], function() { - return aesjs2; - }); - } else { - if (root3.aesjs) { - aesjs2._aesjs = root3.aesjs; + if (typeof exports2 !== "undefined") { + module2.exports = aesjs2; + } else if (typeof define === "function" && define.amd) { + define([], function() { + return aesjs2; + }); + } else { + if (root3.aesjs) { + aesjs2._aesjs = root3.aesjs; } root3.aesjs = aesjs2; } @@ -6866,7 +4783,7 @@ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; var HOT_COUNT = 800, HOT_SPAN = 16; var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; - var INFINITY2 = 1 / 0, MAX_SAFE_INTEGER3 = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN2 = 0 / 0; + var INFINITY2 = 1 / 0, MAX_SAFE_INTEGER4 = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN2 = 0 / 0; var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; var wrapFlags = [ ["ary", WRAP_ARY_FLAG], @@ -7208,16 +5125,16 @@ return func.apply(thisArg, args); } function arrayAggregator(array2, setter, iteratee, accumulator) { - var index = -1, length = array2 == null ? 0 : array2.length; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + while (++index < length2) { var value = array2[index]; setter(accumulator, value, iteratee(value), array2); } return accumulator; } function arrayEach(array2, iteratee) { - var index = -1, length = array2 == null ? 0 : array2.length; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + while (++index < length2) { if (iteratee(array2[index], index, array2) === false) { break; } @@ -7225,17 +5142,17 @@ return array2; } function arrayEachRight(array2, iteratee) { - var length = array2 == null ? 0 : array2.length; - while (length--) { - if (iteratee(array2[length], length, array2) === false) { + var length2 = array2 == null ? 0 : array2.length; + while (length2--) { + if (iteratee(array2[length2], length2, array2) === false) { break; } } return array2; } function arrayEvery(array2, predicate) { - var index = -1, length = array2 == null ? 0 : array2.length; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + while (++index < length2) { if (!predicate(array2[index], index, array2)) { return false; } @@ -7243,8 +5160,8 @@ return true; } function arrayFilter2(array2, predicate) { - var index = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result = []; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length, resIndex = 0, result = []; + while (++index < length2) { var value = array2[index]; if (predicate(value, index, array2)) { result[resIndex++] = value; @@ -7253,12 +5170,12 @@ return result; } function arrayIncludes(array2, value) { - var length = array2 == null ? 0 : array2.length; - return !!length && baseIndexOf(array2, value, 0) > -1; + var length2 = array2 == null ? 0 : array2.length; + return !!length2 && baseIndexOf(array2, value, 0) > -1; } function arrayIncludesWith(array2, value, comparator) { - var index = -1, length = array2 == null ? 0 : array2.length; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + while (++index < length2) { if (comparator(value, array2[index])) { return true; } @@ -7266,42 +5183,42 @@ return false; } function arrayMap2(array2, iteratee) { - var index = -1, length = array2 == null ? 0 : array2.length, result = Array(length); - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length, result = Array(length2); + while (++index < length2) { result[index] = iteratee(array2[index], index, array2); } return result; } function arrayPush2(array2, values) { - var index = -1, length = values.length, offset = array2.length; - while (++index < length) { + var index = -1, length2 = values.length, offset = array2.length; + while (++index < length2) { array2[offset + index] = values[index]; } return array2; } function arrayReduce(array2, iteratee, accumulator, initAccum) { - var index = -1, length = array2 == null ? 0 : array2.length; - if (initAccum && length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + if (initAccum && length2) { accumulator = array2[++index]; } - while (++index < length) { + while (++index < length2) { accumulator = iteratee(accumulator, array2[index], index, array2); } return accumulator; } function arrayReduceRight(array2, iteratee, accumulator, initAccum) { - var length = array2 == null ? 0 : array2.length; - if (initAccum && length) { - accumulator = array2[--length]; + var length2 = array2 == null ? 0 : array2.length; + if (initAccum && length2) { + accumulator = array2[--length2]; } - while (length--) { - accumulator = iteratee(accumulator, array2[length], length, array2); + while (length2--) { + accumulator = iteratee(accumulator, array2[length2], length2, array2); } return accumulator; } function arraySome2(array2, predicate) { - var index = -1, length = array2 == null ? 0 : array2.length; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + while (++index < length2) { if (predicate(array2[index], index, array2)) { return true; } @@ -7326,8 +5243,8 @@ return result; } function baseFindIndex(array2, predicate, fromIndex, fromRight) { - var length = array2.length, index = fromIndex + (fromRight ? 1 : -1); - while (fromRight ? index-- : ++index < length) { + var length2 = array2.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length2) { if (predicate(array2[index], index, array2)) { return index; } @@ -7338,8 +5255,8 @@ return value === value ? strictIndexOf(array2, value, fromIndex) : baseFindIndex(array2, baseIsNaN, fromIndex); } function baseIndexOfWith(array2, value, fromIndex, comparator) { - var index = fromIndex - 1, length = array2.length; - while (++index < length) { + var index = fromIndex - 1, length2 = array2.length; + while (++index < length2) { if (comparator(array2[index], value)) { return index; } @@ -7350,8 +5267,8 @@ return value !== value; } function baseMean(array2, iteratee) { - var length = array2 == null ? 0 : array2.length; - return length ? baseSum(array2, iteratee) / length : NAN2; + var length2 = array2 == null ? 0 : array2.length; + return length2 ? baseSum(array2, iteratee) / length2 : NAN2; } function baseProperty(key) { return function(object) { @@ -7370,16 +5287,16 @@ return accumulator; } function baseSortBy(array2, comparer) { - var length = array2.length; + var length2 = array2.length; array2.sort(comparer); - while (length--) { - array2[length] = array2[length].value; + while (length2--) { + array2[length2] = array2[length2].value; } return array2; } function baseSum(array2, iteratee) { - var result, index = -1, length = array2.length; - while (++index < length) { + var result, index = -1, length2 = array2.length; + while (++index < length2) { var current = iteratee(array2[index]); if (current !== undefined2) { result = result === undefined2 ? current : result + current; @@ -7416,8 +5333,8 @@ return cache.has(key); } function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, length = strSymbols.length; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + var index = -1, length2 = strSymbols.length; + while (++index < length2 && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { } return index; } @@ -7428,9 +5345,9 @@ return index; } function countHolders(array2, placeholder) { - var length = array2.length, result = 0; - while (length--) { - if (array2[length] === placeholder) { + var length2 = array2.length, result = 0; + while (length2--) { + if (array2[length2] === placeholder) { ++result; } } @@ -7470,8 +5387,8 @@ }; } function replaceHolders(array2, placeholder) { - var index = -1, length = array2.length, resIndex = 0, result = []; - while (++index < length) { + var index = -1, length2 = array2.length, resIndex = 0, result = []; + while (++index < length2) { var value = array2[index]; if (value === placeholder || value === PLACEHOLDER) { array2[index] = PLACEHOLDER; @@ -7480,23 +5397,23 @@ } return result; } - function setToArray2(set3) { - var index = -1, result = Array(set3.size); - set3.forEach(function(value) { + function setToArray2(set4) { + var index = -1, result = Array(set4.size); + set4.forEach(function(value) { result[++index] = value; }); return result; } - function setToPairs(set3) { - var index = -1, result = Array(set3.size); - set3.forEach(function(value) { + function setToPairs(set4) { + var index = -1, result = Array(set4.size); + set4.forEach(function(value) { result[++index] = [value, value]; }); return result; } function strictIndexOf(array2, value, fromIndex) { - var index = fromIndex - 1, length = array2.length; - while (++index < length) { + var index = fromIndex - 1, length2 = array2.length; + while (++index < length2) { if (array2[index] === value) { return index; } @@ -7583,7 +5500,7 @@ } return new LodashWrapper(value); } - var baseCreate = function() { + var baseCreate = /* @__PURE__ */ function() { function object() { } return function(proto) { @@ -7688,13 +5605,13 @@ return result2; } function lazyValue() { - var array2 = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array2), isRight = dir < 0, arrLength = isArr ? array2.length : 0, view = getView(0, arrLength, this.__views__), start2 = view.start, end = view.end, length = end - start2, index = isRight ? end : start2 - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin2(length, this.__takeCount__); - if (!isArr || !isRight && arrLength == length && takeCount == length) { + var array2 = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array2), isRight = dir < 0, arrLength = isArr ? array2.length : 0, view = getView(0, arrLength, this.__views__), start2 = view.start, end = view.end, length2 = end - start2, index = isRight ? end : start2 - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin2(length2, this.__takeCount__); + if (!isArr || !isRight && arrLength == length2 && takeCount == length2) { return baseWrapperValue(array2, this.__actions__); } var result2 = []; outer: - while (length-- && resIndex < takeCount) { + while (length2-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array2[index]; while (++iterIndex < iterLength) { @@ -7716,9 +5633,9 @@ LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; function Hash2(entries) { - var index = -1, length = entries == null ? 0 : entries.length; + var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); - while (++index < length) { + while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } @@ -7756,9 +5673,9 @@ Hash2.prototype.has = hashHas2; Hash2.prototype.set = hashSet2; function ListCache2(entries) { - var index = -1, length = entries == null ? 0 : entries.length; + var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); - while (++index < length) { + while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } @@ -7804,9 +5721,9 @@ ListCache2.prototype.has = listCacheHas2; ListCache2.prototype.set = listCacheSet2; function MapCache2(entries) { - var index = -1, length = entries == null ? 0 : entries.length; + var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); - while (++index < length) { + while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } @@ -7842,9 +5759,9 @@ MapCache2.prototype.has = mapCacheHas2; MapCache2.prototype.set = mapCacheSet2; function SetCache2(values2) { - var index = -1, length = values2 == null ? 0 : values2.length; + var index = -1, length2 = values2 == null ? 0 : values2.length; this.__data__ = new MapCache2(); - while (++index < length) { + while (++index < length2) { this.add(values2[index]); } } @@ -7897,21 +5814,21 @@ Stack2.prototype.has = stackHas2; Stack2.prototype.set = stackSet2; function arrayLikeKeys2(value, inherited) { - var isArr = isArray2(value), isArg = !isArr && isArguments2(value), isBuff = !isArr && !isArg && isBuffer2(value), isType = !isArr && !isArg && !isBuff && isTypedArray2(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes2(value.length, String2) : [], length = result2.length; + var isArr = isArray2(value), isArg = !isArr && isArguments2(value), isBuff = !isArr && !isArg && isBuffer2(value), isType = !isArr && !isArg && !isBuff && isTypedArray2(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes2(value.length, String2) : [], length2 = result2.length; for (var key in value) { if ((inherited || hasOwnProperty10.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. - isIndex2(key, length)))) { + isIndex2(key, length2)))) { result2.push(key); } } return result2; } function arraySample(array2) { - var length = array2.length; - return length ? array2[baseRandom(0, length - 1)] : undefined2; + var length2 = array2.length; + return length2 ? array2[baseRandom(0, length2 - 1)] : undefined2; } function arraySampleSize(array2, n3) { return shuffleSelf(copyArray(array2), baseClamp(n3, 0, array2.length)); @@ -7931,10 +5848,10 @@ } } function assocIndexOf2(array2, key) { - var length = array2.length; - while (length--) { - if (eq2(array2[length][0], key)) { - return length; + var length2 = array2.length; + while (length2--) { + if (eq2(array2[length2][0], key)) { + return length2; } } return -1; @@ -7964,8 +5881,8 @@ } } function baseAt(object, paths) { - var index = -1, length = paths.length, result2 = Array2(length), skip = object == null; - while (++index < length) { + var index = -1, length2 = paths.length, result2 = Array2(length2), skip = object == null; + while (++index < length2) { result2[index] = skip ? undefined2 : get4(object, paths[index]); } return result2; @@ -7999,20 +5916,20 @@ return copyArray(value, result2); } } else { - var tag = getTag2(value), isFunc = tag == funcTag3 || tag == genTag2; + var tag2 = getTag2(value), isFunc = tag2 == funcTag3 || tag2 == genTag2; if (isBuffer2(value)) { return cloneBuffer(value, isDeep); } - if (tag == objectTag4 || tag == argsTag4 || isFunc && !object) { + if (tag2 == objectTag4 || tag2 == argsTag4 || isFunc && !object) { result2 = isFlat || isFunc ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result2, value)) : copySymbols(value, baseAssign(result2, value)); } } else { - if (!cloneableTags[tag]) { + if (!cloneableTags[tag2]) { return object ? value : {}; } - result2 = initCloneByTag(value, tag, isDeep); + result2 = initCloneByTag(value, tag2, isDeep); } } stack || (stack = new Stack2()); @@ -8048,13 +5965,13 @@ }; } function baseConformsTo(object, source, props) { - var length = props.length; + var length2 = props.length; if (object == null) { - return !length; + return !length2; } object = Object2(object); - while (length--) { - var key = props[length], predicate = source[key], value = object[key]; + while (length2--) { + var key = props[length2], predicate = source[key], value = object[key]; if (value === undefined2 && !(key in object) || !predicate(value)) { return false; } @@ -8070,8 +5987,8 @@ }, wait); } function baseDifference(array2, values2, iteratee2, comparator) { - var index = -1, includes2 = arrayIncludes, isCommon = true, length = array2.length, result2 = [], valuesLength = values2.length; - if (!length) { + var index = -1, includes2 = arrayIncludes, isCommon = true, length2 = array2.length, result2 = [], valuesLength = values2.length; + if (!length2) { return result2; } if (iteratee2) { @@ -8086,7 +6003,7 @@ values2 = new SetCache2(values2); } outer: - while (++index < length) { + while (++index < length2) { var value = array2[index], computed = iteratee2 == null ? value : iteratee2(value); value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { @@ -8114,8 +6031,8 @@ return result2; } function baseExtremum(array2, iteratee2, comparator) { - var index = -1, length = array2.length; - while (++index < length) { + var index = -1, length2 = array2.length; + while (++index < length2) { var value = array2[index], current = iteratee2(value); if (current != null && (computed === undefined2 ? current === current && !isSymbol2(current) : comparator(current, computed))) { var computed = current, result2 = value; @@ -8124,14 +6041,14 @@ return result2; } function baseFill(array2, value, start2, end) { - var length = array2.length; + var length2 = array2.length; start2 = toInteger(start2); if (start2 < 0) { - start2 = -start2 > length ? 0 : length + start2; + start2 = -start2 > length2 ? 0 : length2 + start2; } - end = end === undefined2 || end > length ? length : toInteger(end); + end = end === undefined2 || end > length2 ? length2 : toInteger(end); if (end < 0) { - end += length; + end += length2; } end = start2 > end ? 0 : toLength(end); while (start2 < end) { @@ -8149,10 +6066,10 @@ return result2; } function baseFlatten(array2, depth, predicate, isStrict, result2) { - var index = -1, length = array2.length; + var index = -1, length2 = array2.length; predicate || (predicate = isFlattenable); result2 || (result2 = []); - while (++index < length) { + while (++index < length2) { var value = array2[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { @@ -8181,11 +6098,11 @@ } function baseGet(object, path) { path = castPath(path, object); - var index = 0, length = path.length; - while (object != null && index < length) { + var index = 0, length2 = path.length; + while (object != null && index < length2) { object = object[toKey(path[index++])]; } - return index && index == length ? object : undefined2; + return index && index == length2 ? object : undefined2; } function baseGetAllKeys2(object, keysFunc, symbolsFunc) { var result2 = keysFunc(object); @@ -8210,19 +6127,19 @@ return number3 >= nativeMin2(start2, end) && number3 < nativeMax2(start2, end); } function baseIntersection(arrays, iteratee2, comparator) { - var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; + var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length2 = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; while (othIndex--) { var array2 = arrays[othIndex]; if (othIndex && iteratee2) { array2 = arrayMap2(array2, baseUnary2(iteratee2)); } maxLength = nativeMin2(array2.length, maxLength); - caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array2.length >= 120) ? new SetCache2(othIndex && array2) : undefined2; + caches[othIndex] = !comparator && (iteratee2 || length2 >= 120 && array2.length >= 120) ? new SetCache2(othIndex && array2) : undefined2; } array2 = arrays[0]; var index = -1, seen = caches[0]; outer: - while (++index < length && result2.length < maxLength) { + while (++index < length2 && result2.length < maxLength) { var value = array2[index], computed = iteratee2 ? iteratee2(value) : value; value = comparator || value !== 0 ? value : 0; if (!(seen ? cacheHas2(seen, computed) : includes2(result2, computed, comparator))) { @@ -8305,9 +6222,9 @@ return isObjectLike2(value) && getTag2(value) == mapTag4; } function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, length = index, noCustomizer = !customizer; + var index = matchData.length, length2 = index, noCustomizer = !customizer; if (object == null) { - return !length; + return !length2; } object = Object2(object); while (index--) { @@ -8316,7 +6233,7 @@ return false; } } - while (++index < length) { + while (++index < length2) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { @@ -8476,12 +6393,12 @@ assignMergeValue(object, key, newValue); } function baseNth(array2, n3) { - var length = array2.length; - if (!length) { + var length2 = array2.length; + if (!length2) { return; } - n3 += n3 < 0 ? length : 0; - return isIndex2(n3, length) ? array2[n3] : undefined2; + n3 += n3 < 0 ? length2 : 0; + return isIndex2(n3, length2) ? array2[n3] : undefined2; } function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { @@ -8514,8 +6431,8 @@ }); } function basePickBy(object, paths, predicate) { - var index = -1, length = paths.length, result2 = {}; - while (++index < length) { + var index = -1, length2 = paths.length, result2 = {}; + while (++index < length2) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result2, castPath(path, object), value); @@ -8529,14 +6446,14 @@ }; } function basePullAll(array2, values2, iteratee2, comparator) { - var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values2.length, seen = array2; + var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length2 = values2.length, seen = array2; if (array2 === values2) { values2 = copyArray(values2); } if (iteratee2) { seen = arrayMap2(array2, baseUnary2(iteratee2)); } - while (++index < length) { + while (++index < length2) { var fromIndex = 0, value = values2[index], computed = iteratee2 ? iteratee2(value) : value; while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array2) { @@ -8548,10 +6465,10 @@ return array2; } function basePullAt(array2, indexes) { - var length = array2 ? indexes.length : 0, lastIndex = length - 1; - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { + var length2 = array2 ? indexes.length : 0, lastIndex = length2 - 1; + while (length2--) { + var index = indexes[length2]; + if (length2 == lastIndex || index !== previous) { var previous = index; if (isIndex2(index)) { splice2.call(array2, index, 1); @@ -8566,16 +6483,16 @@ return lower2 + nativeFloor(nativeRandom() * (upper - lower2 + 1)); } function baseRange(start2, end, step, fromRight) { - var index = -1, length = nativeMax2(nativeCeil((end - start2) / (step || 1)), 0), result2 = Array2(length); - while (length--) { - result2[fromRight ? length : ++index] = start2; + var index = -1, length2 = nativeMax2(nativeCeil((end - start2) / (step || 1)), 0), result2 = Array2(length2); + while (length2--) { + result2[fromRight ? length2 : ++index] = start2; start2 += step; } return result2; } function baseRepeat(string, n3) { var result2 = ""; - if (!string || n3 < 1 || n3 > MAX_SAFE_INTEGER3) { + if (!string || n3 < 1 || n3 > MAX_SAFE_INTEGER4) { return result2; } do { @@ -8604,8 +6521,8 @@ return object; } path = castPath(path, object); - var index = -1, length = path.length, lastIndex = length - 1, nested = object; - while (nested != null && ++index < length) { + var index = -1, length2 = path.length, lastIndex = length2 - 1, nested = object; + while (nested != null && ++index < length2) { var key = toKey(path[index]), newValue = value; if (key === "__proto__" || key === "constructor" || key === "prototype") { return object; @@ -8638,18 +6555,18 @@ return shuffleSelf(values(collection)); } function baseSlice(array2, start2, end) { - var index = -1, length = array2.length; + var index = -1, length2 = array2.length; if (start2 < 0) { - start2 = -start2 > length ? 0 : length + start2; + start2 = -start2 > length2 ? 0 : length2 + start2; } - end = end > length ? length : end; + end = end > length2 ? length2 : end; if (end < 0) { - end += length; + end += length2; } - length = start2 > end ? 0 : end - start2 >>> 0; + length2 = start2 > end ? 0 : end - start2 >>> 0; start2 >>>= 0; - var result2 = Array2(length); - while (++index < length) { + var result2 = Array2(length2); + while (++index < length2) { result2[index] = array2[index + start2]; } return result2; @@ -8708,8 +6625,8 @@ return nativeMin2(high, MAX_ARRAY_INDEX); } function baseSortedUniq(array2, iteratee2) { - var index = -1, length = array2.length, resIndex = 0, result2 = []; - while (++index < length) { + var index = -1, length2 = array2.length, resIndex = 0, result2 = []; + while (++index < length2) { var value = array2[index], computed = iteratee2 ? iteratee2(value) : value; if (!index || !eq2(computed, seen)) { var seen = computed; @@ -8741,14 +6658,14 @@ return result2 == "0" && 1 / value == -INFINITY2 ? "-0" : result2; } function baseUniq(array2, iteratee2, comparator) { - var index = -1, includes2 = arrayIncludes, length = array2.length, isCommon = true, result2 = [], seen = result2; + var index = -1, includes2 = arrayIncludes, length2 = array2.length, isCommon = true, result2 = [], seen = result2; if (comparator) { isCommon = false; includes2 = arrayIncludesWith; - } else if (length >= LARGE_ARRAY_SIZE2) { - var set4 = iteratee2 ? null : createSet(array2); - if (set4) { - return setToArray2(set4); + } else if (length2 >= LARGE_ARRAY_SIZE2) { + var set5 = iteratee2 ? null : createSet(array2); + if (set5) { + return setToArray2(set5); } isCommon = false; includes2 = cacheHas2; @@ -8757,7 +6674,7 @@ seen = iteratee2 ? [] : result2; } outer: - while (++index < length) { + while (++index < length2) { var value = array2[index], computed = iteratee2 ? iteratee2(value) : value; value = comparator || value !== 0 ? value : 0; if (isCommon && computed === computed) { @@ -8789,10 +6706,10 @@ return baseSet(object, path, updater(baseGet(object, path)), customizer); } function baseWhile(array2, predicate, isDrop, fromRight) { - var length = array2.length, index = fromRight ? length : -1; - while ((fromRight ? index-- : ++index < length) && predicate(array2[index], index, array2)) { + var length2 = array2.length, index = fromRight ? length2 : -1; + while ((fromRight ? index-- : ++index < length2) && predicate(array2[index], index, array2)) { } - return isDrop ? baseSlice(array2, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array2, fromRight ? index + 1 : 0, fromRight ? length : index); + return isDrop ? baseSlice(array2, fromRight ? 0 : index, fromRight ? index + 1 : length2) : baseSlice(array2, fromRight ? index + 1 : 0, fromRight ? length2 : index); } function baseWrapperValue(value, actions) { var result2 = value; @@ -8804,14 +6721,14 @@ }, result2); } function baseXor(arrays, iteratee2, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; + var length2 = arrays.length; + if (length2 < 2) { + return length2 ? baseUniq(arrays[0]) : []; } - var index = -1, result2 = Array2(length); - while (++index < length) { + var index = -1, result2 = Array2(length2); + while (++index < length2) { var array2 = arrays[index], othIndex = -1; - while (++othIndex < length) { + while (++othIndex < length2) { if (othIndex != index) { result2[index] = baseDifference(result2[index] || array2, arrays[othIndex], iteratee2, comparator); } @@ -8820,8 +6737,8 @@ return baseUniq(baseFlatten(result2, 1), iteratee2, comparator); } function baseZipObject(props, values2, assignFunc) { - var index = -1, length = props.length, valsLength = values2.length, result2 = {}; - while (++index < length) { + var index = -1, length2 = props.length, valsLength = values2.length, result2 = {}; + while (++index < length2) { var value = index < valsLength ? values2[index] : undefined2; assignFunc(result2, props[index], value); } @@ -8841,9 +6758,9 @@ } var castRest = baseRest; function castSlice(array2, start2, end) { - var length = array2.length; - end = end === undefined2 ? length : end; - return !start2 && end >= length ? array2 : baseSlice(array2, start2, end); + var length2 = array2.length; + end = end === undefined2 ? length2 : end; + return !start2 && end >= length2 ? array2 : baseSlice(array2, start2, end); } var clearTimeout2 = ctxClearTimeout || function(id2) { return root3.clearTimeout(id2); @@ -8852,7 +6769,7 @@ if (isDeep) { return buffer.slice(); } - var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + var length2 = buffer.length, result2 = allocUnsafe ? allocUnsafe(length2) : new buffer.constructor(length2); buffer.copy(result2); return result2; } @@ -8891,8 +6808,8 @@ return 0; } function compareMultiple(object, other, orders) { - var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; - while (++index < length) { + var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length2 = objCriteria.length, ordersLength = orders.length; + while (++index < length2) { var result2 = compareAscending(objCriteria[index], othCriteria[index]); if (result2) { if (index >= ordersLength) { @@ -8936,9 +6853,9 @@ return result2; } function copyArray(source, array2) { - var index = -1, length = source.length; - array2 || (array2 = Array2(length)); - while (++index < length) { + var index = -1, length2 = source.length; + array2 || (array2 = Array2(length2)); + while (++index < length2) { array2[index] = source[index]; } return array2; @@ -8946,8 +6863,8 @@ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); - var index = -1, length = props.length; - while (++index < length) { + var index = -1, length2 = props.length; + while (++index < length2) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined2; if (newValue === undefined2) { @@ -8975,14 +6892,14 @@ } function createAssigner(assigner) { return baseRest(function(object, sources) { - var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined2, guard = length > 2 ? sources[2] : undefined2; - customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined2; + var index = -1, length2 = sources.length, customizer = length2 > 1 ? sources[length2 - 1] : undefined2, guard = length2 > 2 ? sources[2] : undefined2; + customizer = assigner.length > 3 && typeof customizer == "function" ? (length2--, customizer) : undefined2; if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined2 : customizer; - length = 1; + customizer = length2 < 3 ? undefined2 : customizer; + length2 = 1; } object = Object2(object); - while (++index < length) { + while (++index < length2) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); @@ -8999,8 +6916,8 @@ if (!isArrayLike2(collection)) { return eachFunc(collection, iteratee2); } - var length = collection.length, index = fromRight ? length : -1, iterable = Object2(collection); - while (fromRight ? index-- : ++index < length) { + var length2 = collection.length, index = fromRight ? length2 : -1, iterable = Object2(collection); + while (fromRight ? index-- : ++index < length2) { if (iteratee2(iterable[index], index, iterable) === false) { break; } @@ -9010,9 +6927,9 @@ } function createBaseFor(fromRight) { return function(object, iteratee2, keysFunc) { - var index = -1, iterable = Object2(object), props = keysFunc(object), length = props.length; - while (length--) { - var key = props[fromRight ? length : ++index]; + var index = -1, iterable = Object2(object), props = keysFunc(object), length2 = props.length; + while (length2--) { + var key = props[fromRight ? length2 : ++index]; if (iteratee2(iterable[key], key, iterable) === false) { break; } @@ -9070,13 +6987,13 @@ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { - var length = arguments.length, args = Array2(length), index = length, placeholder = getHolder(wrapper); + var length2 = arguments.length, args = Array2(length2), index = length2, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } - var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); - length -= holders.length; - if (length < arity) { + var holders = length2 < 3 && args[0] !== placeholder && args[length2 - 1] !== placeholder ? [] : replaceHolders(args, placeholder); + length2 -= holders.length; + if (length2 < arity) { return createRecurry( func, bitmask, @@ -9087,7 +7004,7 @@ holders, undefined2, undefined2, - arity - length + arity - length2 ); } var fn = this && this !== root3 && this instanceof wrapper ? Ctor : func; @@ -9111,7 +7028,7 @@ } function createFlow(fromRight) { return flatRest(function(funcs) { - var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; + var length2 = funcs.length, index = length2, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } @@ -9124,8 +7041,8 @@ var wrapper = new LodashWrapper([], true); } } - index = wrapper ? index : length; - while (++index < length) { + index = wrapper ? index : length2; + while (++index < length2) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined2; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { @@ -9139,8 +7056,8 @@ if (wrapper && args.length == 1 && isArray2(value)) { return wrapper.plant(value).value(); } - var index2 = 0, result2 = length ? funcs[index2].apply(this, args) : value; - while (++index2 < length) { + var index2 = 0, result2 = length2 ? funcs[index2].apply(this, args) : value; + while (++index2 < length2) { result2 = funcs[index2].call(this, result2); } return result2; @@ -9150,7 +7067,7 @@ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined2 : createCtor(func); function wrapper() { - var length = arguments.length, args = Array2(length), index = length; + var length2 = arguments.length, args = Array2(length2), index = length2; while (index--) { args[index] = arguments[index]; } @@ -9163,8 +7080,8 @@ if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } - length -= holdersCount; - if (isCurried && length < arity) { + length2 -= holdersCount; + if (isCurried && length2 < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, @@ -9176,17 +7093,17 @@ newHolders, argPos, ary2, - arity - length + arity - length2 ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; - length = args.length; + length2 = args.length; if (argPos) { args = reorder(args, argPos); - } else if (isFlip && length > 1) { + } else if (isFlip && length2 > 1) { args.reverse(); } - if (isAry && ary2 < length) { + if (isAry && ary2 < length2) { args.length = ary2; } if (this && this !== root3 && this instanceof wrapper) { @@ -9237,14 +7154,14 @@ }); }); } - function createPadding(length, chars) { + function createPadding(length2, chars) { chars = chars === undefined2 ? " " : baseToString2(chars); var charsLength = chars.length; if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; + return charsLength ? baseRepeat(chars, length2) : chars; } - var result2 = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length); + var result2 = baseRepeat(chars, nativeCeil(length2 / stringSize(chars))); + return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length2).join("") : result2.slice(0, length2); } function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); @@ -9313,13 +7230,13 @@ } function createRound(methodName) { var func = Math2[methodName]; - return function(number3, precision2) { + return function(number3, precision3) { number3 = toNumber3(number3); - precision2 = precision2 == null ? 0 : nativeMin2(toInteger(precision2), 292); - if (precision2 && nativeIsFinite(number3)) { - var pair3 = (toString2(number3) + "e").split("e"), value = func(pair3[0] + "e" + (+pair3[1] + precision2)); + precision3 = precision3 == null ? 0 : nativeMin2(toInteger(precision3), 292); + if (precision3 && nativeIsFinite(number3)) { + var pair3 = (toString2(number3) + "e").split("e"), value = func(pair3[0] + "e" + (+pair3[1] + precision3)); pair3 = (toString2(value) + "e").split("e"); - return +(pair3[0] + "e" + (+pair3[1] - precision2)); + return +(pair3[0] + "e" + (+pair3[1] - precision3)); } return func(number3); }; @@ -9329,11 +7246,11 @@ }; function createToPairs(keysFunc) { return function(object) { - var tag = getTag2(object); - if (tag == mapTag4) { + var tag2 = getTag2(object); + if (tag2 == mapTag4) { return mapToArray2(object); } - if (tag == setTag4) { + if (tag2 == setTag4) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); @@ -9344,14 +7261,14 @@ if (!isBindKey && typeof func != "function") { throw new TypeError2(FUNC_ERROR_TEXT3); } - var length = partials ? partials.length : 0; - if (!length) { + var length2 = partials ? partials.length : 0; + if (!length2) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined2; } ary2 = ary2 === undefined2 ? ary2 : nativeMax2(toInteger(ary2), 0); arity = arity === undefined2 ? arity : toInteger(arity); - length -= holders ? holders.length : 0; + length2 -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined2; @@ -9377,7 +7294,7 @@ thisArg = newData[2]; partials = newData[3]; holders = newData[4]; - arity = newData[9] = newData[9] === undefined2 ? isBindKey ? 0 : func.length : nativeMax2(newData[9] - length, 0); + arity = newData[9] = newData[9] === undefined2 ? isBindKey ? 0 : func.length : nativeMax2(newData[9] - length2, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } @@ -9453,8 +7370,8 @@ stack["delete"](other); return result2; } - function equalByTag2(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { + function equalByTag2(object, other, tag2, bitmask, customizer, equalFunc, stack) { + switch (tag2) { case dataViewTag4: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; @@ -9555,9 +7472,9 @@ return metaMap.get(func); }; function getFuncName(func) { - var result2 = func.name + "", array2 = realNames[result2], length = hasOwnProperty10.call(realNames, result2) ? array2.length : 0; - while (length--) { - var data = array2[length], otherFunc = data.func; + var result2 = func.name + "", array2 = realNames[result2], length2 = hasOwnProperty10.call(realNames, result2) ? array2.length : 0; + while (length2--) { + var data = array2[length2], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } @@ -9578,10 +7495,10 @@ return isKeyable2(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } function getMatchData(object) { - var result2 = keys2(object), length = result2.length; - while (length--) { - var key = result2[length], value = object[key]; - result2[length] = [key, value, isStrictComparable(value)]; + var result2 = keys2(object), length2 = result2.length; + while (length2--) { + var key = result2[length2], value = object[key]; + result2[length2] = [key, value, isStrictComparable(value)]; } return result2; } @@ -9590,7 +7507,7 @@ return baseIsNative2(value) ? value : undefined2; } function getRawTag2(value) { - var isOwn = hasOwnProperty10.call(value, symToStringTag3), tag = value[symToStringTag3]; + var isOwn = hasOwnProperty10.call(value, symToStringTag3), tag2 = value[symToStringTag3]; try { value[symToStringTag3] = undefined2; var unmasked = true; @@ -9599,7 +7516,7 @@ var result2 = nativeObjectToString3.call(value); if (unmasked) { if (isOwn) { - value[symToStringTag3] = tag; + value[symToStringTag3] = tag2; } else { delete value[symToStringTag3]; } @@ -9645,8 +7562,8 @@ }; } function getView(start2, end, transforms) { - var index = -1, length = transforms.length; - while (++index < length) { + var index = -1, length2 = transforms.length; + while (++index < length2) { var data = transforms[index], size2 = data.size; switch (data.type) { case "drop": @@ -9671,23 +7588,23 @@ } function hasPath(object, path, hasFunc) { path = castPath(path, object); - var index = -1, length = path.length, result2 = false; - while (++index < length) { + var index = -1, length2 = path.length, result2 = false; + while (++index < length2) { var key = toKey(path[index]); if (!(result2 = object != null && hasFunc(object, key))) { break; } object = object[key]; } - if (result2 || ++index != length) { + if (result2 || ++index != length2) { return result2; } - length = object == null ? 0 : object.length; - return !!length && isLength2(length) && isIndex2(key, length) && (isArray2(object) || isArguments2(object)); + length2 = object == null ? 0 : object.length; + return !!length2 && isLength2(length2) && isIndex2(key, length2) && (isArray2(object) || isArguments2(object)); } function initCloneArray(array2) { - var length = array2.length, result2 = new array2.constructor(length); - if (length && typeof array2[0] == "string" && hasOwnProperty10.call(array2, "index")) { + var length2 = array2.length, result2 = new array2.constructor(length2); + if (length2 && typeof array2[0] == "string" && hasOwnProperty10.call(array2, "index")) { result2.index = array2.index; result2.input = array2.input; } @@ -9696,9 +7613,9 @@ function initCloneObject(object) { return typeof object.constructor == "function" && !isPrototype2(object) ? baseCreate(getPrototype(object)) : {}; } - function initCloneByTag(object, tag, isDeep) { + function initCloneByTag(object, tag2, isDeep) { var Ctor = object.constructor; - switch (tag) { + switch (tag2) { case arrayBufferTag3: return cloneArrayBuffer(object); case boolTag3: @@ -9730,22 +7647,22 @@ } } function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { + var length2 = details.length; + if (!length2) { return source; } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; - details = details.join(length > 2 ? ", " : " "); + var lastIndex = length2 - 1; + details[lastIndex] = (length2 > 1 ? "& " : "") + details[lastIndex]; + details = details.join(length2 > 2 ? ", " : " "); return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); } function isFlattenable(value) { return isArray2(value) || isArguments2(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } - function isIndex2(value, length) { + function isIndex2(value, length2) { var type2 = typeof value; - length = length == null ? MAX_SAFE_INTEGER3 : length; - return !!length && (type2 == "number" || type2 != "symbol" && reIsUint2.test(value)) && (value > -1 && value % 1 == 0 && value < length); + length2 = length2 == null ? MAX_SAFE_INTEGER4 : length2; + return !!length2 && (type2 == "number" || type2 != "symbol" && reIsUint2.test(value)) && (value > -1 && value % 1 == 0 && value < length2); } function isIterateeCall(value, index, object) { if (!isObject3(object)) { @@ -9862,8 +7779,8 @@ function overRest(func, start2, transform3) { start2 = nativeMax2(start2 === undefined2 ? func.length - 1 : start2, 0); return function() { - var args = arguments, index = -1, length = nativeMax2(args.length - start2, 0), array2 = Array2(length); - while (++index < length) { + var args = arguments, index = -1, length2 = nativeMax2(args.length - start2, 0), array2 = Array2(length2); + while (++index < length2) { array2[index] = args[start2 + index]; } index = -1; @@ -9879,10 +7796,10 @@ return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } function reorder(array2, indexes) { - var arrLength = array2.length, length = nativeMin2(indexes.length, arrLength), oldArray = copyArray(array2); - while (length--) { - var index = indexes[length]; - array2[length] = isIndex2(index, arrLength) ? oldArray[index] : undefined2; + var arrLength = array2.length, length2 = nativeMin2(indexes.length, arrLength), oldArray = copyArray(array2); + while (length2--) { + var index = indexes[length2]; + array2[length2] = isIndex2(index, arrLength) ? oldArray[index] : undefined2; } return array2; } @@ -9920,8 +7837,8 @@ }; } function shuffleSelf(array2, size2) { - var index = -1, length = array2.length, lastIndex = length - 1; - size2 = size2 === undefined2 ? length : size2; + var index = -1, length2 = array2.length, lastIndex = length2 - 1; + size2 = size2 === undefined2 ? length2 : size2; while (++index < size2) { var rand = baseRandom(index, lastIndex), value = array2[rand]; array2[rand] = array2[index]; @@ -9935,8 +7852,8 @@ if (string.charCodeAt(0) === 46) { result2.push(""); } - string.replace(rePropName, function(match, number3, quote2, subString) { - result2.push(quote2 ? subString.replace(reEscapeChar, "$1") : number3 || match); + string.replace(rePropName, function(match, number3, quote, subString) { + result2.push(quote ? subString.replace(reEscapeChar, "$1") : number3 || match); }); return result2; }); @@ -9985,19 +7902,19 @@ } else { size2 = nativeMax2(toInteger(size2), 0); } - var length = array2 == null ? 0 : array2.length; - if (!length || size2 < 1) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2 || size2 < 1) { return []; } - var index = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2)); - while (index < length) { + var index = 0, resIndex = 0, result2 = Array2(nativeCeil(length2 / size2)); + while (index < length2) { result2[resIndex++] = baseSlice(array2, index, index += size2); } return result2; } function compact(array2) { - var index = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result2 = []; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length, resIndex = 0, result2 = []; + while (++index < length2) { var value = array2[index]; if (value) { result2[resIndex++] = value; @@ -10006,17 +7923,17 @@ return result2; } function concat() { - var length = arguments.length; - if (!length) { + var length2 = arguments.length; + if (!length2) { return []; } - var args = Array2(length - 1), array2 = arguments[0], index = length; + var args = Array2(length2 - 1), array2 = arguments[0], index = length2; while (index--) { args[index - 1] = arguments[index]; } return arrayPush2(isArray2(array2) ? copyArray(array2) : [array2], baseFlatten(args, 1)); } - var difference = baseRest(function(array2, values2) { + var difference2 = baseRest(function(array2, values2) { return isArrayLikeObject(array2) ? baseDifference(array2, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; }); var differenceBy = baseRest(function(array2, values2) { @@ -10034,20 +7951,20 @@ return isArrayLikeObject(array2) ? baseDifference(array2, baseFlatten(values2, 1, isArrayLikeObject, true), undefined2, comparator) : []; }); function drop(array2, n3, guard) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return []; } n3 = guard || n3 === undefined2 ? 1 : toInteger(n3); - return baseSlice(array2, n3 < 0 ? 0 : n3, length); + return baseSlice(array2, n3 < 0 ? 0 : n3, length2); } function dropRight(array2, n3, guard) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return []; } n3 = guard || n3 === undefined2 ? 1 : toInteger(n3); - n3 = length - n3; + n3 = length2 - n3; return baseSlice(array2, 0, n3 < 0 ? 0 : n3); } function dropRightWhile(array2, predicate) { @@ -10057,58 +7974,58 @@ return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), true) : []; } function fill(array2, value, start2, end) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return []; } if (start2 && typeof start2 != "number" && isIterateeCall(array2, value, start2)) { start2 = 0; - end = length; + end = length2; } return baseFill(array2, value, start2, end); } function findIndex(array2, predicate, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { - index = nativeMax2(length + index, 0); + index = nativeMax2(length2 + index, 0); } return baseFindIndex(array2, getIteratee(predicate, 3), index); } function findLastIndex(array2, predicate, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return -1; } - var index = length - 1; + var index = length2 - 1; if (fromIndex !== undefined2) { index = toInteger(fromIndex); - index = fromIndex < 0 ? nativeMax2(length + index, 0) : nativeMin2(index, length - 1); + index = fromIndex < 0 ? nativeMax2(length2 + index, 0) : nativeMin2(index, length2 - 1); } return baseFindIndex(array2, getIteratee(predicate, 3), index, true); } function flatten2(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseFlatten(array2, 1) : []; + var length2 = array2 == null ? 0 : array2.length; + return length2 ? baseFlatten(array2, 1) : []; } function flattenDeep(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseFlatten(array2, INFINITY2) : []; + var length2 = array2 == null ? 0 : array2.length; + return length2 ? baseFlatten(array2, INFINITY2) : []; } function flattenDepth(array2, depth) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return []; } depth = depth === undefined2 ? 1 : toInteger(depth); return baseFlatten(array2, depth); } function fromPairs(pairs2) { - var index = -1, length = pairs2 == null ? 0 : pairs2.length, result2 = {}; - while (++index < length) { + var index = -1, length2 = pairs2 == null ? 0 : pairs2.length, result2 = {}; + while (++index < length2) { var pair3 = pairs2[index]; result2[pair3[0]] = pair3[1]; } @@ -10118,21 +8035,21 @@ return array2 && array2.length ? array2[0] : undefined2; } function indexOf(array2, value, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { - index = nativeMax2(length + index, 0); + index = nativeMax2(length2 + index, 0); } return baseIndexOf(array2, value, index); } function initial(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseSlice(array2, 0, -1) : []; + var length2 = array2 == null ? 0 : array2.length; + return length2 ? baseSlice(array2, 0, -1) : []; } - var intersection = baseRest(function(arrays) { + var intersection2 = baseRest(function(arrays) { var mapped = arrayMap2(arrays, castArrayLikeObject); return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; }); @@ -10157,18 +8074,18 @@ return array2 == null ? "" : nativeJoin.call(array2, separator); } function last(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? array2[length - 1] : undefined2; + var length2 = array2 == null ? 0 : array2.length; + return length2 ? array2[length2 - 1] : undefined2; } function lastIndexOf(array2, value, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return -1; } - var index = length; + var index = length2; if (fromIndex !== undefined2) { index = toInteger(fromIndex); - index = index < 0 ? nativeMax2(length + index, 0) : nativeMin2(index, length - 1); + index = index < 0 ? nativeMax2(length2 + index, 0) : nativeMin2(index, length2 - 1); } return value === value ? strictLastIndexOf(array2, value, index) : baseFindIndex(array2, baseIsNaN, index, true); } @@ -10186,9 +8103,9 @@ return array2 && array2.length && values2 && values2.length ? basePullAll(array2, values2, undefined2, comparator) : array2; } var pullAt = flatRest(function(array2, indexes) { - var length = array2 == null ? 0 : array2.length, result2 = baseAt(array2, indexes); + var length2 = array2 == null ? 0 : array2.length, result2 = baseAt(array2, indexes); basePullAt(array2, arrayMap2(indexes, function(index) { - return isIndex2(index, length) ? +index : index; + return isIndex2(index, length2) ? +index : index; }).sort(compareAscending)); return result2; }); @@ -10197,9 +8114,9 @@ if (!(array2 && array2.length)) { return result2; } - var index = -1, indexes = [], length = array2.length; + var index = -1, indexes = [], length2 = array2.length; predicate = getIteratee(predicate, 3); - while (++index < length) { + while (++index < length2) { var value = array2[index]; if (predicate(value, index, array2)) { result2.push(value); @@ -10213,16 +8130,16 @@ return array2 == null ? array2 : nativeReverse.call(array2); } function slice(array2, start2, end) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return []; } if (end && typeof end != "number" && isIterateeCall(array2, start2, end)) { start2 = 0; - end = length; + end = length2; } else { start2 = start2 == null ? 0 : toInteger(start2); - end = end === undefined2 ? length : toInteger(end); + end = end === undefined2 ? length2 : toInteger(end); } return baseSlice(array2, start2, end); } @@ -10233,10 +8150,10 @@ return baseSortedIndexBy(array2, value, getIteratee(iteratee2, 2)); } function sortedIndexOf(array2, value) { - var length = array2 == null ? 0 : array2.length; - if (length) { + var length2 = array2 == null ? 0 : array2.length; + if (length2) { var index = baseSortedIndex(array2, value); - if (index < length && eq2(array2[index], value)) { + if (index < length2 && eq2(array2[index], value)) { return index; } } @@ -10249,8 +8166,8 @@ return baseSortedIndexBy(array2, value, getIteratee(iteratee2, 2), true); } function sortedLastIndexOf(array2, value) { - var length = array2 == null ? 0 : array2.length; - if (length) { + var length2 = array2 == null ? 0 : array2.length; + if (length2) { var index = baseSortedIndex(array2, value, true) - 1; if (eq2(array2[index], value)) { return index; @@ -10265,8 +8182,8 @@ return array2 && array2.length ? baseSortedUniq(array2, getIteratee(iteratee2, 2)) : []; } function tail(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseSlice(array2, 1, length) : []; + var length2 = array2 == null ? 0 : array2.length; + return length2 ? baseSlice(array2, 1, length2) : []; } function take(array2, n3, guard) { if (!(array2 && array2.length)) { @@ -10276,13 +8193,13 @@ return baseSlice(array2, 0, n3 < 0 ? 0 : n3); } function takeRight(array2, n3, guard) { - var length = array2 == null ? 0 : array2.length; - if (!length) { + var length2 = array2 == null ? 0 : array2.length; + if (!length2) { return []; } n3 = guard || n3 === undefined2 ? 1 : toInteger(n3); - n3 = length - n3; - return baseSlice(array2, n3 < 0 ? 0 : n3, length); + n3 = length2 - n3; + return baseSlice(array2, n3 < 0 ? 0 : n3, length2); } function takeRightWhile(array2, predicate) { return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), false, true) : []; @@ -10290,7 +8207,7 @@ function takeWhile(array2, predicate) { return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3)) : []; } - var union = baseRest(function(arrays) { + var union2 = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); var unionBy = baseRest(function(arrays) { @@ -10319,14 +8236,14 @@ if (!(array2 && array2.length)) { return []; } - var length = 0; + var length2 = 0; array2 = arrayFilter2(array2, function(group) { if (isArrayLikeObject(group)) { - length = nativeMax2(group.length, length); + length2 = nativeMax2(group.length, length2); return true; } }); - return baseTimes2(length, function(index) { + return baseTimes2(length2, function(index) { return arrayMap2(array2, baseProperty(index)); }); } @@ -10368,7 +8285,7 @@ return baseZipObject(props || [], values2 || [], baseSet); } var zipWith = baseRest(function(arrays) { - var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined2; + var length2 = arrays.length, iteratee2 = length2 > 1 ? arrays[length2 - 1] : undefined2; iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined2; return unzipWith(arrays, iteratee2); }); @@ -10385,20 +8302,20 @@ return interceptor(value); } var wrapperAt = flatRest(function(paths) { - var length = paths.length, start2 = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { + var length2 = paths.length, start2 = length2 ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; - if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex2(start2)) { + if (length2 > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex2(start2)) { return this.thru(interceptor); } - value = value.slice(start2, +start2 + (length ? 1 : 0)); + value = value.slice(start2, +start2 + (length2 ? 1 : 0)); value.__actions__.push({ "func": thru, "args": [interceptor], "thisArg": undefined2 }); return new LodashWrapper(value, this.__chain__).thru(function(array2) { - if (length && !array2.length) { + if (length2 && !array2.length) { array2.push(undefined2); } return array2; @@ -10423,15 +8340,15 @@ function wrapperPlant(value) { var result2, parent2 = this; while (parent2 instanceof baseLodash) { - var clone2 = wrapperClone(parent2); - clone2.__index__ = 0; - clone2.__values__ = undefined2; + var clone3 = wrapperClone(parent2); + clone3.__index__ = 0; + clone3.__values__ = undefined2; if (result2) { - previous.__wrapped__ = clone2; + previous.__wrapped__ = clone3; } else { - result2 = clone2; + result2 = clone3; } - var previous = clone2; + var previous = clone3; parent2 = parent2.__wrapped__; } previous.__wrapped__ = value; @@ -10505,11 +8422,11 @@ function includes(collection, value, fromIndex, guard) { collection = isArrayLike2(collection) ? collection : values(collection); fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; - var length = collection.length; + var length2 = collection.length; if (fromIndex < 0) { - fromIndex = nativeMax2(length + fromIndex, 0); + fromIndex = nativeMax2(length2 + fromIndex, 0); } - return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; + return isString(collection) ? fromIndex <= length2 && collection.indexOf(value, fromIndex) > -1 : !!length2 && baseIndexOf(collection, value, fromIndex) > -1; } var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == "function", result2 = isArrayLike2(collection) ? Array2(collection.length) : []; @@ -10579,8 +8496,8 @@ if (isArrayLike2(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } - var tag = getTag2(collection); - if (tag == mapTag4 || tag == setTag4) { + var tag2 = getTag2(collection); + if (tag2 == mapTag4 || tag2 == setTag4) { return collection.size; } return baseKeys2(collection).length; @@ -10596,10 +8513,10 @@ if (collection == null) { return []; } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + var length2 = iteratees.length; + if (length2 > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + } else if (length2 > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); @@ -10800,8 +8717,8 @@ transforms = transforms.length == 1 && isArray2(transforms[0]) ? arrayMap2(transforms[0], baseUnary2(getIteratee())) : arrayMap2(baseFlatten(transforms, 1), baseUnary2(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { - var index = -1, length = nativeMin2(args.length, funcsLength); - while (++index < length) { + var index = -1, length2 = nativeMin2(args.length, funcsLength); + while (++index < length2) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); @@ -10866,7 +8783,7 @@ var value = arguments[0]; return isArray2(value) ? value : [value]; } - function clone(value) { + function clone2(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } function cloneWith(value, customizer) { @@ -10890,7 +8807,7 @@ var gte = createRelationalOperation(function(value, other) { return value >= other; }); - var isArguments2 = baseIsArguments2(function() { + var isArguments2 = baseIsArguments2(/* @__PURE__ */ function() { return arguments; }()) ? baseIsArguments2 : function(value) { return isObjectLike2(value) && hasOwnProperty10.call(value, "callee") && !propertyIsEnumerable3.call(value, "callee"); @@ -10918,8 +8835,8 @@ if (isArrayLike2(value) && (isArray2(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer2(value) || isTypedArray2(value) || isArguments2(value))) { return !value.length; } - var tag = getTag2(value); - if (tag == mapTag4 || tag == setTag4) { + var tag2 = getTag2(value); + if (tag2 == mapTag4 || tag2 == setTag4) { return !value.size; } if (isPrototype2(value)) { @@ -10944,8 +8861,8 @@ if (!isObjectLike2(value)) { return false; } - var tag = baseGetTag2(value); - return tag == errorTag3 || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value); + var tag2 = baseGetTag2(value); + return tag2 == errorTag3 || tag2 == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value); } function isFinite2(value) { return typeof value == "number" && nativeIsFinite(value); @@ -10954,14 +8871,14 @@ if (!isObject3(value)) { return false; } - var tag = baseGetTag2(value); - return tag == funcTag3 || tag == genTag2 || tag == asyncTag2 || tag == proxyTag2; + var tag2 = baseGetTag2(value); + return tag2 == funcTag3 || tag2 == genTag2 || tag2 == asyncTag2 || tag2 == proxyTag2; } function isInteger(value) { return typeof value == "number" && value == toInteger(value); } function isLength2(value) { - return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER3; + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER4; } function isObject3(value) { var type2 = typeof value; @@ -11009,7 +8926,7 @@ } var isRegExp = nodeIsRegExp ? baseUnary2(nodeIsRegExp) : baseIsRegExp; function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER3 && value <= MAX_SAFE_INTEGER3; + return isInteger(value) && value >= -MAX_SAFE_INTEGER4 && value <= MAX_SAFE_INTEGER4; } var isSet = nodeIsSet ? baseUnary2(nodeIsSet) : baseIsSet; function isString(value) { @@ -11042,7 +8959,7 @@ if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } - var tag = getTag2(value), func = tag == mapTag4 ? mapToArray2 : tag == setTag4 ? setToArray2 : values; + var tag2 = getTag2(value), func = tag2 == mapTag4 ? mapToArray2 : tag2 == setTag4 ? setToArray2 : values; return func(value); } function toFinite(value) { @@ -11085,7 +9002,7 @@ return copyObject(value, keysIn(value)); } function toSafeInteger(value) { - return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER3, MAX_SAFE_INTEGER3) : value === 0 ? value : 0; + return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER4, MAX_SAFE_INTEGER4) : value === 0 ? value : 0; } function toString2(value) { return value == null ? "" : baseToString2(value); @@ -11118,12 +9035,12 @@ var defaults = baseRest(function(object, sources) { object = Object2(object); var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined2; + var length2 = sources.length; + var guard = length2 > 2 ? sources[2] : undefined2; if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; + length2 = 1; } - while (++index < length) { + while (++index < length2) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; @@ -11236,9 +9153,9 @@ if (isDeep) { result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } - var length = paths.length; - while (length--) { - baseUnset(result2, paths[length]); + var length2 = paths.length; + while (length2--) { + baseUnset(result2, paths[length2]); } return result2; }); @@ -11262,22 +9179,22 @@ } function result(object, path, defaultValue) { path = castPath(path, object); - var index = -1, length = path.length; - if (!length) { - length = 1; + var index = -1, length2 = path.length; + if (!length2) { + length2 = 1; object = undefined2; } - while (++index < length) { + while (++index < length2) { var value = object == null ? undefined2 : object[toKey(path[index])]; if (value === undefined2) { - index = length; + index = length2; value = defaultValue; } object = isFunction2(value) ? value.call(object) : value; } return object; } - function set3(object, path, value) { + function set4(object, path, value) { return object == null ? object : baseSet(object, path, value); } function setWith(object, path, value, customizer) { @@ -11396,8 +9313,8 @@ function endsWith(string, target, position) { string = toString2(string); target = baseToString2(target); - var length = string.length; - position = position === undefined2 ? length : baseClamp(toInteger(position), 0, length); + var length2 = string.length; + position = position === undefined2 ? length2 : baseClamp(toInteger(position), 0, length2); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; @@ -11417,27 +9334,27 @@ return result2 + (index ? " " : "") + word.toLowerCase(); }); var lowerFirst = createCaseFirst("toLowerCase"); - function pad2(string, length, chars) { + function pad2(string, length2, chars) { string = toString2(string); - length = toInteger(length); - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { + length2 = toInteger(length2); + var strLength = length2 ? stringSize(string) : 0; + if (!length2 || strLength >= length2) { return string; } - var mid = (length - strLength) / 2; + var mid = (length2 - strLength) / 2; return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); } - function padEnd(string, length, chars) { + function padEnd(string, length2, chars) { string = toString2(string); - length = toInteger(length); - var strLength = length ? stringSize(string) : 0; - return length && strLength < length ? string + createPadding(length - strLength, chars) : string; + length2 = toInteger(length2); + var strLength = length2 ? stringSize(string) : 0; + return length2 && strLength < length2 ? string + createPadding(length2 - strLength, chars) : string; } - function padStart(string, length, chars) { + function padStart(string, length2, chars) { string = toString2(string); - length = toInteger(length); - var strLength = length ? stringSize(string) : 0; - return length && strLength < length ? createPadding(length - strLength, chars) + string : string; + length2 = toInteger(length2); + var strLength = length2 ? stringSize(string) : 0; + return length2 && strLength < length2 ? createPadding(length2 - strLength, chars) + string : string; } function parseInt2(string, radix, guard) { if (guard || radix == null) { @@ -11577,10 +9494,10 @@ return castSlice(strSymbols, start2).join(""); } function truncate(string, options2) { - var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; + var length2 = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject3(options2)) { var separator = "separator" in options2 ? options2.separator : separator; - length = "length" in options2 ? toInteger(options2.length) : length; + length2 = "length" in options2 ? toInteger(options2.length) : length2; omission = "omission" in options2 ? baseToString2(options2.omission) : omission; } string = toString2(string); @@ -11589,10 +9506,10 @@ var strSymbols = stringToArray(string); strLength = strSymbols.length; } - if (length >= strLength) { + if (length2 >= strLength) { return string; } - var end = length - stringSize(omission); + var end = length2 - stringSize(omission); if (end < 1) { return omission; } @@ -11623,7 +9540,7 @@ } return result2 + omission; } - function unescape4(string) { + function unescape3(string) { string = toString2(string); return string && reHasEscapedHtml2.test(string) ? string.replace(reEscapedHtml2, unescapeHtmlChar2) : string; } @@ -11654,8 +9571,8 @@ return object; }); function cond(pairs2) { - var length = pairs2 == null ? 0 : pairs2.length, toIteratee = getIteratee(); - pairs2 = !length ? [] : arrayMap2(pairs2, function(pair3) { + var length2 = pairs2 == null ? 0 : pairs2.length, toIteratee = getIteratee(); + pairs2 = !length2 ? [] : arrayMap2(pairs2, function(pair3) { if (typeof pair3[1] != "function") { throw new TypeError2(FUNC_ERROR_TEXT3); } @@ -11663,7 +9580,7 @@ }); return baseRest(function(args) { var index = -1; - while (++index < length) { + while (++index < length2) { var pair3 = pairs2[index]; if (apply(pair3[0], this, args)) { return apply(pair3[1], this, args); @@ -11777,13 +9694,13 @@ } function times(n3, iteratee2) { n3 = toInteger(n3); - if (n3 < 1 || n3 > MAX_SAFE_INTEGER3) { + if (n3 < 1 || n3 > MAX_SAFE_INTEGER4) { return []; } - var index = MAX_ARRAY_LENGTH, length = nativeMin2(n3, MAX_ARRAY_LENGTH); + var index = MAX_ARRAY_LENGTH, length2 = nativeMin2(n3, MAX_ARRAY_LENGTH); iteratee2 = getIteratee(iteratee2); n3 -= MAX_ARRAY_LENGTH; - var result2 = baseTimes2(length, iteratee2); + var result2 = baseTimes2(length2, iteratee2); while (++index < n3) { iteratee2(index); } @@ -11866,7 +9783,7 @@ lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; - lodash.difference = difference; + lodash.difference = difference2; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; @@ -11889,7 +9806,7 @@ lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; - lodash.intersection = intersection; + lodash.intersection = intersection2; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; @@ -11940,7 +9857,7 @@ lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; - lodash.set = set3; + lodash.set = set4; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; @@ -11964,7 +9881,7 @@ lodash.toPlainObject = toPlainObject; lodash.transform = transform2; lodash.unary = unary; - lodash.union = union; + lodash.union = union2; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; @@ -11998,7 +9915,7 @@ lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp3; - lodash.clone = clone; + lodash.clone = clone2; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; @@ -12137,7 +10054,7 @@ lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; - lodash.unescape = unescape4; + lodash.unescape = unescape3; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; @@ -12339,12 +10256,12 @@ if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") { if (a2.constructor !== b2.constructor) return false; - var length, i3, keys2; + var length2, i3, keys2; if (Array.isArray(a2)) { - length = a2.length; - if (length != b2.length) + length2 = a2.length; + if (length2 != b2.length) return false; - for (i3 = length; i3-- !== 0; ) + for (i3 = length2; i3-- !== 0; ) if (!equal(a2[i3], b2[i3])) return false; return true; @@ -12356,13 +10273,13 @@ if (a2.toString !== Object.prototype.toString) return a2.toString() === b2.toString(); keys2 = Object.keys(a2); - length = keys2.length; - if (length !== Object.keys(b2).length) + length2 = keys2.length; + if (length2 !== Object.keys(b2).length) return false; - for (i3 = length; i3-- !== 0; ) + for (i3 = length2; i3-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b2, keys2[i3])) return false; - for (i3 = length; i3-- !== 0; ) { + for (i3 = length2; i3-- !== 0; ) { var key = keys2[i3]; if (!equal(a2[key], b2[key])) return false; @@ -12385,7 +10302,7 @@ !function t4(n4, r4, e6, a4, h4) { for (; a4 > e6; ) { if (a4 - e6 > 600) { - var o3 = a4 - e6 + 1, s3 = r4 - e6 + 1, l3 = Math.log(o3), f4 = 0.5 * Math.exp(2 * l3 / 3), u3 = 0.5 * Math.sqrt(l3 * f4 * (o3 - f4) / o3) * (s3 - o3 / 2 < 0 ? -1 : 1), m3 = Math.max(e6, Math.floor(r4 - s3 * f4 / o3 + u3)), c3 = Math.min(a4, Math.floor(r4 + (o3 - s3) * f4 / o3 + u3)); + var o3 = a4 - e6 + 1, s3 = r4 - e6 + 1, l3 = Math.log(o3), f3 = 0.5 * Math.exp(2 * l3 / 3), u3 = 0.5 * Math.sqrt(l3 * f3 * (o3 - f3) / o3) * (s3 - o3 / 2 < 0 ? -1 : 1), m3 = Math.max(e6, Math.floor(r4 - s3 * f3 / o3 + u3)), c3 = Math.min(a4, Math.floor(r4 + (o3 - s3) * f3 / o3 + u3)); t4(n4, r4, m3, c3, h4); } var p3 = n4[r4], d4 = e6, x2 = a4; @@ -12437,7 +10354,7 @@ function l2(t3, i4) { return t3.minY - i4.minY; } - function f3(t3) { + function f2(t3) { return (t3.maxX - t3.minX) * (t3.maxY - t3.minY); } function u2(t3) { @@ -12520,9 +10437,9 @@ return this; for (var n4, r3, a3, h3 = this.data, o3 = this.toBBox(t3), s3 = [], l3 = []; h3 || s3.length; ) { if (h3 || (h3 = s3.pop(), r3 = s3[s3.length - 1], n4 = l3.pop(), a3 = true), h3.leaf) { - var f4 = e3(t3, h3.children, i4); - if (-1 !== f4) - return h3.children.splice(f4, 1), s3.push(h3), this._condense(s3), this; + var f3 = e3(t3, h3.children, i4); + if (-1 !== f3) + return h3.children.splice(f3, 1), s3.push(h3), this._condense(s3), this; } a3 || h3.leaf || !m2(h3, o3) ? r3 ? (n4++, h3 = r3.children[n4], a3 = false) : h3 = null : (s3.push(h3), l3.push(n4), n4 = 0, r3 = h3, h3 = h3.children[0]); } @@ -12548,10 +10465,10 @@ r3 || (r3 = Math.ceil(Math.log(h3) / Math.log(o3)), o3 = Math.ceil(h3 / Math.pow(o3, r3 - 1))), (e4 = p2([])).leaf = false, e4.height = r3; var s3 = Math.ceil(h3 / o3), l3 = s3 * Math.ceil(Math.sqrt(o3)); d2(t3, i4, n4, l3, this.compareMinX); - for (var f4 = i4; f4 <= n4; f4 += l3) { - var u3 = Math.min(f4 + l3 - 1, n4); - d2(t3, f4, u3, s3, this.compareMinY); - for (var m3 = f4; m3 <= u3; m3 += s3) { + for (var f3 = i4; f3 <= n4; f3 += l3) { + var u3 = Math.min(f3 + l3 - 1, n4); + d2(t3, f3, u3, s3, this.compareMinY); + for (var m3 = f3; m3 <= u3; m3 += s3) { var c3 = Math.min(m3 + s3 - 1, u3); e4.children.push(this._build(t3, m3, c3, r3 - 1)); } @@ -12560,7 +10477,7 @@ }, r2.prototype._chooseSubtree = function(t3, i4, n4, r3) { for (; r3.push(i4), !i4.leaf && r3.length - 1 !== n4; ) { for (var e4 = 1 / 0, a3 = 1 / 0, h3 = void 0, o3 = 0; o3 < i4.children.length; o3++) { - var s3 = i4.children[o3], l3 = f3(s3), u3 = (m3 = t3, c3 = s3, (Math.max(c3.maxX, m3.maxX) - Math.min(c3.minX, m3.minX)) * (Math.max(c3.maxY, m3.maxY) - Math.min(c3.minY, m3.minY)) - l3); + var s3 = i4.children[o3], l3 = f2(s3), u3 = (m3 = t3, c3 = s3, (Math.max(c3.maxX, m3.maxX) - Math.min(c3.minX, m3.minX)) * (Math.max(c3.maxY, m3.maxY) - Math.min(c3.minY, m3.minY)) - l3); u3 < a3 ? (a3 = u3, e4 = l3 < e4 ? l3 : e4, h3 = s3) : u3 === a3 && l3 < e4 && (e4 = l3, h3 = s3); } i4 = h3 || i4.children[0]; @@ -12581,7 +10498,7 @@ this.data = p2([t3, i4]), this.data.height = t3.height + 1, this.data.leaf = false, a2(this.data, this.toBBox); }, r2.prototype._chooseSplitIndex = function(t3, i4, n4) { for (var r3, e4, a3, o3, s3, l3, u3, m3 = 1 / 0, c3 = 1 / 0, p3 = i4; p3 <= n4 - i4; p3++) { - var d4 = h2(t3, 0, p3, this.toBBox), x2 = h2(t3, p3, n4, this.toBBox), v2 = (e4 = d4, a3 = x2, o3 = void 0, s3 = void 0, l3 = void 0, u3 = void 0, o3 = Math.max(e4.minX, a3.minX), s3 = Math.max(e4.minY, a3.minY), l3 = Math.min(e4.maxX, a3.maxX), u3 = Math.min(e4.maxY, a3.maxY), Math.max(0, l3 - o3) * Math.max(0, u3 - s3)), M2 = f3(d4) + f3(x2); + var d4 = h2(t3, 0, p3, this.toBBox), x2 = h2(t3, p3, n4, this.toBBox), v2 = (e4 = d4, a3 = x2, o3 = void 0, s3 = void 0, l3 = void 0, u3 = void 0, o3 = Math.max(e4.minX, a3.minX), s3 = Math.max(e4.minY, a3.minY), l3 = Math.min(e4.maxX, a3.maxX), u3 = Math.min(e4.maxY, a3.maxY), Math.max(0, l3 - o3) * Math.max(0, u3 - s3)), M2 = f2(d4) + f2(x2); v2 < m3 ? (m3 = v2, r3 = p3, c3 = M2 < c3 ? M2 : c3) : v2 === m3 && M2 < c3 && (c3 = M2, r3 = p3); } return r3 || n4 - i4; @@ -12590,8 +10507,8 @@ this._allDistMargin(t3, i4, n4, r3) < this._allDistMargin(t3, i4, n4, e4) && t3.children.sort(r3); }, r2.prototype._allDistMargin = function(t3, i4, n4, r3) { t3.children.sort(r3); - for (var e4 = this.toBBox, a3 = h2(t3, 0, i4, e4), s3 = h2(t3, n4 - i4, n4, e4), l3 = u2(a3) + u2(s3), f4 = i4; f4 < n4 - i4; f4++) { - var m3 = t3.children[f4]; + for (var e4 = this.toBBox, a3 = h2(t3, 0, i4, e4), s3 = h2(t3, n4 - i4, n4, e4), l3 = u2(a3) + u2(s3), f3 = i4; f3 < n4 - i4; f3++) { + var m3 = t3.children[f3]; o2(a3, t3.leaf ? e4(m3) : m3), l3 += u2(a3); } for (var c3 = n4 - i4 - 1; c3 >= i4; c3--) { @@ -12721,9 +10638,9 @@ readFields: function(readField, result, end) { end = end || this.length; while (this.pos < end) { - var val = this.readVarint(), tag = val >> 3, startPos = this.pos; + var val = this.readVarint(), tag2 = val >> 3, startPos = this.pos; this.type = val & 7; - readField(tag, result, this); + readField(tag2, result, this); if (this.pos === startPos) this.skip(val); } @@ -12906,18 +10823,18 @@ throw new Error("Unimplemented type: " + type2); }, // === WRITING ================================================================= - writeTag: function(tag, type2) { - this.writeVarint(tag << 3 | type2); + writeTag: function(tag2, type2) { + this.writeVarint(tag2 << 3 | type2); }, realloc: function(min3) { - var length = this.length || 16; - while (length < this.pos + min3) - length *= 2; - if (length !== this.length) { - var buf = new Uint8Array(length); + var length2 = this.length || 16; + while (length2 < this.pos + min3) + length2 *= 2; + if (length2 !== this.length) { + var buf = new Uint8Array(length2); buf.set(this.buf); this.buf = buf; - this.length = length; + this.length = length2; } }, finish: function() { @@ -12971,12 +10888,12 @@ writeBoolean: function(val) { this.writeVarint(Boolean(val)); }, - writeString: function(str2) { - str2 = String(str2); - this.realloc(str2.length * 4); + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); this.pos++; var startPos = this.pos; - this.pos = writeUtf8(this.buf, str2, this.pos); + this.pos = writeUtf8(this.buf, str, this.pos); var len = this.pos - startPos; if (len >= 128) makeRoomForExtraLength(startPos, len, this); @@ -13012,88 +10929,88 @@ this.writeVarint(len); this.pos += len; }, - writeMessage: function(tag, fn, obj) { - this.writeTag(tag, Pbf.Bytes); + writeMessage: function(tag2, fn, obj) { + this.writeTag(tag2, Pbf.Bytes); this.writeRawMessage(fn, obj); }, - writePackedVarint: function(tag, arr) { + writePackedVarint: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedVarint, arr); + this.writeMessage(tag2, writePackedVarint, arr); }, - writePackedSVarint: function(tag, arr) { + writePackedSVarint: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedSVarint, arr); + this.writeMessage(tag2, writePackedSVarint, arr); }, - writePackedBoolean: function(tag, arr) { + writePackedBoolean: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedBoolean, arr); + this.writeMessage(tag2, writePackedBoolean, arr); }, - writePackedFloat: function(tag, arr) { + writePackedFloat: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedFloat, arr); + this.writeMessage(tag2, writePackedFloat, arr); }, - writePackedDouble: function(tag, arr) { + writePackedDouble: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedDouble, arr); + this.writeMessage(tag2, writePackedDouble, arr); }, - writePackedFixed32: function(tag, arr) { + writePackedFixed32: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedFixed32, arr); + this.writeMessage(tag2, writePackedFixed32, arr); }, - writePackedSFixed32: function(tag, arr) { + writePackedSFixed32: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedSFixed32, arr); + this.writeMessage(tag2, writePackedSFixed32, arr); }, - writePackedFixed64: function(tag, arr) { + writePackedFixed64: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedFixed64, arr); + this.writeMessage(tag2, writePackedFixed64, arr); }, - writePackedSFixed64: function(tag, arr) { + writePackedSFixed64: function(tag2, arr) { if (arr.length) - this.writeMessage(tag, writePackedSFixed64, arr); + this.writeMessage(tag2, writePackedSFixed64, arr); }, - writeBytesField: function(tag, buffer) { - this.writeTag(tag, Pbf.Bytes); + writeBytesField: function(tag2, buffer) { + this.writeTag(tag2, Pbf.Bytes); this.writeBytes(buffer); }, - writeFixed32Field: function(tag, val) { - this.writeTag(tag, Pbf.Fixed32); + writeFixed32Field: function(tag2, val) { + this.writeTag(tag2, Pbf.Fixed32); this.writeFixed32(val); }, - writeSFixed32Field: function(tag, val) { - this.writeTag(tag, Pbf.Fixed32); + writeSFixed32Field: function(tag2, val) { + this.writeTag(tag2, Pbf.Fixed32); this.writeSFixed32(val); }, - writeFixed64Field: function(tag, val) { - this.writeTag(tag, Pbf.Fixed64); + writeFixed64Field: function(tag2, val) { + this.writeTag(tag2, Pbf.Fixed64); this.writeFixed64(val); }, - writeSFixed64Field: function(tag, val) { - this.writeTag(tag, Pbf.Fixed64); + writeSFixed64Field: function(tag2, val) { + this.writeTag(tag2, Pbf.Fixed64); this.writeSFixed64(val); }, - writeVarintField: function(tag, val) { - this.writeTag(tag, Pbf.Varint); + writeVarintField: function(tag2, val) { + this.writeTag(tag2, Pbf.Varint); this.writeVarint(val); }, - writeSVarintField: function(tag, val) { - this.writeTag(tag, Pbf.Varint); + writeSVarintField: function(tag2, val) { + this.writeTag(tag2, Pbf.Varint); this.writeSVarint(val); }, - writeStringField: function(tag, str2) { - this.writeTag(tag, Pbf.Bytes); - this.writeString(str2); + writeStringField: function(tag2, str) { + this.writeTag(tag2, Pbf.Bytes); + this.writeString(str); }, - writeFloatField: function(tag, val) { - this.writeTag(tag, Pbf.Fixed32); + writeFloatField: function(tag2, val) { + this.writeTag(tag2, Pbf.Fixed32); this.writeFloat(val); }, - writeDoubleField: function(tag, val) { - this.writeTag(tag, Pbf.Fixed64); + writeDoubleField: function(tag2, val) { + this.writeTag(tag2, Pbf.Fixed64); this.writeDouble(val); }, - writeBooleanField: function(tag, val) { - this.writeVarintField(tag, Boolean(val)); + writeBooleanField: function(tag2, val) { + this.writeVarintField(tag2, Boolean(val)); } }; function readVarintRemainder(l2, s2, p2) { @@ -13240,7 +11157,7 @@ return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + (buf[pos + 3] << 24); } function readUtf8(buf, pos, end) { - var str2 = ""; + var str = ""; var i3 = pos; while (i3 < end) { var b0 = buf[i3]; @@ -13286,20 +11203,20 @@ bytesPerSequence = 1; } else if (c2 > 65535) { c2 -= 65536; - str2 += String.fromCharCode(c2 >>> 10 & 1023 | 55296); + str += String.fromCharCode(c2 >>> 10 & 1023 | 55296); c2 = 56320 | c2 & 1023; } - str2 += String.fromCharCode(c2); + str += String.fromCharCode(c2); i3 += bytesPerSequence; } - return str2; + return str; } function readUtf8TextDecoder(buf, pos, end) { return utf8TextDecoder.decode(buf.subarray(pos, end)); } - function writeUtf8(buf, str2, pos) { - for (var i3 = 0, c2, lead; i3 < str2.length; i3++) { - c2 = str2.charCodeAt(i3); + function writeUtf8(buf, str, pos) { + for (var i3 = 0, c2, lead; i3 < str.length; i3++) { + c2 = str.charCodeAt(i3); if (c2 > 55295 && c2 < 57344) { if (lead) { if (c2 < 56320) { @@ -13313,7 +11230,7 @@ lead = null; } } else { - if (c2 > 56319 || i3 + 1 === str2.length) { + if (c2 > 56319 || i3 + 1 === str.length) { buf[pos++] = 239; buf[pos++] = 191; buf[pos++] = 189; @@ -13642,14 +11559,14 @@ this._values = values; pbf.readFields(readFeature, this, end); } - function readFeature(tag, feature3, pbf) { - if (tag == 1) + function readFeature(tag2, feature3, pbf) { + if (tag2 == 1) feature3.id = pbf.readVarint(); - else if (tag == 2) + else if (tag2 == 2) readTag(pbf, feature3); - else if (tag == 3) + else if (tag2 == 3) feature3.type = pbf.readVarint(); - else if (tag == 4) + else if (tag2 == 4) feature3._geometry = pbf.pos; } function readTag(pbf, feature3) { @@ -13663,14 +11580,14 @@ VectorTileFeature.prototype.loadGeometry = function() { var pbf = this._pbf; pbf.pos = this._geometry; - var end = pbf.readVarint() + pbf.pos, cmd = 1, length = 0, x2 = 0, y2 = 0, lines = [], line; + var end = pbf.readVarint() + pbf.pos, cmd = 1, length2 = 0, x2 = 0, y2 = 0, lines = [], line; while (pbf.pos < end) { - if (length <= 0) { + if (length2 <= 0) { var cmdLen = pbf.readVarint(); cmd = cmdLen & 7; - length = cmdLen >> 3; + length2 = cmdLen >> 3; } - length--; + length2--; if (cmd === 1 || cmd === 2) { x2 += pbf.readSVarint(); y2 += pbf.readSVarint(); @@ -13695,14 +11612,14 @@ VectorTileFeature.prototype.bbox = function() { var pbf = this._pbf; pbf.pos = this._geometry; - var end = pbf.readVarint() + pbf.pos, cmd = 1, length = 0, x2 = 0, y2 = 0, x12 = Infinity, x22 = -Infinity, y12 = Infinity, y22 = -Infinity; + var end = pbf.readVarint() + pbf.pos, cmd = 1, length2 = 0, x2 = 0, y2 = 0, x12 = Infinity, x22 = -Infinity, y12 = Infinity, y22 = -Infinity; while (pbf.pos < end) { - if (length <= 0) { + if (length2 <= 0) { var cmdLen = pbf.readVarint(); cmd = cmdLen & 7; - length = cmdLen >> 3; + length2 = cmdLen >> 3; } - length--; + length2--; if (cmd === 1 || cmd === 2) { x2 += pbf.readSVarint(); y2 += pbf.readSVarint(); @@ -13721,11 +11638,11 @@ return [x12, y12, x22, y22]; }; VectorTileFeature.prototype.toGeoJSON = function(x2, y2, z2) { - var size = this.extent * Math.pow(2, z2), x05 = this.extent * x2, y05 = this.extent * y2, coords = this.loadGeometry(), type2 = VectorTileFeature.types[this.type], i3, j3; + var size = this.extent * Math.pow(2, z2), x05 = this.extent * x2, y05 = this.extent * y2, coords = this.loadGeometry(), type2 = VectorTileFeature.types[this.type], i3, j2; function project(line) { - for (var j4 = 0; j4 < line.length; j4++) { - var p2 = line[j4], y22 = 180 - (p2.y + y05) * 360 / size; - line[j4] = [ + for (var j3 = 0; j3 < line.length; j3++) { + var p2 = line[j3], y22 = 180 - (p2.y + y05) * 360 / size; + line[j3] = [ (p2.x + x05) * 360 / size - 180, 360 / Math.PI * Math.atan(Math.exp(y22 * Math.PI / 180)) - 90 ]; @@ -13748,8 +11665,8 @@ case 3: coords = classifyRings(coords); for (i3 = 0; i3 < coords.length; i3++) { - for (j3 = 0; j3 < coords[i3].length; j3++) { - project(coords[i3][j3]); + for (j2 = 0; j2 < coords[i3].length; j2++) { + project(coords[i3][j2]); } } break; @@ -13797,9 +11714,9 @@ } function signedArea(ring) { var sum = 0; - for (var i3 = 0, len = ring.length, j3 = len - 1, p1, p2; i3 < len; j3 = i3++) { + for (var i3 = 0, len = ring.length, j2 = len - 1, p1, p2; i3 < len; j2 = i3++) { p1 = ring[i3]; - p2 = ring[j3]; + p2 = ring[j2]; sum += (p2.x - p1.x) * (p1.y + p2.y); } return sum; @@ -13825,25 +11742,25 @@ pbf.readFields(readLayer, this, end); this.length = this._features.length; } - function readLayer(tag, layer, pbf) { - if (tag === 15) + function readLayer(tag2, layer, pbf) { + if (tag2 === 15) layer.version = pbf.readVarint(); - else if (tag === 1) + else if (tag2 === 1) layer.name = pbf.readString(); - else if (tag === 5) + else if (tag2 === 5) layer.extent = pbf.readVarint(); - else if (tag === 2) + else if (tag2 === 2) layer._features.push(pbf.pos); - else if (tag === 3) + else if (tag2 === 3) layer._keys.push(pbf.readString()); - else if (tag === 4) + else if (tag2 === 4) layer._values.push(readValueMessage(pbf)); } function readValueMessage(pbf) { var value = null, end = pbf.readVarint() + pbf.pos; while (pbf.pos < end) { - var tag = pbf.readVarint() >> 3; - value = tag === 1 ? pbf.readString() : tag === 2 ? pbf.readFloat() : tag === 3 ? pbf.readDouble() : tag === 4 ? pbf.readVarint64() : tag === 5 ? pbf.readVarint() : tag === 6 ? pbf.readSVarint() : tag === 7 ? pbf.readBoolean() : null; + var tag2 = pbf.readVarint() >> 3; + value = tag2 === 1 ? pbf.readString() : tag2 === 2 ? pbf.readFloat() : tag2 === 3 ? pbf.readDouble() : tag2 === 4 ? pbf.readVarint64() : tag2 === 5 ? pbf.readVarint() : tag2 === 6 ? pbf.readSVarint() : tag2 === 7 ? pbf.readBoolean() : null; } return value; } @@ -13866,8 +11783,8 @@ function VectorTile3(pbf, end) { this.layers = pbf.readFields(readTile, {}, end); } - function readTile(tag, layers, pbf) { - if (tag === 3) { + function readTile(tag2, layers, pbf) { + if (tag2 === 3) { var layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos); if (layer.length) layers[layer.name] = layer; @@ -13895,12 +11812,12 @@ if (typeof opts === "function") opts = { cmp: opts }; var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false; - var cmp = opts.cmp && function(f3) { + var cmp = opts.cmp && /* @__PURE__ */ function(f2) { return function(node) { return function(a2, b2) { var aobj = { key: a2, value: node[a2] }; var bobj = { key: b2, value: node[b2] }; - return f3(aobj, bobj); + return f2(aobj, bobj); }; }; }(opts.cmp); @@ -14043,854 +11960,2281 @@ } }); - // node_modules/store/src/util.js - var require_util = __commonJS({ - "node_modules/store/src/util.js"(exports2, module2) { - var assign = make_assign(); - var create2 = make_create(); - var trim = make_trim(); - var Global = typeof window !== "undefined" ? window : global; - module2.exports = { - assign, - create: create2, - trim, - bind, - slice, - each, - map: map2, - pluck, - isList, - isFunction: isFunction2, - isObject: isObject3, - Global - }; - function make_assign() { - if (Object.assign) { - return Object.assign; - } else { - return function shimAssign(obj, props1, props2, etc) { - for (var i3 = 1; i3 < arguments.length; i3++) { - each(Object(arguments[i3]), function(val, key) { - obj[key] = val; - }); - } - return obj; - }; - } - } - function make_create() { - if (Object.create) { - return function create3(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - return assign.apply(this, [Object.create(obj)].concat(assignArgsList)); - }; - } else { - let F3 = function() { - }; - var F2 = F3; - return function create3(obj, assignProps1, assignProps2, etc) { - var assignArgsList = slice(arguments, 1); - F3.prototype = obj; - return assign.apply(this, [new F3()].concat(assignArgsList)); - }; - } - } - function make_trim() { - if (String.prototype.trim) { - return function trim2(str2) { - return String.prototype.trim.call(str2); - }; - } else { - return function trim2(str2) { - return str2.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); - }; - } - } - function bind(obj, fn) { - return function() { - return fn.apply(obj, Array.prototype.slice.call(arguments, 0)); - }; - } - function slice(arr, index) { - return Array.prototype.slice.call(arr, index || 0); - } - function each(obj, fn) { - pluck(obj, function(val, key) { - fn(val, key); - return false; - }); - } - function map2(obj, fn) { - var res = isList(obj) ? [] : {}; - pluck(obj, function(v2, k2) { - res[k2] = fn(v2, k2); - return false; - }); - return res; - } - function pluck(obj, fn) { - if (isList(obj)) { - for (var i3 = 0; i3 < obj.length; i3++) { - if (fn(obj[i3], i3)) { - return obj[i3]; - } + // node_modules/polygon-clipping/dist/polygon-clipping.umd.js + var require_polygon_clipping_umd = __commonJS({ + "node_modules/polygon-clipping/dist/polygon-clipping.umd.js"(exports2, module2) { + (function(global2, factory) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.polygonClipping = factory()); + })(exports2, function() { + "use strict"; + function __generator(thisArg, body) { + var _2 = { + label: 0, + sent: function() { + if (t2[0] & 1) + throw t2[1]; + return t2[1]; + }, + trys: [], + ops: [] + }, f2, y2, t2, g3; + return g3 = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() { + return this; + }), g3; + function verb(n3) { + return function(v2) { + return step([n3, v2]); + }; } - } else { - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - if (fn(obj[key], key)) { - return obj[key]; + function step(op) { + if (f2) + throw new TypeError("Generator is already executing."); + while (_2) + try { + if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) + return t2; + if (y2 = 0, t2) + op = [op[0] & 2, t2.value]; + switch (op[0]) { + case 0: + case 1: + t2 = op; + break; + case 4: + _2.label++; + return { + value: op[1], + done: false + }; + case 5: + _2.label++; + y2 = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; + } + if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { + _2.label = op[1]; + break; + } + if (op[0] === 6 && _2.label < t2[1]) { + _2.label = t2[1]; + t2 = op; + break; + } + if (t2 && _2.label < t2[2]) { + _2.label = t2[2]; + _2.ops.push(op); + break; + } + if (t2[2]) + _2.ops.pop(); + _2.trys.pop(); + continue; + } + op = body.call(thisArg, _2); + } catch (e3) { + op = [6, e3]; + y2 = 0; + } finally { + f2 = t2 = 0; } - } + if (op[0] & 5) + throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; } } - } - function isList(val) { - return val != null && typeof val != "function" && typeof val.length == "number"; - } - function isFunction2(val) { - return val && {}.toString.call(val) === "[object Function]"; - } - function isObject3(val) { - return val && {}.toString.call(val) === "[object Object]"; - } - } - }); - - // node_modules/store/src/store-engine.js - var require_store_engine = __commonJS({ - "node_modules/store/src/store-engine.js"(exports2, module2) { - var util = require_util(); - var slice = util.slice; - var pluck = util.pluck; - var each = util.each; - var bind = util.bind; - var create2 = util.create; - var isList = util.isList; - var isFunction2 = util.isFunction; - var isObject3 = util.isObject; - module2.exports = { - createStore - }; - var storeAPI = { - version: "2.0.12", - enabled: false, - // get returns the value of the given key. If that value - // is undefined, it returns optionalDefaultValue instead. - get: function(key, optionalDefaultValue) { - var data = this.storage.read(this._namespacePrefix + key); - return this._deserialize(data, optionalDefaultValue); - }, - // set will store the given value at key and returns value. - // Calling set with value === undefined is equivalent to calling remove. - set: function(key, value) { - if (value === void 0) { - return this.remove(key); - } - this.storage.write(this._namespacePrefix + key, this._serialize(value)); - return value; - }, - // remove deletes the key and value stored at the given key. - remove: function(key) { - this.storage.remove(this._namespacePrefix + key); - }, - // each will call the given callback once for each key-value pair - // in this store. - each: function(callback) { - var self2 = this; - this.storage.each(function(val, namespacedKey) { - callback.call(self2, self2._deserialize(val), (namespacedKey || "").replace(self2._namespaceRegexp, "")); - }); - }, - // clearAll will remove all the stored key-value pairs in this store. - clearAll: function() { - this.storage.clearAll(); - }, - // additional functionality that can't live in plugins - // --------------------------------------------------- - // hasNamespace returns true if this store instance has the given namespace. - hasNamespace: function(namespace) { - return this._namespacePrefix == "__storejs_" + namespace + "_"; - }, - // createStore creates a store.js instance with the first - // functioning storage in the list of storage candidates, - // and applies the the given mixins to the instance. - createStore: function() { - return createStore.apply(this, arguments); - }, - addPlugin: function(plugin) { - this._addPlugin(plugin); - }, - namespace: function(namespace) { - return createStore(this.storage, this.plugins, namespace); - } - }; - function _warn() { - var _console = typeof console == "undefined" ? null : console; - if (!_console) { - return; - } - var fn = _console.warn ? _console.warn : _console.log; - fn.apply(_console, arguments); - } - function createStore(storages, plugins, namespace) { - if (!namespace) { - namespace = ""; - } - if (storages && !isList(storages)) { - storages = [storages]; - } - if (plugins && !isList(plugins)) { - plugins = [plugins]; - } - var namespacePrefix = namespace ? "__storejs_" + namespace + "_" : ""; - var namespaceRegexp = namespace ? new RegExp("^" + namespacePrefix) : null; - var legalNamespaces = /^[a-zA-Z0-9_\-]*$/; - if (!legalNamespaces.test(namespace)) { - throw new Error("store.js namespaces can only have alphanumerics + underscores and dashes"); - } - var _privateStoreProps = { - _namespacePrefix: namespacePrefix, - _namespaceRegexp: namespaceRegexp, - _testStorage: function(storage) { - try { - var testStr = "__storejs__test__"; - storage.write(testStr, testStr); - var ok = storage.read(testStr) === testStr; - storage.remove(testStr); - return ok; - } catch (e3) { - return false; + var Node = ( + /** @class */ + /* @__PURE__ */ function() { + function Node2(key, data) { + this.next = null; + this.key = key; + this.data = data; + this.left = null; + this.right = null; } - }, - _assignPluginFnProp: function(pluginFnProp, propName) { - var oldFn = this[propName]; - this[propName] = function pluginFn() { - var args = slice(arguments, 0); - var self2 = this; - function super_fn() { - if (!oldFn) { - return; - } - each(arguments, function(arg, i3) { - args[i3] = arg; - }); - return oldFn.apply(self2, args); + return Node2; + }() + ); + function DEFAULT_COMPARE(a2, b2) { + return a2 > b2 ? 1 : a2 < b2 ? -1 : 0; + } + function splay(i3, t2, comparator) { + var N2 = new Node(null, null); + var l2 = N2; + var r2 = N2; + while (true) { + var cmp2 = comparator(i3, t2.key); + if (cmp2 < 0) { + if (t2.left === null) + break; + if (comparator(i3, t2.left.key) < 0) { + var y2 = t2.left; + t2.left = y2.right; + y2.right = t2; + t2 = y2; + if (t2.left === null) + break; } - var newFnArgs = [super_fn].concat(args); - return pluginFnProp.apply(self2, newFnArgs); - }; - }, - _serialize: function(obj) { - return JSON.stringify(obj); - }, - _deserialize: function(strVal, defaultVal) { - if (!strVal) { - return defaultVal; - } - var val = ""; - try { - val = JSON.parse(strVal); - } catch (e3) { - val = strVal; - } - return val !== void 0 ? val : defaultVal; - }, - _addStorage: function(storage) { - if (this.enabled) { - return; - } - if (this._testStorage(storage)) { - this.storage = storage; - this.enabled = true; - } - }, - _addPlugin: function(plugin) { - var self2 = this; - if (isList(plugin)) { - each(plugin, function(plugin2) { - self2._addPlugin(plugin2); - }); - return; - } - var seenPlugin = pluck(this.plugins, function(seenPlugin2) { - return plugin === seenPlugin2; - }); - if (seenPlugin) { - return; - } - this.plugins.push(plugin); - if (!isFunction2(plugin)) { - throw new Error("Plugins must be function values that return objects"); - } - var pluginProperties = plugin.call(this); - if (!isObject3(pluginProperties)) { - throw new Error("Plugins must return an object of function properties"); - } - each(pluginProperties, function(pluginFnProp, propName) { - if (!isFunction2(pluginFnProp)) { - throw new Error("Bad plugin property: " + propName + " from plugin " + plugin.name + ". Plugins should only return functions."); + r2.left = t2; + r2 = t2; + t2 = t2.left; + } else if (cmp2 > 0) { + if (t2.right === null) + break; + if (comparator(i3, t2.right.key) > 0) { + var y2 = t2.right; + t2.right = y2.left; + y2.left = t2; + t2 = y2; + if (t2.right === null) + break; } - self2._assignPluginFnProp(pluginFnProp, propName); - }); - }, - // Put deprecated properties in the private API, so as to not expose it to accidential - // discovery through inspection of the store object. - // Deprecated: addStorage - addStorage: function(storage) { - _warn("store.addStorage(storage) is deprecated. Use createStore([storages])"); - this._addStorage(storage); - } - }; - var store2 = create2(_privateStoreProps, storeAPI, { - plugins: [] - }); - store2.raw = {}; - each(store2, function(prop, propName) { - if (isFunction2(prop)) { - store2.raw[propName] = bind(store2, prop); + l2.right = t2; + l2 = t2; + t2 = t2.right; + } else + break; } - }); - each(storages, function(storage) { - store2._addStorage(storage); - }); - each(plugins, function(plugin) { - store2._addPlugin(plugin); - }); - return store2; - } - } - }); - - // node_modules/store/storages/localStorage.js - var require_localStorage = __commonJS({ - "node_modules/store/storages/localStorage.js"(exports2, module2) { - var util = require_util(); - var Global = util.Global; - module2.exports = { - name: "localStorage", - read, - write, - each, - remove: remove2, - clearAll - }; - function localStorage2() { - return Global.localStorage; - } - function read(key) { - return localStorage2().getItem(key); - } - function write(key, data) { - return localStorage2().setItem(key, data); - } - function each(fn) { - for (var i3 = localStorage2().length - 1; i3 >= 0; i3--) { - var key = localStorage2().key(i3); - fn(read(key), key); - } - } - function remove2(key) { - return localStorage2().removeItem(key); - } - function clearAll() { - return localStorage2().clear(); - } - } - }); - - // node_modules/store/storages/oldFF-globalStorage.js - var require_oldFF_globalStorage = __commonJS({ - "node_modules/store/storages/oldFF-globalStorage.js"(exports2, module2) { - var util = require_util(); - var Global = util.Global; - module2.exports = { - name: "oldFF-globalStorage", - read, - write, - each, - remove: remove2, - clearAll - }; - var globalStorage = Global.globalStorage; - function read(key) { - return globalStorage[key]; - } - function write(key, data) { - globalStorage[key] = data; - } - function each(fn) { - for (var i3 = globalStorage.length - 1; i3 >= 0; i3--) { - var key = globalStorage.key(i3); - fn(globalStorage[key], key); - } - } - function remove2(key) { - return globalStorage.removeItem(key); - } - function clearAll() { - each(function(key, _2) { - delete globalStorage[key]; - }); - } - } - }); - - // node_modules/store/storages/oldIE-userDataStorage.js - var require_oldIE_userDataStorage = __commonJS({ - "node_modules/store/storages/oldIE-userDataStorage.js"(exports2, module2) { - var util = require_util(); - var Global = util.Global; - module2.exports = { - name: "oldIE-userDataStorage", - write, - read, - each, - remove: remove2, - clearAll - }; - var storageName = "storejs"; - var doc = Global.document; - var _withStorageEl = _makeIEStorageElFunction(); - var disable = (Global.navigator ? Global.navigator.userAgent : "").match(/ (MSIE 8|MSIE 9|MSIE 10)\./); - function write(unfixedKey, data) { - if (disable) { - return; - } - var fixedKey = fixKey(unfixedKey); - _withStorageEl(function(storageEl) { - storageEl.setAttribute(fixedKey, data); - storageEl.save(storageName); - }); - } - function read(unfixedKey) { - if (disable) { - return; + l2.right = t2.left; + r2.left = t2.right; + t2.left = N2.right; + t2.right = N2.left; + return t2; } - var fixedKey = fixKey(unfixedKey); - var res = null; - _withStorageEl(function(storageEl) { - res = storageEl.getAttribute(fixedKey); - }); - return res; - } - function each(callback) { - _withStorageEl(function(storageEl) { - var attributes = storageEl.XMLDocument.documentElement.attributes; - for (var i3 = attributes.length - 1; i3 >= 0; i3--) { - var attr = attributes[i3]; - callback(storageEl.getAttribute(attr.name), attr.name); + function insert(i3, data, t2, comparator) { + var node = new Node(i3, data); + if (t2 === null) { + node.left = node.right = null; + return node; } - }); - } - function remove2(unfixedKey) { - var fixedKey = fixKey(unfixedKey); - _withStorageEl(function(storageEl) { - storageEl.removeAttribute(fixedKey); - storageEl.save(storageName); - }); - } - function clearAll() { - _withStorageEl(function(storageEl) { - var attributes = storageEl.XMLDocument.documentElement.attributes; - storageEl.load(storageName); - for (var i3 = attributes.length - 1; i3 >= 0; i3--) { - storageEl.removeAttribute(attributes[i3].name); + t2 = splay(i3, t2, comparator); + var cmp2 = comparator(i3, t2.key); + if (cmp2 < 0) { + node.left = t2.left; + node.right = t2; + t2.left = null; + } else if (cmp2 >= 0) { + node.right = t2.right; + node.left = t2; + t2.right = null; } - storageEl.save(storageName); - }); - } - var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g"); - function fixKey(key) { - return key.replace(/^\d/, "___$&").replace(forbiddenCharsRegex, "___"); - } - function _makeIEStorageElFunction() { - if (!doc || !doc.documentElement || !doc.documentElement.addBehavior) { - return null; - } - var scriptTag = "script", storageOwner, storageContainer, storageEl; - try { - storageContainer = new ActiveXObject("htmlfile"); - storageContainer.open(); - storageContainer.write("<" + scriptTag + ">document.w=window'); - storageContainer.close(); - storageOwner = storageContainer.w.frames[0].document; - storageEl = storageOwner.createElement("div"); - } catch (e3) { - storageEl = doc.createElement("div"); - storageOwner = doc.body; - } - return function(storeFunction) { - var args = [].slice.call(arguments, 0); - args.unshift(storageEl); - storageOwner.appendChild(storageEl); - storageEl.addBehavior("#default#userData"); - storageEl.load(storageName); - storeFunction.apply(this, args); - storageOwner.removeChild(storageEl); - return; - }; - } - } - }); - - // node_modules/store/storages/cookieStorage.js - var require_cookieStorage = __commonJS({ - "node_modules/store/storages/cookieStorage.js"(exports2, module2) { - var util = require_util(); - var Global = util.Global; - var trim = util.trim; - module2.exports = { - name: "cookieStorage", - read, - write, - each, - remove: remove2, - clearAll - }; - var doc = Global.document; - function read(key) { - if (!key || !_has(key)) { - return null; + return node; } - var regexpStr = "(?:^|.*;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"; - return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")); - } - function each(callback) { - var cookies = doc.cookie.split(/; ?/g); - for (var i3 = cookies.length - 1; i3 >= 0; i3--) { - if (!trim(cookies[i3])) { - continue; + function split(key, v2, comparator) { + var left = null; + var right = null; + if (v2) { + v2 = splay(key, v2, comparator); + var cmp2 = comparator(v2.key, key); + if (cmp2 === 0) { + left = v2.left; + right = v2.right; + } else if (cmp2 < 0) { + right = v2.right; + v2.right = null; + left = v2; + } else { + left = v2.left; + v2.left = null; + right = v2; + } } - var kvp = cookies[i3].split("="); - var key = unescape(kvp[0]); - var val = unescape(kvp[1]); - callback(val, key); - } - } - function write(key, data) { - if (!key) { - return; - } - doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; - } - function remove2(key) { - if (!key || !_has(key)) { - return; + return { + left, + right + }; } - doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; - } - function clearAll() { - each(function(_2, key) { - remove2(key); - }); - } - function _has(key) { - return new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=").test(doc.cookie); - } - } - }); - - // node_modules/store/storages/sessionStorage.js - var require_sessionStorage = __commonJS({ - "node_modules/store/storages/sessionStorage.js"(exports2, module2) { - var util = require_util(); - var Global = util.Global; - module2.exports = { - name: "sessionStorage", - read, - write, - each, - remove: remove2, - clearAll - }; - function sessionStorage() { - return Global.sessionStorage; - } - function read(key) { - return sessionStorage().getItem(key); - } - function write(key, data) { - return sessionStorage().setItem(key, data); - } - function each(fn) { - for (var i3 = sessionStorage().length - 1; i3 >= 0; i3--) { - var key = sessionStorage().key(i3); - fn(read(key), key); + function merge2(left, right, comparator) { + if (right === null) + return left; + if (left === null) + return right; + right = splay(left.key, right, comparator); + right.left = left; + return right; } - } - function remove2(key) { - return sessionStorage().removeItem(key); - } - function clearAll() { - return sessionStorage().clear(); - } - } - }); - - // node_modules/store/storages/memoryStorage.js - var require_memoryStorage = __commonJS({ - "node_modules/store/storages/memoryStorage.js"(exports2, module2) { - module2.exports = { - name: "memoryStorage", - read, - write, - each, - remove: remove2, - clearAll - }; - var memoryStorage = {}; - function read(key) { - return memoryStorage[key]; - } - function write(key, data) { - memoryStorage[key] = data; - } - function each(callback) { - for (var key in memoryStorage) { - if (memoryStorage.hasOwnProperty(key)) { - callback(memoryStorage[key], key); + function printRow(root3, prefix, isTail, out, printNode) { + if (root3) { + out("" + prefix + (isTail ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ") + printNode(root3) + "\n"); + var indent = prefix + (isTail ? " " : "\u2502 "); + if (root3.left) + printRow(root3.left, indent, false, out, printNode); + if (root3.right) + printRow(root3.right, indent, true, out, printNode); } } - } - function remove2(key) { - delete memoryStorage[key]; - } - function clearAll(key) { - memoryStorage = {}; - } - } - }); - - // node_modules/store/storages/all.js - var require_all = __commonJS({ - "node_modules/store/storages/all.js"(exports2, module2) { - module2.exports = [ - // Listed in order of usage preference - require_localStorage(), - require_oldFF_globalStorage(), - require_oldIE_userDataStorage(), - require_cookieStorage(), - require_sessionStorage(), - require_memoryStorage() - ]; - } - }); - - // node_modules/store/plugins/lib/json2.js - var require_json2 = __commonJS({ - "node_modules/store/plugins/lib/json2.js"(exports, module) { - if (typeof JSON !== "object") { - JSON = {}; - } - (function() { - "use strict"; - var rx_one = /^[\],:{}\s]*$/; - var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; - var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; - var rx_four = /(?:^|:|,)(?:\s*\[)+/g; - var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - function f(n3) { - return n3 < 10 ? "0" + n3 : n3; - } - function this_value() { - return this.valueOf(); - } - if (typeof Date.prototype.toJSON !== "function") { - Date.prototype.toJSON = function() { - return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null; - }; - Boolean.prototype.toJSON = this_value; - Number.prototype.toJSON = this_value; - String.prototype.toJSON = this_value; - } - var gap; - var indent; - var meta; - var rep; - function quote(string) { - rx_escapable.lastIndex = 0; - return rx_escapable.test(string) ? '"' + string.replace(rx_escapable, function(a2) { - var c2 = meta[a2]; - return typeof c2 === "string" ? c2 : "\\u" + ("0000" + a2.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - function str(key, holder) { - var i3; - var k2; - var v2; - var length; - var mind = gap; - var partial; - var value = holder[key]; - if (value && typeof value === "object" && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - if (typeof rep === "function") { - value = rep.call(holder, key, value); - } - switch (typeof value) { - case "string": - return quote(value); - case "number": - return isFinite(value) ? String(value) : "null"; - case "boolean": - case "null": - return String(value); - case "object": - if (!value) { - return "null"; + var Tree = ( + /** @class */ + function() { + function Tree2(comparator) { + if (comparator === void 0) { + comparator = DEFAULT_COMPARE; } - gap += indent; - partial = []; - if (Object.prototype.toString.apply(value) === "[object Array]") { - length = value.length; - for (i3 = 0; i3 < length; i3 += 1) { - partial[i3] = str(i3, value) || "null"; - } - v2 = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]"; - gap = mind; - return v2; + this._root = null; + this._size = 0; + this._comparator = comparator; + } + Tree2.prototype.insert = function(key, data) { + this._size++; + return this._root = insert(key, data, this._root, this._comparator); + }; + Tree2.prototype.add = function(key, data) { + var node = new Node(key, data); + if (this._root === null) { + node.left = node.right = null; + this._size++; + this._root = node; } - if (rep && typeof rep === "object") { - length = rep.length; - for (i3 = 0; i3 < length; i3 += 1) { - if (typeof rep[i3] === "string") { - k2 = rep[i3]; - v2 = str(k2, value); - if (v2) { - partial.push(quote(k2) + (gap ? ": " : ":") + v2); - } - } + var comparator = this._comparator; + var t2 = splay(key, this._root, comparator); + var cmp2 = comparator(key, t2.key); + if (cmp2 === 0) + this._root = t2; + else { + if (cmp2 < 0) { + node.left = t2.left; + node.right = t2; + t2.left = null; + } else if (cmp2 > 0) { + node.right = t2.right; + node.left = t2; + t2.right = null; } - } else { - for (k2 in value) { - if (Object.prototype.hasOwnProperty.call(value, k2)) { - v2 = str(k2, value); - if (v2) { - partial.push(quote(k2) + (gap ? ": " : ":") + v2); - } - } + this._size++; + this._root = node; + } + return this._root; + }; + Tree2.prototype.remove = function(key) { + this._root = this._remove(key, this._root, this._comparator); + }; + Tree2.prototype._remove = function(i3, t2, comparator) { + var x2; + if (t2 === null) + return null; + t2 = splay(i3, t2, comparator); + var cmp2 = comparator(i3, t2.key); + if (cmp2 === 0) { + if (t2.left === null) { + x2 = t2.right; + } else { + x2 = splay(i3, t2.left, comparator); + x2.right = t2.right; } + this._size--; + return x2; } - v2 = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; - gap = mind; - return v2; - } - } - if (typeof JSON.stringify !== "function") { - meta = { - // table of character substitutions - "\b": "\\b", - " ": "\\t", - "\n": "\\n", - "\f": "\\f", - "\r": "\\r", - '"': '\\"', - "\\": "\\\\" - }; - JSON.stringify = function(value, replacer, space) { - var i3; - gap = ""; - indent = ""; - if (typeof space === "number") { - for (i3 = 0; i3 < space; i3 += 1) { - indent += " "; + return t2; + }; + Tree2.prototype.pop = function() { + var node = this._root; + if (node) { + while (node.left) + node = node.left; + this._root = splay(node.key, this._root, this._comparator); + this._root = this._remove(node.key, this._root, this._comparator); + return { + key: node.key, + data: node.data + }; } - } else if (typeof space === "string") { - indent = space; - } - rep = replacer; - if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { - throw new Error("JSON.stringify"); - } - return str("", { "": value }); - }; - } - if (typeof JSON.parse !== "function") { - JSON.parse = function(text, reviver) { - var j; - function walk(holder, key) { - var k2; - var v2; - var value = holder[key]; - if (value && typeof value === "object") { - for (k2 in value) { - if (Object.prototype.hasOwnProperty.call(value, k2)) { - v2 = walk(value, k2); - if (v2 !== void 0) { - value[k2] = v2; - } else { - delete value[k2]; - } + return null; + }; + Tree2.prototype.findStatic = function(key) { + var current = this._root; + var compare2 = this._comparator; + while (current) { + var cmp2 = compare2(key, current.key); + if (cmp2 === 0) + return current; + else if (cmp2 < 0) + current = current.left; + else + current = current.right; + } + return null; + }; + Tree2.prototype.find = function(key) { + if (this._root) { + this._root = splay(key, this._root, this._comparator); + if (this._comparator(key, this._root.key) !== 0) + return null; + } + return this._root; + }; + Tree2.prototype.contains = function(key) { + var current = this._root; + var compare2 = this._comparator; + while (current) { + var cmp2 = compare2(key, current.key); + if (cmp2 === 0) + return true; + else if (cmp2 < 0) + current = current.left; + else + current = current.right; + } + return false; + }; + Tree2.prototype.forEach = function(visitor, ctx) { + var current = this._root; + var Q2 = []; + var done = false; + while (!done) { + if (current !== null) { + Q2.push(current); + current = current.left; + } else { + if (Q2.length !== 0) { + current = Q2.pop(); + visitor.call(ctx, current); + current = current.right; + } else + done = true; + } + } + return this; + }; + Tree2.prototype.range = function(low, high, fn, ctx) { + var Q2 = []; + var compare2 = this._comparator; + var node = this._root; + var cmp2; + while (Q2.length !== 0 || node) { + if (node) { + Q2.push(node); + node = node.left; + } else { + node = Q2.pop(); + cmp2 = compare2(node.key, high); + if (cmp2 > 0) { + break; + } else if (compare2(node.key, low) >= 0) { + if (fn.call(ctx, node)) + return this; } + node = node.right; } } - return reviver.call(holder, key, value); - } - text = String(text); - rx_dangerous.lastIndex = 0; - if (rx_dangerous.test(text)) { - text = text.replace(rx_dangerous, function(a2) { - return "\\u" + ("0000" + a2.charCodeAt(0).toString(16)).slice(-4); + return this; + }; + Tree2.prototype.keys = function() { + var keys2 = []; + this.forEach(function(_a2) { + var key = _a2.key; + return keys2.push(key); }); - } - if (rx_one.test( - text.replace(rx_two, "@").replace(rx_three, "]").replace(rx_four, "") - )) { - j = eval("(" + text + ")"); - return typeof reviver === "function" ? walk({ "": j }, "") : j; - } - throw new SyntaxError("JSON.parse"); - }; - } - })(); - } - }); - - // node_modules/store/plugins/json2.js - var require_json22 = __commonJS({ - "node_modules/store/plugins/json2.js"(exports2, module2) { - module2.exports = json2Plugin; - function json2Plugin() { - require_json2(); - return {}; - } - } - }); - - // node_modules/store/dist/store.legacy.js - var require_store_legacy = __commonJS({ - "node_modules/store/dist/store.legacy.js"(exports2, module2) { - var engine = require_store_engine(); - var storages = require_all(); - var plugins = [require_json22()]; - module2.exports = engine.createStore(storages, plugins); - } - }); - - // node_modules/whatwg-fetch/fetch.js - var g = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef - typeof global !== "undefined" && global || {}; - var support = { - searchParams: "URLSearchParams" in g, - iterable: "Symbol" in g && "iterator" in Symbol, - blob: "FileReader" in g && "Blob" in g && function() { - try { - new Blob(); - return true; - } catch (e3) { - return false; - } - }(), - formData: "FormData" in g, - arrayBuffer: "ArrayBuffer" in g - }; - function isDataView(obj) { - return obj && DataView.prototype.isPrototypeOf(obj); - } - if (support.arrayBuffer) { + return keys2; + }; + Tree2.prototype.values = function() { + var values = []; + this.forEach(function(_a2) { + var data = _a2.data; + return values.push(data); + }); + return values; + }; + Tree2.prototype.min = function() { + if (this._root) + return this.minNode(this._root).key; + return null; + }; + Tree2.prototype.max = function() { + if (this._root) + return this.maxNode(this._root).key; + return null; + }; + Tree2.prototype.minNode = function(t2) { + if (t2 === void 0) { + t2 = this._root; + } + if (t2) + while (t2.left) + t2 = t2.left; + return t2; + }; + Tree2.prototype.maxNode = function(t2) { + if (t2 === void 0) { + t2 = this._root; + } + if (t2) + while (t2.right) + t2 = t2.right; + return t2; + }; + Tree2.prototype.at = function(index2) { + var current = this._root; + var done = false; + var i3 = 0; + var Q2 = []; + while (!done) { + if (current) { + Q2.push(current); + current = current.left; + } else { + if (Q2.length > 0) { + current = Q2.pop(); + if (i3 === index2) + return current; + i3++; + current = current.right; + } else + done = true; + } + } + return null; + }; + Tree2.prototype.next = function(d2) { + var root3 = this._root; + var successor = null; + if (d2.right) { + successor = d2.right; + while (successor.left) + successor = successor.left; + return successor; + } + var comparator = this._comparator; + while (root3) { + var cmp2 = comparator(d2.key, root3.key); + if (cmp2 === 0) + break; + else if (cmp2 < 0) { + successor = root3; + root3 = root3.left; + } else + root3 = root3.right; + } + return successor; + }; + Tree2.prototype.prev = function(d2) { + var root3 = this._root; + var predecessor = null; + if (d2.left !== null) { + predecessor = d2.left; + while (predecessor.right) + predecessor = predecessor.right; + return predecessor; + } + var comparator = this._comparator; + while (root3) { + var cmp2 = comparator(d2.key, root3.key); + if (cmp2 === 0) + break; + else if (cmp2 < 0) + root3 = root3.left; + else { + predecessor = root3; + root3 = root3.right; + } + } + return predecessor; + }; + Tree2.prototype.clear = function() { + this._root = null; + this._size = 0; + return this; + }; + Tree2.prototype.toList = function() { + return toList(this._root); + }; + Tree2.prototype.load = function(keys2, values, presort) { + if (values === void 0) { + values = []; + } + if (presort === void 0) { + presort = false; + } + var size = keys2.length; + var comparator = this._comparator; + if (presort) + sort(keys2, values, 0, size - 1, comparator); + if (this._root === null) { + this._root = loadRecursive(keys2, values, 0, size); + this._size = size; + } else { + var mergedList = mergeLists(this.toList(), createList(keys2, values), comparator); + size = this._size + size; + this._root = sortedListToBST({ + head: mergedList + }, 0, size); + } + return this; + }; + Tree2.prototype.isEmpty = function() { + return this._root === null; + }; + Object.defineProperty(Tree2.prototype, "size", { + get: function() { + return this._size; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tree2.prototype, "root", { + get: function() { + return this._root; + }, + enumerable: true, + configurable: true + }); + Tree2.prototype.toString = function(printNode) { + if (printNode === void 0) { + printNode = function(n3) { + return String(n3.key); + }; + } + var out = []; + printRow(this._root, "", true, function(v2) { + return out.push(v2); + }, printNode); + return out.join(""); + }; + Tree2.prototype.update = function(key, newKey, newData) { + var comparator = this._comparator; + var _a2 = split(key, this._root, comparator), left = _a2.left, right = _a2.right; + if (comparator(key, newKey) < 0) { + right = insert(newKey, newData, right, comparator); + } else { + left = insert(newKey, newData, left, comparator); + } + this._root = merge2(left, right, comparator); + }; + Tree2.prototype.split = function(key) { + return split(key, this._root, this._comparator); + }; + Tree2.prototype[Symbol.iterator] = function() { + var current, Q2, done; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + current = this._root; + Q2 = []; + done = false; + _a2.label = 1; + case 1: + if (!!done) + return [3, 6]; + if (!(current !== null)) + return [3, 2]; + Q2.push(current); + current = current.left; + return [3, 5]; + case 2: + if (!(Q2.length !== 0)) + return [3, 4]; + current = Q2.pop(); + return [4, current]; + case 3: + _a2.sent(); + current = current.right; + return [3, 5]; + case 4: + done = true; + _a2.label = 5; + case 5: + return [3, 1]; + case 6: + return [ + 2 + /*return*/ + ]; + } + }); + }; + return Tree2; + }() + ); + function loadRecursive(keys2, values, start2, end) { + var size = end - start2; + if (size > 0) { + var middle = start2 + Math.floor(size / 2); + var key = keys2[middle]; + var data = values[middle]; + var node = new Node(key, data); + node.left = loadRecursive(keys2, values, start2, middle); + node.right = loadRecursive(keys2, values, middle + 1, end); + return node; + } + return null; + } + function createList(keys2, values) { + var head = new Node(null, null); + var p2 = head; + for (var i3 = 0; i3 < keys2.length; i3++) { + p2 = p2.next = new Node(keys2[i3], values[i3]); + } + p2.next = null; + return head.next; + } + function toList(root3) { + var current = root3; + var Q2 = []; + var done = false; + var head = new Node(null, null); + var p2 = head; + while (!done) { + if (current) { + Q2.push(current); + current = current.left; + } else { + if (Q2.length > 0) { + current = p2 = p2.next = Q2.pop(); + current = current.right; + } else + done = true; + } + } + p2.next = null; + return head.next; + } + function sortedListToBST(list2, start2, end) { + var size = end - start2; + if (size > 0) { + var middle = start2 + Math.floor(size / 2); + var left = sortedListToBST(list2, start2, middle); + var root3 = list2.head; + root3.left = left; + list2.head = list2.head.next; + root3.right = sortedListToBST(list2, middle + 1, end); + return root3; + } + return null; + } + function mergeLists(l1, l2, compare2) { + var head = new Node(null, null); + var p2 = head; + var p1 = l1; + var p22 = l2; + while (p1 !== null && p22 !== null) { + if (compare2(p1.key, p22.key) < 0) { + p2.next = p1; + p1 = p1.next; + } else { + p2.next = p22; + p22 = p22.next; + } + p2 = p2.next; + } + if (p1 !== null) { + p2.next = p1; + } else if (p22 !== null) { + p2.next = p22; + } + return head.next; + } + function sort(keys2, values, left, right, compare2) { + if (left >= right) + return; + var pivot = keys2[left + right >> 1]; + var i3 = left - 1; + var j2 = right + 1; + while (true) { + do + i3++; + while (compare2(keys2[i3], pivot) < 0); + do + j2--; + while (compare2(keys2[j2], pivot) > 0); + if (i3 >= j2) + break; + var tmp = keys2[i3]; + keys2[i3] = keys2[j2]; + keys2[j2] = tmp; + tmp = values[i3]; + values[i3] = values[j2]; + values[j2] = tmp; + } + sort(keys2, values, left, j2, compare2); + sort(keys2, values, j2 + 1, right, compare2); + } + const isInBbox2 = (bbox2, point2) => { + return bbox2.ll.x <= point2.x && point2.x <= bbox2.ur.x && bbox2.ll.y <= point2.y && point2.y <= bbox2.ur.y; + }; + const getBboxOverlap2 = (b1, b2) => { + if (b2.ur.x < b1.ll.x || b1.ur.x < b2.ll.x || b2.ur.y < b1.ll.y || b1.ur.y < b2.ll.y) + return null; + const lowerX = b1.ll.x < b2.ll.x ? b2.ll.x : b1.ll.x; + const upperX = b1.ur.x < b2.ur.x ? b1.ur.x : b2.ur.x; + const lowerY = b1.ll.y < b2.ll.y ? b2.ll.y : b1.ll.y; + const upperY = b1.ur.y < b2.ur.y ? b1.ur.y : b2.ur.y; + return { + ll: { + x: lowerX, + y: lowerY + }, + ur: { + x: upperX, + y: upperY + } + }; + }; + let epsilon$1 = Number.EPSILON; + if (epsilon$1 === void 0) + epsilon$1 = Math.pow(2, -52); + const EPSILON_SQ = epsilon$1 * epsilon$1; + const cmp = (a2, b2) => { + if (-epsilon$1 < a2 && a2 < epsilon$1) { + if (-epsilon$1 < b2 && b2 < epsilon$1) { + return 0; + } + } + const ab = a2 - b2; + if (ab * ab < EPSILON_SQ * a2 * b2) { + return 0; + } + return a2 < b2 ? -1 : 1; + }; + class PtRounder { + constructor() { + this.reset(); + } + reset() { + this.xRounder = new CoordRounder(); + this.yRounder = new CoordRounder(); + } + round(x2, y2) { + return { + x: this.xRounder.round(x2), + y: this.yRounder.round(y2) + }; + } + } + class CoordRounder { + constructor() { + this.tree = new Tree(); + this.round(0); + } + // Note: this can rounds input values backwards or forwards. + // You might ask, why not restrict this to just rounding + // forwards? Wouldn't that allow left endpoints to always + // remain left endpoints during splitting (never change to + // right). No - it wouldn't, because we snap intersections + // to endpoints (to establish independence from the segment + // angle for t-intersections). + round(coord2) { + const node = this.tree.add(coord2); + const prevNode = this.tree.prev(node); + if (prevNode !== null && cmp(node.key, prevNode.key) === 0) { + this.tree.remove(coord2); + return prevNode.key; + } + const nextNode = this.tree.next(node); + if (nextNode !== null && cmp(node.key, nextNode.key) === 0) { + this.tree.remove(coord2); + return nextNode.key; + } + return coord2; + } + } + const rounder = new PtRounder(); + const epsilon3 = 11102230246251565e-32; + const splitter = 134217729; + const resulterrbound = (3 + 8 * epsilon3) * epsilon3; + function sum(elen, e3, flen, f2, h2) { + let Q2, Qnew, hh, bvirt; + let enow = e3[0]; + let fnow = f2[0]; + let eindex = 0; + let findex = 0; + if (fnow > enow === fnow > -enow) { + Q2 = enow; + enow = e3[++eindex]; + } else { + Q2 = fnow; + fnow = f2[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if (fnow > enow === fnow > -enow) { + Qnew = enow + Q2; + hh = Q2 - (Qnew - enow); + enow = e3[++eindex]; + } else { + Qnew = fnow + Q2; + hh = Q2 - (Qnew - fnow); + fnow = f2[++findex]; + } + Q2 = Qnew; + if (hh !== 0) { + h2[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if (fnow > enow === fnow > -enow) { + Qnew = Q2 + enow; + bvirt = Qnew - Q2; + hh = Q2 - (Qnew - bvirt) + (enow - bvirt); + enow = e3[++eindex]; + } else { + Qnew = Q2 + fnow; + bvirt = Qnew - Q2; + hh = Q2 - (Qnew - bvirt) + (fnow - bvirt); + fnow = f2[++findex]; + } + Q2 = Qnew; + if (hh !== 0) { + h2[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q2 + enow; + bvirt = Qnew - Q2; + hh = Q2 - (Qnew - bvirt) + (enow - bvirt); + enow = e3[++eindex]; + Q2 = Qnew; + if (hh !== 0) { + h2[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q2 + fnow; + bvirt = Qnew - Q2; + hh = Q2 - (Qnew - bvirt) + (fnow - bvirt); + fnow = f2[++findex]; + Q2 = Qnew; + if (hh !== 0) { + h2[hindex++] = hh; + } + } + if (Q2 !== 0 || hindex === 0) { + h2[hindex++] = Q2; + } + return hindex; + } + function estimate(elen, e3) { + let Q2 = e3[0]; + for (let i3 = 1; i3 < elen; i3++) + Q2 += e3[i3]; + return Q2; + } + function vec(n3) { + return new Float64Array(n3); + } + const ccwerrboundA = (3 + 16 * epsilon3) * epsilon3; + const ccwerrboundB = (2 + 12 * epsilon3) * epsilon3; + const ccwerrboundC = (9 + 64 * epsilon3) * epsilon3 * epsilon3; + const B2 = vec(4); + const C1 = vec(8); + const C2 = vec(12); + const D2 = vec(16); + const u2 = vec(4); + function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) { + let acxtail, acytail, bcxtail, bcytail; + let bvirt, c2, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + const acx = ax - cx; + const bcx = bx - cx; + const acy = ay - cy; + const bcy = by - cy; + s1 = acx * bcy; + c2 = splitter * acx; + ahi = c2 - (c2 - acx); + alo = acx - ahi; + c2 = splitter * bcy; + bhi = c2 - (c2 - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcx; + c2 = splitter * acy; + ahi = c2 - (c2 - acy); + alo = acy - ahi; + c2 = splitter * bcx; + bhi = c2 - (c2 - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + B2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + B2[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + B2[2] = _j - (u3 - bvirt) + (_i - bvirt); + B2[3] = u3; + let det = estimate(4, B2); + let errbound = ccwerrboundB * detsum; + if (det >= errbound || -det >= errbound) { + return det; + } + bvirt = ax - acx; + acxtail = ax - (acx + bvirt) + (bvirt - cx); + bvirt = bx - bcx; + bcxtail = bx - (bcx + bvirt) + (bvirt - cx); + bvirt = ay - acy; + acytail = ay - (acy + bvirt) + (bvirt - cy); + bvirt = by - bcy; + bcytail = by - (bcy + bvirt) + (bvirt - cy); + if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) { + return det; + } + errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det); + det += acx * bcytail + bcy * acxtail - (acy * bcxtail + bcx * acytail); + if (det >= errbound || -det >= errbound) + return det; + s1 = acxtail * bcy; + c2 = splitter * acxtail; + ahi = c2 - (c2 - acxtail); + alo = acxtail - ahi; + c2 = splitter * bcy; + bhi = c2 - (c2 - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcx; + c2 = splitter * acytail; + ahi = c2 - (c2 - acytail); + alo = acytail - ahi; + c2 = splitter * bcx; + bhi = c2 - (c2 - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u2[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u2[2] = _j - (u3 - bvirt) + (_i - bvirt); + u2[3] = u3; + const C1len = sum(4, B2, 4, u2, C1); + s1 = acx * bcytail; + c2 = splitter * acx; + ahi = c2 - (c2 - acx); + alo = acx - ahi; + c2 = splitter * bcytail; + bhi = c2 - (c2 - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcxtail; + c2 = splitter * acy; + ahi = c2 - (c2 - acy); + alo = acy - ahi; + c2 = splitter * bcxtail; + bhi = c2 - (c2 - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u2[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u2[2] = _j - (u3 - bvirt) + (_i - bvirt); + u2[3] = u3; + const C2len = sum(C1len, C1, 4, u2, C2); + s1 = acxtail * bcytail; + c2 = splitter * acxtail; + ahi = c2 - (c2 - acxtail); + alo = acxtail - ahi; + c2 = splitter * bcytail; + bhi = c2 - (c2 - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcxtail; + c2 = splitter * acytail; + ahi = c2 - (c2 - acytail); + alo = acytail - ahi; + c2 = splitter * bcxtail; + bhi = c2 - (c2 - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u2[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u2[2] = _j - (u3 - bvirt) + (_i - bvirt); + u2[3] = u3; + const Dlen = sum(C2len, C2, 4, u2, D2); + return D2[Dlen - 1]; + } + function orient2d(ax, ay, bx, by, cx, cy) { + const detleft = (ay - cy) * (bx - cx); + const detright = (ax - cx) * (by - cy); + const det = detleft - detright; + const detsum = Math.abs(detleft + detright); + if (Math.abs(det) >= ccwerrboundA * detsum) + return det; + return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum); + } + const crossProduct2 = (a2, b2) => a2.x * b2.y - a2.y * b2.x; + const dotProduct2 = (a2, b2) => a2.x * b2.x + a2.y * b2.y; + const compareVectorAngles = (basePt, endPt1, endPt2) => { + const res = orient2d(basePt.x, basePt.y, endPt1.x, endPt1.y, endPt2.x, endPt2.y); + if (res > 0) + return -1; + if (res < 0) + return 1; + return 0; + }; + const length2 = (v2) => Math.sqrt(dotProduct2(v2, v2)); + const sineOfAngle2 = (pShared, pBase, pAngle) => { + const vBase = { + x: pBase.x - pShared.x, + y: pBase.y - pShared.y + }; + const vAngle = { + x: pAngle.x - pShared.x, + y: pAngle.y - pShared.y + }; + return crossProduct2(vAngle, vBase) / length2(vAngle) / length2(vBase); + }; + const cosineOfAngle2 = (pShared, pBase, pAngle) => { + const vBase = { + x: pBase.x - pShared.x, + y: pBase.y - pShared.y + }; + const vAngle = { + x: pAngle.x - pShared.x, + y: pAngle.y - pShared.y + }; + return dotProduct2(vAngle, vBase) / length2(vAngle) / length2(vBase); + }; + const horizontalIntersection2 = (pt2, v2, y2) => { + if (v2.y === 0) + return null; + return { + x: pt2.x + v2.x / v2.y * (y2 - pt2.y), + y: y2 + }; + }; + const verticalIntersection2 = (pt2, v2, x2) => { + if (v2.x === 0) + return null; + return { + x: x2, + y: pt2.y + v2.y / v2.x * (x2 - pt2.x) + }; + }; + const intersection$1 = (pt1, v1, pt2, v2) => { + if (v1.x === 0) + return verticalIntersection2(pt2, v2, pt1.x); + if (v2.x === 0) + return verticalIntersection2(pt1, v1, pt2.x); + if (v1.y === 0) + return horizontalIntersection2(pt2, v2, pt1.y); + if (v2.y === 0) + return horizontalIntersection2(pt1, v1, pt2.y); + const kross = crossProduct2(v1, v2); + if (kross == 0) + return null; + const ve2 = { + x: pt2.x - pt1.x, + y: pt2.y - pt1.y + }; + const d1 = crossProduct2(ve2, v1) / kross; + const d2 = crossProduct2(ve2, v2) / kross; + const x12 = pt1.x + d2 * v1.x, x2 = pt2.x + d1 * v2.x; + const y12 = pt1.y + d2 * v1.y, y2 = pt2.y + d1 * v2.y; + const x3 = (x12 + x2) / 2; + const y3 = (y12 + y2) / 2; + return { + x: x3, + y: y3 + }; + }; + class SweepEvent2 { + // for ordering sweep events in the sweep event queue + static compare(a2, b2) { + const ptCmp = SweepEvent2.comparePoints(a2.point, b2.point); + if (ptCmp !== 0) + return ptCmp; + if (a2.point !== b2.point) + a2.link(b2); + if (a2.isLeft !== b2.isLeft) + return a2.isLeft ? 1 : -1; + return Segment2.compare(a2.segment, b2.segment); + } + // for ordering points in sweep line order + static comparePoints(aPt, bPt) { + if (aPt.x < bPt.x) + return -1; + if (aPt.x > bPt.x) + return 1; + if (aPt.y < bPt.y) + return -1; + if (aPt.y > bPt.y) + return 1; + return 0; + } + // Warning: 'point' input will be modified and re-used (for performance) + constructor(point2, isLeft) { + if (point2.events === void 0) + point2.events = [this]; + else + point2.events.push(this); + this.point = point2; + this.isLeft = isLeft; + } + link(other) { + if (other.point === this.point) { + throw new Error("Tried to link already linked events"); + } + const otherEvents = other.point.events; + for (let i3 = 0, iMax = otherEvents.length; i3 < iMax; i3++) { + const evt = otherEvents[i3]; + this.point.events.push(evt); + evt.point = this.point; + } + this.checkForConsuming(); + } + /* Do a pass over our linked events and check to see if any pair + * of segments match, and should be consumed. */ + checkForConsuming() { + const numEvents = this.point.events.length; + for (let i3 = 0; i3 < numEvents; i3++) { + const evt1 = this.point.events[i3]; + if (evt1.segment.consumedBy !== void 0) + continue; + for (let j2 = i3 + 1; j2 < numEvents; j2++) { + const evt2 = this.point.events[j2]; + if (evt2.consumedBy !== void 0) + continue; + if (evt1.otherSE.point.events !== evt2.otherSE.point.events) + continue; + evt1.segment.consume(evt2.segment); + } + } + } + getAvailableLinkedEvents() { + const events = []; + for (let i3 = 0, iMax = this.point.events.length; i3 < iMax; i3++) { + const evt = this.point.events[i3]; + if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) { + events.push(evt); + } + } + return events; + } + /** + * Returns a comparator function for sorting linked events that will + * favor the event that will give us the smallest left-side angle. + * All ring construction starts as low as possible heading to the right, + * so by always turning left as sharp as possible we'll get polygons + * without uncessary loops & holes. + * + * The comparator function has a compute cache such that it avoids + * re-computing already-computed values. + */ + getLeftmostComparator(baseEvent) { + const cache = /* @__PURE__ */ new Map(); + const fillCache = (linkedEvent) => { + const nextEvent = linkedEvent.otherSE; + cache.set(linkedEvent, { + sine: sineOfAngle2(this.point, baseEvent.point, nextEvent.point), + cosine: cosineOfAngle2(this.point, baseEvent.point, nextEvent.point) + }); + }; + return (a2, b2) => { + if (!cache.has(a2)) + fillCache(a2); + if (!cache.has(b2)) + fillCache(b2); + const { + sine: asine, + cosine: acosine + } = cache.get(a2); + const { + sine: bsine, + cosine: bcosine + } = cache.get(b2); + if (asine >= 0 && bsine >= 0) { + if (acosine < bcosine) + return 1; + if (acosine > bcosine) + return -1; + return 0; + } + if (asine < 0 && bsine < 0) { + if (acosine < bcosine) + return -1; + if (acosine > bcosine) + return 1; + return 0; + } + if (bsine < asine) + return -1; + if (bsine > asine) + return 1; + return 0; + }; + } + } + let segmentId2 = 0; + class Segment2 { + /* This compare() function is for ordering segments in the sweep + * line tree, and does so according to the following criteria: + * + * Consider the vertical line that lies an infinestimal step to the + * right of the right-more of the two left endpoints of the input + * segments. Imagine slowly moving a point up from negative infinity + * in the increasing y direction. Which of the two segments will that + * point intersect first? That segment comes 'before' the other one. + * + * If neither segment would be intersected by such a line, (if one + * or more of the segments are vertical) then the line to be considered + * is directly on the right-more of the two left inputs. + */ + static compare(a2, b2) { + const alx = a2.leftSE.point.x; + const blx = b2.leftSE.point.x; + const arx = a2.rightSE.point.x; + const brx = b2.rightSE.point.x; + if (brx < alx) + return 1; + if (arx < blx) + return -1; + const aly = a2.leftSE.point.y; + const bly = b2.leftSE.point.y; + const ary = a2.rightSE.point.y; + const bry = b2.rightSE.point.y; + if (alx < blx) { + if (bly < aly && bly < ary) + return 1; + if (bly > aly && bly > ary) + return -1; + const aCmpBLeft = a2.comparePoint(b2.leftSE.point); + if (aCmpBLeft < 0) + return 1; + if (aCmpBLeft > 0) + return -1; + const bCmpARight = b2.comparePoint(a2.rightSE.point); + if (bCmpARight !== 0) + return bCmpARight; + return -1; + } + if (alx > blx) { + if (aly < bly && aly < bry) + return -1; + if (aly > bly && aly > bry) + return 1; + const bCmpALeft = b2.comparePoint(a2.leftSE.point); + if (bCmpALeft !== 0) + return bCmpALeft; + const aCmpBRight = a2.comparePoint(b2.rightSE.point); + if (aCmpBRight < 0) + return 1; + if (aCmpBRight > 0) + return -1; + return 1; + } + if (aly < bly) + return -1; + if (aly > bly) + return 1; + if (arx < brx) { + const bCmpARight = b2.comparePoint(a2.rightSE.point); + if (bCmpARight !== 0) + return bCmpARight; + } + if (arx > brx) { + const aCmpBRight = a2.comparePoint(b2.rightSE.point); + if (aCmpBRight < 0) + return 1; + if (aCmpBRight > 0) + return -1; + } + if (arx !== brx) { + const ay = ary - aly; + const ax = arx - alx; + const by = bry - bly; + const bx = brx - blx; + if (ay > ax && by < bx) + return 1; + if (ay < ax && by > bx) + return -1; + } + if (arx > brx) + return 1; + if (arx < brx) + return -1; + if (ary < bry) + return -1; + if (ary > bry) + return 1; + if (a2.id < b2.id) + return -1; + if (a2.id > b2.id) + return 1; + return 0; + } + /* Warning: a reference to ringWindings input will be stored, + * and possibly will be later modified */ + constructor(leftSE, rightSE, rings, windings) { + this.id = ++segmentId2; + this.leftSE = leftSE; + leftSE.segment = this; + leftSE.otherSE = rightSE; + this.rightSE = rightSE; + rightSE.segment = this; + rightSE.otherSE = leftSE; + this.rings = rings; + this.windings = windings; + } + static fromRing(pt1, pt2, ring) { + let leftPt, rightPt, winding; + const cmpPts = SweepEvent2.comparePoints(pt1, pt2); + if (cmpPts < 0) { + leftPt = pt1; + rightPt = pt2; + winding = 1; + } else if (cmpPts > 0) { + leftPt = pt2; + rightPt = pt1; + winding = -1; + } else + throw new Error("Tried to create degenerate segment at [".concat(pt1.x, ", ").concat(pt1.y, "]")); + const leftSE = new SweepEvent2(leftPt, true); + const rightSE = new SweepEvent2(rightPt, false); + return new Segment2(leftSE, rightSE, [ring], [winding]); + } + /* When a segment is split, the rightSE is replaced with a new sweep event */ + replaceRightSE(newRightSE) { + this.rightSE = newRightSE; + this.rightSE.segment = this; + this.rightSE.otherSE = this.leftSE; + this.leftSE.otherSE = this.rightSE; + } + bbox() { + const y12 = this.leftSE.point.y; + const y2 = this.rightSE.point.y; + return { + ll: { + x: this.leftSE.point.x, + y: y12 < y2 ? y12 : y2 + }, + ur: { + x: this.rightSE.point.x, + y: y12 > y2 ? y12 : y2 + } + }; + } + /* A vector from the left point to the right */ + vector() { + return { + x: this.rightSE.point.x - this.leftSE.point.x, + y: this.rightSE.point.y - this.leftSE.point.y + }; + } + isAnEndpoint(pt2) { + return pt2.x === this.leftSE.point.x && pt2.y === this.leftSE.point.y || pt2.x === this.rightSE.point.x && pt2.y === this.rightSE.point.y; + } + /* Compare this segment with a point. + * + * A point P is considered to be colinear to a segment if there + * exists a distance D such that if we travel along the segment + * from one * endpoint towards the other a distance D, we find + * ourselves at point P. + * + * Return value indicates: + * + * 1: point lies above the segment (to the left of vertical) + * 0: point is colinear to segment + * -1: point lies below the segment (to the right of vertical) + */ + comparePoint(point2) { + if (this.isAnEndpoint(point2)) + return 0; + const lPt = this.leftSE.point; + const rPt = this.rightSE.point; + const v2 = this.vector(); + if (lPt.x === rPt.x) { + if (point2.x === lPt.x) + return 0; + return point2.x < lPt.x ? 1 : -1; + } + const yDist = (point2.y - lPt.y) / v2.y; + const xFromYDist = lPt.x + yDist * v2.x; + if (point2.x === xFromYDist) + return 0; + const xDist = (point2.x - lPt.x) / v2.x; + const yFromXDist = lPt.y + xDist * v2.y; + if (point2.y === yFromXDist) + return 0; + return point2.y < yFromXDist ? -1 : 1; + } + /** + * Given another segment, returns the first non-trivial intersection + * between the two segments (in terms of sweep line ordering), if it exists. + * + * A 'non-trivial' intersection is one that will cause one or both of the + * segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection: + * + * * endpoint of segA with endpoint of segB --> trivial + * * endpoint of segA with point along segB --> non-trivial + * * endpoint of segB with point along segA --> non-trivial + * * point along segA with point along segB --> non-trivial + * + * If no non-trivial intersection exists, return null + * Else, return null. + */ + getIntersection(other) { + const tBbox = this.bbox(); + const oBbox = other.bbox(); + const bboxOverlap = getBboxOverlap2(tBbox, oBbox); + if (bboxOverlap === null) + return null; + const tlp = this.leftSE.point; + const trp = this.rightSE.point; + const olp = other.leftSE.point; + const orp = other.rightSE.point; + const touchesOtherLSE = isInBbox2(tBbox, olp) && this.comparePoint(olp) === 0; + const touchesThisLSE = isInBbox2(oBbox, tlp) && other.comparePoint(tlp) === 0; + const touchesOtherRSE = isInBbox2(tBbox, orp) && this.comparePoint(orp) === 0; + const touchesThisRSE = isInBbox2(oBbox, trp) && other.comparePoint(trp) === 0; + if (touchesThisLSE && touchesOtherLSE) { + if (touchesThisRSE && !touchesOtherRSE) + return trp; + if (!touchesThisRSE && touchesOtherRSE) + return orp; + return null; + } + if (touchesThisLSE) { + if (touchesOtherRSE) { + if (tlp.x === orp.x && tlp.y === orp.y) + return null; + } + return tlp; + } + if (touchesOtherLSE) { + if (touchesThisRSE) { + if (trp.x === olp.x && trp.y === olp.y) + return null; + } + return olp; + } + if (touchesThisRSE && touchesOtherRSE) + return null; + if (touchesThisRSE) + return trp; + if (touchesOtherRSE) + return orp; + const pt2 = intersection$1(tlp, this.vector(), olp, other.vector()); + if (pt2 === null) + return null; + if (!isInBbox2(bboxOverlap, pt2)) + return null; + return rounder.round(pt2.x, pt2.y); + } + /** + * Split the given segment into multiple segments on the given points. + * * Each existing segment will retain its leftSE and a new rightSE will be + * generated for it. + * * A new segment will be generated which will adopt the original segment's + * rightSE, and a new leftSE will be generated for it. + * * If there are more than two points given to split on, new segments + * in the middle will be generated with new leftSE and rightSE's. + * * An array of the newly generated SweepEvents will be returned. + * + * Warning: input array of points is modified + */ + split(point2) { + const newEvents = []; + const alreadyLinked = point2.events !== void 0; + const newLeftSE = new SweepEvent2(point2, true); + const newRightSE = new SweepEvent2(point2, false); + const oldRightSE = this.rightSE; + this.replaceRightSE(newRightSE); + newEvents.push(newRightSE); + newEvents.push(newLeftSE); + const newSeg = new Segment2(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice()); + if (SweepEvent2.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) { + newSeg.swapEvents(); + } + if (SweepEvent2.comparePoints(this.leftSE.point, this.rightSE.point) > 0) { + this.swapEvents(); + } + if (alreadyLinked) { + newLeftSE.checkForConsuming(); + newRightSE.checkForConsuming(); + } + return newEvents; + } + /* Swap which event is left and right */ + swapEvents() { + const tmpEvt = this.rightSE; + this.rightSE = this.leftSE; + this.leftSE = tmpEvt; + this.leftSE.isLeft = true; + this.rightSE.isLeft = false; + for (let i3 = 0, iMax = this.windings.length; i3 < iMax; i3++) { + this.windings[i3] *= -1; + } + } + /* Consume another segment. We take their rings under our wing + * and mark them as consumed. Use for perfectly overlapping segments */ + consume(other) { + let consumer = this; + let consumee = other; + while (consumer.consumedBy) + consumer = consumer.consumedBy; + while (consumee.consumedBy) + consumee = consumee.consumedBy; + const cmp2 = Segment2.compare(consumer, consumee); + if (cmp2 === 0) + return; + if (cmp2 > 0) { + const tmp = consumer; + consumer = consumee; + consumee = tmp; + } + if (consumer.prev === consumee) { + const tmp = consumer; + consumer = consumee; + consumee = tmp; + } + for (let i3 = 0, iMax = consumee.rings.length; i3 < iMax; i3++) { + const ring = consumee.rings[i3]; + const winding = consumee.windings[i3]; + const index2 = consumer.rings.indexOf(ring); + if (index2 === -1) { + consumer.rings.push(ring); + consumer.windings.push(winding); + } else + consumer.windings[index2] += winding; + } + consumee.rings = null; + consumee.windings = null; + consumee.consumedBy = consumer; + consumee.leftSE.consumedBy = consumer.leftSE; + consumee.rightSE.consumedBy = consumer.rightSE; + } + /* The first segment previous segment chain that is in the result */ + prevInResult() { + if (this._prevInResult !== void 0) + return this._prevInResult; + if (!this.prev) + this._prevInResult = null; + else if (this.prev.isInResult()) + this._prevInResult = this.prev; + else + this._prevInResult = this.prev.prevInResult(); + return this._prevInResult; + } + beforeState() { + if (this._beforeState !== void 0) + return this._beforeState; + if (!this.prev) + this._beforeState = { + rings: [], + windings: [], + multiPolys: [] + }; + else { + const seg = this.prev.consumedBy || this.prev; + this._beforeState = seg.afterState(); + } + return this._beforeState; + } + afterState() { + if (this._afterState !== void 0) + return this._afterState; + const beforeState = this.beforeState(); + this._afterState = { + rings: beforeState.rings.slice(0), + windings: beforeState.windings.slice(0), + multiPolys: [] + }; + const ringsAfter = this._afterState.rings; + const windingsAfter = this._afterState.windings; + const mpsAfter = this._afterState.multiPolys; + for (let i3 = 0, iMax = this.rings.length; i3 < iMax; i3++) { + const ring = this.rings[i3]; + const winding = this.windings[i3]; + const index2 = ringsAfter.indexOf(ring); + if (index2 === -1) { + ringsAfter.push(ring); + windingsAfter.push(winding); + } else + windingsAfter[index2] += winding; + } + const polysAfter = []; + const polysExclude = []; + for (let i3 = 0, iMax = ringsAfter.length; i3 < iMax; i3++) { + if (windingsAfter[i3] === 0) + continue; + const ring = ringsAfter[i3]; + const poly = ring.poly; + if (polysExclude.indexOf(poly) !== -1) + continue; + if (ring.isExterior) + polysAfter.push(poly); + else { + if (polysExclude.indexOf(poly) === -1) + polysExclude.push(poly); + const index2 = polysAfter.indexOf(ring.poly); + if (index2 !== -1) + polysAfter.splice(index2, 1); + } + } + for (let i3 = 0, iMax = polysAfter.length; i3 < iMax; i3++) { + const mp = polysAfter[i3].multiPoly; + if (mpsAfter.indexOf(mp) === -1) + mpsAfter.push(mp); + } + return this._afterState; + } + /* Is this segment part of the final result? */ + isInResult() { + if (this.consumedBy) + return false; + if (this._isInResult !== void 0) + return this._isInResult; + const mpsBefore = this.beforeState().multiPolys; + const mpsAfter = this.afterState().multiPolys; + switch (operation2.type) { + case "union": { + const noBefores = mpsBefore.length === 0; + const noAfters = mpsAfter.length === 0; + this._isInResult = noBefores !== noAfters; + break; + } + case "intersection": { + let least; + let most; + if (mpsBefore.length < mpsAfter.length) { + least = mpsBefore.length; + most = mpsAfter.length; + } else { + least = mpsAfter.length; + most = mpsBefore.length; + } + this._isInResult = most === operation2.numMultiPolys && least < most; + break; + } + case "xor": { + const diff = Math.abs(mpsBefore.length - mpsAfter.length); + this._isInResult = diff % 2 === 1; + break; + } + case "difference": { + const isJustSubject = (mps) => mps.length === 1 && mps[0].isSubject; + this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter); + break; + } + default: + throw new Error("Unrecognized operation type found ".concat(operation2.type)); + } + return this._isInResult; + } + } + class RingIn2 { + constructor(geomRing, poly, isExterior) { + if (!Array.isArray(geomRing) || geomRing.length === 0) { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + this.poly = poly; + this.isExterior = isExterior; + this.segments = []; + if (typeof geomRing[0][0] !== "number" || typeof geomRing[0][1] !== "number") { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + const firstPoint = rounder.round(geomRing[0][0], geomRing[0][1]); + this.bbox = { + ll: { + x: firstPoint.x, + y: firstPoint.y + }, + ur: { + x: firstPoint.x, + y: firstPoint.y + } + }; + let prevPoint = firstPoint; + for (let i3 = 1, iMax = geomRing.length; i3 < iMax; i3++) { + if (typeof geomRing[i3][0] !== "number" || typeof geomRing[i3][1] !== "number") { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + let point2 = rounder.round(geomRing[i3][0], geomRing[i3][1]); + if (point2.x === prevPoint.x && point2.y === prevPoint.y) + continue; + this.segments.push(Segment2.fromRing(prevPoint, point2, this)); + if (point2.x < this.bbox.ll.x) + this.bbox.ll.x = point2.x; + if (point2.y < this.bbox.ll.y) + this.bbox.ll.y = point2.y; + if (point2.x > this.bbox.ur.x) + this.bbox.ur.x = point2.x; + if (point2.y > this.bbox.ur.y) + this.bbox.ur.y = point2.y; + prevPoint = point2; + } + if (firstPoint.x !== prevPoint.x || firstPoint.y !== prevPoint.y) { + this.segments.push(Segment2.fromRing(prevPoint, firstPoint, this)); + } + } + getSweepEvents() { + const sweepEvents = []; + for (let i3 = 0, iMax = this.segments.length; i3 < iMax; i3++) { + const segment = this.segments[i3]; + sweepEvents.push(segment.leftSE); + sweepEvents.push(segment.rightSE); + } + return sweepEvents; + } + } + class PolyIn2 { + constructor(geomPoly, multiPoly) { + if (!Array.isArray(geomPoly)) { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + this.exteriorRing = new RingIn2(geomPoly[0], this, true); + this.bbox = { + ll: { + x: this.exteriorRing.bbox.ll.x, + y: this.exteriorRing.bbox.ll.y + }, + ur: { + x: this.exteriorRing.bbox.ur.x, + y: this.exteriorRing.bbox.ur.y + } + }; + this.interiorRings = []; + for (let i3 = 1, iMax = geomPoly.length; i3 < iMax; i3++) { + const ring = new RingIn2(geomPoly[i3], this, false); + if (ring.bbox.ll.x < this.bbox.ll.x) + this.bbox.ll.x = ring.bbox.ll.x; + if (ring.bbox.ll.y < this.bbox.ll.y) + this.bbox.ll.y = ring.bbox.ll.y; + if (ring.bbox.ur.x > this.bbox.ur.x) + this.bbox.ur.x = ring.bbox.ur.x; + if (ring.bbox.ur.y > this.bbox.ur.y) + this.bbox.ur.y = ring.bbox.ur.y; + this.interiorRings.push(ring); + } + this.multiPoly = multiPoly; + } + getSweepEvents() { + const sweepEvents = this.exteriorRing.getSweepEvents(); + for (let i3 = 0, iMax = this.interiorRings.length; i3 < iMax; i3++) { + const ringSweepEvents = this.interiorRings[i3].getSweepEvents(); + for (let j2 = 0, jMax = ringSweepEvents.length; j2 < jMax; j2++) { + sweepEvents.push(ringSweepEvents[j2]); + } + } + return sweepEvents; + } + } + class MultiPolyIn2 { + constructor(geom, isSubject) { + if (!Array.isArray(geom)) { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + try { + if (typeof geom[0][0][0] === "number") + geom = [geom]; + } catch (ex) { + } + this.polys = []; + this.bbox = { + ll: { + x: Number.POSITIVE_INFINITY, + y: Number.POSITIVE_INFINITY + }, + ur: { + x: Number.NEGATIVE_INFINITY, + y: Number.NEGATIVE_INFINITY + } + }; + for (let i3 = 0, iMax = geom.length; i3 < iMax; i3++) { + const poly = new PolyIn2(geom[i3], this); + if (poly.bbox.ll.x < this.bbox.ll.x) + this.bbox.ll.x = poly.bbox.ll.x; + if (poly.bbox.ll.y < this.bbox.ll.y) + this.bbox.ll.y = poly.bbox.ll.y; + if (poly.bbox.ur.x > this.bbox.ur.x) + this.bbox.ur.x = poly.bbox.ur.x; + if (poly.bbox.ur.y > this.bbox.ur.y) + this.bbox.ur.y = poly.bbox.ur.y; + this.polys.push(poly); + } + this.isSubject = isSubject; + } + getSweepEvents() { + const sweepEvents = []; + for (let i3 = 0, iMax = this.polys.length; i3 < iMax; i3++) { + const polySweepEvents = this.polys[i3].getSweepEvents(); + for (let j2 = 0, jMax = polySweepEvents.length; j2 < jMax; j2++) { + sweepEvents.push(polySweepEvents[j2]); + } + } + return sweepEvents; + } + } + class RingOut2 { + /* Given the segments from the sweep line pass, compute & return a series + * of closed rings from all the segments marked to be part of the result */ + static factory(allSegments) { + const ringsOut = []; + for (let i3 = 0, iMax = allSegments.length; i3 < iMax; i3++) { + const segment = allSegments[i3]; + if (!segment.isInResult() || segment.ringOut) + continue; + let prevEvent = null; + let event = segment.leftSE; + let nextEvent = segment.rightSE; + const events = [event]; + const startingPoint = event.point; + const intersectionLEs = []; + while (true) { + prevEvent = event; + event = nextEvent; + events.push(event); + if (event.point === startingPoint) + break; + while (true) { + const availableLEs = event.getAvailableLinkedEvents(); + if (availableLEs.length === 0) { + const firstPt = events[0].point; + const lastPt = events[events.length - 1].point; + throw new Error("Unable to complete output ring starting at [".concat(firstPt.x, ",") + " ".concat(firstPt.y, "]. Last matching segment found ends at") + " [".concat(lastPt.x, ", ").concat(lastPt.y, "].")); + } + if (availableLEs.length === 1) { + nextEvent = availableLEs[0].otherSE; + break; + } + let indexLE = null; + for (let j2 = 0, jMax = intersectionLEs.length; j2 < jMax; j2++) { + if (intersectionLEs[j2].point === event.point) { + indexLE = j2; + break; + } + } + if (indexLE !== null) { + const intersectionLE = intersectionLEs.splice(indexLE)[0]; + const ringEvents = events.splice(intersectionLE.index); + ringEvents.unshift(ringEvents[0].otherSE); + ringsOut.push(new RingOut2(ringEvents.reverse())); + continue; + } + intersectionLEs.push({ + index: events.length, + point: event.point + }); + const comparator = event.getLeftmostComparator(prevEvent); + nextEvent = availableLEs.sort(comparator)[0].otherSE; + break; + } + } + ringsOut.push(new RingOut2(events)); + } + return ringsOut; + } + constructor(events) { + this.events = events; + for (let i3 = 0, iMax = events.length; i3 < iMax; i3++) { + events[i3].segment.ringOut = this; + } + this.poly = null; + } + getGeom() { + let prevPt = this.events[0].point; + const points = [prevPt]; + for (let i3 = 1, iMax = this.events.length - 1; i3 < iMax; i3++) { + const pt3 = this.events[i3].point; + const nextPt2 = this.events[i3 + 1].point; + if (compareVectorAngles(pt3, prevPt, nextPt2) === 0) + continue; + points.push(pt3); + prevPt = pt3; + } + if (points.length === 1) + return null; + const pt2 = points[0]; + const nextPt = points[1]; + if (compareVectorAngles(pt2, prevPt, nextPt) === 0) + points.shift(); + points.push(points[0]); + const step = this.isExteriorRing() ? 1 : -1; + const iStart = this.isExteriorRing() ? 0 : points.length - 1; + const iEnd = this.isExteriorRing() ? points.length : -1; + const orderedPoints = []; + for (let i3 = iStart; i3 != iEnd; i3 += step) + orderedPoints.push([points[i3].x, points[i3].y]); + return orderedPoints; + } + isExteriorRing() { + if (this._isExteriorRing === void 0) { + const enclosing = this.enclosingRing(); + this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true; + } + return this._isExteriorRing; + } + enclosingRing() { + if (this._enclosingRing === void 0) { + this._enclosingRing = this._calcEnclosingRing(); + } + return this._enclosingRing; + } + /* Returns the ring that encloses this one, if any */ + _calcEnclosingRing() { + let leftMostEvt = this.events[0]; + for (let i3 = 1, iMax = this.events.length; i3 < iMax; i3++) { + const evt = this.events[i3]; + if (SweepEvent2.compare(leftMostEvt, evt) > 0) + leftMostEvt = evt; + } + let prevSeg = leftMostEvt.segment.prevInResult(); + let prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null; + while (true) { + if (!prevSeg) + return null; + if (!prevPrevSeg) + return prevSeg.ringOut; + if (prevPrevSeg.ringOut !== prevSeg.ringOut) { + if (prevPrevSeg.ringOut.enclosingRing() !== prevSeg.ringOut) { + return prevSeg.ringOut; + } else + return prevSeg.ringOut.enclosingRing(); + } + prevSeg = prevPrevSeg.prevInResult(); + prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null; + } + } + } + class PolyOut2 { + constructor(exteriorRing) { + this.exteriorRing = exteriorRing; + exteriorRing.poly = this; + this.interiorRings = []; + } + addInterior(ring) { + this.interiorRings.push(ring); + ring.poly = this; + } + getGeom() { + const geom = [this.exteriorRing.getGeom()]; + if (geom[0] === null) + return null; + for (let i3 = 0, iMax = this.interiorRings.length; i3 < iMax; i3++) { + const ringGeom = this.interiorRings[i3].getGeom(); + if (ringGeom === null) + continue; + geom.push(ringGeom); + } + return geom; + } + } + class MultiPolyOut2 { + constructor(rings) { + this.rings = rings; + this.polys = this._composePolys(rings); + } + getGeom() { + const geom = []; + for (let i3 = 0, iMax = this.polys.length; i3 < iMax; i3++) { + const polyGeom = this.polys[i3].getGeom(); + if (polyGeom === null) + continue; + geom.push(polyGeom); + } + return geom; + } + _composePolys(rings) { + const polys = []; + for (let i3 = 0, iMax = rings.length; i3 < iMax; i3++) { + const ring = rings[i3]; + if (ring.poly) + continue; + if (ring.isExteriorRing()) + polys.push(new PolyOut2(ring)); + else { + const enclosingRing = ring.enclosingRing(); + if (!enclosingRing.poly) + polys.push(new PolyOut2(enclosingRing)); + enclosingRing.poly.addInterior(ring); + } + } + return polys; + } + } + class SweepLine2 { + constructor(queue) { + let comparator = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : Segment2.compare; + this.queue = queue; + this.tree = new Tree(comparator); + this.segments = []; + } + process(event) { + const segment = event.segment; + const newEvents = []; + if (event.consumedBy) { + if (event.isLeft) + this.queue.remove(event.otherSE); + else + this.tree.remove(segment); + return newEvents; + } + const node = event.isLeft ? this.tree.add(segment) : this.tree.find(segment); + if (!node) + throw new Error("Unable to find segment #".concat(segment.id, " ") + "[".concat(segment.leftSE.point.x, ", ").concat(segment.leftSE.point.y, "] -> ") + "[".concat(segment.rightSE.point.x, ", ").concat(segment.rightSE.point.y, "] ") + "in SweepLine tree."); + let prevNode = node; + let nextNode = node; + let prevSeg = void 0; + let nextSeg = void 0; + while (prevSeg === void 0) { + prevNode = this.tree.prev(prevNode); + if (prevNode === null) + prevSeg = null; + else if (prevNode.key.consumedBy === void 0) + prevSeg = prevNode.key; + } + while (nextSeg === void 0) { + nextNode = this.tree.next(nextNode); + if (nextNode === null) + nextSeg = null; + else if (nextNode.key.consumedBy === void 0) + nextSeg = nextNode.key; + } + if (event.isLeft) { + let prevMySplitter = null; + if (prevSeg) { + const prevInter = prevSeg.getIntersection(segment); + if (prevInter !== null) { + if (!segment.isAnEndpoint(prevInter)) + prevMySplitter = prevInter; + if (!prevSeg.isAnEndpoint(prevInter)) { + const newEventsFromSplit = this._splitSafely(prevSeg, prevInter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + } + } + let nextMySplitter = null; + if (nextSeg) { + const nextInter = nextSeg.getIntersection(segment); + if (nextInter !== null) { + if (!segment.isAnEndpoint(nextInter)) + nextMySplitter = nextInter; + if (!nextSeg.isAnEndpoint(nextInter)) { + const newEventsFromSplit = this._splitSafely(nextSeg, nextInter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + } + } + if (prevMySplitter !== null || nextMySplitter !== null) { + let mySplitter = null; + if (prevMySplitter === null) + mySplitter = nextMySplitter; + else if (nextMySplitter === null) + mySplitter = prevMySplitter; + else { + const cmpSplitters = SweepEvent2.comparePoints(prevMySplitter, nextMySplitter); + mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter; + } + this.queue.remove(segment.rightSE); + newEvents.push(segment.rightSE); + const newEventsFromSplit = segment.split(mySplitter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + if (newEvents.length > 0) { + this.tree.remove(segment); + newEvents.push(event); + } else { + this.segments.push(segment); + segment.prev = prevSeg; + } + } else { + if (prevSeg && nextSeg) { + const inter = prevSeg.getIntersection(nextSeg); + if (inter !== null) { + if (!prevSeg.isAnEndpoint(inter)) { + const newEventsFromSplit = this._splitSafely(prevSeg, inter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + if (!nextSeg.isAnEndpoint(inter)) { + const newEventsFromSplit = this._splitSafely(nextSeg, inter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + } + } + this.tree.remove(segment); + } + return newEvents; + } + /* Safely split a segment that is currently in the datastructures + * IE - a segment other than the one that is currently being processed. */ + _splitSafely(seg, pt2) { + this.tree.remove(seg); + const rightSE = seg.rightSE; + this.queue.remove(rightSE); + const newEvents = seg.split(pt2); + newEvents.push(rightSE); + if (seg.consumedBy === void 0) + this.tree.add(seg); + return newEvents; + } + } + const POLYGON_CLIPPING_MAX_QUEUE_SIZE = typeof process !== "undefined" && process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE || 1e6; + const POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS = typeof process !== "undefined" && process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS || 1e6; + class Operation2 { + run(type2, geom, moreGeoms) { + operation2.type = type2; + rounder.reset(); + const multipolys = [new MultiPolyIn2(geom, true)]; + for (let i3 = 0, iMax = moreGeoms.length; i3 < iMax; i3++) { + multipolys.push(new MultiPolyIn2(moreGeoms[i3], false)); + } + operation2.numMultiPolys = multipolys.length; + if (operation2.type === "difference") { + const subject = multipolys[0]; + let i3 = 1; + while (i3 < multipolys.length) { + if (getBboxOverlap2(multipolys[i3].bbox, subject.bbox) !== null) + i3++; + else + multipolys.splice(i3, 1); + } + } + if (operation2.type === "intersection") { + for (let i3 = 0, iMax = multipolys.length; i3 < iMax; i3++) { + const mpA = multipolys[i3]; + for (let j2 = i3 + 1, jMax = multipolys.length; j2 < jMax; j2++) { + if (getBboxOverlap2(mpA.bbox, multipolys[j2].bbox) === null) + return []; + } + } + } + const queue = new Tree(SweepEvent2.compare); + for (let i3 = 0, iMax = multipolys.length; i3 < iMax; i3++) { + const sweepEvents = multipolys[i3].getSweepEvents(); + for (let j2 = 0, jMax = sweepEvents.length; j2 < jMax; j2++) { + queue.insert(sweepEvents[j2]); + if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) { + throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big)."); + } + } + } + const sweepLine = new SweepLine2(queue); + let prevQueueSize = queue.size; + let node = queue.pop(); + while (node) { + const evt = node.key; + if (queue.size === prevQueueSize) { + const seg = evt.segment; + throw new Error("Unable to pop() ".concat(evt.isLeft ? "left" : "right", " SweepEvent ") + "[".concat(evt.point.x, ", ").concat(evt.point.y, "] from segment #").concat(seg.id, " ") + "[".concat(seg.leftSE.point.x, ", ").concat(seg.leftSE.point.y, "] -> ") + "[".concat(seg.rightSE.point.x, ", ").concat(seg.rightSE.point.y, "] from queue.")); + } + if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) { + throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big)."); + } + if (sweepLine.segments.length > POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS) { + throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments)."); + } + const newEvents = sweepLine.process(evt); + for (let i3 = 0, iMax = newEvents.length; i3 < iMax; i3++) { + const evt2 = newEvents[i3]; + if (evt2.consumedBy === void 0) + queue.insert(evt2); + } + prevQueueSize = queue.size; + node = queue.pop(); + } + rounder.reset(); + const ringsOut = RingOut2.factory(sweepLine.segments); + const result = new MultiPolyOut2(ringsOut); + return result.getGeom(); + } + } + const operation2 = new Operation2(); + const union2 = function(geom) { + for (var _len = arguments.length, moreGeoms = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + moreGeoms[_key - 1] = arguments[_key]; + } + return operation2.run("union", geom, moreGeoms); + }; + const intersection2 = function(geom) { + for (var _len2 = arguments.length, moreGeoms = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + moreGeoms[_key2 - 1] = arguments[_key2]; + } + return operation2.run("intersection", geom, moreGeoms); + }; + const xor = function(geom) { + for (var _len3 = arguments.length, moreGeoms = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + moreGeoms[_key3 - 1] = arguments[_key3]; + } + return operation2.run("xor", geom, moreGeoms); + }; + const difference2 = function(subjectGeom) { + for (var _len4 = arguments.length, clippingGeoms = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + clippingGeoms[_key4 - 1] = arguments[_key4]; + } + return operation2.run("difference", subjectGeom, clippingGeoms); + }; + var index = { + union: union2, + intersection: intersection2, + xor, + difference: difference2 + }; + return index; + }); + } + }); + + // node_modules/whatwg-fetch/fetch.js + var g = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef + typeof global !== "undefined" && global || {}; + var support = { + searchParams: "URLSearchParams" in g, + iterable: "Symbol" in g && "iterator" in Symbol, + blob: "FileReader" in g && "Blob" in g && function() { + try { + new Blob(); + return true; + } catch (e3) { + return false; + } + }(), + formData: "FormData" in g, + arrayBuffer: "ArrayBuffer" in g + }; + function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj); + } + if (support.arrayBuffer) { viewClasses = [ "[object Int8Array]", "[object Uint8Array]", @@ -15275,6 +14619,7 @@ }; Response.error = function() { var response = new Response(null, { status: 200, statusText: "" }); + response.ok = false; response.status = 0; response.type = "error"; return response; @@ -15311,10 +14656,14 @@ } xhr.onload = function() { var options2 = { - status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || "") }; + if (request3.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) { + options2.status = 200; + } else { + options2.status = xhr.status; + } options2.url = "responseURL" in xhr ? xhr.responseURL : options2.headers.get("X-Request-URL"); var body = "response" in xhr ? xhr.response : xhr.responseText; setTimeout(function() { @@ -15328,7 +14677,7 @@ }; xhr.ontimeout = function() { setTimeout(function() { - reject(new TypeError("Network request failed")); + reject(new TypeError("Network request timed out")); }, 0); }; xhr.onabort = function() { @@ -15857,6 +15206,8 @@ coreValidator: () => coreValidator, d3: () => d3, debug: () => debug, + dmsCoordinatePair: () => dmsCoordinatePair, + dmsMatcher: () => dmsMatcher, fileFetcher: () => _mainFileFetcher, geoAngle: () => geoAngle, geoChooseEdge: () => geoChooseEdge, @@ -16226,6 +15577,7 @@ validationMismatchedGeometry: () => validationMismatchedGeometry, validationMissingRole: () => validationMissingRole, validationMissingTag: () => validationMissingTag, + validationMutuallyExclusiveTags: () => validationMutuallyExclusiveTags, validationOutdatedTags: () => validationOutdatedTags, validationPrivateData: () => validationPrivateData, validationSuspiciousName: () => validationSuspiciousName, @@ -16265,6 +15617,11 @@ forwards: "backward", backwards: "forward" }; + const valueReplacementsExceptions = { + "side": [ + { highway: "cyclist_waiting_aid" } + ] + }; var roleReplacements = { forward: "backward", backward: "forward", @@ -16303,7 +15660,7 @@ } return key; } - function reverseValue(key, value, includeAbsolute) { + function reverseValue(key, value, includeAbsolute, allTags) { if (ignoreKey.test(key)) return value; if (turn_lanes.test(key)) { @@ -16331,6 +15688,14 @@ } }).join(";"); } + if (valueReplacementsExceptions[key] && valueReplacementsExceptions[key].some( + (exceptionTags) => Object.keys(exceptionTags).every((k2) => { + const v2 = exceptionTags[k2]; + return allTags[k2] && (v2 === "*" || allTags[k2] === v2); + }) + )) { + return value; + } return valueReplacements[value] || value; } function reverseNodeTags(graph, nodeIDs) { @@ -16340,7 +15705,7 @@ continue; var tags = {}; for (var key in node.tags) { - tags[reverseKey(key)] = reverseValue(key, node.tags[key], node.id === entityID); + tags[reverseKey(key)] = reverseValue(key, node.tags[key], node.id === entityID, node.tags); } graph = graph.replace(node.update({ tags })); } @@ -16351,7 +15716,7 @@ var tags = {}; var role; for (var key in way.tags) { - tags[reverseKey(key)] = reverseValue(key, way.tags[key]); + tags[reverseKey(key)] = reverseValue(key, way.tags[key], false, way.tags); } graph.parentRelations(way).forEach(function(relation) { relation.members.forEach(function(member, index) { @@ -16376,7 +15741,7 @@ return false; for (var key in entity.tags) { var value = entity.tags[key]; - if (reverseKey(key) !== key || reverseValue(key, value, true) !== value) { + if (reverseKey(key) !== key || reverseValue(key, value, true, entity.tags) !== value) { return false; } } @@ -16444,9 +15809,6 @@ turntable: true, wash: true }, - traffic_calming: { - island: true - }, waterway: { dam: true } @@ -16603,6 +15965,7 @@ track: true, living_street: true, bus_guideway: true, + busway: true, path: true, footway: true, cycleway: true, @@ -16642,6 +16005,24 @@ tidal_channel: true }; var allowUpperCaseTagValues = /network|taxon|genus|species|brand|grape_variety|royal_cypher|listed_status|booth|rating|stars|:output|_hours|_times|_ref|manufacturer|country|target|brewery|cai_scale|traffic_sign/; + function isColourValid(value) { + if (!value.match(/^(#([0-9a-fA-F]{3}){1,2}|\w+)$/)) { + return false; + } + if (!CSS.supports("color", value) || ["unset", "inherit", "initial", "revert"].includes(value)) { + return false; + } + return true; + } + var osmMutuallyExclusiveTagPairs = [ + ["noname", "name"], + ["noref", "ref"], + ["nohousenumber", "addr:housenumber"], + ["noaddress", "addr:housenumber"], + ["noaddress", "addr:housename"], + ["noaddress", "addr:unit"], + ["addr:nostreet", "addr:street"] + ]; // node_modules/d3-array/src/ascending.js function ascending(a2, b2) { @@ -16654,16 +16035,16 @@ } // node_modules/d3-array/src/bisector.js - function bisector(f3) { + function bisector(f2) { let compare1, compare2, delta; - if (f3.length !== 2) { + if (f2.length !== 2) { compare1 = ascending; - compare2 = (d2, x2) => ascending(f3(d2), x2); - delta = (d2, x2) => f3(d2) - x2; + compare2 = (d2, x2) => ascending(f2(d2), x2); + delta = (d2, x2) => f2(d2) - x2; } else { - compare1 = f3 === ascending || f3 === descending ? f3 : zero; - compare2 = f3; - delta = f3; + compare1 = f2 === ascending || f2 === descending ? f2 : zero; + compare2 = f2; + delta = f2; } function left(a2, x2, lo = 0, hi = a2.length) { if (lo < hi) { @@ -16740,8 +16121,8 @@ add(x2) { const p2 = this._partials; let i3 = 0; - for (let j3 = 0; j3 < this._n && j3 < 32; j3++) { - const y2 = p2[j3], hi = x2 + y2, lo = Math.abs(x2) < Math.abs(y2) ? x2 - (hi - y2) : y2 - (hi - x2); + for (let j2 = 0; j2 < this._n && j2 < 32; j2++) { + const y2 = p2[j2], hi = x2 + y2, lo = Math.abs(x2) < Math.abs(y2) ? x2 - (hi - y2) : y2 - (hi - x2); if (lo) p2[i3++] = lo; x2 = hi; @@ -16775,16 +16156,16 @@ }; // node_modules/d3-array/src/sort.js - function compareDefined(compare = ascending) { - if (compare === ascending) + function compareDefined(compare2 = ascending) { + if (compare2 === ascending) return ascendingDefined; - if (typeof compare !== "function") + if (typeof compare2 !== "function") throw new TypeError("compare is not a function"); return (a2, b2) => { - const x2 = compare(a2, b2); + const x2 = compare2(a2, b2); if (x2 || x2 === 0) return x2; - return (compare(b2, b2) === 0) - (compare(a2, a2) === 0); + return (compare2(b2, b2) === 0) - (compare2(a2, a2) === 0); }; } function ascendingDefined(a2, b2) { @@ -16884,8 +16265,8 @@ } // node_modules/d3-array/src/quickselect.js - function quickselect(array2, k2, left = 0, right = array2.length - 1, compare) { - compare = compare === void 0 ? ascendingDefined : compareDefined(compare); + function quickselect(array2, k2, left = 0, right = array2.length - 1, compare2) { + compare2 = compare2 === void 0 ? ascendingDefined : compareDefined(compare2); while (right > left) { if (right - left > 600) { const n3 = right - left + 1; @@ -16895,36 +16276,36 @@ const sd = 0.5 * Math.sqrt(z2 * s2 * (n3 - s2) / n3) * (m2 - n3 / 2 < 0 ? -1 : 1); const newLeft = Math.max(left, Math.floor(k2 - m2 * s2 / n3 + sd)); const newRight = Math.min(right, Math.floor(k2 + (n3 - m2) * s2 / n3 + sd)); - quickselect(array2, k2, newLeft, newRight, compare); + quickselect(array2, k2, newLeft, newRight, compare2); } const t2 = array2[k2]; let i3 = left; - let j3 = right; + let j2 = right; swap(array2, left, k2); - if (compare(array2[right], t2) > 0) + if (compare2(array2[right], t2) > 0) swap(array2, left, right); - while (i3 < j3) { - swap(array2, i3, j3), ++i3, --j3; - while (compare(array2[i3], t2) < 0) + while (i3 < j2) { + swap(array2, i3, j2), ++i3, --j2; + while (compare2(array2[i3], t2) < 0) ++i3; - while (compare(array2[j3], t2) > 0) - --j3; + while (compare2(array2[j2], t2) > 0) + --j2; } - if (compare(array2[left], t2) === 0) - swap(array2, left, j3); + if (compare2(array2[left], t2) === 0) + swap(array2, left, j2); else - ++j3, swap(array2, j3, right); - if (j3 <= k2) - left = j3 + 1; - if (k2 <= j3) - right = j3 - 1; + ++j2, swap(array2, j2, right); + if (j2 <= k2) + left = j2 + 1; + if (k2 <= j2) + right = j2 - 1; } return array2; } - function swap(array2, i3, j3) { + function swap(array2, i3, j2) { const t2 = array2[i3]; - array2[i3] = array2[j3]; - array2[j3] = t2; + array2[i3] = array2[j2]; + array2[j2] = t2; } // node_modules/d3-array/src/quantile.js @@ -16948,7 +16329,7 @@ // node_modules/d3-array/src/merge.js function* flatten(arrays) { for (const array2 of arrays) { - yield* __yieldStar(array2); + yield* array2; } } function merge(arrays) { @@ -17547,16 +16928,16 @@ if (!(m2 = (ring = polygon2[i3]).length)) continue; var ring, m2, point0 = ring[m2 - 1], lambda04 = longitude(point0), phi02 = point0[1] / 2 + quarterPi, sinPhi03 = sin(phi02), cosPhi03 = cos(phi02); - for (var j3 = 0; j3 < m2; ++j3, lambda04 = lambda12, sinPhi03 = sinPhi1, cosPhi03 = cosPhi1, point0 = point1) { - var point1 = ring[j3], lambda12 = longitude(point1), phi12 = point1[1] / 2 + quarterPi, sinPhi1 = sin(phi12), cosPhi1 = cos(phi12), delta = lambda12 - lambda04, sign2 = delta >= 0 ? 1 : -1, absDelta = sign2 * delta, antimeridian = absDelta > pi, k2 = sinPhi03 * sinPhi1; + for (var j2 = 0; j2 < m2; ++j2, lambda04 = lambda12, sinPhi03 = sinPhi1, cosPhi03 = cosPhi1, point0 = point1) { + var point1 = ring[j2], lambda12 = longitude(point1), phi12 = point1[1] / 2 + quarterPi, sinPhi1 = sin(phi12), cosPhi1 = cos(phi12), delta = lambda12 - lambda04, sign2 = delta >= 0 ? 1 : -1, absDelta = sign2 * delta, antimeridian = absDelta > pi, k2 = sinPhi03 * sinPhi1; sum.add(atan2(k2 * sign2 * sin(absDelta), cosPhi03 * cosPhi1 + k2 * cos(absDelta))); angle2 += antimeridian ? delta + sign2 * tau : delta; if (antimeridian ^ lambda04 >= lambda ^ lambda12 >= lambda) { var arc = cartesianCross(cartesian(point0), cartesian(point1)); cartesianNormalizeInPlace(arc); - var intersection = cartesianCross(normal, arc); - cartesianNormalizeInPlace(intersection); - var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]); + var intersection2 = cartesianCross(normal, arc); + cartesianNormalizeInPlace(intersection2); + var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection2[2]); if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) { winding += antimeridian ^ delta >= 0 ? 1 : -1; } @@ -17972,8 +17353,8 @@ function polygonInside() { var winding = 0; for (var i3 = 0, n3 = polygon2.length; i3 < n3; ++i3) { - for (var ring2 = polygon2[i3], j3 = 1, m2 = ring2.length, point3 = ring2[0], a0, a1, b0 = point3[0], b1 = point3[1]; j3 < m2; ++j3) { - a0 = b0, a1 = b1, point3 = ring2[j3], b0 = point3[0], b1 = point3[1]; + for (var ring2 = polygon2[i3], j2 = 1, m2 = ring2.length, point3 = ring2[0], a0, a1, b0 = point3[0], b1 = point3[1]; j2 < m2; ++j2) { + a0 = b0, a1 = b1, point3 = ring2[j2], b0 = point3[0], b1 = point3[1]; if (a1 <= y12) { if (b1 > y12 && (b0 - a0) * (y12 - a1) > (b1 - a1) * (x05 - a0)) ++winding; @@ -18318,9 +17699,9 @@ lengthRing = null; }, result: function() { - var length = +lengthSum2; + var length2 = +lengthSum2; lengthSum2 = new Adder(); - return length; + return length2; } }; function lengthPointFirst2(x2, y2) { @@ -18974,6 +18355,15 @@ }, toParam: function() { return this.rectangle().join(","); + }, + split: function() { + const center = this.center(); + return [ + geoExtent(this[0], center), + geoExtent([center[0], this[0][1]], [this[1][0], center[1]]), + geoExtent(center, this[1]), + geoExtent([this[0][0], center[1]], [center[0], this[1][1]]) + ]; } }); @@ -19074,9 +18464,9 @@ return x2 * x2 + y2 * y2; } function geoVecNormalize(a2) { - var length = Math.sqrt(a2[0] * a2[0] + a2[1] * a2[1]); - if (length !== 0) { - return geoVecScale(a2, 1 / length); + var length2 = Math.sqrt(a2[0] * a2[0] + a2[1] * a2[1]); + if (length2 !== 0) { + return geoVecScale(a2, 1 / length2); } return [0, 0]; } @@ -19190,24 +18580,24 @@ function geoHasLineIntersections(activeNodes, inactiveNodes, activeID) { var actives = []; var inactives = []; - var j3, k2, n1, n22, segment; - for (j3 = 0; j3 < activeNodes.length - 1; j3++) { - n1 = activeNodes[j3]; - n22 = activeNodes[j3 + 1]; + var j2, k2, n1, n22, segment; + for (j2 = 0; j2 < activeNodes.length - 1; j2++) { + n1 = activeNodes[j2]; + n22 = activeNodes[j2 + 1]; segment = [n1.loc, n22.loc]; if (n1.id === activeID || n22.id === activeID) { actives.push(segment); } } - for (j3 = 0; j3 < inactiveNodes.length - 1; j3++) { - n1 = inactiveNodes[j3]; - n22 = inactiveNodes[j3 + 1]; + for (j2 = 0; j2 < inactiveNodes.length - 1; j2++) { + n1 = inactiveNodes[j2]; + n22 = inactiveNodes[j2 + 1]; segment = [n1.loc, n22.loc]; inactives.push(segment); } - for (j3 = 0; j3 < actives.length; j3++) { + for (j2 = 0; j2 < actives.length; j2++) { for (k2 = 0; k2 < inactives.length; k2++) { - var p2 = actives[j3]; + var p2 = actives[j2]; var q2 = inactives[k2]; var hit = geoLineIntersection(p2, q2); if (hit) { @@ -19220,10 +18610,10 @@ function geoHasSelfIntersections(nodes, activeID) { var actives = []; var inactives = []; - var j3, k2; - for (j3 = 0; j3 < nodes.length - 1; j3++) { - var n1 = nodes[j3]; - var n22 = nodes[j3 + 1]; + var j2, k2; + for (j2 = 0; j2 < nodes.length - 1; j2++) { + var n1 = nodes[j2]; + var n22 = nodes[j2 + 1]; var segment = [n1.loc, n22.loc]; if (n1.id === activeID || n22.id === activeID) { actives.push(segment); @@ -19231,9 +18621,9 @@ inactives.push(segment); } } - for (j3 = 0; j3 < actives.length; j3++) { + for (j2 = 0; j2 < actives.length; j2++) { for (k2 = 0; k2 < inactives.length; k2++) { - var p2 = actives[j3]; + var p2 = actives[j2]; var q2 = inactives[k2]; if (geoVecEqual(p2[1], q2[0]) || geoVecEqual(p2[0], q2[1]) || geoVecEqual(p2[0], q2[0]) || geoVecEqual(p2[1], q2[1])) { continue; @@ -19272,9 +18662,9 @@ function geoPathIntersections(path1, path2) { var intersections = []; for (var i3 = 0; i3 < path1.length - 1; i3++) { - for (var j3 = 0; j3 < path2.length - 1; j3++) { + for (var j2 = 0; j2 < path2.length - 1; j2++) { var a2 = [path1[i3], path1[i3 + 1]]; - var b2 = [path2[j3], path2[j3 + 1]]; + var b2 = [path2[j2], path2[j2 + 1]]; var hit = geoLineIntersection(a2, b2); if (hit) { intersections.push(hit); @@ -19285,9 +18675,9 @@ } function geoPathHasIntersections(path1, path2) { for (var i3 = 0; i3 < path1.length - 1; i3++) { - for (var j3 = 0; j3 < path2.length - 1; j3++) { + for (var j2 = 0; j2 < path2.length - 1; j2++) { var a2 = [path1[i3], path1[i3 + 1]]; - var b2 = [path2[j3], path2[j3 + 1]]; + var b2 = [path2[j2], path2[j2 + 1]]; var hit = geoLineIntersection(a2, b2); if (hit) { return true; @@ -19300,11 +18690,11 @@ var x2 = point2[0]; var y2 = point2[1]; var inside = false; - for (var i3 = 0, j3 = polygon2.length - 1; i3 < polygon2.length; j3 = i3++) { + for (var i3 = 0, j2 = polygon2.length - 1; i3 < polygon2.length; j2 = i3++) { var xi = polygon2[i3][0]; var yi = polygon2[i3][1]; - var xj = polygon2[j3][0]; - var yj = polygon2[j3][1]; + var xj = polygon2[j2][0]; + var yj = polygon2[j2][1]; var intersect2 = yi > y2 !== yj > y2 && x2 < (xj - xi) * (y2 - yi) / (yj - yi) + xi; if (intersect2) inside = !inside; @@ -19352,11 +18742,11 @@ }; } function geoPathLength(path) { - var length = 0; + var length2 = 0; for (var i3 = 0; i3 < path.length - 1; i3++) { - length += geoVecLength(path[i3], path[i3 + 1]); + length2 += geoVecLength(path[i3], path[i3 + 1]); } - return length; + return length2; } function geoViewportEdge(point2, dimensions) { var pad2 = [80, 20, 50, 20]; @@ -19516,8 +18906,8 @@ function select_default(select) { if (typeof select !== "function") select = selector_default(select); - for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, subgroup = subgroups[j3] = new Array(n3), node, subnode, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, subgroup = subgroups[j2] = new Array(n3), node, subnode, i3 = 0; i3 < n3; ++i3) { if ((node = group[i3]) && (subnode = select.call(node, node.__data__, i3, group))) { if ("__data__" in node) subnode.__data__ = node.__data__; @@ -19554,8 +18944,8 @@ select = arrayAll(select); else select = selectorAll_default(select); - for (var groups = this._groups, m2 = groups.length, subgroups = [], parents = [], j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, subgroups = [], parents = [], j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { if (node = group[i3]) { subgroups.push(select.call(node, node.__data__, i3, group)); parents.push(node); @@ -19609,8 +18999,8 @@ function filter_default(match) { if (typeof match !== "function") match = matcher_default(match); - for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, subgroup = subgroups[j3] = [], node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, subgroup = subgroups[j2] = [], node, i3 = 0; i3 < n3; ++i3) { if ((node = group[i3]) && match.call(node, node.__data__, i3, group)) { subgroup.push(node); } @@ -19712,8 +19102,8 @@ var bind = key ? bindKey : bindIndex, parents = this._parents, groups = this._groups; if (typeof value !== "function") value = constant_default(value); - for (var m2 = groups.length, update = new Array(m2), enter = new Array(m2), exit = new Array(m2), j3 = 0; j3 < m2; ++j3) { - var parent = parents[j3], group = groups[j3], groupLength = group.length, data = arraylike(value.call(parent, parent && parent.__data__, j3, parents)), dataLength = data.length, enterGroup = enter[j3] = new Array(dataLength), updateGroup = update[j3] = new Array(dataLength), exitGroup = exit[j3] = new Array(groupLength); + for (var m2 = groups.length, update = new Array(m2), enter = new Array(m2), exit = new Array(m2), j2 = 0; j2 < m2; ++j2) { + var parent = parents[j2], group = groups[j2], groupLength = group.length, data = arraylike(value.call(parent, parent && parent.__data__, j2, parents)), dataLength = data.length, enterGroup = enter[j2] = new Array(dataLength), updateGroup = update[j2] = new Array(dataLength), exitGroup = exit[j2] = new Array(groupLength); bind(parent, group, enterGroup, updateGroup, exitGroup, data, key); for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) { if (previous = enterGroup[i0]) { @@ -19764,23 +19154,23 @@ // node_modules/d3-selection/src/selection/merge.js function merge_default(context) { var selection2 = context.selection ? context.selection() : context; - for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j3 = 0; j3 < m2; ++j3) { - for (var group0 = groups0[j3], group1 = groups1[j3], n3 = group0.length, merge2 = merges[j3] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) { + for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j2 = 0; j2 < m2; ++j2) { + for (var group0 = groups0[j2], group1 = groups1[j2], n3 = group0.length, merge2 = merges[j2] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) { if (node = group0[i3] || group1[i3]) { merge2[i3] = node; } } } - for (; j3 < m0; ++j3) { - merges[j3] = groups0[j3]; + for (; j2 < m0; ++j2) { + merges[j2] = groups0[j2]; } return new Selection(merges, this._parents); } // node_modules/d3-selection/src/selection/order.js function order_default() { - for (var groups = this._groups, j3 = -1, m2 = groups.length; ++j3 < m2; ) { - for (var group = groups[j3], i3 = group.length - 1, next = group[i3], node; --i3 >= 0; ) { + for (var groups = this._groups, j2 = -1, m2 = groups.length; ++j2 < m2; ) { + for (var group = groups[j2], i3 = group.length - 1, next = group[i3], node; --i3 >= 0; ) { if (node = group[i3]) { if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next); @@ -19792,14 +19182,14 @@ } // node_modules/d3-selection/src/selection/sort.js - function sort_default(compare) { - if (!compare) - compare = ascending2; + function sort_default(compare2) { + if (!compare2) + compare2 = ascending2; function compareNode(a2, b2) { - return a2 && b2 ? compare(a2.__data__, b2.__data__) : !a2 - !b2; + return a2 && b2 ? compare2(a2.__data__, b2.__data__) : !a2 - !b2; } - for (var groups = this._groups, m2 = groups.length, sortgroups = new Array(m2), j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, sortgroup = sortgroups[j3] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, sortgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, sortgroup = sortgroups[j2] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) { if (node = group[i3]) { sortgroup[i3] = node; } @@ -19827,8 +19217,8 @@ // node_modules/d3-selection/src/selection/node.js function node_default() { - for (var groups = this._groups, j3 = 0, m2 = groups.length; j3 < m2; ++j3) { - for (var group = groups[j3], i3 = 0, n3 = group.length; i3 < n3; ++i3) { + for (var groups = this._groups, j2 = 0, m2 = groups.length; j2 < m2; ++j2) { + for (var group = groups[j2], i3 = 0, n3 = group.length; i3 < n3; ++i3) { var node = group[i3]; if (node) return node; @@ -19852,8 +19242,8 @@ // node_modules/d3-selection/src/selection/each.js function each_default(callback) { - for (var groups = this._groups, j3 = 0, m2 = groups.length; j3 < m2; ++j3) { - for (var group = groups[j3], i3 = 0, n3 = group.length, node; i3 < n3; ++i3) { + for (var groups = this._groups, j2 = 0, m2 = groups.length; j2 < m2; ++j2) { + for (var group = groups[j2], i3 = 0, n3 = group.length, node; i3 < n3; ++i3) { if (node = group[i3]) callback.call(node, node.__data__, i3, group); } @@ -19996,14 +19386,14 @@ } }; function classedAdd(node, names) { - var list = classList(node), i3 = -1, n3 = names.length; + var list2 = classList(node), i3 = -1, n3 = names.length; while (++i3 < n3) - list.add(names[i3]); + list2.add(names[i3]); } function classedRemove(node, names) { - var list = classList(node), i3 = -1, n3 = names.length; + var list2 = classList(node), i3 = -1, n3 = names.length; while (++i3 < n3) - list.remove(names[i3]); + list2.remove(names[i3]); } function classedTrue(names) { return function() { @@ -20023,9 +19413,9 @@ function classed_default(name, value) { var names = classArray(name + ""); if (arguments.length < 2) { - var list = classList(this.node()), i3 = -1, n3 = names.length; + var list2 = classList(this.node()), i3 = -1, n3 = names.length; while (++i3 < n3) - if (!list.contains(names[i3])) + if (!list2.contains(names[i3])) return false; return true; } @@ -20119,12 +19509,12 @@ // node_modules/d3-selection/src/selection/clone.js function selection_cloneShallow() { - var clone = this.cloneNode(false), parent = this.parentNode; - return parent ? parent.insertBefore(clone, this.nextSibling) : clone; + var clone2 = this.cloneNode(false), parent = this.parentNode; + return parent ? parent.insertBefore(clone2, this.nextSibling) : clone2; } function selection_cloneDeep() { - var clone = this.cloneNode(true), parent = this.parentNode; - return parent ? parent.insertBefore(clone, this.nextSibling) : clone; + var clone2 = this.cloneNode(true), parent = this.parentNode; + return parent ? parent.insertBefore(clone2, this.nextSibling) : clone2; } function clone_default(deep) { return this.select(deep ? selection_cloneDeep : selection_cloneShallow); @@ -20154,8 +19544,8 @@ var on = this.__on; if (!on) return; - for (var j3 = 0, i3 = -1, m2 = on.length, o2; j3 < m2; ++j3) { - if (o2 = on[j3], (!typename.type || o2.type === typename.type) && o2.name === typename.name) { + for (var j2 = 0, i3 = -1, m2 = on.length, o2; j2 < m2; ++j2) { + if (o2 = on[j2], (!typename.type || o2.type === typename.type) && o2.name === typename.name) { this.removeEventListener(o2.type, o2.listener, o2.options); } else { on[++i3] = o2; @@ -20171,8 +19561,8 @@ return function() { var on = this.__on, o2, listener = contextListener(value); if (on) - for (var j3 = 0, m2 = on.length; j3 < m2; ++j3) { - if ((o2 = on[j3]).type === typename.type && o2.name === typename.name) { + for (var j2 = 0, m2 = on.length; j2 < m2; ++j2) { + if ((o2 = on[j2]).type === typename.type && o2.name === typename.name) { this.removeEventListener(o2.type, o2.listener, o2.options); this.addEventListener(o2.type, o2.listener = listener, o2.options = options2); o2.value = value; @@ -20192,8 +19582,8 @@ if (arguments.length < 2) { var on = this.node().__on; if (on) - for (var j3 = 0, m2 = on.length, o2; j3 < m2; ++j3) { - for (i3 = 0, o2 = on[j3]; i3 < n3; ++i3) { + for (var j2 = 0, m2 = on.length, o2; j2 < m2; ++j2) { + for (i3 = 0, o2 = on[j2]; i3 < n3; ++i3) { if ((t2 = typenames[i3]).type === o2.type && t2.name === o2.name) { return o2.value; } @@ -20237,8 +19627,8 @@ // node_modules/d3-selection/src/selection/iterator.js function* iterator_default() { - for (var groups = this._groups, j3 = 0, m2 = groups.length; j3 < m2; ++j3) { - for (var group = groups[j3], i3 = 0, n3 = group.length, node; i3 < n3; ++i3) { + for (var groups = this._groups, j2 = 0, m2 = groups.length; j2 < m2; ++j2) { + for (var group = groups[j2], i3 = 0, n3 = group.length, node; i3 < n3; ++i3) { if (node = group[i3]) yield node; } @@ -21142,7 +20532,7 @@ scaleX: 1, scaleY: 1 }; - function decompose_default(a2, b2, c2, d2, e3, f3) { + function decompose_default(a2, b2, c2, d2, e3, f2) { var scaleX, scaleY, skewX; if (scaleX = Math.sqrt(a2 * a2 + b2 * b2)) a2 /= scaleX, b2 /= scaleX; @@ -21154,7 +20544,7 @@ a2 = -a2, b2 = -b2, skewX = -skewX, scaleX = -scaleX; return { translateX: e3, - translateY: f3, + translateY: f2, rotate: Math.atan2(b2, a2) * degrees2, skewX: Math.atan(skewX) * degrees2, scaleX, @@ -21302,8 +20692,8 @@ var clockNow = 0; var clockSkew = 0; var clock = typeof performance === "object" && performance.now ? performance : Date; - var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f3) { - setTimeout(f3, 17); + var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f2) { + setTimeout(f2, 17); }; function now() { return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew); @@ -21476,7 +20866,7 @@ start2(elapsed - self2.delay); } function start2(elapsed) { - var i3, j3, n3, o2; + var i3, j2, n3, o2; if (self2.state !== SCHEDULED) return stop(); for (i3 in schedules) { @@ -21510,12 +20900,12 @@ return; self2.state = STARTED; tween = new Array(n3 = self2.tween.length); - for (i3 = 0, j3 = -1; i3 < n3; ++i3) { + for (i3 = 0, j2 = -1; i3 < n3; ++i3) { if (o2 = self2.tween[i3].value.call(node, node.__data__, self2.index, self2.group)) { - tween[++j3] = o2; + tween[++j2] = o2; } } - tween.length = j3 + 1; + tween.length = j2 + 1; } function tick(elapsed) { var t2 = elapsed < self2.duration ? self2.ease.call(null, elapsed / self2.duration) : (self2.timer.restart(stop), self2.state = ENDING, 1), i3 = -1, n3 = tween.length; @@ -21795,8 +21185,8 @@ function filter_default2(match) { if (typeof match !== "function") match = matcher_default(match); - for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, subgroup = subgroups[j3] = [], node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, subgroup = subgroups[j2] = [], node, i3 = 0; i3 < n3; ++i3) { if ((node = group[i3]) && match.call(node, node.__data__, i3, group)) { subgroup.push(node); } @@ -21809,15 +21199,15 @@ function merge_default2(transition2) { if (transition2._id !== this._id) throw new Error(); - for (var groups0 = this._groups, groups1 = transition2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j3 = 0; j3 < m2; ++j3) { - for (var group0 = groups0[j3], group1 = groups1[j3], n3 = group0.length, merge2 = merges[j3] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) { + for (var groups0 = this._groups, groups1 = transition2._groups, m0 = groups0.length, m1 = groups1.length, m2 = Math.min(m0, m1), merges = new Array(m0), j2 = 0; j2 < m2; ++j2) { + for (var group0 = groups0[j2], group1 = groups1[j2], n3 = group0.length, merge2 = merges[j2] = new Array(n3), node, i3 = 0; i3 < n3; ++i3) { if (node = group0[i3] || group1[i3]) { merge2[i3] = node; } } } - for (; j3 < m0; ++j3) { - merges[j3] = groups0[j3]; + for (; j2 < m0; ++j2) { + merges[j2] = groups0[j2]; } return new Transition(merges, this._parents, this._name, this._id); } @@ -21865,8 +21255,8 @@ var name = this._name, id2 = this._id; if (typeof select !== "function") select = selector_default(select); - for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, subgroup = subgroups[j3] = new Array(n3), node, subnode, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, subgroups = new Array(m2), j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, subgroup = subgroups[j2] = new Array(n3), node, subnode, i3 = 0; i3 < n3; ++i3) { if ((node = group[i3]) && (subnode = select.call(node, node.__data__, i3, group))) { if ("__data__" in node) subnode.__data__ = node.__data__; @@ -21883,8 +21273,8 @@ var name = this._name, id2 = this._id; if (typeof select !== "function") select = selectorAll_default(select); - for (var groups = this._groups, m2 = groups.length, subgroups = [], parents = [], j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, subgroups = [], parents = [], j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { if (node = group[i3]) { for (var children2 = select.call(node, node.__data__, i3, group), child, inherit2 = get2(node, id2), k2 = 0, l2 = children2.length; k2 < l2; ++k2) { if (child = children2[k2]) { @@ -22023,8 +21413,8 @@ // node_modules/d3-transition/src/transition/transition.js function transition_default() { var name = this._name, id0 = this._id, id1 = newId(); - for (var groups = this._groups, m2 = groups.length, j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { if (node = group[i3]) { var inherit2 = get2(node, id0); schedule_default(node, name, id1, i3, group, { @@ -22142,8 +21532,8 @@ } else { id2 = newId(), (timing = defaultTiming).time = now(), name = name == null ? null : name + ""; } - for (var groups = this._groups, m2 = groups.length, j3 = 0; j3 < m2; ++j3) { - for (var group = groups[j3], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { + for (var groups = this._groups, m2 = groups.length, j2 = 0; j2 < m2; ++j2) { + for (var group = groups[j2], n3 = group.length, node, i3 = 0; i3 < n3; ++i3) { if (node = group[i3]) { schedule_default(node, name, id2, i3, group, timing || inherit(node, id2)); } @@ -22824,7 +22214,7 @@ _storage = localStorage; } catch (e3) { } - _storage = _storage || (() => { + _storage = _storage || /* @__PURE__ */ (() => { let s2 = {}; return { getItem: (k2) => s2[k2], @@ -22882,6 +22272,7 @@ if (false) { osmApiConnections.push({ url: null, + apiUrl: ENV__ID_API_CONNECTION_API_URL, client_id: null, client_secret: null }); @@ -22893,11 +22284,12 @@ } var taginfoApiUrl = "https://taginfo.openstreetmap.org/api/4/"; var nominatimApiUrl = "https://nominatim.openstreetmap.org/"; + var showDonationMessage = true; // package.json var package_default = { name: "iD", - version: "2.27.3", + version: "2.28.1", description: "A friendly editor for OpenStreetMap", main: "dist/iD.min.js", repository: "github:openstreetmap/iD", @@ -22925,8 +22317,8 @@ "dist:svg:community": 'svg-sprite --symbol --symbol-dest . --shape-id-generator "community-%s" --symbol-sprite dist/img/community-sprite.svg node_modules/osm-community-index/dist/img/*.svg', "dist:svg:fa": "svg-sprite --symbol --symbol-dest . --symbol-sprite dist/img/fa-sprite.svg svg/fontawesome/*.svg", "dist:svg:maki": 'svg-sprite --symbol --symbol-dest . --shape-id-generator "maki-%s" --symbol-sprite dist/img/maki-sprite.svg node_modules/@mapbox/maki/icons/*.svg', - "dist:svg:mapillary:signs": "svg-sprite --symbol --symbol-dest . --symbol-sprite dist/img/mapillary-sprite.svg node_modules/mapillary_sprite_source/package_signs/*.svg", - "dist:svg:mapillary:objects": "svg-sprite --symbol --symbol-dest . --symbol-sprite dist/img/mapillary-object-sprite.svg node_modules/mapillary_sprite_source/package_objects/*.svg", + "dist:svg:mapillary:signs": "svg-sprite --symbol --symbol-dest . --symbol-sprite dist/img/mapillary-sprite.svg node_modules/@rapideditor/mapillary_sprite_source/package_signs/*.svg", + "dist:svg:mapillary:objects": "svg-sprite --symbol --symbol-dest . --symbol-sprite dist/img/mapillary-object-sprite.svg node_modules/@rapideditor/mapillary_sprite_source/package_objects/*.svg", "dist:svg:roentgen": 'svg-sprite --shape-id-generator "roentgen-%s" --shape-dim-width 16 --shape-dim-height 16 --symbol --symbol-dest . --symbol-sprite dist/img/roentgen-sprite.svg svg/roentgen/*.svg', "dist:svg:temaki": 'svg-sprite --symbol --symbol-dest . --shape-id-generator "temaki-%s" --symbol-sprite dist/img/temaki-sprite.svg node_modules/@rapideditor/temaki/icons/*.svg', imagery: "node scripts/update_imagery.js", @@ -22944,72 +22336,73 @@ "@mapbox/geojson-area": "^0.2.2", "@mapbox/sexagesimal": "1.2.0", "@mapbox/vector-tile": "^1.3.1", - "@rapideditor/country-coder": "~5.2.0", - "@rapideditor/location-conflation": "~1.2.1", + "@rapideditor/country-coder": "~5.2.2", + "@rapideditor/location-conflation": "~1.3.0", "@tmcw/togeojson": "^5.8.1", "@turf/bbox": "^6.0.0", "@turf/bbox-clip": "^6.0.0", "abortcontroller-polyfill": "^1.7.5", "aes-js": "^3.1.2", "alif-toolkit": "^1.2.9", - "core-js-bundle": "^3.33.2", + "core-js-bundle": "^3.36.0", diacritics: "1.3.0", exifr: "^7.1.3", "fast-deep-equal": "~3.1.1", "fast-json-stable-stringify": "2.1.0", "lodash-es": "~4.17.15", - marked: "~7.0.3", + marked: "~12.0.0", "node-diff3": "~3.1.0", - "osm-auth": "~2.2.0", + "osm-auth": "~2.4.0", pannellum: "2.5.6", pbf: "^3.2.1", - "polygon-clipping": "~0.15.1", + "polygon-clipping": "~0.15.7", rbush: "3.0.1", - "whatwg-fetch": "^3.6.17", + "whatwg-fetch": "^3.6.20", "which-polygon": "2.2.1" }, devDependencies: { - "@fortawesome/fontawesome-svg-core": "~6.4.2", - "@fortawesome/free-brands-svg-icons": "~6.4.2", - "@fortawesome/free-regular-svg-icons": "~6.4.2", - "@fortawesome/free-solid-svg-icons": "~6.4.2", + "@fortawesome/fontawesome-svg-core": "~6.5.1", + "@fortawesome/free-brands-svg-icons": "~6.5.1", + "@fortawesome/free-regular-svg-icons": "~6.5.1", + "@fortawesome/free-solid-svg-icons": "~6.5.1", "@mapbox/maki": "^8.0.1", - "@openstreetmap/id-tagging-schema": "^6.4.1", - "@rapideditor/temaki": "^5.6.0", - "@transifex/api": "^5.4.0", - autoprefixer: "^10.4.15", - "browserslist-to-esbuild": "^1.2.0", - chai: "^4.3.10", + "@openstreetmap/id-tagging-schema": "^6.6.0", + "@rapideditor/mapillary_sprite_source": "^1.8.0", + "@rapideditor/temaki": "^5.7.0", + "@transifex/api": "^7.1.0", + autoprefixer: "^10.4.17", + browserslist: "^4.23.0", + "browserslist-to-esbuild": "^2.1.1", + chai: "^4.4.1", chalk: "^4.1.2", - "cldr-core": "^43.0.0", - "cldr-localenames-full": "^43.1.0", + "cldr-core": "^44.0.1", + "cldr-localenames-full": "^44.1.0", "concat-files": "^0.1.1", d3: "~7.8.5", - dotenv: "^16.3.1", + dotenv: "^16.4.5", "editor-layer-index": "github:osmlab/editor-layer-index#gh-pages", - esbuild: "^0.19.2", - "esbuild-visualizer": "^0.4.1", - eslint: "^8.47.0", + esbuild: "^0.20.1", + "esbuild-visualizer": "^0.6.0", + eslint: "^8.57.0", "fetch-mock": "^9.11.0", gaze: "^1.1.3", - glob: "^10.3.3", + glob: "^10.3.10", happen: "^0.3.2", "js-yaml": "^4.0.0", "json-stringify-pretty-compact": "^3.0.0", - karma: "^6.4.2", + karma: "^6.4.3", "karma-chrome-launcher": "^3.2.0", "karma-coverage": "2.1.1", "karma-mocha": "^2.0.1", "karma-remap-istanbul": "^0.6.0", - mapillary_sprite_source: "^1.8.0", - "mapillary-js": "4.1.1", + "mapillary-js": "4.1.2", minimist: "^1.2.8", - mocha: "^10.2.0", + mocha: "^10.3.0", "name-suggestion-index": "~6.0", "node-fetch": "^2.7.0", "npm-run-all": "^4.0.0", - "osm-community-index": "~5.6.0", - postcss: "^8.4.31", + "osm-community-index": "~5.6.2", + postcss: "^8.4.35", "postcss-selector-prepend": "^0.5.0", shelljs: "^0.8.0", shx: "^0.3.0", @@ -23021,10 +22414,10 @@ vparse: "~1.1.0" }, engines: { - node: ">=16.14" + node: ">=18" }, browserslist: [ - "> 0.3%, last 6 major versions, Firefox ESR, maintained node versions" + "> 0.3%, last 6 major versions, not dead, Firefox ESR, maintained node versions" ] }; @@ -23538,431 +22931,3626 @@ if (s2.charAt(0) === ".") { return s2.toUpperCase(); } else { - return s2.replace(idFilterRegex, "").toUpperCase(); + return s2.replace(idFilterRegex, "").toUpperCase(); + } + } + var levels = [ + "subterritory", + "territory", + "subcountryGroup", + "country", + "sharedLandform", + "intermediateRegion", + "subregion", + "region", + "subunion", + "union", + "unitedNations", + "world" + ]; + loadDerivedDataAndCaches(borders); + function loadDerivedDataAndCaches(borders2) { + const identifierProps = ["iso1A2", "iso1A3", "m49", "wikidata", "emojiFlag", "ccTLD", "nameEn"]; + let geometryFeatures = []; + for (const feature22 of borders2.features) { + const props = feature22.properties; + props.id = props.iso1A2 || props.m49 || props.wikidata; + loadM49(feature22); + loadTLD(feature22); + loadIsoStatus(feature22); + loadLevel(feature22); + loadGroups(feature22); + loadFlag(feature22); + cacheFeatureByIDs(feature22); + if (feature22.geometry) { + geometryFeatures.push(feature22); + } + } + for (const feature22 of borders2.features) { + feature22.properties.groups = feature22.properties.groups.map((groupID) => { + return _featuresByCode[groupID].properties.id; + }); + loadMembersForGroupsOf(feature22); + } + for (const feature22 of borders2.features) { + loadRoadSpeedUnit(feature22); + loadRoadHeightUnit(feature22); + loadDriveSide(feature22); + loadCallingCodes(feature22); + loadGroupGroups(feature22); + } + for (const feature22 of borders2.features) { + feature22.properties.groups.sort((groupID1, groupID2) => { + return levels.indexOf(_featuresByCode[groupID1].properties.level) - levels.indexOf(_featuresByCode[groupID2].properties.level); + }); + if (feature22.properties.members) { + feature22.properties.members.sort((id1, id2) => { + const diff = levels.indexOf(_featuresByCode[id1].properties.level) - levels.indexOf(_featuresByCode[id2].properties.level); + if (diff === 0) { + return borders2.features.indexOf(_featuresByCode[id1]) - borders2.features.indexOf(_featuresByCode[id2]); + } + return diff; + }); + } + } + const geometryOnlyCollection = { + type: "FeatureCollection", + features: geometryFeatures + }; + _whichPolygon = (0, import_which_polygon.default)(geometryOnlyCollection); + function loadGroups(feature22) { + const props = feature22.properties; + if (!props.groups) { + props.groups = []; + } + if (feature22.geometry && props.country) { + props.groups.push(props.country); + } + if (props.m49 !== "001") { + props.groups.push("001"); + } + } + function loadM49(feature22) { + const props = feature22.properties; + if (!props.m49 && props.iso1N3) { + props.m49 = props.iso1N3; + } + } + function loadTLD(feature22) { + const props = feature22.properties; + if (props.level === "unitedNations") + return; + if (!props.ccTLD && props.iso1A2) { + props.ccTLD = "." + props.iso1A2.toLowerCase(); + } + } + function loadIsoStatus(feature22) { + const props = feature22.properties; + if (!props.isoStatus && props.iso1A2) { + props.isoStatus = "official"; + } + } + function loadLevel(feature22) { + const props = feature22.properties; + if (props.level) + return; + if (!props.country) { + props.level = "country"; + } else if (!props.iso1A2 || props.isoStatus === "official") { + props.level = "territory"; + } else { + props.level = "subterritory"; + } + } + function loadGroupGroups(feature22) { + const props = feature22.properties; + if (feature22.geometry || !props.members) + return; + const featureLevelIndex = levels.indexOf(props.level); + let sharedGroups = []; + props.members.forEach((memberID, index) => { + const member = _featuresByCode[memberID]; + const memberGroups = member.properties.groups.filter((groupID) => { + return groupID !== feature22.properties.id && featureLevelIndex < levels.indexOf(_featuresByCode[groupID].properties.level); + }); + if (index === 0) { + sharedGroups = memberGroups; + } else { + sharedGroups = sharedGroups.filter((groupID) => memberGroups.indexOf(groupID) !== -1); + } + }); + props.groups = props.groups.concat( + sharedGroups.filter((groupID) => props.groups.indexOf(groupID) === -1) + ); + for (const groupID of sharedGroups) { + const groupFeature = _featuresByCode[groupID]; + if (groupFeature.properties.members.indexOf(props.id) === -1) { + groupFeature.properties.members.push(props.id); + } + } + } + function loadRoadSpeedUnit(feature22) { + const props = feature22.properties; + if (feature22.geometry) { + if (!props.roadSpeedUnit) + props.roadSpeedUnit = "km/h"; + } else if (props.members) { + const vals = Array.from( + new Set( + props.members.map((id2) => { + const member = _featuresByCode[id2]; + if (member.geometry) + return member.properties.roadSpeedUnit || "km/h"; + }).filter(Boolean) + ) + ); + if (vals.length === 1) + props.roadSpeedUnit = vals[0]; + } + } + function loadRoadHeightUnit(feature22) { + const props = feature22.properties; + if (feature22.geometry) { + if (!props.roadHeightUnit) + props.roadHeightUnit = "m"; + } else if (props.members) { + const vals = Array.from( + new Set( + props.members.map((id2) => { + const member = _featuresByCode[id2]; + if (member.geometry) + return member.properties.roadHeightUnit || "m"; + }).filter(Boolean) + ) + ); + if (vals.length === 1) + props.roadHeightUnit = vals[0]; + } + } + function loadDriveSide(feature22) { + const props = feature22.properties; + if (feature22.geometry) { + if (!props.driveSide) + props.driveSide = "right"; + } else if (props.members) { + const vals = Array.from( + new Set( + props.members.map((id2) => { + const member = _featuresByCode[id2]; + if (member.geometry) + return member.properties.driveSide || "right"; + }).filter(Boolean) + ) + ); + if (vals.length === 1) + props.driveSide = vals[0]; + } + } + function loadCallingCodes(feature22) { + const props = feature22.properties; + if (!feature22.geometry && props.members) { + props.callingCodes = Array.from( + new Set( + props.members.reduce((array2, id2) => { + const member = _featuresByCode[id2]; + if (member.geometry && member.properties.callingCodes) { + return array2.concat(member.properties.callingCodes); + } + return array2; + }, []) + ) + ); + } + } + function loadFlag(feature22) { + if (!feature22.properties.iso1A2) + return; + const flag = feature22.properties.iso1A2.replace(/./g, function(char) { + return String.fromCodePoint(char.charCodeAt(0) + 127397); + }); + feature22.properties.emojiFlag = flag; + } + function loadMembersForGroupsOf(feature22) { + for (const groupID of feature22.properties.groups) { + const groupFeature = _featuresByCode[groupID]; + if (!groupFeature.properties.members) { + groupFeature.properties.members = []; + } + groupFeature.properties.members.push(feature22.properties.id); + } + } + function cacheFeatureByIDs(feature22) { + let ids = []; + for (const prop of identifierProps) { + const id2 = feature22.properties[prop]; + if (id2) { + ids.push(id2); + } + } + for (const alias of feature22.properties.aliases || []) { + ids.push(alias); + } + for (const id2 of ids) { + const cid = canonicalID(id2); + _featuresByCode[cid] = feature22; + } + } + } + function locArray(loc) { + if (Array.isArray(loc)) { + return loc; + } else if (loc.coordinates) { + return loc.coordinates; + } + return loc.geometry.coordinates; + } + function smallestFeature(loc) { + const query = locArray(loc); + const featureProperties = _whichPolygon(query); + if (!featureProperties) + return null; + return _featuresByCode[featureProperties.id]; + } + function countryFeature(loc) { + const feature22 = smallestFeature(loc); + if (!feature22) + return null; + const countryCode = feature22.properties.country || feature22.properties.iso1A2; + return _featuresByCode[countryCode] || null; + } + var defaultOpts = { + level: void 0, + maxLevel: void 0, + withProp: void 0 + }; + function featureForLoc(loc, opts) { + const targetLevel = opts.level || "country"; + const maxLevel = opts.maxLevel || "world"; + const withProp = opts.withProp; + const targetLevelIndex = levels.indexOf(targetLevel); + if (targetLevelIndex === -1) + return null; + const maxLevelIndex = levels.indexOf(maxLevel); + if (maxLevelIndex === -1) + return null; + if (maxLevelIndex < targetLevelIndex) + return null; + if (targetLevel === "country") { + const fastFeature = countryFeature(loc); + if (fastFeature) { + if (!withProp || fastFeature.properties[withProp]) { + return fastFeature; + } + } + } + const features = featuresContaining(loc); + const match = features.find((feature22) => { + let levelIndex = levels.indexOf(feature22.properties.level); + if (feature22.properties.level === targetLevel || // if no feature exists at the target level, return the first feature at the next level up + levelIndex > targetLevelIndex && levelIndex <= maxLevelIndex) { + if (!withProp || feature22.properties[withProp]) { + return feature22; + } + } + return false; + }); + return match || null; + } + function featureForID(id2) { + let stringID; + if (typeof id2 === "number") { + stringID = id2.toString(); + if (stringID.length === 1) { + stringID = "00" + stringID; + } else if (stringID.length === 2) { + stringID = "0" + stringID; + } + } else { + stringID = canonicalID(id2); + } + return _featuresByCode[stringID] || null; + } + function smallestFeaturesForBbox(bbox2) { + return _whichPolygon.bbox(bbox2).map((props) => _featuresByCode[props.id]); + } + function smallestOrMatchingFeature(query) { + if (typeof query === "object") { + return smallestFeature(query); + } + return featureForID(query); + } + function feature(query, opts = defaultOpts) { + if (typeof query === "object") { + return featureForLoc(query, opts); + } + return featureForID(query); + } + function iso1A2Code(query, opts = defaultOpts) { + opts.withProp = "iso1A2"; + const match = feature(query, opts); + if (!match) + return null; + return match.properties.iso1A2 || null; + } + function propertiesForQuery(query, property) { + const features = featuresContaining(query, false); + return features.map((feature22) => feature22.properties[property]).filter(Boolean); + } + function iso1A2Codes(query) { + return propertiesForQuery(query, "iso1A2"); + } + function featuresContaining(query, strict) { + let matchingFeatures; + if (Array.isArray(query) && query.length === 4) { + matchingFeatures = smallestFeaturesForBbox(query); + } else { + const smallestOrMatching = smallestOrMatchingFeature(query); + matchingFeatures = smallestOrMatching ? [smallestOrMatching] : []; + } + if (!matchingFeatures.length) + return []; + let returnFeatures; + if (!strict || typeof query === "object") { + returnFeatures = matchingFeatures.slice(); + } else { + returnFeatures = []; + } + for (const feature22 of matchingFeatures) { + const properties = feature22.properties; + for (const groupID of properties.groups) { + const groupFeature = _featuresByCode[groupID]; + if (returnFeatures.indexOf(groupFeature) === -1) { + returnFeatures.push(groupFeature); + } + } + } + return returnFeatures; + } + function featuresIn(id2, strict) { + const feature22 = featureForID(id2); + if (!feature22) + return []; + let features = []; + if (!strict) { + features.push(feature22); + } + const properties = feature22.properties; + for (const memberID of properties.members || []) { + features.push(_featuresByCode[memberID]); + } + return features; + } + function aggregateFeature(id2) { + var _a2; + const features = featuresIn(id2, false); + if (features.length === 0) + return null; + let aggregateCoordinates = []; + for (const feature22 of features) { + if (((_a2 = feature22.geometry) == null ? void 0 : _a2.type) === "MultiPolygon" && feature22.geometry.coordinates) { + aggregateCoordinates = aggregateCoordinates.concat(feature22.geometry.coordinates); + } + } + return { + type: "Feature", + properties: features[0].properties, + geometry: { + type: "MultiPolygon", + coordinates: aggregateCoordinates + } + }; + } + function roadSpeedUnit(query) { + const feature22 = smallestOrMatchingFeature(query); + return feature22 && feature22.properties.roadSpeedUnit || null; + } + function roadHeightUnit(query) { + const feature22 = smallestOrMatchingFeature(query); + return feature22 && feature22.properties.roadHeightUnit || null; + } + + // node_modules/polyclip-ts/dist/constant.js + var constant_default5 = (x2) => { + return () => { + return x2; + }; + }; + + // node_modules/polyclip-ts/dist/compare.js + var compare_default = (eps) => { + const almostEqual = eps ? (a2, b2) => b2.minus(a2).abs().isLessThanOrEqualTo(eps) : constant_default5(false); + return (a2, b2) => { + if (almostEqual(a2, b2)) + return 0; + return a2.comparedTo(b2); + }; + }; + + // node_modules/polyclip-ts/dist/orient.js + function orient_default(eps) { + const almostCollinear = eps ? (area2, ax, ay, cx, cy) => area2.exponentiatedBy(2).isLessThanOrEqualTo(cx.minus(ax).exponentiatedBy(2).plus(cy.minus(ay).exponentiatedBy(2)).times(eps)) : constant_default5(false); + return (a2, b2, c2) => { + const ax = a2.x, ay = a2.y, cx = c2.x, cy = c2.y; + const area2 = ay.minus(cy).times(b2.x.minus(cx)).minus(ax.minus(cx).times(b2.y.minus(cy))); + if (almostCollinear(area2, ax, ay, cx, cy)) + return 0; + return area2.comparedTo(0); + }; + } + + // node_modules/bignumber.js/bignumber.mjs + var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; + var mathceil = Math.ceil; + var mathfloor = Math.floor; + var bignumberError = "[BigNumber Error] "; + var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; + var BASE = 1e14; + var LOG_BASE = 14; + var MAX_SAFE_INTEGER = 9007199254740991; + var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13]; + var SQRT_BASE = 1e7; + var MAX = 1e9; + function clone(configObject) { + var div, convertBase, parseNumeric2, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber2(v2, b2) { + var alphabet, c2, caseChanged, e3, i3, isNum, len, str, x2 = this; + if (!(x2 instanceof BigNumber2)) + return new BigNumber2(v2, b2); + if (b2 == null) { + if (v2 && v2._isBigNumber === true) { + x2.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x2.c = x2.e = null; + } else if (v2.e < MIN_EXP) { + x2.c = [x2.e = 0]; + } else { + x2.e = v2.e; + x2.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x2.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e3 = 0, i3 = v2; i3 >= 10; i3 /= 10, e3++) + ; + if (e3 > MAX_EXP) { + x2.c = x2.e = null; + } else { + x2.e = e3; + x2.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric.test(str = String(v2))) + return parseNumeric2(x2, str, isNum); + x2.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e3 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i3 = str.search(/e/i)) > 0) { + if (e3 < 0) + e3 = i3; + e3 += +str.slice(i3 + 1); + str = str.substring(0, i3); + } else if (e3 < 0) { + e3 = str.length; + } + } else { + intCheck(b2, 2, ALPHABET.length, "Base"); + if (b2 == 10 && alphabetHasNormalDecimalDigits) { + x2 = new BigNumber2(v2); + return round(x2, DECIMAL_PLACES + x2.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric2(x2, str, isNum, b2); + x2.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits + v2); + } + } else { + x2.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet = ALPHABET.slice(0, b2); + e3 = i3 = 0; + for (len = str.length; i3 < len; i3++) { + if (alphabet.indexOf(c2 = str.charAt(i3)) < 0) { + if (c2 == ".") { + if (i3 > e3) { + e3 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i3 = -1; + e3 = 0; + continue; + } + } + return parseNumeric2(x2, String(v2), isNum, b2); + } + } + isNum = false; + str = convertBase(str, b2, 10, x2.s); + if ((e3 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e3 = str.length; + } + for (i3 = 0; str.charCodeAt(i3) === 48; i3++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i3, ++len)) { + len -= i3; + if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) { + throw Error(tooManyDigits + x2.s * v2); + } + if ((e3 = e3 - i3 - 1) > MAX_EXP) { + x2.c = x2.e = null; + } else if (e3 < MIN_EXP) { + x2.c = [x2.e = 0]; + } else { + x2.e = e3; + x2.c = []; + i3 = (e3 + 1) % LOG_BASE; + if (e3 < 0) + i3 += LOG_BASE; + if (i3 < len) { + if (i3) + x2.c.push(+str.slice(0, i3)); + for (len -= LOG_BASE; i3 < len; ) { + x2.c.push(+str.slice(i3, i3 += LOG_BASE)); + } + i3 = LOG_BASE - (str = str.slice(i3)).length; + } else { + i3 -= len; + } + for (; i3--; str += "0") + ; + x2.c.push(+str); + } + } else { + x2.c = [x2.e = 0]; + } + } + BigNumber2.clone = clone; + BigNumber2.ROUND_UP = 0; + BigNumber2.ROUND_DOWN = 1; + BigNumber2.ROUND_CEIL = 2; + BigNumber2.ROUND_FLOOR = 3; + BigNumber2.ROUND_HALF_UP = 4; + BigNumber2.ROUND_HALF_DOWN = 5; + BigNumber2.ROUND_HALF_EVEN = 6; + BigNumber2.ROUND_HALF_CEIL = 7; + BigNumber2.ROUND_HALF_FLOOR = 8; + BigNumber2.EUCLID = 9; + BigNumber2.config = BigNumber2.set = function(obj) { + var p2, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p2 = "DECIMAL_PLACES")) { + v2 = obj[p2]; + intCheck(v2, 0, MAX, p2); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p2 = "ROUNDING_MODE")) { + v2 = obj[p2]; + intCheck(v2, 0, 8, p2); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p2 = "EXPONENTIAL_AT")) { + v2 = obj[p2]; + if (v2 && v2.pop) { + intCheck(v2[0], -MAX, 0, p2); + intCheck(v2[1], 0, MAX, p2); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck(v2, -MAX, MAX, p2); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p2 = "RANGE")) { + v2 = obj[p2]; + if (v2 && v2.pop) { + intCheck(v2[0], -MAX, -1, p2); + intCheck(v2[1], 1, MAX, p2); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck(v2, -MAX, MAX, p2); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError + p2 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p2 = "CRYPTO")) { + v2 = obj[p2]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError + p2 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p2 = "MODULO_MODE")) { + v2 = obj[p2]; + intCheck(v2, 0, 9, p2); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p2 = "POW_PRECISION")) { + v2 = obj[p2]; + intCheck(v2, 0, MAX, p2); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p2 = "FORMAT")) { + v2 = obj[p2]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError + p2 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p2 = "ALPHABET")) { + v2 = obj[p2]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; + ALPHABET = v2; + } else { + throw Error(bignumberError + p2 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber2.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber2.DEBUG) + return true; + var i3, n3, c2 = v2.c, e3 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c2) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e3 >= -MAX && e3 <= MAX && e3 === mathfloor(e3)) { + if (c2[0] === 0) { + if (e3 === 0 && c2.length === 1) + return true; + break out; + } + i3 = (e3 + 1) % LOG_BASE; + if (i3 < 1) + i3 += LOG_BASE; + if (String(c2[0]).length == i3) { + for (i3 = 0; i3 < c2.length; i3++) { + n3 = c2[i3]; + if (n3 < 0 || n3 >= BASE || n3 !== mathfloor(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c2 === null && e3 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError + "Invalid BigNumber: " + v2); + }; + BigNumber2.maximum = BigNumber2.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber2.minimum = BigNumber2.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber2.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a2, b2, e3, k2, v2, i3 = 0, c2 = [], rand = new BigNumber2(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck(dp, 0, MAX); + k2 = mathceil(dp / LOG_BASE); + if (CRYPTO) { + if (crypto.getRandomValues) { + a2 = crypto.getRandomValues(new Uint32Array(k2 *= 2)); + for (; i3 < k2; ) { + v2 = a2[i3] * 131072 + (a2[i3 + 1] >>> 11); + if (v2 >= 9e15) { + b2 = crypto.getRandomValues(new Uint32Array(2)); + a2[i3] = b2[0]; + a2[i3 + 1] = b2[1]; + } else { + c2.push(v2 % 1e14); + i3 += 2; + } + } + i3 = k2 / 2; + } else if (crypto.randomBytes) { + a2 = crypto.randomBytes(k2 *= 7); + for (; i3 < k2; ) { + v2 = (a2[i3] & 31) * 281474976710656 + a2[i3 + 1] * 1099511627776 + a2[i3 + 2] * 4294967296 + a2[i3 + 3] * 16777216 + (a2[i3 + 4] << 16) + (a2[i3 + 5] << 8) + a2[i3 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a2, i3); + } else { + c2.push(v2 % 1e14); + i3 += 7; + } + } + i3 = k2 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i3 < k2; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c2[i3++] = v2 % 1e14; + } + } + k2 = c2[--i3]; + dp %= LOG_BASE; + if (k2 && dp) { + v2 = POWS_TEN[LOG_BASE - dp]; + c2[i3] = mathfloor(k2 / v2) * v2; + } + for (; c2[i3] === 0; c2.pop(), i3--) + ; + if (i3 < 0) { + c2 = [e3 = 0]; + } else { + for (e3 = -1; c2[0] === 0; c2.splice(0, 1), e3 -= LOG_BASE) + ; + for (i3 = 1, v2 = c2[0]; v2 >= 10; v2 /= 10, i3++) + ; + if (i3 < LOG_BASE) + e3 -= LOG_BASE - i3; + } + rand.e = e3; + rand.c = c2; + return rand; + }; + }(); + BigNumber2.sum = function() { + var i3 = 1, args = arguments, sum = new BigNumber2(args[0]); + for (; i3 < args.length; ) + sum = sum.plus(args[i3++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j2, arr = [0], arrL, i3 = 0, len = str.length; + for (; i3 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet.indexOf(str.charAt(i3++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet, d2, e3, k2, r2, x2, xc, y2, i3 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i3 >= 0) { + k2 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y2 = new BigNumber2(baseIn); + x2 = y2.pow(str.length - i3); + POW_PRECISION = k2; + y2.c = toBaseOut( + toFixedPoint(coeffToString(x2.c), x2.e, "0"), + 10, + baseOut, + decimal + ); + y2.e = y2.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); + e3 = k2 = xc.length; + for (; xc[--k2] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet.charAt(0); + if (i3 < 0) { + --e3; + } else { + x2.c = xc; + x2.e = e3; + x2.s = sign2; + x2 = div(x2, y2, dp, rm, baseOut); + xc = x2.c; + r2 = x2.r; + e3 = x2.e; + } + d2 = e3 + dp + 1; + i3 = xc[d2]; + k2 = baseOut / 2; + r2 = r2 || d2 < 0 || xc[d2 + 1] != null; + r2 = rm < 4 ? (i3 != null || r2) && (rm == 0 || rm == (x2.s < 0 ? 3 : 2)) : i3 > k2 || i3 == k2 && (rm == 4 || r2 || rm == 6 && xc[d2 - 1] & 1 || rm == (x2.s < 0 ? 8 : 7)); + if (d2 < 1 || !xc[0]) { + str = r2 ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + xc.length = d2; + if (r2) { + for (--baseOut; ++xc[--d2] > baseOut; ) { + xc[d2] = 0; + if (!d2) { + ++e3; + xc = [1].concat(xc); + } + } + } + for (k2 = xc.length; !xc[--k2]; ) + ; + for (i3 = 0, str = ""; i3 <= k2; str += alphabet.charAt(xc[i3++])) + ; + str = toFixedPoint(str, e3, alphabet.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x2, k2, base) { + var m2, temp, xlo, xhi, carry = 0, i3 = x2.length, klo = k2 % SQRT_BASE, khi = k2 / SQRT_BASE | 0; + for (x2 = x2.slice(); i3--; ) { + xlo = x2[i3] % SQRT_BASE; + xhi = x2[i3] / SQRT_BASE | 0; + m2 = khi * xlo + xhi * klo; + temp = klo * xlo + m2 % SQRT_BASE * SQRT_BASE + carry; + carry = (temp / base | 0) + (m2 / SQRT_BASE | 0) + khi * xhi; + x2[i3] = temp % base; + } + if (carry) + x2 = [carry].concat(x2); + return x2; + } + function compare2(a2, b2, aL, bL) { + var i3, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i3 = cmp = 0; i3 < aL; i3++) { + if (a2[i3] != b2[i3]) { + cmp = a2[i3] > b2[i3] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a2, b2, aL, base) { + var i3 = 0; + for (; aL--; ) { + a2[aL] -= i3; + i3 = a2[aL] < b2[aL] ? 1 : 0; + a2[aL] = i3 * base + a2[aL] - b2[aL]; + } + for (; !a2[0] && a2.length > 1; a2.splice(0, 1)) + ; + } + return function(x2, y2, dp, rm, base) { + var cmp, e3, i3, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x2.s == y2.s ? 1 : -1, xc = x2.c, yc = y2.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber2( + // Return NaN if either NaN, or both Infinity or 0. + !x2.s || !y2.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber2(s2); + qc = q2.c = []; + e3 = x2.e - y2.e; + s2 = dp + e3 + 1; + if (!base) { + base = BASE; + e3 = bitFloor(x2.e / LOG_BASE) - bitFloor(y2.e / LOG_BASE); + s2 = s2 / LOG_BASE | 0; + } + for (i3 = 0; yc[i3] == (xc[i3] || 0); i3++) + ; + if (yc[i3] > (xc[i3] || 0)) + e3--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i3 = 0; + s2 += 2; + n3 = mathfloor(base / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base); + xc = multiply(xc, n3, base); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) + yc0++; + do { + n3 = 0; + cmp = compare2(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base + (rem[1] || 0); + n3 = mathfloor(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base) + n3 = base - 1; + prod = multiply(yc, n3, base); + prodL = prod.length; + remL = rem.length; + while (compare2(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base); + remL = rem.length; + if (cmp == -1) { + while (compare2(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i3++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base == BASE) { + for (i3 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i3++) + ; + round(q2, dp + (q2.e = i3 + e3 * LOG_BASE - 1) + 1, rm, more); + } else { + q2.e = e3; + q2.r = +more; + } + return q2; + }; + }(); + function format2(n3, i3, rm, id2) { + var c0, e3, ne2, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne2 = n3.e; + if (i3 == null) { + str = coeffToString(n3.c); + str = id2 == 1 || id2 == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential(str, ne2) : toFixedPoint(str, ne2, "0"); + } else { + n3 = round(new BigNumber2(n3), i3, rm); + e3 = n3.e; + str = coeffToString(n3.c); + len = str.length; + if (id2 == 1 || id2 == 2 && (i3 <= e3 || e3 <= TO_EXP_NEG)) { + for (; len < i3; str += "0", len++) + ; + str = toExponential(str, e3); + } else { + i3 -= ne2; + str = toFixedPoint(str, e3, "0"); + if (e3 + 1 > len) { + if (--i3 > 0) + for (str += "."; i3--; str += "0") + ; + } else { + i3 += e3 - len; + if (i3 > 0) { + if (e3 + 1 == len) + str += "."; + for (; i3--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, n3) { + var k2, y2, i3 = 1, x2 = new BigNumber2(args[0]); + for (; i3 < args.length; i3++) { + y2 = new BigNumber2(args[i3]); + if (!y2.s || (k2 = compare(x2, y2)) === n3 || k2 === 0 && x2.s === n3) { + x2 = y2; + } + } + return x2; + } + function normalise(n3, c2, e3) { + var i3 = 1, j2 = c2.length; + for (; !c2[--j2]; c2.pop()) + ; + for (j2 = c2[0]; j2 >= 10; j2 /= 10, i3++) + ; + if ((e3 = i3 + e3 * LOG_BASE - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e3 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e3; + n3.c = c2; + } + return n3; + } + parseNumeric2 = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x2, str, isNum, b2) { + var base, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x2.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m2, p1, p2) { + base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; + return !b2 || b2 == base ? p1 : m2; + }); + if (b2) { + base = b2; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber2(s2, base); + } + if (BigNumber2.DEBUG) { + throw Error(bignumberError + "Not a" + (b2 ? " base " + b2 : "") + " number: " + str); + } + x2.s = null; + } + x2.c = x2.e = null; + }; + }(); + function round(x2, sd, rm, r2) { + var d2, i3, j2, k2, n3, ni, rd, xc = x2.c, pows10 = POWS_TEN; + if (xc) { + out: { + for (d2 = 1, k2 = xc[0]; k2 >= 10; k2 /= 10, d2++) + ; + i3 = sd - d2; + if (i3 < 0) { + i3 += LOG_BASE; + j2 = sd; + n3 = xc[ni = 0]; + rd = mathfloor(n3 / pows10[d2 - j2 - 1] % 10); + } else { + ni = mathceil((i3 + 1) / LOG_BASE); + if (ni >= xc.length) { + if (r2) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d2 = 1; + i3 %= LOG_BASE; + j2 = i3 - LOG_BASE + 1; + } else { + break out; + } + } else { + n3 = k2 = xc[ni]; + for (d2 = 1; k2 >= 10; k2 /= 10, d2++) + ; + i3 %= LOG_BASE; + j2 = i3 - LOG_BASE + d2; + rd = j2 < 0 ? 0 : mathfloor(n3 / pows10[d2 - j2 - 1] % 10); + } + } + r2 = r2 || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d2 - j2 - 1]); + r2 = rm < 4 ? (rd || r2) && (rm == 0 || rm == (x2.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r2 || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i3 > 0 ? j2 > 0 ? n3 / pows10[d2 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x2.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r2) { + sd -= x2.e + 1; + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x2.e = -sd || 0; + } else { + xc[0] = x2.e = 0; + } + return x2; + } + if (i3 == 0) { + xc.length = ni; + k2 = 1; + ni--; + } else { + xc.length = ni + 1; + k2 = pows10[LOG_BASE - i3]; + xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d2 - j2] % pows10[j2]) * k2 : 0; + } + if (r2) { + for (; ; ) { + if (ni == 0) { + for (i3 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i3++) + ; + j2 = xc[0] += k2; + for (k2 = 1; j2 >= 10; j2 /= 10, k2++) + ; + if (i3 != k2) { + x2.e++; + if (xc[0] == BASE) + xc[0] = 1; + } + break; + } else { + xc[ni] += k2; + if (xc[ni] != BASE) + break; + xc[ni--] = 0; + k2 = 1; + } + } + } + for (i3 = xc.length; xc[--i3] === 0; xc.pop()) + ; + } + if (x2.e > MAX_EXP) { + x2.c = x2.e = null; + } else if (x2.e < MIN_EXP) { + x2.c = [x2.e = 0]; + } + } + return x2; + } + function valueOf(n3) { + var str, e3 = n3.e; + if (e3 === null) + return n3.toString(); + str = coeffToString(n3.c); + str = e3 <= TO_EXP_NEG || e3 >= TO_EXP_POS ? toExponential(str, e3) : toFixedPoint(str, e3, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x2 = new BigNumber2(this); + if (x2.s < 0) + x2.s = 1; + return x2; + }; + P2.comparedTo = function(y2, b2) { + return compare(this, new BigNumber2(y2, b2)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c2, n3, v2, x2 = this; + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber2(x2), dp + x2.e + 1, rm); + } + if (!(c2 = x2.c)) + return null; + n3 = ((v2 = c2.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + if (v2 = c2[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y2, b2) { + return div(this, new BigNumber2(y2, b2), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y2, b2) { + return div(this, new BigNumber2(y2, b2), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m2) { + var half, isModExp, i3, k2, more, nIsBig, nIsNeg, nIsOdd, y2, x2 = this; + n3 = new BigNumber2(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError + "Exponent not an integer: " + valueOf(n3)); + } + if (m2 != null) + m2 = new BigNumber2(m2); + nIsBig = n3.e > 14; + if (!x2.c || !x2.c[0] || x2.c[0] == 1 && !x2.e && x2.c.length == 1 || !n3.c || !n3.c[0]) { + y2 = new BigNumber2(Math.pow(+valueOf(x2), nIsBig ? n3.s * (2 - isOdd(n3)) : +valueOf(n3))); + return m2 ? y2.mod(m2) : y2; + } + nIsNeg = n3.s < 0; + if (m2) { + if (m2.c ? !m2.c[0] : !m2.s) + return new BigNumber2(NaN); + isModExp = !nIsNeg && x2.isInteger() && m2.isInteger(); + if (isModExp) + x2 = x2.mod(m2); + } else if (n3.e > 9 && (x2.e > 0 || x2.e < -1 || (x2.e == 0 ? x2.c[0] > 1 || nIsBig && x2.c[1] >= 24e7 : x2.c[0] < 8e13 || nIsBig && x2.c[0] <= 9999975e7))) { + k2 = x2.s < 0 && isOdd(n3) ? -0 : 0; + if (x2.e > -1) + k2 = 1 / k2; + return new BigNumber2(nIsNeg ? 1 / k2 : k2); + } else if (POW_PRECISION) { + k2 = mathceil(POW_PRECISION / LOG_BASE + 2); + } + if (nIsBig) { + half = new BigNumber2(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd(n3); + } else { + i3 = Math.abs(+valueOf(n3)); + nIsOdd = i3 % 2; + } + y2 = new BigNumber2(ONE); + for (; ; ) { + if (nIsOdd) { + y2 = y2.times(x2); + if (!y2.c) + break; + if (k2) { + if (y2.c.length > k2) + y2.c.length = k2; + } else if (isModExp) { + y2 = y2.mod(m2); + } + } + if (i3) { + i3 = mathfloor(i3 / 2); + if (i3 === 0) + break; + nIsOdd = i3 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd(n3); + } else { + i3 = +valueOf(n3); + if (i3 === 0) + break; + nIsOdd = i3 % 2; + } + } + x2 = x2.times(x2); + if (k2) { + if (x2.c && x2.c.length > k2) + x2.c.length = k2; + } else if (isModExp) { + x2 = x2.mod(m2); + } + } + if (isModExp) + return y2; + if (nIsNeg) + y2 = ONE.div(y2); + return m2 ? y2.mod(m2) : k2 ? round(y2, POW_PRECISION, ROUNDING_MODE, more) : y2; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber2(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y2, b2) { + return compare(this, new BigNumber2(y2, b2)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y2, b2) { + return compare(this, new BigNumber2(y2, b2)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y2, b2) { + return (b2 = compare(this, new BigNumber2(y2, b2))) === 1 || b2 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y2, b2) { + return compare(this, new BigNumber2(y2, b2)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y2, b2) { + return (b2 = compare(this, new BigNumber2(y2, b2))) === -1 || b2 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y2, b2) { + var i3, j2, t2, xLTy, x2 = this, a2 = x2.s; + y2 = new BigNumber2(y2, b2); + b2 = y2.s; + if (!a2 || !b2) + return new BigNumber2(NaN); + if (a2 != b2) { + y2.s = -b2; + return x2.plus(y2); + } + var xe2 = x2.e / LOG_BASE, ye2 = y2.e / LOG_BASE, xc = x2.c, yc = y2.c; + if (!xe2 || !ye2) { + if (!xc || !yc) + return xc ? (y2.s = -b2, y2) : new BigNumber2(yc ? x2 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y2.s = -b2, y2) : new BigNumber2(xc[0] ? x2 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe2 = bitFloor(xe2); + ye2 = bitFloor(ye2); + xc = xc.slice(); + if (a2 = xe2 - ye2) { + if (xLTy = a2 < 0) { + a2 = -a2; + t2 = xc; + } else { + ye2 = xe2; + t2 = yc; + } + t2.reverse(); + for (b2 = a2; b2--; t2.push(0)) + ; + t2.reverse(); + } else { + j2 = (xLTy = (a2 = xc.length) < (b2 = yc.length)) ? a2 : b2; + for (a2 = b2 = 0; b2 < j2; b2++) { + if (xc[b2] != yc[b2]) { + xLTy = xc[b2] < yc[b2]; + break; + } + } + } + if (xLTy) { + t2 = xc; + xc = yc; + yc = t2; + y2.s = -y2.s; + } + b2 = (j2 = yc.length) - (i3 = xc.length); + if (b2 > 0) + for (; b2--; xc[i3++] = 0) + ; + b2 = BASE - 1; + for (; j2 > a2; ) { + if (xc[--j2] < yc[j2]) { + for (i3 = j2; i3 && !xc[--i3]; xc[i3] = b2) + ; + --xc[i3]; + xc[j2] += BASE; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye2) + ; + if (!xc[0]) { + y2.s = ROUNDING_MODE == 3 ? -1 : 1; + y2.c = [y2.e = 0]; + return y2; + } + return normalise(y2, xc, ye2); + }; + P2.modulo = P2.mod = function(y2, b2) { + var q2, s2, x2 = this; + y2 = new BigNumber2(y2, b2); + if (!x2.c || !y2.s || y2.c && !y2.c[0]) { + return new BigNumber2(NaN); + } else if (!y2.c || x2.c && !x2.c[0]) { + return new BigNumber2(x2); + } + if (MODULO_MODE == 9) { + s2 = y2.s; + y2.s = 1; + q2 = div(x2, y2, 0, 3); + y2.s = s2; + q2.s *= s2; + } else { + q2 = div(x2, y2, 0, MODULO_MODE); + } + y2 = x2.minus(q2.times(y2)); + if (!y2.c[0] && MODULO_MODE == 1) + y2.s = x2.s; + return y2; + }; + P2.multipliedBy = P2.times = function(y2, b2) { + var c2, e3, i3, j2, k2, m2, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x2 = this, xc = x2.c, yc = (y2 = new BigNumber2(y2, b2)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x2.s || !y2.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y2.c = y2.e = y2.s = null; + } else { + y2.s *= x2.s; + if (!xc || !yc) { + y2.c = y2.e = null; + } else { + y2.c = [0]; + y2.e = 0; + } + } + return y2; + } + e3 = bitFloor(x2.e / LOG_BASE) + bitFloor(y2.e / LOG_BASE); + y2.s *= x2.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i3 = xcL; + xcL = ycL; + ycL = i3; + } + for (i3 = xcL + ycL, zc = []; i3--; zc.push(0)) + ; + base = BASE; + sqrtBase = SQRT_BASE; + for (i3 = ycL; --i3 >= 0; ) { + c2 = 0; + ylo = yc[i3] % sqrtBase; + yhi = yc[i3] / sqrtBase | 0; + for (k2 = xcL, j2 = i3 + k2; j2 > i3; ) { + xlo = xc[--k2] % sqrtBase; + xhi = xc[k2] / sqrtBase | 0; + m2 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m2 % sqrtBase * sqrtBase + zc[j2] + c2; + c2 = (xlo / base | 0) + (m2 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base; + } + zc[j2] = c2; + } + if (c2) { + ++e3; + } else { + zc.splice(0, 1); + } + return normalise(y2, zc, e3); + }; + P2.negated = function() { + var x2 = new BigNumber2(this); + x2.s = -x2.s || null; + return x2; + }; + P2.plus = function(y2, b2) { + var t2, x2 = this, a2 = x2.s; + y2 = new BigNumber2(y2, b2); + b2 = y2.s; + if (!a2 || !b2) + return new BigNumber2(NaN); + if (a2 != b2) { + y2.s = -b2; + return x2.minus(y2); + } + var xe2 = x2.e / LOG_BASE, ye2 = y2.e / LOG_BASE, xc = x2.c, yc = y2.c; + if (!xe2 || !ye2) { + if (!xc || !yc) + return new BigNumber2(a2 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y2 : new BigNumber2(xc[0] ? x2 : a2 * 0); + } + xe2 = bitFloor(xe2); + ye2 = bitFloor(ye2); + xc = xc.slice(); + if (a2 = xe2 - ye2) { + if (a2 > 0) { + ye2 = xe2; + t2 = yc; + } else { + a2 = -a2; + t2 = xc; + } + t2.reverse(); + for (; a2--; t2.push(0)) + ; + t2.reverse(); + } + a2 = xc.length; + b2 = yc.length; + if (a2 - b2 < 0) { + t2 = yc; + yc = xc; + xc = t2; + b2 = a2; + } + for (a2 = 0; b2; ) { + a2 = (xc[--b2] = xc[b2] + yc[b2] + a2) / BASE | 0; + xc[b2] = BASE === xc[b2] ? 0 : xc[b2] % BASE; + } + if (a2) { + xc = [a2].concat(xc); + ++ye2; + } + return normalise(y2, xc, ye2); + }; + P2.precision = P2.sd = function(sd, rm) { + var c2, n3, v2, x2 = this; + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber2(x2), sd, rm); + } + if (!(c2 = x2.c)) + return null; + v2 = c2.length - 1; + n3 = v2 * LOG_BASE + 1; + if (v2 = c2[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c2[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x2.e + 1 > n3) + n3 = x2.e + 1; + return n3; + }; + P2.shiftedBy = function(k2) { + intCheck(k2, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times("1e" + k2); + }; + P2.squareRoot = P2.sqrt = function() { + var m2, n3, r2, rep, t2, x2 = this, c2 = x2.c, s2 = x2.s, e3 = x2.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); + if (s2 !== 1 || !c2 || !c2[0]) { + return new BigNumber2(!s2 || s2 < 0 && (!c2 || c2[0]) ? NaN : c2 ? x2 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x2)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString(c2); + if ((n3.length + e3) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e3 = bitFloor((e3 + 1) / 2) - (e3 < 0 || e3 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e3; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e3; + } + r2 = new BigNumber2(n3); + } else { + r2 = new BigNumber2(s2 + ""); + } + if (r2.c[0]) { + e3 = r2.e; + s2 = e3 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t2 = r2; + r2 = half.times(t2.plus(div(x2, t2, dp, 1))); + if (coeffToString(t2.c).slice(0, s2) === (n3 = coeffToString(r2.c)).slice(0, s2)) { + if (r2.e < e3) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t2, t2.e + DECIMAL_PLACES + 2, 0); + if (t2.times(t2).eq(x2)) { + r2 = t2; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r2, r2.e + DECIMAL_PLACES + 2, 1); + m2 = !r2.times(r2).eq(x2); + } + break; + } + } + } + } + return round(r2, r2.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m2); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format2(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format2(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format3) { + var str, x2 = this; + if (format3 == null) { + if (dp != null && rm && typeof rm == "object") { + format3 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format3 = dp; + dp = rm = null; + } else { + format3 = FORMAT; + } + } else if (typeof format3 != "object") { + throw Error(bignumberError + "Argument not an object: " + format3); + } + str = x2.toFixed(dp, rm); + if (x2.c) { + var i3, arr = str.split("."), g1 = +format3.groupSize, g22 = +format3.secondaryGroupSize, groupSeparator = format3.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x2.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) { + i3 = g1; + g1 = g22; + g22 = i3; + len -= i3; + } + if (g1 > 0 && len > 0) { + i3 = len % g1 || g1; + intPart = intDigits.substr(0, i3); + for (; i3 < len; i3 += g1) + intPart += groupSeparator + intDigits.substr(i3, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i3); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format3.decimalSeparator || "") + ((g22 = +format3.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format3.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format3.prefix || "") + str + (format3.suffix || ""); + }; + P2.toFraction = function(md) { + var d2, d0, d1, d22, e3, exp2, n3, n0, n1, q2, r2, s2, x2 = this, xc = x2.c; + if (md != null) { + n3 = new BigNumber2(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber2(x2); + d2 = new BigNumber2(ONE); + n1 = d0 = new BigNumber2(ONE); + d1 = n0 = new BigNumber2(ONE); + s2 = coeffToString(xc); + e3 = d2.e = s2.length - x2.e - 1; + d2.c[0] = POWS_TEN[(exp2 = e3 % LOG_BASE) < 0 ? LOG_BASE + exp2 : exp2]; + md = !md || n3.comparedTo(d2) > 0 ? e3 > 0 ? d2 : n1 : n3; + exp2 = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber2(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d2, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d2 = n3.minus(q2.times(d22 = d2)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x2.s; + e3 = e3 * 2; + r2 = div(n1, d1, e3, ROUNDING_MODE).minus(x2).abs().comparedTo( + div(n0, d0, e3, ROUNDING_MODE).minus(x2).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp2; + return r2; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck(sd, 1, MAX); + return format2(this, sd, rm, 2); + }; + P2.toString = function(b2) { + var str, n3 = this, s2 = n3.s, e3 = n3.e; + if (e3 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b2 == null) { + str = e3 <= TO_EXP_NEG || e3 >= TO_EXP_POS ? toExponential(coeffToString(n3.c), e3) : toFixedPoint(coeffToString(n3.c), e3, "0"); + } else if (b2 === 10 && alphabetHasNormalDecimalDigits) { + n3 = round(new BigNumber2(n3), DECIMAL_PLACES + e3 + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n3.c), n3.e, "0"); + } else { + intCheck(b2, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint(coeffToString(n3.c), e3, "0"), 10, b2, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + P2[Symbol.toStringTag] = "BigNumber"; + P2[Symbol.for("nodejs.util.inspect.custom")] = P2.valueOf; + if (configObject != null) + BigNumber2.set(configObject); + return BigNumber2; + } + function bitFloor(n3) { + var i3 = n3 | 0; + return n3 > 0 || n3 === i3 ? i3 : i3 - 1; + } + function coeffToString(a2) { + var s2, z2, i3 = 1, j2 = a2.length, r2 = a2[0] + ""; + for (; i3 < j2; ) { + s2 = a2[i3++] + ""; + z2 = LOG_BASE - s2.length; + for (; z2--; s2 = "0" + s2) + ; + r2 += s2; + } + for (j2 = r2.length; r2.charCodeAt(--j2) === 48; ) + ; + return r2.slice(0, j2 + 1 || 1); + } + function compare(x2, y2) { + var a2, b2, xc = x2.c, yc = y2.c, i3 = x2.s, j2 = y2.s, k2 = x2.e, l2 = y2.e; + if (!i3 || !j2) + return null; + a2 = xc && !xc[0]; + b2 = yc && !yc[0]; + if (a2 || b2) + return a2 ? b2 ? 0 : -j2 : i3; + if (i3 != j2) + return i3; + a2 = i3 < 0; + b2 = k2 == l2; + if (!xc || !yc) + return b2 ? 0 : !xc ^ a2 ? 1 : -1; + if (!b2) + return k2 > l2 ^ a2 ? 1 : -1; + j2 = (k2 = xc.length) < (l2 = yc.length) ? k2 : l2; + for (i3 = 0; i3 < j2; i3++) + if (xc[i3] != yc[i3]) + return xc[i3] > yc[i3] ^ a2 ? 1 : -1; + return k2 == l2 ? 0 : k2 > l2 ^ a2 ? 1 : -1; + } + function intCheck(n3, min3, max3, name) { + if (n3 < min3 || n3 > max3 || n3 !== mathfloor(n3)) { + throw Error(bignumberError + (name || "Argument") + (typeof n3 == "number" ? n3 < min3 || n3 > max3 ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } + } + function isOdd(n3) { + var k2 = n3.c.length - 1; + return bitFloor(n3.e / LOG_BASE) == k2 && n3.c[k2] % 2 != 0; + } + function toExponential(str, e3) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e3 < 0 ? "e" : "e+") + e3; + } + function toFixedPoint(str, e3, z2) { + var len, zs; + if (e3 < 0) { + for (zs = z2 + "."; ++e3; zs += z2) + ; + str = zs + str; + } else { + len = str.length; + if (++e3 > len) { + for (zs = z2, e3 -= len; --e3; zs += z2) + ; + str += zs; + } else if (e3 < len) { + str = str.slice(0, e3) + "." + str.slice(e3); + } } + return str; } - var levels = [ - "subterritory", - "territory", - "subcountryGroup", - "country", - "sharedLandform", - "intermediateRegion", - "subregion", - "region", - "subunion", - "union", - "unitedNations", - "world" - ]; - loadDerivedDataAndCaches(borders); - function loadDerivedDataAndCaches(borders2) { - const identifierProps = ["iso1A2", "iso1A3", "m49", "wikidata", "emojiFlag", "ccTLD", "nameEn"]; - let geometryFeatures = []; - for (const feature22 of borders2.features) { - const props = feature22.properties; - props.id = props.iso1A2 || props.m49 || props.wikidata; - loadM49(feature22); - loadTLD(feature22); - loadIsoStatus(feature22); - loadLevel(feature22); - loadGroups(feature22); - loadFlag(feature22); - cacheFeatureByIDs(feature22); - if (feature22.geometry) { - geometryFeatures.push(feature22); + var BigNumber = clone(); + var bignumber_default = BigNumber; + + // node_modules/splaytree-ts/dist/index.js + var SplayTreeNode = class { + constructor(key) { + __publicField(this, "key"); + __publicField(this, "left", null); + __publicField(this, "right", null); + this.key = key; + } + }; + var SplayTreeSetNode = class extends SplayTreeNode { + constructor(key) { + super(key); + } + }; + var SplayTree = class { + constructor() { + __publicField(this, "size", 0); + __publicField(this, "modificationCount", 0); + __publicField(this, "splayCount", 0); + } + splay(key) { + const root3 = this.root; + if (root3 == null) { + this.compare(key, key); + return -1; + } + let right = null; + let newTreeRight = null; + let left = null; + let newTreeLeft = null; + let current = root3; + const compare2 = this.compare; + let comp; + while (true) { + comp = compare2(current.key, key); + if (comp > 0) { + let currentLeft = current.left; + if (currentLeft == null) + break; + comp = compare2(currentLeft.key, key); + if (comp > 0) { + current.left = currentLeft.right; + currentLeft.right = current; + current = currentLeft; + currentLeft = current.left; + if (currentLeft == null) + break; + } + if (right == null) { + newTreeRight = current; + } else { + right.left = current; + } + right = current; + current = currentLeft; + } else if (comp < 0) { + let currentRight = current.right; + if (currentRight == null) + break; + comp = compare2(currentRight.key, key); + if (comp < 0) { + current.right = currentRight.left; + currentRight.left = current; + current = currentRight; + currentRight = current.right; + if (currentRight == null) + break; + } + if (left == null) { + newTreeLeft = current; + } else { + left.right = current; + } + left = current; + current = currentRight; + } else { + break; + } } + if (left != null) { + left.right = current.left; + current.left = newTreeLeft; + } + if (right != null) { + right.left = current.right; + current.right = newTreeRight; + } + if (this.root !== current) { + this.root = current; + this.splayCount++; + } + return comp; } - for (const feature22 of borders2.features) { - feature22.properties.groups = feature22.properties.groups.map((groupID) => { - return _featuresByCode[groupID].properties.id; - }); - loadMembersForGroupsOf(feature22); + splayMin(node) { + let current = node; + let nextLeft = current.left; + while (nextLeft != null) { + const left = nextLeft; + current.left = left.right; + left.right = current; + current = left; + nextLeft = current.left; + } + return current; } - for (const feature22 of borders2.features) { - loadRoadSpeedUnit(feature22); - loadRoadHeightUnit(feature22); - loadDriveSide(feature22); - loadCallingCodes(feature22); - loadGroupGroups(feature22); + splayMax(node) { + let current = node; + let nextRight = current.right; + while (nextRight != null) { + const right = nextRight; + current.right = right.left; + right.left = current; + current = right; + nextRight = current.right; + } + return current; + } + _delete(key) { + if (this.root == null) + return null; + const comp = this.splay(key); + if (comp != 0) + return null; + let root3 = this.root; + const result = root3; + const left = root3.left; + this.size--; + if (left == null) { + this.root = root3.right; + } else { + const right = root3.right; + root3 = this.splayMax(left); + root3.right = right; + this.root = root3; + } + this.modificationCount++; + return result; + } + addNewRoot(node, comp) { + this.size++; + this.modificationCount++; + const root3 = this.root; + if (root3 == null) { + this.root = node; + return; + } + if (comp < 0) { + node.left = root3; + node.right = root3.right; + root3.right = null; + } else { + node.right = root3; + node.left = root3.left; + root3.left = null; + } + this.root = node; + } + _first() { + const root3 = this.root; + if (root3 == null) + return null; + this.root = this.splayMin(root3); + return this.root; + } + _last() { + const root3 = this.root; + if (root3 == null) + return null; + this.root = this.splayMax(root3); + return this.root; + } + clear() { + this.root = null; + this.size = 0; + this.modificationCount++; + } + has(key) { + return this.validKey(key) && this.splay(key) == 0; + } + defaultCompare() { + return (a2, b2) => a2 < b2 ? -1 : a2 > b2 ? 1 : 0; + } + wrap() { + return { + getRoot: () => { + return this.root; + }, + setRoot: (root3) => { + this.root = root3; + }, + getSize: () => { + return this.size; + }, + getModificationCount: () => { + return this.modificationCount; + }, + getSplayCount: () => { + return this.splayCount; + }, + setSplayCount: (count) => { + this.splayCount = count; + }, + splay: (key) => { + return this.splay(key); + }, + has: (key) => { + return this.has(key); + } + }; + } + }; + var _a; + var _SplayTreeSet = class _SplayTreeSet extends SplayTree { + constructor(compare2, isValidKey) { + super(); + __publicField(this, "root", null); + __publicField(this, "compare"); + __publicField(this, "validKey"); + __publicField(this, _a, "[object Set]"); + this.compare = compare2 != null ? compare2 : this.defaultCompare(); + this.validKey = isValidKey != null ? isValidKey : (v2) => v2 != null && v2 != void 0; + } + delete(element) { + if (!this.validKey(element)) + return false; + return this._delete(element) != null; + } + deleteAll(elements) { + for (const element of elements) { + this.delete(element); + } + } + forEach(f2) { + const nodes = this[Symbol.iterator](); + let result; + while (result = nodes.next(), !result.done) { + f2(result.value, result.value, this); + } + } + add(element) { + const compare2 = this.splay(element); + if (compare2 != 0) + this.addNewRoot(new SplayTreeSetNode(element), compare2); + return this; + } + addAndReturn(element) { + const compare2 = this.splay(element); + if (compare2 != 0) + this.addNewRoot(new SplayTreeSetNode(element), compare2); + return this.root.key; + } + addAll(elements) { + for (const element of elements) { + this.add(element); + } + } + isEmpty() { + return this.root == null; + } + isNotEmpty() { + return this.root != null; + } + single() { + if (this.size == 0) + throw "Bad state: No element"; + if (this.size > 1) + throw "Bad state: Too many element"; + return this.root.key; + } + first() { + if (this.size == 0) + throw "Bad state: No element"; + return this._first().key; + } + last() { + if (this.size == 0) + throw "Bad state: No element"; + return this._last().key; + } + lastBefore(element) { + if (element == null) + throw "Invalid arguments(s)"; + if (this.root == null) + return null; + const comp = this.splay(element); + if (comp < 0) + return this.root.key; + let node = this.root.left; + if (node == null) + return null; + let nodeRight = node.right; + while (nodeRight != null) { + node = nodeRight; + nodeRight = node.right; + } + return node.key; + } + firstAfter(element) { + if (element == null) + throw "Invalid arguments(s)"; + if (this.root == null) + return null; + const comp = this.splay(element); + if (comp > 0) + return this.root.key; + let node = this.root.right; + if (node == null) + return null; + let nodeLeft = node.left; + while (nodeLeft != null) { + node = nodeLeft; + nodeLeft = node.left; + } + return node.key; + } + retainAll(elements) { + const retainSet = new _SplayTreeSet(this.compare, this.validKey); + const modificationCount = this.modificationCount; + for (const object of elements) { + if (modificationCount != this.modificationCount) { + throw "Concurrent modification during iteration."; + } + if (this.validKey(object) && this.splay(object) == 0) { + retainSet.add(this.root.key); + } + } + if (retainSet.size != this.size) { + this.root = retainSet.root; + this.size = retainSet.size; + this.modificationCount++; + } + } + lookup(object) { + if (!this.validKey(object)) + return null; + const comp = this.splay(object); + if (comp != 0) + return null; + return this.root.key; + } + intersection(other) { + const result = new _SplayTreeSet(this.compare, this.validKey); + for (const element of this) { + if (other.has(element)) + result.add(element); + } + return result; + } + difference(other) { + const result = new _SplayTreeSet(this.compare, this.validKey); + for (const element of this) { + if (!other.has(element)) + result.add(element); + } + return result; + } + union(other) { + const u2 = this.clone(); + u2.addAll(other); + return u2; + } + clone() { + const set4 = new _SplayTreeSet(this.compare, this.validKey); + set4.size = this.size; + set4.root = this.copyNode(this.root); + return set4; + } + copyNode(node) { + if (node == null) + return null; + function copyChildren(node2, dest) { + let left; + let right; + do { + left = node2.left; + right = node2.right; + if (left != null) { + const newLeft = new SplayTreeSetNode(left.key); + dest.left = newLeft; + copyChildren(left, newLeft); + } + if (right != null) { + const newRight = new SplayTreeSetNode(right.key); + dest.right = newRight; + node2 = right; + dest = newRight; + } + } while (right != null); + } + const result = new SplayTreeSetNode(node.key); + copyChildren(node, result); + return result; + } + toSet() { + return this.clone(); + } + entries() { + return new SplayTreeSetEntryIterableIterator(this.wrap()); + } + keys() { + return this[Symbol.iterator](); + } + values() { + return this[Symbol.iterator](); + } + [Symbol.iterator]() { + return new SplayTreeKeyIterableIterator(this.wrap()); + } + }; + _a = Symbol.toStringTag; + var SplayTreeSet = _SplayTreeSet; + var SplayTreeIterableIterator = class { + constructor(tree) { + __publicField(this, "tree"); + __publicField(this, "path", new Array()); + __publicField(this, "modificationCount", null); + __publicField(this, "splayCount"); + this.tree = tree; + this.splayCount = tree.getSplayCount(); + } + [Symbol.iterator]() { + return this; + } + next() { + if (this.moveNext()) + return { done: false, value: this.current() }; + return { done: true, value: null }; + } + current() { + if (!this.path.length) + return null; + const node = this.path[this.path.length - 1]; + return this.getValue(node); + } + rebuildPath(key) { + this.path.splice(0, this.path.length); + this.tree.splay(key); + this.path.push(this.tree.getRoot()); + this.splayCount = this.tree.getSplayCount(); + } + findLeftMostDescendent(node) { + while (node != null) { + this.path.push(node); + node = node.left; + } + } + moveNext() { + if (this.modificationCount != this.tree.getModificationCount()) { + if (this.modificationCount == null) { + this.modificationCount = this.tree.getModificationCount(); + let node2 = this.tree.getRoot(); + while (node2 != null) { + this.path.push(node2); + node2 = node2.left; + } + return this.path.length > 0; + } + throw "Concurrent modification during iteration."; + } + if (!this.path.length) + return false; + if (this.splayCount != this.tree.getSplayCount()) { + this.rebuildPath(this.path[this.path.length - 1].key); + } + let node = this.path[this.path.length - 1]; + let next = node.right; + if (next != null) { + while (next != null) { + this.path.push(next); + next = next.left; + } + return true; + } + this.path.pop(); + while (this.path.length && this.path[this.path.length - 1].right === node) { + node = this.path.pop(); + } + return this.path.length > 0; + } + }; + var SplayTreeKeyIterableIterator = class extends SplayTreeIterableIterator { + getValue(node) { + return node.key; + } + }; + var SplayTreeSetEntryIterableIterator = class extends SplayTreeIterableIterator { + getValue(node) { + return [node.key, node.key]; + } + }; + + // node_modules/polyclip-ts/dist/identity.js + var identity_default3 = (x2) => { + return x2; + }; + + // node_modules/polyclip-ts/dist/snap.js + var snap_default = (eps) => { + if (eps) { + const xTree = new SplayTreeSet(compare_default(eps)); + const yTree = new SplayTreeSet(compare_default(eps)); + const snapCoord = (coord2, tree) => { + return tree.addAndReturn(coord2); + }; + const snap = (v2) => { + return { + x: snapCoord(v2.x, xTree), + y: snapCoord(v2.y, yTree) + }; + }; + snap({ x: new bignumber_default(0), y: new bignumber_default(0) }); + return snap; + } + return identity_default3; + }; + + // node_modules/polyclip-ts/dist/precision.js + var set3 = (eps) => { + return { + set: (eps2) => { + precision = set3(eps2); + }, + reset: () => set3(eps), + compare: compare_default(eps), + snap: snap_default(eps), + orient: orient_default(eps) + }; + }; + var precision = set3(); + + // node_modules/polyclip-ts/dist/bbox.js + var isInBbox = (bbox2, point2) => { + return bbox2.ll.x.isLessThanOrEqualTo(point2.x) && point2.x.isLessThanOrEqualTo(bbox2.ur.x) && bbox2.ll.y.isLessThanOrEqualTo(point2.y) && point2.y.isLessThanOrEqualTo(bbox2.ur.y); + }; + var getBboxOverlap = (b1, b2) => { + if (b2.ur.x.isLessThan(b1.ll.x) || b1.ur.x.isLessThan(b2.ll.x) || b2.ur.y.isLessThan(b1.ll.y) || b1.ur.y.isLessThan(b2.ll.y)) + return null; + const lowerX = b1.ll.x.isLessThan(b2.ll.x) ? b2.ll.x : b1.ll.x; + const upperX = b1.ur.x.isLessThan(b2.ur.x) ? b1.ur.x : b2.ur.x; + const lowerY = b1.ll.y.isLessThan(b2.ll.y) ? b2.ll.y : b1.ll.y; + const upperY = b1.ur.y.isLessThan(b2.ur.y) ? b1.ur.y : b2.ur.y; + return { ll: { x: lowerX, y: lowerY }, ur: { x: upperX, y: upperY } }; + }; + + // node_modules/polyclip-ts/dist/vector.js + var crossProduct = (a2, b2) => a2.x.times(b2.y).minus(a2.y.times(b2.x)); + var dotProduct = (a2, b2) => a2.x.times(b2.x).plus(a2.y.times(b2.y)); + var length = (v2) => dotProduct(v2, v2).sqrt(); + var sineOfAngle = (pShared, pBase, pAngle) => { + const vBase = { x: pBase.x.minus(pShared.x), y: pBase.y.minus(pShared.y) }; + const vAngle = { x: pAngle.x.minus(pShared.x), y: pAngle.y.minus(pShared.y) }; + return crossProduct(vAngle, vBase).div(length(vAngle)).div(length(vBase)); + }; + var cosineOfAngle = (pShared, pBase, pAngle) => { + const vBase = { x: pBase.x.minus(pShared.x), y: pBase.y.minus(pShared.y) }; + const vAngle = { x: pAngle.x.minus(pShared.x), y: pAngle.y.minus(pShared.y) }; + return dotProduct(vAngle, vBase).div(length(vAngle)).div(length(vBase)); + }; + var horizontalIntersection = (pt2, v2, y2) => { + if (v2.y.isZero()) + return null; + return { x: pt2.x.plus(v2.x.div(v2.y).times(y2.minus(pt2.y))), y: y2 }; + }; + var verticalIntersection = (pt2, v2, x2) => { + if (v2.x.isZero()) + return null; + return { x: x2, y: pt2.y.plus(v2.y.div(v2.x).times(x2.minus(pt2.x))) }; + }; + var intersection = (pt1, v1, pt2, v2) => { + if (v1.x.isZero()) + return verticalIntersection(pt2, v2, pt1.x); + if (v2.x.isZero()) + return verticalIntersection(pt1, v1, pt2.x); + if (v1.y.isZero()) + return horizontalIntersection(pt2, v2, pt1.y); + if (v2.y.isZero()) + return horizontalIntersection(pt1, v1, pt2.y); + const kross = crossProduct(v1, v2); + if (kross.isZero()) + return null; + const ve2 = { x: pt2.x.minus(pt1.x), y: pt2.y.minus(pt1.y) }; + const d1 = crossProduct(ve2, v1).div(kross); + const d2 = crossProduct(ve2, v2).div(kross); + const x12 = pt1.x.plus(d2.times(v1.x)), x2 = pt2.x.plus(d1.times(v2.x)); + const y12 = pt1.y.plus(d2.times(v1.y)), y2 = pt2.y.plus(d1.times(v2.y)); + const x3 = x12.plus(x2).div(2); + const y3 = y12.plus(y2).div(2); + return { x: x3, y: y3 }; + }; + + // node_modules/polyclip-ts/dist/sweep-event.js + var SweepEvent = class _SweepEvent { + // Warning: 'point' input will be modified and re-used (for performance) + constructor(point2, isLeft) { + __publicField(this, "point"); + __publicField(this, "isLeft"); + __publicField(this, "segment"); + __publicField(this, "otherSE"); + __publicField(this, "consumedBy"); + if (point2.events === void 0) + point2.events = [this]; + else + point2.events.push(this); + this.point = point2; + this.isLeft = isLeft; + } + // for ordering sweep events in the sweep event queue + static compare(a2, b2) { + const ptCmp = _SweepEvent.comparePoints(a2.point, b2.point); + if (ptCmp !== 0) + return ptCmp; + if (a2.point !== b2.point) + a2.link(b2); + if (a2.isLeft !== b2.isLeft) + return a2.isLeft ? 1 : -1; + return Segment.compare(a2.segment, b2.segment); + } + // for ordering points in sweep line order + static comparePoints(aPt, bPt) { + if (aPt.x.isLessThan(bPt.x)) + return -1; + if (aPt.x.isGreaterThan(bPt.x)) + return 1; + if (aPt.y.isLessThan(bPt.y)) + return -1; + if (aPt.y.isGreaterThan(bPt.y)) + return 1; + return 0; + } + link(other) { + if (other.point === this.point) { + throw new Error("Tried to link already linked events"); + } + const otherEvents = other.point.events; + for (let i3 = 0, iMax = otherEvents.length; i3 < iMax; i3++) { + const evt = otherEvents[i3]; + this.point.events.push(evt); + evt.point = this.point; + } + this.checkForConsuming(); + } + /* Do a pass over our linked events and check to see if any pair + * of segments match, and should be consumed. */ + checkForConsuming() { + const numEvents = this.point.events.length; + for (let i3 = 0; i3 < numEvents; i3++) { + const evt1 = this.point.events[i3]; + if (evt1.segment.consumedBy !== void 0) + continue; + for (let j2 = i3 + 1; j2 < numEvents; j2++) { + const evt2 = this.point.events[j2]; + if (evt2.consumedBy !== void 0) + continue; + if (evt1.otherSE.point.events !== evt2.otherSE.point.events) + continue; + evt1.segment.consume(evt2.segment); + } + } + } + getAvailableLinkedEvents() { + const events = []; + for (let i3 = 0, iMax = this.point.events.length; i3 < iMax; i3++) { + const evt = this.point.events[i3]; + if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) { + events.push(evt); + } + } + return events; } - for (const feature22 of borders2.features) { - feature22.properties.groups.sort((groupID1, groupID2) => { - return levels.indexOf(_featuresByCode[groupID1].properties.level) - levels.indexOf(_featuresByCode[groupID2].properties.level); - }); - if (feature22.properties.members) { - feature22.properties.members.sort((id1, id2) => { - const diff = levels.indexOf(_featuresByCode[id1].properties.level) - levels.indexOf(_featuresByCode[id2].properties.level); - if (diff === 0) { - return borders2.features.indexOf(_featuresByCode[id1]) - borders2.features.indexOf(_featuresByCode[id2]); - } - return diff; + /** + * Returns a comparator function for sorting linked events that will + * favor the event that will give us the smallest left-side angle. + * All ring construction starts as low as possible heading to the right, + * so by always turning left as sharp as possible we'll get polygons + * without uncessary loops & holes. + * + * The comparator function has a compute cache such that it avoids + * re-computing already-computed values. + */ + getLeftmostComparator(baseEvent) { + const cache = /* @__PURE__ */ new Map(); + const fillCache = (linkedEvent) => { + const nextEvent = linkedEvent.otherSE; + cache.set(linkedEvent, { + sine: sineOfAngle(this.point, baseEvent.point, nextEvent.point), + cosine: cosineOfAngle(this.point, baseEvent.point, nextEvent.point) }); - } + }; + return (a2, b2) => { + if (!cache.has(a2)) + fillCache(a2); + if (!cache.has(b2)) + fillCache(b2); + const { sine: asine, cosine: acosine } = cache.get(a2); + const { sine: bsine, cosine: bcosine } = cache.get(b2); + if (asine.isGreaterThanOrEqualTo(0) && bsine.isGreaterThanOrEqualTo(0)) { + if (acosine.isLessThan(bcosine)) + return 1; + if (acosine.isGreaterThan(bcosine)) + return -1; + return 0; + } + if (asine.isLessThan(0) && bsine.isLessThan(0)) { + if (acosine.isLessThan(bcosine)) + return -1; + if (acosine.isGreaterThan(bcosine)) + return 1; + return 0; + } + if (bsine.isLessThan(asine)) + return -1; + if (bsine.isGreaterThan(asine)) + return 1; + return 0; + }; } - const geometryOnlyCollection = { - type: "FeatureCollection", - features: geometryFeatures - }; - _whichPolygon = (0, import_which_polygon.default)(geometryOnlyCollection); - function loadGroups(feature22) { - const props = feature22.properties; - if (!props.groups) { - props.groups = []; + }; + + // node_modules/polyclip-ts/dist/segment.js + var segmentId = 0; + var Segment = class _Segment { + /* Warning: a reference to ringWindings input will be stored, + * and possibly will be later modified */ + constructor(leftSE, rightSE, rings, windings) { + __publicField(this, "id"); + __publicField(this, "leftSE"); + __publicField(this, "rightSE"); + __publicField(this, "rings"); + __publicField(this, "windings"); + __publicField(this, "ringOut"); + __publicField(this, "consumedBy"); + __publicField(this, "prev"); + __publicField(this, "_prevInResult"); + __publicField(this, "_beforeState"); + __publicField(this, "_afterState"); + __publicField(this, "_isInResult"); + this.id = ++segmentId; + this.leftSE = leftSE; + leftSE.segment = this; + leftSE.otherSE = rightSE; + this.rightSE = rightSE; + rightSE.segment = this; + rightSE.otherSE = leftSE; + this.rings = rings; + this.windings = windings; + } + /* This compare() function is for ordering segments in the sweep + * line tree, and does so according to the following criteria: + * + * Consider the vertical line that lies an infinestimal step to the + * right of the right-more of the two left endpoints of the input + * segments. Imagine slowly moving a point up from negative infinity + * in the increasing y direction. Which of the two segments will that + * point intersect first? That segment comes 'before' the other one. + * + * If neither segment would be intersected by such a line, (if one + * or more of the segments are vertical) then the line to be considered + * is directly on the right-more of the two left inputs. + */ + static compare(a2, b2) { + const alx = a2.leftSE.point.x; + const blx = b2.leftSE.point.x; + const arx = a2.rightSE.point.x; + const brx = b2.rightSE.point.x; + if (brx.isLessThan(alx)) + return 1; + if (arx.isLessThan(blx)) + return -1; + const aly = a2.leftSE.point.y; + const bly = b2.leftSE.point.y; + const ary = a2.rightSE.point.y; + const bry = b2.rightSE.point.y; + if (alx.isLessThan(blx)) { + if (bly.isLessThan(aly) && bly.isLessThan(ary)) + return 1; + if (bly.isGreaterThan(aly) && bly.isGreaterThan(ary)) + return -1; + const aCmpBLeft = a2.comparePoint(b2.leftSE.point); + if (aCmpBLeft < 0) + return 1; + if (aCmpBLeft > 0) + return -1; + const bCmpARight = b2.comparePoint(a2.rightSE.point); + if (bCmpARight !== 0) + return bCmpARight; + return -1; } - if (feature22.geometry && props.country) { - props.groups.push(props.country); + if (alx.isGreaterThan(blx)) { + if (aly.isLessThan(bly) && aly.isLessThan(bry)) + return -1; + if (aly.isGreaterThan(bly) && aly.isGreaterThan(bry)) + return 1; + const bCmpALeft = b2.comparePoint(a2.leftSE.point); + if (bCmpALeft !== 0) + return bCmpALeft; + const aCmpBRight = a2.comparePoint(b2.rightSE.point); + if (aCmpBRight < 0) + return 1; + if (aCmpBRight > 0) + return -1; + return 1; } - if (props.m49 !== "001") { - props.groups.push("001"); + if (aly.isLessThan(bly)) + return -1; + if (aly.isGreaterThan(bly)) + return 1; + if (arx.isLessThan(brx)) { + const bCmpARight = b2.comparePoint(a2.rightSE.point); + if (bCmpARight !== 0) + return bCmpARight; + } + if (arx.isGreaterThan(brx)) { + const aCmpBRight = a2.comparePoint(b2.rightSE.point); + if (aCmpBRight < 0) + return 1; + if (aCmpBRight > 0) + return -1; } - } - function loadM49(feature22) { - const props = feature22.properties; - if (!props.m49 && props.iso1N3) { - props.m49 = props.iso1N3; + if (!arx.eq(brx)) { + const ay = ary.minus(aly); + const ax = arx.minus(alx); + const by = bry.minus(bly); + const bx = brx.minus(blx); + if (ay.isGreaterThan(ax) && by.isLessThan(bx)) + return 1; + if (ay.isLessThan(ax) && by.isGreaterThan(bx)) + return -1; } + if (arx.isGreaterThan(brx)) + return 1; + if (arx.isLessThan(brx)) + return -1; + if (ary.isLessThan(bry)) + return -1; + if (ary.isGreaterThan(bry)) + return 1; + if (a2.id < b2.id) + return -1; + if (a2.id > b2.id) + return 1; + return 0; } - function loadTLD(feature22) { - const props = feature22.properties; - if (props.level === "unitedNations") - return; - if (!props.ccTLD && props.iso1A2) { - props.ccTLD = "." + props.iso1A2.toLowerCase(); - } + static fromRing(pt1, pt2, ring) { + let leftPt, rightPt, winding; + const cmpPts = SweepEvent.comparePoints(pt1, pt2); + if (cmpPts < 0) { + leftPt = pt1; + rightPt = pt2; + winding = 1; + } else if (cmpPts > 0) { + leftPt = pt2; + rightPt = pt1; + winding = -1; + } else + throw new Error("Tried to create degenerate segment at [".concat(pt1.x, ", ").concat(pt1.y, "]")); + const leftSE = new SweepEvent(leftPt, true); + const rightSE = new SweepEvent(rightPt, false); + return new _Segment(leftSE, rightSE, [ring], [winding]); + } + /* When a segment is split, the rightSE is replaced with a new sweep event */ + replaceRightSE(newRightSE) { + this.rightSE = newRightSE; + this.rightSE.segment = this; + this.rightSE.otherSE = this.leftSE; + this.leftSE.otherSE = this.rightSE; + } + bbox() { + const y12 = this.leftSE.point.y; + const y2 = this.rightSE.point.y; + return { + ll: { x: this.leftSE.point.x, y: y12.isLessThan(y2) ? y12 : y2 }, + ur: { x: this.rightSE.point.x, y: y12.isGreaterThan(y2) ? y12 : y2 } + }; } - function loadIsoStatus(feature22) { - const props = feature22.properties; - if (!props.isoStatus && props.iso1A2) { - props.isoStatus = "official"; - } + /* A vector from the left point to the right */ + vector() { + return { + x: this.rightSE.point.x.minus(this.leftSE.point.x), + y: this.rightSE.point.y.minus(this.leftSE.point.y) + }; } - function loadLevel(feature22) { - const props = feature22.properties; - if (props.level) - return; - if (!props.country) { - props.level = "country"; - } else if (!props.iso1A2 || props.isoStatus === "official") { - props.level = "territory"; - } else { - props.level = "subterritory"; + isAnEndpoint(pt2) { + return pt2.x.eq(this.leftSE.point.x) && pt2.y.eq(this.leftSE.point.y) || pt2.x.eq(this.rightSE.point.x) && pt2.y.eq(this.rightSE.point.y); + } + /* Compare this segment with a point. + * + * A point P is considered to be colinear to a segment if there + * exists a distance D such that if we travel along the segment + * from one * endpoint towards the other a distance D, we find + * ourselves at point P. + * + * Return value indicates: + * + * 1: point lies above the segment (to the left of vertical) + * 0: point is colinear to segment + * -1: point lies below the segment (to the right of vertical) + */ + comparePoint(point2) { + return precision.orient(this.leftSE.point, point2, this.rightSE.point); + } + /** + * Given another segment, returns the first non-trivial intersection + * between the two segments (in terms of sweep line ordering), if it exists. + * + * A 'non-trivial' intersection is one that will cause one or both of the + * segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection: + * + * * endpoint of segA with endpoint of segB --> trivial + * * endpoint of segA with point along segB --> non-trivial + * * endpoint of segB with point along segA --> non-trivial + * * point along segA with point along segB --> non-trivial + * + * If no non-trivial intersection exists, return null + * Else, return null. + */ + getIntersection(other) { + const tBbox = this.bbox(); + const oBbox = other.bbox(); + const bboxOverlap = getBboxOverlap(tBbox, oBbox); + if (bboxOverlap === null) + return null; + const tlp = this.leftSE.point; + const trp = this.rightSE.point; + const olp = other.leftSE.point; + const orp = other.rightSE.point; + const touchesOtherLSE = isInBbox(tBbox, olp) && this.comparePoint(olp) === 0; + const touchesThisLSE = isInBbox(oBbox, tlp) && other.comparePoint(tlp) === 0; + const touchesOtherRSE = isInBbox(tBbox, orp) && this.comparePoint(orp) === 0; + const touchesThisRSE = isInBbox(oBbox, trp) && other.comparePoint(trp) === 0; + if (touchesThisLSE && touchesOtherLSE) { + if (touchesThisRSE && !touchesOtherRSE) + return trp; + if (!touchesThisRSE && touchesOtherRSE) + return orp; + return null; + } + if (touchesThisLSE) { + if (touchesOtherRSE) { + if (tlp.x.eq(orp.x) && tlp.y.eq(orp.y)) + return null; + } + return tlp; } + if (touchesOtherLSE) { + if (touchesThisRSE) { + if (trp.x.eq(olp.x) && trp.y.eq(olp.y)) + return null; + } + return olp; + } + if (touchesThisRSE && touchesOtherRSE) + return null; + if (touchesThisRSE) + return trp; + if (touchesOtherRSE) + return orp; + const pt2 = intersection(tlp, this.vector(), olp, other.vector()); + if (pt2 === null) + return null; + if (!isInBbox(bboxOverlap, pt2)) + return null; + return precision.snap(pt2); } - function loadGroupGroups(feature22) { - const props = feature22.properties; - if (feature22.geometry || !props.members) + /** + * Split the given segment into multiple segments on the given points. + * * Each existing segment will retain its leftSE and a new rightSE will be + * generated for it. + * * A new segment will be generated which will adopt the original segment's + * rightSE, and a new leftSE will be generated for it. + * * If there are more than two points given to split on, new segments + * in the middle will be generated with new leftSE and rightSE's. + * * An array of the newly generated SweepEvents will be returned. + * + * Warning: input array of points is modified + */ + split(point2) { + const newEvents = []; + const alreadyLinked = point2.events !== void 0; + const newLeftSE = new SweepEvent(point2, true); + const newRightSE = new SweepEvent(point2, false); + const oldRightSE = this.rightSE; + this.replaceRightSE(newRightSE); + newEvents.push(newRightSE); + newEvents.push(newLeftSE); + const newSeg = new _Segment(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice()); + if (SweepEvent.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) { + newSeg.swapEvents(); + } + if (SweepEvent.comparePoints(this.leftSE.point, this.rightSE.point) > 0) { + this.swapEvents(); + } + if (alreadyLinked) { + newLeftSE.checkForConsuming(); + newRightSE.checkForConsuming(); + } + return newEvents; + } + /* Swap which event is left and right */ + swapEvents() { + const tmpEvt = this.rightSE; + this.rightSE = this.leftSE; + this.leftSE = tmpEvt; + this.leftSE.isLeft = true; + this.rightSE.isLeft = false; + for (let i3 = 0, iMax = this.windings.length; i3 < iMax; i3++) { + this.windings[i3] *= -1; + } + } + /* Consume another segment. We take their rings under our wing + * and mark them as consumed. Use for perfectly overlapping segments */ + consume(other) { + let consumer = this; + let consumee = other; + while (consumer.consumedBy) + consumer = consumer.consumedBy; + while (consumee.consumedBy) + consumee = consumee.consumedBy; + const cmp = _Segment.compare(consumer, consumee); + if (cmp === 0) return; - const featureLevelIndex = levels.indexOf(props.level); - let sharedGroups = []; - props.members.forEach((memberID, index) => { - const member = _featuresByCode[memberID]; - const memberGroups = member.properties.groups.filter((groupID) => { - return groupID !== feature22.properties.id && featureLevelIndex < levels.indexOf(_featuresByCode[groupID].properties.level); - }); - if (index === 0) { - sharedGroups = memberGroups; - } else { - sharedGroups = sharedGroups.filter((groupID) => memberGroups.indexOf(groupID) !== -1); + if (cmp > 0) { + const tmp = consumer; + consumer = consumee; + consumee = tmp; + } + if (consumer.prev === consumee) { + const tmp = consumer; + consumer = consumee; + consumee = tmp; + } + for (let i3 = 0, iMax = consumee.rings.length; i3 < iMax; i3++) { + const ring = consumee.rings[i3]; + const winding = consumee.windings[i3]; + const index = consumer.rings.indexOf(ring); + if (index === -1) { + consumer.rings.push(ring); + consumer.windings.push(winding); + } else + consumer.windings[index] += winding; + } + consumee.rings = null; + consumee.windings = null; + consumee.consumedBy = consumer; + consumee.leftSE.consumedBy = consumer.leftSE; + consumee.rightSE.consumedBy = consumer.rightSE; + } + /* The first segment previous segment chain that is in the result */ + prevInResult() { + if (this._prevInResult !== void 0) + return this._prevInResult; + if (!this.prev) + this._prevInResult = null; + else if (this.prev.isInResult()) + this._prevInResult = this.prev; + else + this._prevInResult = this.prev.prevInResult(); + return this._prevInResult; + } + beforeState() { + if (this._beforeState !== void 0) + return this._beforeState; + if (!this.prev) + this._beforeState = { + rings: [], + windings: [], + multiPolys: [] + }; + else { + const seg = this.prev.consumedBy || this.prev; + this._beforeState = seg.afterState(); + } + return this._beforeState; + } + afterState() { + if (this._afterState !== void 0) + return this._afterState; + const beforeState = this.beforeState(); + this._afterState = { + rings: beforeState.rings.slice(0), + windings: beforeState.windings.slice(0), + multiPolys: [] + }; + const ringsAfter = this._afterState.rings; + const windingsAfter = this._afterState.windings; + const mpsAfter = this._afterState.multiPolys; + for (let i3 = 0, iMax = this.rings.length; i3 < iMax; i3++) { + const ring = this.rings[i3]; + const winding = this.windings[i3]; + const index = ringsAfter.indexOf(ring); + if (index === -1) { + ringsAfter.push(ring); + windingsAfter.push(winding); + } else + windingsAfter[index] += winding; + } + const polysAfter = []; + const polysExclude = []; + for (let i3 = 0, iMax = ringsAfter.length; i3 < iMax; i3++) { + if (windingsAfter[i3] === 0) + continue; + const ring = ringsAfter[i3]; + const poly = ring.poly; + if (polysExclude.indexOf(poly) !== -1) + continue; + if (ring.isExterior) + polysAfter.push(poly); + else { + if (polysExclude.indexOf(poly) === -1) + polysExclude.push(poly); + const index = polysAfter.indexOf(ring.poly); + if (index !== -1) + polysAfter.splice(index, 1); + } + } + for (let i3 = 0, iMax = polysAfter.length; i3 < iMax; i3++) { + const mp = polysAfter[i3].multiPoly; + if (mpsAfter.indexOf(mp) === -1) + mpsAfter.push(mp); + } + return this._afterState; + } + /* Is this segment part of the final result? */ + isInResult() { + if (this.consumedBy) + return false; + if (this._isInResult !== void 0) + return this._isInResult; + const mpsBefore = this.beforeState().multiPolys; + const mpsAfter = this.afterState().multiPolys; + switch (operation_default.type) { + case "union": { + const noBefores = mpsBefore.length === 0; + const noAfters = mpsAfter.length === 0; + this._isInResult = noBefores !== noAfters; + break; } - }); - props.groups = props.groups.concat( - sharedGroups.filter((groupID) => props.groups.indexOf(groupID) === -1) - ); - for (const groupID of sharedGroups) { - const groupFeature = _featuresByCode[groupID]; - if (groupFeature.properties.members.indexOf(props.id) === -1) { - groupFeature.properties.members.push(props.id); + case "intersection": { + let least; + let most; + if (mpsBefore.length < mpsAfter.length) { + least = mpsBefore.length; + most = mpsAfter.length; + } else { + least = mpsAfter.length; + most = mpsBefore.length; + } + this._isInResult = most === operation_default.numMultiPolys && least < most; + break; + } + case "xor": { + const diff = Math.abs(mpsBefore.length - mpsAfter.length); + this._isInResult = diff % 2 === 1; + break; + } + case "difference": { + const isJustSubject = (mps) => mps.length === 1 && mps[0].isSubject; + this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter); + break; } } + return this._isInResult; } - function loadRoadSpeedUnit(feature22) { - const props = feature22.properties; - if (feature22.geometry) { - if (!props.roadSpeedUnit) - props.roadSpeedUnit = "km/h"; - } else if (props.members) { - const vals = Array.from( - new Set( - props.members.map((id2) => { - const member = _featuresByCode[id2]; - if (member.geometry) - return member.properties.roadSpeedUnit || "km/h"; - }).filter(Boolean) - ) - ); - if (vals.length === 1) - props.roadSpeedUnit = vals[0]; - } + }; + + // node_modules/polyclip-ts/dist/geom-in.js + var RingIn = class { + constructor(geomRing, poly, isExterior) { + __publicField(this, "poly"); + __publicField(this, "isExterior"); + __publicField(this, "segments"); + __publicField(this, "bbox"); + if (!Array.isArray(geomRing) || geomRing.length === 0) { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + this.poly = poly; + this.isExterior = isExterior; + this.segments = []; + if (typeof geomRing[0][0] !== "number" || typeof geomRing[0][1] !== "number") { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + const firstPoint = precision.snap({ x: new bignumber_default(geomRing[0][0]), y: new bignumber_default(geomRing[0][1]) }); + this.bbox = { + ll: { x: firstPoint.x, y: firstPoint.y }, + ur: { x: firstPoint.x, y: firstPoint.y } + }; + let prevPoint = firstPoint; + for (let i3 = 1, iMax = geomRing.length; i3 < iMax; i3++) { + if (typeof geomRing[i3][0] !== "number" || typeof geomRing[i3][1] !== "number") { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + const point2 = precision.snap({ x: new bignumber_default(geomRing[i3][0]), y: new bignumber_default(geomRing[i3][1]) }); + if (point2.x.eq(prevPoint.x) && point2.y.eq(prevPoint.y)) + continue; + this.segments.push(Segment.fromRing(prevPoint, point2, this)); + if (point2.x.isLessThan(this.bbox.ll.x)) + this.bbox.ll.x = point2.x; + if (point2.y.isLessThan(this.bbox.ll.y)) + this.bbox.ll.y = point2.y; + if (point2.x.isGreaterThan(this.bbox.ur.x)) + this.bbox.ur.x = point2.x; + if (point2.y.isGreaterThan(this.bbox.ur.y)) + this.bbox.ur.y = point2.y; + prevPoint = point2; + } + if (!firstPoint.x.eq(prevPoint.x) || !firstPoint.y.eq(prevPoint.y)) { + this.segments.push(Segment.fromRing(prevPoint, firstPoint, this)); + } + } + getSweepEvents() { + const sweepEvents = []; + for (let i3 = 0, iMax = this.segments.length; i3 < iMax; i3++) { + const segment = this.segments[i3]; + sweepEvents.push(segment.leftSE); + sweepEvents.push(segment.rightSE); + } + return sweepEvents; } - function loadRoadHeightUnit(feature22) { - const props = feature22.properties; - if (feature22.geometry) { - if (!props.roadHeightUnit) - props.roadHeightUnit = "m"; - } else if (props.members) { - const vals = Array.from( - new Set( - props.members.map((id2) => { - const member = _featuresByCode[id2]; - if (member.geometry) - return member.properties.roadHeightUnit || "m"; - }).filter(Boolean) - ) - ); - if (vals.length === 1) - props.roadHeightUnit = vals[0]; - } + }; + var PolyIn = class { + constructor(geomPoly, multiPoly) { + __publicField(this, "multiPoly"); + __publicField(this, "exteriorRing"); + __publicField(this, "interiorRings"); + __publicField(this, "bbox"); + if (!Array.isArray(geomPoly)) { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); + } + this.exteriorRing = new RingIn(geomPoly[0], this, true); + this.bbox = { + ll: { x: this.exteriorRing.bbox.ll.x, y: this.exteriorRing.bbox.ll.y }, + ur: { x: this.exteriorRing.bbox.ur.x, y: this.exteriorRing.bbox.ur.y } + }; + this.interiorRings = []; + for (let i3 = 1, iMax = geomPoly.length; i3 < iMax; i3++) { + const ring = new RingIn(geomPoly[i3], this, false); + if (ring.bbox.ll.x.isLessThan(this.bbox.ll.x)) + this.bbox.ll.x = ring.bbox.ll.x; + if (ring.bbox.ll.y.isLessThan(this.bbox.ll.y)) + this.bbox.ll.y = ring.bbox.ll.y; + if (ring.bbox.ur.x.isGreaterThan(this.bbox.ur.x)) + this.bbox.ur.x = ring.bbox.ur.x; + if (ring.bbox.ur.y.isGreaterThan(this.bbox.ur.y)) + this.bbox.ur.y = ring.bbox.ur.y; + this.interiorRings.push(ring); + } + this.multiPoly = multiPoly; + } + getSweepEvents() { + const sweepEvents = this.exteriorRing.getSweepEvents(); + for (let i3 = 0, iMax = this.interiorRings.length; i3 < iMax; i3++) { + const ringSweepEvents = this.interiorRings[i3].getSweepEvents(); + for (let j2 = 0, jMax = ringSweepEvents.length; j2 < jMax; j2++) { + sweepEvents.push(ringSweepEvents[j2]); + } + } + return sweepEvents; } - function loadDriveSide(feature22) { - const props = feature22.properties; - if (feature22.geometry) { - if (!props.driveSide) - props.driveSide = "right"; - } else if (props.members) { - const vals = Array.from( - new Set( - props.members.map((id2) => { - const member = _featuresByCode[id2]; - if (member.geometry) - return member.properties.driveSide || "right"; - }).filter(Boolean) - ) - ); - if (vals.length === 1) - props.driveSide = vals[0]; + }; + var MultiPolyIn = class { + constructor(geom, isSubject) { + __publicField(this, "isSubject"); + __publicField(this, "polys"); + __publicField(this, "bbox"); + if (!Array.isArray(geom)) { + throw new Error("Input geometry is not a valid Polygon or MultiPolygon"); } - } - function loadCallingCodes(feature22) { - const props = feature22.properties; - if (!feature22.geometry && props.members) { - props.callingCodes = Array.from( - new Set( - props.members.reduce((array2, id2) => { - const member = _featuresByCode[id2]; - if (member.geometry && member.properties.callingCodes) { - return array2.concat(member.properties.callingCodes); - } - return array2; - }, []) - ) - ); + try { + if (typeof geom[0][0][0] === "number") + geom = [geom]; + } catch (ex) { } + this.polys = []; + this.bbox = { + ll: { x: new bignumber_default(Number.POSITIVE_INFINITY), y: new bignumber_default(Number.POSITIVE_INFINITY) }, + ur: { x: new bignumber_default(Number.NEGATIVE_INFINITY), y: new bignumber_default(Number.NEGATIVE_INFINITY) } + }; + for (let i3 = 0, iMax = geom.length; i3 < iMax; i3++) { + const poly = new PolyIn(geom[i3], this); + if (poly.bbox.ll.x.isLessThan(this.bbox.ll.x)) + this.bbox.ll.x = poly.bbox.ll.x; + if (poly.bbox.ll.y.isLessThan(this.bbox.ll.y)) + this.bbox.ll.y = poly.bbox.ll.y; + if (poly.bbox.ur.x.isGreaterThan(this.bbox.ur.x)) + this.bbox.ur.x = poly.bbox.ur.x; + if (poly.bbox.ur.y.isGreaterThan(this.bbox.ur.y)) + this.bbox.ur.y = poly.bbox.ur.y; + this.polys.push(poly); + } + this.isSubject = isSubject; + } + getSweepEvents() { + const sweepEvents = []; + for (let i3 = 0, iMax = this.polys.length; i3 < iMax; i3++) { + const polySweepEvents = this.polys[i3].getSweepEvents(); + for (let j2 = 0, jMax = polySweepEvents.length; j2 < jMax; j2++) { + sweepEvents.push(polySweepEvents[j2]); + } + } + return sweepEvents; } - function loadFlag(feature22) { - if (!feature22.properties.iso1A2) - return; - const flag = feature22.properties.iso1A2.replace(/./g, function(char) { - return String.fromCodePoint(char.charCodeAt(0) + 127397); - }); - feature22.properties.emojiFlag = flag; - } - function loadMembersForGroupsOf(feature22) { - for (const groupID of feature22.properties.groups) { - const groupFeature = _featuresByCode[groupID]; - if (!groupFeature.properties.members) { - groupFeature.properties.members = []; + }; + + // node_modules/polyclip-ts/dist/geom-out.js + var RingOut = class _RingOut { + constructor(events) { + __publicField(this, "events"); + __publicField(this, "poly"); + __publicField(this, "_isExteriorRing"); + __publicField(this, "_enclosingRing"); + this.events = events; + for (let i3 = 0, iMax = events.length; i3 < iMax; i3++) { + events[i3].segment.ringOut = this; + } + this.poly = null; + } + /* Given the segments from the sweep line pass, compute & return a series + * of closed rings from all the segments marked to be part of the result */ + static factory(allSegments) { + const ringsOut = []; + for (let i3 = 0, iMax = allSegments.length; i3 < iMax; i3++) { + const segment = allSegments[i3]; + if (!segment.isInResult() || segment.ringOut) + continue; + let prevEvent = null; + let event = segment.leftSE; + let nextEvent = segment.rightSE; + const events = [event]; + const startingPoint = event.point; + const intersectionLEs = []; + while (true) { + prevEvent = event; + event = nextEvent; + events.push(event); + if (event.point === startingPoint) + break; + while (true) { + const availableLEs = event.getAvailableLinkedEvents(); + if (availableLEs.length === 0) { + const firstPt = events[0].point; + const lastPt = events[events.length - 1].point; + throw new Error("Unable to complete output ring starting at [".concat(firstPt.x, ",") + " ".concat(firstPt.y, "]. Last matching segment found ends at") + " [".concat(lastPt.x, ", ").concat(lastPt.y, "].")); + } + if (availableLEs.length === 1) { + nextEvent = availableLEs[0].otherSE; + break; + } + let indexLE = null; + for (let j2 = 0, jMax = intersectionLEs.length; j2 < jMax; j2++) { + if (intersectionLEs[j2].point === event.point) { + indexLE = j2; + break; + } + } + if (indexLE !== null) { + const intersectionLE = intersectionLEs.splice(indexLE)[0]; + const ringEvents = events.splice(intersectionLE.index); + ringEvents.unshift(ringEvents[0].otherSE); + ringsOut.push(new _RingOut(ringEvents.reverse())); + continue; + } + intersectionLEs.push({ + index: events.length, + point: event.point + }); + const comparator = event.getLeftmostComparator(prevEvent); + nextEvent = availableLEs.sort(comparator)[0].otherSE; + break; + } } - groupFeature.properties.members.push(feature22.properties.id); + ringsOut.push(new _RingOut(events)); } + return ringsOut; } - function cacheFeatureByIDs(feature22) { - let ids = []; - for (const prop of identifierProps) { - const id2 = feature22.properties[prop]; - if (id2) { - ids.push(id2); + getGeom() { + let prevPt = this.events[0].point; + const points = [prevPt]; + for (let i3 = 1, iMax = this.events.length - 1; i3 < iMax; i3++) { + const pt3 = this.events[i3].point; + const nextPt2 = this.events[i3 + 1].point; + if (precision.orient(pt3, prevPt, nextPt2) === 0) + continue; + points.push(pt3); + prevPt = pt3; + } + if (points.length === 1) + return null; + const pt2 = points[0]; + const nextPt = points[1]; + if (precision.orient(pt2, prevPt, nextPt) === 0) + points.shift(); + points.push(points[0]); + const step = this.isExteriorRing() ? 1 : -1; + const iStart = this.isExteriorRing() ? 0 : points.length - 1; + const iEnd = this.isExteriorRing() ? points.length : -1; + const orderedPoints = []; + for (let i3 = iStart; i3 != iEnd; i3 += step) + orderedPoints.push([points[i3].x.toNumber(), points[i3].y.toNumber()]); + return orderedPoints; + } + isExteriorRing() { + if (this._isExteriorRing === void 0) { + const enclosing = this.enclosingRing(); + this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true; + } + return this._isExteriorRing; + } + enclosingRing() { + if (this._enclosingRing === void 0) { + this._enclosingRing = this._calcEnclosingRing(); + } + return this._enclosingRing; + } + /* Returns the ring that encloses this one, if any */ + _calcEnclosingRing() { + var _a2, _b; + let leftMostEvt = this.events[0]; + for (let i3 = 1, iMax = this.events.length; i3 < iMax; i3++) { + const evt = this.events[i3]; + if (SweepEvent.compare(leftMostEvt, evt) > 0) + leftMostEvt = evt; + } + let prevSeg = leftMostEvt.segment.prevInResult(); + let prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null; + while (true) { + if (!prevSeg) + return null; + if (!prevPrevSeg) + return prevSeg.ringOut; + if (prevPrevSeg.ringOut !== prevSeg.ringOut) { + if (((_a2 = prevPrevSeg.ringOut) == null ? void 0 : _a2.enclosingRing()) !== prevSeg.ringOut) { + return prevSeg.ringOut; + } else + return (_b = prevSeg.ringOut) == null ? void 0 : _b.enclosingRing(); } + prevSeg = prevPrevSeg.prevInResult(); + prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null; } - for (const alias of feature22.properties.aliases || []) { - ids.push(alias); + } + }; + var PolyOut = class { + constructor(exteriorRing) { + __publicField(this, "exteriorRing"); + __publicField(this, "interiorRings"); + this.exteriorRing = exteriorRing; + exteriorRing.poly = this; + this.interiorRings = []; + } + addInterior(ring) { + this.interiorRings.push(ring); + ring.poly = this; + } + getGeom() { + const geom = [this.exteriorRing.getGeom()]; + if (geom[0] === null) + return null; + for (let i3 = 0, iMax = this.interiorRings.length; i3 < iMax; i3++) { + const ringGeom = this.interiorRings[i3].getGeom(); + if (ringGeom === null) + continue; + geom.push(ringGeom); } - for (const id2 of ids) { - const cid = canonicalID(id2); - _featuresByCode[cid] = feature22; + return geom; + } + }; + var MultiPolyOut = class { + constructor(rings) { + __publicField(this, "rings"); + __publicField(this, "polys"); + this.rings = rings; + this.polys = this._composePolys(rings); + } + getGeom() { + const geom = []; + for (let i3 = 0, iMax = this.polys.length; i3 < iMax; i3++) { + const polyGeom = this.polys[i3].getGeom(); + if (polyGeom === null) + continue; + geom.push(polyGeom); } + return geom; } - } - function locArray(loc) { - if (Array.isArray(loc)) { - return loc; - } else if (loc.coordinates) { - return loc.coordinates; + _composePolys(rings) { + var _a2; + const polys = []; + for (let i3 = 0, iMax = rings.length; i3 < iMax; i3++) { + const ring = rings[i3]; + if (ring.poly) + continue; + if (ring.isExteriorRing()) + polys.push(new PolyOut(ring)); + else { + const enclosingRing = ring.enclosingRing(); + if (!(enclosingRing == null ? void 0 : enclosingRing.poly)) + polys.push(new PolyOut(enclosingRing)); + (_a2 = enclosingRing == null ? void 0 : enclosingRing.poly) == null ? void 0 : _a2.addInterior(ring); + } + } + return polys; } - return loc.geometry.coordinates; - } - function smallestFeature(loc) { - const query = locArray(loc); - const featureProperties = _whichPolygon(query); - if (!featureProperties) - return null; - return _featuresByCode[featureProperties.id]; - } - function countryFeature(loc) { - const feature22 = smallestFeature(loc); - if (!feature22) - return null; - const countryCode = feature22.properties.country || feature22.properties.iso1A2; - return _featuresByCode[countryCode] || null; - } - var defaultOpts = { - level: void 0, - maxLevel: void 0, - withProp: void 0 }; - function featureForLoc(loc, opts) { - const targetLevel = opts.level || "country"; - const maxLevel = opts.maxLevel || "world"; - const withProp = opts.withProp; - const targetLevelIndex = levels.indexOf(targetLevel); - if (targetLevelIndex === -1) - return null; - const maxLevelIndex = levels.indexOf(maxLevel); - if (maxLevelIndex === -1) - return null; - if (maxLevelIndex < targetLevelIndex) - return null; - if (targetLevel === "country") { - const fastFeature = countryFeature(loc); - if (fastFeature) { - if (!withProp || fastFeature.properties[withProp]) { - return fastFeature; + + // node_modules/polyclip-ts/dist/sweep-line.js + var SweepLine = class { + constructor(queue, comparator = Segment.compare) { + __publicField(this, "queue"); + __publicField(this, "tree"); + __publicField(this, "segments"); + this.queue = queue; + this.tree = new SplayTreeSet(comparator); + this.segments = []; + } + process(event) { + const segment = event.segment; + const newEvents = []; + if (event.consumedBy) { + if (event.isLeft) + this.queue.delete(event.otherSE); + else + this.tree.delete(segment); + return newEvents; + } + if (event.isLeft) + this.tree.add(segment); + let prevSeg = segment; + let nextSeg = segment; + do { + prevSeg = this.tree.lastBefore(prevSeg); + } while (prevSeg != null && prevSeg.consumedBy != void 0); + do { + nextSeg = this.tree.firstAfter(nextSeg); + } while (nextSeg != null && nextSeg.consumedBy != void 0); + if (event.isLeft) { + let prevMySplitter = null; + if (prevSeg) { + const prevInter = prevSeg.getIntersection(segment); + if (prevInter !== null) { + if (!segment.isAnEndpoint(prevInter)) + prevMySplitter = prevInter; + if (!prevSeg.isAnEndpoint(prevInter)) { + const newEventsFromSplit = this._splitSafely(prevSeg, prevInter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + } + } + let nextMySplitter = null; + if (nextSeg) { + const nextInter = nextSeg.getIntersection(segment); + if (nextInter !== null) { + if (!segment.isAnEndpoint(nextInter)) + nextMySplitter = nextInter; + if (!nextSeg.isAnEndpoint(nextInter)) { + const newEventsFromSplit = this._splitSafely(nextSeg, nextInter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + } + } + if (prevMySplitter !== null || nextMySplitter !== null) { + let mySplitter = null; + if (prevMySplitter === null) + mySplitter = nextMySplitter; + else if (nextMySplitter === null) + mySplitter = prevMySplitter; + else { + const cmpSplitters = SweepEvent.comparePoints(prevMySplitter, nextMySplitter); + mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter; + } + this.queue.delete(segment.rightSE); + newEvents.push(segment.rightSE); + const newEventsFromSplit = segment.split(mySplitter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + if (newEvents.length > 0) { + this.tree.delete(segment); + newEvents.push(event); + } else { + this.segments.push(segment); + segment.prev = prevSeg; + } + } else { + if (prevSeg && nextSeg) { + const inter = prevSeg.getIntersection(nextSeg); + if (inter !== null) { + if (!prevSeg.isAnEndpoint(inter)) { + const newEventsFromSplit = this._splitSafely(prevSeg, inter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + if (!nextSeg.isAnEndpoint(inter)) { + const newEventsFromSplit = this._splitSafely(nextSeg, inter); + for (let i3 = 0, iMax = newEventsFromSplit.length; i3 < iMax; i3++) { + newEvents.push(newEventsFromSplit[i3]); + } + } + } } + this.tree.delete(segment); } + return newEvents; } - const features = featuresContaining(loc); - const match = features.find((feature22) => { - let levelIndex = levels.indexOf(feature22.properties.level); - if (feature22.properties.level === targetLevel || // if no feature exists at the target level, return the first feature at the next level up - levelIndex > targetLevelIndex && levelIndex <= maxLevelIndex) { - if (!withProp || feature22.properties[withProp]) { - return feature22; + /* Safely split a segment that is currently in the datastructures + * IE - a segment other than the one that is currently being processed. */ + _splitSafely(seg, pt2) { + this.tree.delete(seg); + const rightSE = seg.rightSE; + this.queue.delete(rightSE); + const newEvents = seg.split(pt2); + newEvents.push(rightSE); + if (seg.consumedBy === void 0) + this.tree.add(seg); + return newEvents; + } + }; + + // node_modules/polyclip-ts/dist/operation.js + var Operation = class { + constructor() { + __publicField(this, "type"); + __publicField(this, "numMultiPolys"); + } + run(type2, geom, moreGeoms) { + operation.type = type2; + const multipolys = [new MultiPolyIn(geom, true)]; + for (let i3 = 0, iMax = moreGeoms.length; i3 < iMax; i3++) { + multipolys.push(new MultiPolyIn(moreGeoms[i3], false)); + } + operation.numMultiPolys = multipolys.length; + if (operation.type === "difference") { + const subject = multipolys[0]; + let i3 = 1; + while (i3 < multipolys.length) { + if (getBboxOverlap(multipolys[i3].bbox, subject.bbox) !== null) + i3++; + else + multipolys.splice(i3, 1); } } - return false; - }); - return match || null; - } - function featureForID(id2) { - let stringID; - if (typeof id2 === "number") { - stringID = id2.toString(); - if (stringID.length === 1) { - stringID = "00" + stringID; - } else if (stringID.length === 2) { - stringID = "0" + stringID; + if (operation.type === "intersection") { + for (let i3 = 0, iMax = multipolys.length; i3 < iMax; i3++) { + const mpA = multipolys[i3]; + for (let j2 = i3 + 1, jMax = multipolys.length; j2 < jMax; j2++) { + if (getBboxOverlap(mpA.bbox, multipolys[j2].bbox) === null) + return []; + } + } } - } else { - stringID = canonicalID(id2); - } - return _featuresByCode[stringID] || null; - } - function smallestFeaturesForBbox(bbox2) { - return _whichPolygon.bbox(bbox2).map((props) => _featuresByCode[props.id]); - } - function smallestOrMatchingFeature(query) { - if (typeof query === "object") { - return smallestFeature(query); - } - return featureForID(query); - } - function feature(query, opts = defaultOpts) { - if (typeof query === "object") { - return featureForLoc(query, opts); - } - return featureForID(query); - } - function iso1A2Code(query, opts = defaultOpts) { - opts.withProp = "iso1A2"; - const match = feature(query, opts); - if (!match) - return null; - return match.properties.iso1A2 || null; - } - function propertiesForQuery(query, property) { - const features = featuresContaining(query, false); - return features.map((feature22) => feature22.properties[property]).filter(Boolean); - } - function iso1A2Codes(query) { - return propertiesForQuery(query, "iso1A2"); - } - function featuresContaining(query, strict) { - let matchingFeatures; - if (Array.isArray(query) && query.length === 4) { - matchingFeatures = smallestFeaturesForBbox(query); - } else { - const smallestOrMatching = smallestOrMatchingFeature(query); - matchingFeatures = smallestOrMatching ? [smallestOrMatching] : []; - } - if (!matchingFeatures.length) - return []; - let returnFeatures; - if (!strict || typeof query === "object") { - returnFeatures = matchingFeatures.slice(); - } else { - returnFeatures = []; - } - for (const feature22 of matchingFeatures) { - const properties = feature22.properties; - for (const groupID of properties.groups) { - const groupFeature = _featuresByCode[groupID]; - if (returnFeatures.indexOf(groupFeature) === -1) { - returnFeatures.push(groupFeature); + const queue = new SplayTreeSet(SweepEvent.compare); + for (let i3 = 0, iMax = multipolys.length; i3 < iMax; i3++) { + const sweepEvents = multipolys[i3].getSweepEvents(); + for (let j2 = 0, jMax = sweepEvents.length; j2 < jMax; j2++) { + queue.add(sweepEvents[j2]); } } - } - return returnFeatures; - } - function featuresIn(id2, strict) { - const feature22 = featureForID(id2); - if (!feature22) - return []; - let features = []; - if (!strict) { - features.push(feature22); - } - const properties = feature22.properties; - for (const memberID of properties.members || []) { - features.push(_featuresByCode[memberID]); - } - return features; - } - function aggregateFeature(id2) { - var _a; - const features = featuresIn(id2, false); - if (features.length === 0) - return null; - let aggregateCoordinates = []; - for (const feature22 of features) { - if (((_a = feature22.geometry) == null ? void 0 : _a.type) === "MultiPolygon" && feature22.geometry.coordinates) { - aggregateCoordinates = aggregateCoordinates.concat(feature22.geometry.coordinates); + const sweepLine = new SweepLine(queue); + let evt = null; + if (queue.size != 0) { + evt = queue.first(); + queue.delete(evt); } - } - return { - type: "Feature", - properties: features[0].properties, - geometry: { - type: "MultiPolygon", - coordinates: aggregateCoordinates + while (evt) { + const newEvents = sweepLine.process(evt); + for (let i3 = 0, iMax = newEvents.length; i3 < iMax; i3++) { + const evt2 = newEvents[i3]; + if (evt2.consumedBy === void 0) + queue.add(evt2); + } + if (queue.size != 0) { + evt = queue.first(); + queue.delete(evt); + } else { + evt = null; + } } - }; - } - function roadSpeedUnit(query) { - const feature22 = smallestOrMatchingFeature(query); - return feature22 && feature22.properties.roadSpeedUnit || null; - } - function roadHeightUnit(query) { - const feature22 = smallestOrMatchingFeature(query); - return feature22 && feature22.properties.roadHeightUnit || null; - } + precision.reset(); + const ringsOut = RingOut.factory(sweepLine.segments); + const result = new MultiPolyOut(ringsOut); + return result.getGeom(); + } + }; + var operation = new Operation(); + var operation_default = operation; + + // node_modules/polyclip-ts/dist/index.js + var union = (geom, ...moreGeoms) => operation_default.run("union", geom, moreGeoms); + var difference = (geom, ...moreGeoms) => operation_default.run("difference", geom, moreGeoms); + var setPrecision = precision.set; // node_modules/@rapideditor/location-conflation/index.mjs var import_geojson_area = __toESM(require_geojson_area(), 1); var import_circle_to_polygon = __toESM(require_circle_to_polygon(), 1); - var import_polygon_clipping = __toESM(require_polygon_clipping_umd(), 1); var import_geojson_precision = __toESM(require_geojson_precision(), 1); var import_json_stringify_pretty_compact = __toESM(require_json_stringify_pretty_compact(), 1); - var location_conflation_default = class { + var LocationConflation = class { // constructor // // `fc` Optional FeatureCollection of known features @@ -23983,7 +26571,7 @@ // } constructor(fc) { this._cache = {}; - this._strict = true; + this.strict = true; if (fc && fc.type === "FeatureCollection" && Array.isArray(fc.features)) { fc.features.forEach((feature3) => { feature3.properties = feature3.properties || {}; @@ -24045,7 +26633,7 @@ return { type: "countrycoder", location, id: id2 }; } } - if (this._strict) { + if (this.strict) { throw new Error('validateLocation: Invalid location: "'.concat(location, '".')); } else { return null; @@ -24106,7 +26694,7 @@ this._cache[id2] = feature3; return Object.assign(valid, { feature: feature3 }); } - if (this._strict) { + if (this.strict) { throw new Error("resolveLocation: Couldn't resolve location \"".concat(location, '".')); } else { return null; @@ -24135,7 +26723,7 @@ let include = (locationSet.include || []).map(validator).filter(Boolean); let exclude = (locationSet.exclude || []).map(validator).filter(Boolean); if (!include.length) { - if (this._strict) { + if (this.strict) { throw new Error("validateLocationSet: LocationSet includes nothing."); } else { locationSet.include = ["Q2"]; @@ -24192,21 +26780,6 @@ this._cache[id2] = resultGeoJSON; return Object.assign(valid, { feature: resultGeoJSON }); } - // strict - // - strict(val) { - if (val === void 0) { - return this._strict; - } else { - this._strict = val; - return this; - } - } - // cache - // convenience method to access the internal cache - cache() { - return this._cache; - } // stringify // convenience method to prettyStringify the given object stringify(obj, options2) { @@ -24216,7 +26789,7 @@ function _clip(features, which) { if (!Array.isArray(features) || !features.length) return null; - const fn = { UNION: import_polygon_clipping.default.union, DIFFERENCE: import_polygon_clipping.default.difference }[which]; + const fn = { UNION: union, DIFFERENCE: difference }[which]; const args = features.map((feature3) => feature3.geometry.coordinates); const coords = fn.apply(null, args); return { @@ -24248,7 +26821,7 @@ // modules/core/LocationManager.js var import_which_polygon2 = __toESM(require_which_polygon()); var import_geojson_area2 = __toESM(require_geojson_area()); - var _loco = new location_conflation_default(); + var _loco = new LocationConflation(); var LocationManager = class { /** * @constructor @@ -24537,7 +27110,7 @@ var nativeObjectToString = objectProto.toString; var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0; function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + var isOwn = hasOwnProperty.call(value, symToStringTag), tag2 = value[symToStringTag]; try { value[symToStringTag] = void 0; var unmasked = true; @@ -24546,7 +27119,7 @@ var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { - value[symToStringTag] = tag; + value[symToStringTag] = tag2; } else { delete value[symToStringTag]; } @@ -24590,8 +27163,8 @@ // node_modules/lodash-es/_arrayMap.js function arrayMap(array2, iteratee) { - var index = -1, length = array2 == null ? 0 : array2.length, result = Array(length); - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length, result = Array(length2); + while (++index < length2) { result[index] = iteratee(array2[index], index, array2); } return result; @@ -24680,8 +27253,8 @@ if (!isObject_default(value)) { return false; } - var tag = baseGetTag_default(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + var tag2 = baseGetTag_default(value); + return tag2 == funcTag || tag2 == genTag || tag2 == asyncTag || tag2 == proxyTag; } var isFunction_default = isFunction; @@ -24754,12 +27327,12 @@ var WeakMap_default = WeakMap; // node_modules/lodash-es/_isIndex.js - var MAX_SAFE_INTEGER = 9007199254740991; + var MAX_SAFE_INTEGER2 = 9007199254740991; var reIsUint = /^(?:0|[1-9]\d*)$/; - function isIndex(value, length) { + function isIndex(value, length2) { var type2 = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && (type2 == "number" || type2 != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); + length2 = length2 == null ? MAX_SAFE_INTEGER2 : length2; + return !!length2 && (type2 == "number" || type2 != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length2); } var isIndex_default = isIndex; @@ -24770,9 +27343,9 @@ var eq_default = eq; // node_modules/lodash-es/isLength.js - var MAX_SAFE_INTEGER2 = 9007199254740991; + var MAX_SAFE_INTEGER3 = 9007199254740991; function isLength(value) { - return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER3; } var isLength_default = isLength; @@ -24811,7 +27384,7 @@ var objectProto5 = Object.prototype; var hasOwnProperty3 = objectProto5.hasOwnProperty; var propertyIsEnumerable = objectProto5.propertyIsEnumerable; - var isArguments = baseIsArguments_default(function() { + var isArguments = baseIsArguments_default(/* @__PURE__ */ function() { return arguments; }()) ? baseIsArguments_default : function(value) { return isObjectLike_default(value) && hasOwnProperty3.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); @@ -24900,13 +27473,13 @@ var objectProto6 = Object.prototype; var hasOwnProperty4 = objectProto6.hasOwnProperty; function arrayLikeKeys(value, inherited) { - var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length; + var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length2 = result.length; for (var key in value) { if ((inherited || hasOwnProperty4.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. - isIndex_default(key, length)))) { + isIndex_default(key, length2)))) { result.push(key); } } @@ -25003,9 +27576,9 @@ // node_modules/lodash-es/_Hash.js function Hash(entries) { - var index = -1, length = entries == null ? 0 : entries.length; + var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); - while (++index < length) { + while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } @@ -25026,10 +27599,10 @@ // node_modules/lodash-es/_assocIndexOf.js function assocIndexOf(array2, key) { - var length = array2.length; - while (length--) { - if (eq_default(array2[length][0], key)) { - return length; + var length2 = array2.length; + while (length2--) { + if (eq_default(array2[length2][0], key)) { + return length2; } } return -1; @@ -25083,9 +27656,9 @@ // node_modules/lodash-es/_ListCache.js function ListCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; + var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); - while (++index < length) { + while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } @@ -25157,9 +27730,9 @@ // node_modules/lodash-es/_MapCache.js function MapCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; + var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); - while (++index < length) { + while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } @@ -25179,8 +27752,8 @@ // node_modules/lodash-es/_arrayPush.js function arrayPush(array2, values) { - var index = -1, length = values.length, offset = array2.length; - while (++index < length) { + var index = -1, length2 = values.length, offset = array2.length; + while (++index < length2) { array2[offset + index] = values[index]; } return array2; @@ -25255,8 +27828,8 @@ // node_modules/lodash-es/_arrayFilter.js function arrayFilter(array2, predicate) { - var index = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result = []; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length, resIndex = 0, result = []; + while (++index < length2) { var value = array2[index]; if (predicate(value, index, array2)) { result[resIndex++] = value; @@ -25367,9 +27940,9 @@ // node_modules/lodash-es/_SetCache.js function SetCache(values) { - var index = -1, length = values == null ? 0 : values.length; + var index = -1, length2 = values == null ? 0 : values.length; this.__data__ = new MapCache_default(); - while (++index < length) { + while (++index < length2) { this.add(values[index]); } } @@ -25379,8 +27952,8 @@ // node_modules/lodash-es/_arraySome.js function arraySome(array2, predicate) { - var index = -1, length = array2 == null ? 0 : array2.length; - while (++index < length) { + var index = -1, length2 = array2 == null ? 0 : array2.length; + while (++index < length2) { if (predicate(array2[index], index, array2)) { return true; } @@ -25454,9 +28027,9 @@ var mapToArray_default = mapToArray; // node_modules/lodash-es/_setToArray.js - function setToArray(set3) { - var index = -1, result = Array(set3.size); - set3.forEach(function(value) { + function setToArray(set4) { + var index = -1, result = Array(set4.size); + set4.forEach(function(value) { result[++index] = value; }); return result; @@ -25479,8 +28052,8 @@ var dataViewTag3 = "[object DataView]"; var symbolProto2 = Symbol_default ? Symbol_default.prototype : void 0; var symbolValueOf = symbolProto2 ? symbolProto2.valueOf : void 0; - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { + function equalByTag(object, other, tag2, bitmask, customizer, equalFunc, stack) { + switch (tag2) { case dataViewTag3: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; @@ -25786,11 +28359,11 @@ // node_modules/lodash-es/unescape.js var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g; var reHasEscapedHtml = RegExp(reEscapedHtml.source); - function unescape2(string) { + function unescape(string) { string = toString_default(string); return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar_default) : string; } - var unescape_default = unescape2; + var unescape_default = unescape; // modules/util/detect.js var _detected; @@ -25879,9 +28452,9 @@ // modules/util/aes.js var import_aes_js = __toESM(require_aes_js()); var DEFAULT_128 = [250, 157, 60, 79, 142, 134, 229, 129, 138, 126, 210, 129, 29, 71, 160, 208]; - function utilAesEncrypt(text2, key) { + function utilAesEncrypt(text, key) { key = key || DEFAULT_128; - const textBytes = import_aes_js.default.utils.utf8.toBytes(text2); + const textBytes = import_aes_js.default.utils.utf8.toBytes(text); const aesCtr = new import_aes_js.default.ModeOfOperation.ctr(key); const encryptedBytes = aesCtr.encrypt(textBytes); const encryptedHex = import_aes_js.default.utils.hex.fromBytes(encryptedBytes); @@ -25892,8 +28465,8 @@ const encryptedBytes = import_aes_js.default.utils.hex.toBytes(encryptedHex); const aesCtr = new import_aes_js.default.ModeOfOperation.ctr(key); const decryptedBytes = aesCtr.decrypt(encryptedBytes); - const text2 = import_aes_js.default.utils.utf8.fromBytes(decryptedBytes); - return text2; + const text = import_aes_js.default.utils.utf8.fromBytes(decryptedBytes); + return text; } // modules/util/clean_tags.js @@ -26094,16 +28667,16 @@ } _keybindings[id2] = binding; var matches = arr[i3].toLowerCase().match(/(?:(?:[^+⇧⌃⌥⌘])+|[⇧⌃⌥⌘]|\+\+|^\+$)/g); - for (var j3 = 0; j3 < matches.length; j3++) { - if (matches[j3] === "++") - matches[j3] = "+"; - if (matches[j3] in utilKeybinding.modifierCodes) { - var prop = utilKeybinding.modifierProperties[utilKeybinding.modifierCodes[matches[j3]]]; + for (var j2 = 0; j2 < matches.length; j2++) { + if (matches[j2] === "++") + matches[j2] = "+"; + if (matches[j2] in utilKeybinding.modifierCodes) { + var prop = utilKeybinding.modifierProperties[utilKeybinding.modifierCodes[matches[j2]]]; binding.event.modifiers[prop] = true; } else { - binding.event.key = utilKeybinding.keys[matches[j3]] || matches[j3]; - if (matches[j3] in utilKeybinding.keyCodes) { - binding.event.keyCode = utilKeybinding.keyCodes[matches[j3]]; + binding.event.key = utilKeybinding.keys[matches[j2]] || matches[j2]; + if (matches[j2] in utilKeybinding.keyCodes) { + binding.event.keyCode = utilKeybinding.keyCodes[matches[j2]]; } } } @@ -26235,7 +28808,7 @@ "open-bracket": "[", // Back slash, or \ "back-slash": "\\", - // Close backet, or ] + // Close bracket, or ] "close-bracket": "]", // Apostrophe, or Quote, or ' quote: "'", @@ -26392,7 +28965,7 @@ // Back slash, or \ "\\": 220, "back-slash": 220, - // Close backet, or ] + // Close bracket, or ] "]": 221, "close-bracket": 221, // Apostrophe, or Quote, or ' @@ -26527,9 +29100,9 @@ var tiles = []; for (var i3 = 0; i3 < rows.length; i3++) { var y2 = rows[i3]; - for (var j3 = 0; j3 < cols.length; j3++) { - var x2 = cols[j3]; - if (i3 >= _margin && i3 <= rows.length - _margin && j3 >= _margin && j3 <= cols.length - _margin) { + for (var j2 = 0; j2 < cols.length; j2++) { + var x2 = cols[j2]; + if (i3 >= _margin && i3 <= rows.length - _margin && j2 >= _margin && j2 <= cols.length - _margin) { tiles.unshift([x2, y2, z0]); } else { tiles.push([x2, y2, z0]); @@ -26640,6 +29213,176 @@ }); } + // modules/util/units.js + var OSM_PRECISION = 7; + function displayLength(m2, isImperial) { + var d2 = m2 * (isImperial ? 3.28084 : 1); + var unit2; + if (isImperial) { + if (d2 >= 5280) { + d2 /= 5280; + unit2 = "miles"; + } else { + unit2 = "feet"; + } + } else { + if (d2 >= 1e3) { + d2 /= 1e3; + unit2 = "kilometers"; + } else { + unit2 = "meters"; + } + } + return _t("units." + unit2, { + quantity: d2.toLocaleString(_mainLocalizer.localeCode(), { + maximumSignificantDigits: 4 + }) + }); + } + function displayArea(m2, isImperial) { + var locale2 = _mainLocalizer.localeCode(); + var d2 = m2 * (isImperial ? 10.7639111056 : 1); + var d1, d22, area; + var unit1 = ""; + var unit2 = ""; + if (isImperial) { + if (d2 >= 6969600) { + d1 = d2 / 27878400; + unit1 = "square_miles"; + } else { + d1 = d2; + unit1 = "square_feet"; + } + if (d2 > 4356 && d2 < 4356e4) { + d22 = d2 / 43560; + unit2 = "acres"; + } + } else { + if (d2 >= 25e4) { + d1 = d2 / 1e6; + unit1 = "square_kilometers"; + } else { + d1 = d2; + unit1 = "square_meters"; + } + if (d2 > 1e3 && d2 < 1e7) { + d22 = d2 / 1e4; + unit2 = "hectares"; + } + } + area = _t("units." + unit1, { + quantity: d1.toLocaleString(locale2, { + maximumSignificantDigits: 4 + }) + }); + if (d22) { + return _t("units.area_pair", { + area1: area, + area2: _t("units." + unit2, { + quantity: d22.toLocaleString(locale2, { + maximumSignificantDigits: 2 + }) + }) + }); + } else { + return area; + } + } + function wrap(x2, min3, max3) { + var d2 = max3 - min3; + return ((x2 - min3) % d2 + d2) % d2 + min3; + } + function clamp(x2, min3, max3) { + return Math.max(min3, Math.min(x2, max3)); + } + function roundToDecimal(target, decimalPlace) { + target = Number(target); + decimalPlace = Number(decimalPlace); + const factor = Math.pow(10, decimalPlace); + return Math.round(target * factor) / factor; + } + function displayCoordinate(deg, pos, neg) { + var displayCoordinate2; + var locale2 = _mainLocalizer.localeCode(); + var degreesFloor = Math.floor(Math.abs(deg)); + var min3 = (Math.abs(deg) - degreesFloor) * 60; + var minFloor = Math.floor(min3); + var sec = (min3 - minFloor) * 60; + var fix = roundToDecimal(sec, 8); + var secRounded = roundToDecimal(fix, 0); + if (secRounded === 60) { + secRounded = 0; + minFloor += 1; + if (minFloor === 60) { + minFloor = 0; + degreesFloor += 1; + } + } + displayCoordinate2 = _t("units.arcdegrees", { + quantity: degreesFloor.toLocaleString(locale2) + }) + (minFloor !== 0 || secRounded !== 0 ? _t("units.arcminutes", { + quantity: minFloor.toLocaleString(locale2) + }) : "") + (secRounded !== 0 ? _t("units.arcseconds", { + quantity: secRounded.toLocaleString(locale2) + }) : ""); + if (deg === 0) { + return displayCoordinate2; + } else { + return _t("units.coordinate", { + coordinate: displayCoordinate2, + direction: _t("units." + (deg > 0 ? pos : neg)) + }); + } + } + function dmsCoordinatePair(coord2) { + return _t("units.coordinate_pair", { + latitude: displayCoordinate(clamp(coord2[1], -90, 90), "north", "south"), + longitude: displayCoordinate(wrap(coord2[0], -180, 180), "east", "west") + }); + } + function decimalCoordinatePair(coord2) { + return _t("units.coordinate_pair", { + latitude: clamp(coord2[1], -90, 90).toFixed(OSM_PRECISION), + longitude: wrap(coord2[0], -180, 180).toFixed(OSM_PRECISION) + }); + } + function dmsMatcher(q2) { + const matchers = [ + // D M SS , D M SS ex: 35 11 10.1 , 136 49 53.8 + { + condition: /^\s*(-?)\s*(\d+)\s+(\d+)\s+(\d+\.?\d*)\s*\,\s*(-?)\s*(\d+)\s+(\d+)\s+(\d+\.?\d*)\s*$/, + parser: function(q3) { + const match = this.condition.exec(q3); + const lat = +match[2] + +match[3] / 60 + +match[4] / 3600; + const lng = +match[6] + +match[7] / 60 + +match[8] / 3600; + const isNegLat = match[1] === "-" ? -lat : lat; + const isNegLng = match[5] === "-" ? -lng : lng; + const d2 = [isNegLat, isNegLng]; + return d2; + } + }, + // D MM , D MM ex: 35 11.1683 , 136 49.8966 + { + condition: /^\s*(-?)\s*(\d+)\s+(\d+\.?\d*)\s*\,\s*(-?)\s*(\d+)\s+(\d+\.?\d*)\s*$/, + parser: function(q3) { + const match = this.condition.exec(q3); + const lat = +match[2] + +match[3] / 60; + const lng = +match[5] + +match[6] / 60; + const isNegLat = match[1] === "-" ? -lat : lat; + const isNegLng = match[4] === "-" ? -lng : lng; + const d2 = [isNegLat, isNegLng]; + return d2; + } + } + ]; + for (const matcher of matchers) { + if (matcher.condition.test(q2)) { + return matcher.parser(q2); + } + } + return null; + } + // modules/core/localizer.js var _mainLocalizer = coreLocalizer(); var _t = _mainLocalizer.t; @@ -27430,9 +30173,9 @@ return []; } } - function shouldInherit(f3) { - if (f3.key && _this.tags[f3.key] !== void 0 && // inherit anyway if multiple values are allowed or just a checkbox - f3.type !== "multiCombo" && f3.type !== "semiCombo" && f3.type !== "manyCombo" && f3.type !== "check") + function shouldInherit(f2) { + if (f2.key && _this.tags[f2.key] !== void 0 && // inherit anyway if multiple values are allowed or just a checkbox + f2.type !== "multiCombo" && f2.type !== "semiCombo" && f2.type !== "manyCombo" && f2.type !== "check") return false; return true; } @@ -27497,12 +30240,12 @@ let newLocationSets = []; if (d2.fields) { Object.keys(d2.fields).forEach((fieldID) => { - let f3 = d2.fields[fieldID]; - if (f3) { - f3 = presetField(fieldID, f3, _fields); - if (f3.locationSet) - newLocationSets.push(f3); - _fields[fieldID] = f3; + let f2 = d2.fields[fieldID]; + if (f2) { + f2 = presetField(fieldID, f2, _fields); + if (f2.locationSet) + newLocationSets.push(f2); + _fields[fieldID] = f2; } else { delete _fields[fieldID]; } @@ -27541,10 +30284,10 @@ _this.collection = Object.values(_presets).concat(Object.values(_categories)); if (d2.defaults) { Object.keys(d2.defaults).forEach((geometry) => { - const def = d2.defaults[geometry]; - if (Array.isArray(def)) { + const def2 = d2.defaults[geometry]; + if (Array.isArray(def2)) { _defaults2[geometry] = presetCollection( - def.map((id2) => _presets[id2] || _categories[id2]).filter(Boolean) + def2.map((id2) => _presets[id2] || _categories[id2]).filter(Boolean) ); } else { delete _defaults2[geometry]; @@ -27659,7 +30402,6 @@ footway: true, railway: true, junction: true, - traffic_calming: true, type: true }; let areaKeys = {}; @@ -28211,12 +30953,12 @@ } return tags; } - function utilStringQs(str2) { + function utilStringQs(str) { var i3 = 0; - while (i3 < str2.length && (str2[i3] === "?" || str2[i3] === "#")) + while (i3 < str.length && (str[i3] === "?" || str[i3] === "#")) i3++; - str2 = str2.slice(i3); - return str2.split("&").reduce(function(obj, pair3) { + str = str.slice(i3); + return str.split("&").reduce(function(obj, pair3) { var parts = pair3.split("="); if (parts.length === 2) { obj[parts[0]] = null === parts[1] ? "" : decodeURIComponent(parts[1]); @@ -28276,25 +31018,25 @@ if (b2.length === 0) return a2.length; var matrix = []; - var i3, j3; + var i3, j2; for (i3 = 0; i3 <= b2.length; i3++) { matrix[i3] = [i3]; } - for (j3 = 0; j3 <= a2.length; j3++) { - matrix[0][j3] = j3; + for (j2 = 0; j2 <= a2.length; j2++) { + matrix[0][j2] = j2; } for (i3 = 1; i3 <= b2.length; i3++) { - for (j3 = 1; j3 <= a2.length; j3++) { - if (b2.charAt(i3 - 1) === a2.charAt(j3 - 1)) { - matrix[i3][j3] = matrix[i3 - 1][j3 - 1]; + for (j2 = 1; j2 <= a2.length; j2++) { + if (b2.charAt(i3 - 1) === a2.charAt(j2 - 1)) { + matrix[i3][j2] = matrix[i3 - 1][j2 - 1]; } else { - matrix[i3][j3] = Math.min( - matrix[i3 - 1][j3 - 1] + 1, + matrix[i3][j2] = Math.min( + matrix[i3 - 1][j2 - 1] + 1, // substitution Math.min( - matrix[i3][j3 - 1] + 1, + matrix[i3][j2 - 1] + 1, // insertion - matrix[i3 - 1][j3] + 1 + matrix[i3 - 1][j2] + 1 ) ); } @@ -28329,11 +31071,11 @@ }); }); } - function utilWrap(index, length) { + function utilWrap(index, length2) { if (index < 0) { - index += Math.ceil(-index / length) * length; + index += Math.ceil(-index / length2) * length2; } - return index % length; + return index % length2; } function utilFunctor(value) { if (typeof value === "function") @@ -28346,29 +31088,29 @@ var isText = selection2.size() && selection2.node().tagName.toLowerCase() === "textarea"; return selection2.attr("autocomplete", "new-password").attr("autocorrect", "off").attr("autocapitalize", "off").attr("spellcheck", isText ? "true" : "false"); } - function utilHashcode(str2) { + function utilHashcode(str) { var hash = 0; - if (str2.length === 0) { + if (str.length === 0) { return hash; } - for (var i3 = 0; i3 < str2.length; i3++) { - var char = str2.charCodeAt(i3); + for (var i3 = 0; i3 < str.length; i3++) { + var char = str.charCodeAt(i3); hash = (hash << 5) - hash + char; hash = hash & hash; } return hash; } - function utilSafeClassName(str2) { - return str2.toLowerCase().replace(/[^a-z0-9]+/g, "_"); + function utilSafeClassName(str) { + return str.toLowerCase().replace(/[^a-z0-9]+/g, "_"); } function utilUniqueDomId(val) { return "ideditor-" + utilSafeClassName(val.toString()) + "-" + (/* @__PURE__ */ new Date()).getTime().toString(); } - function utilUnicodeCharsCount(str2) { - return Array.from(str2).length; + function utilUnicodeCharsCount(str) { + return Array.from(str).length; } - function utilUnicodeCharsTruncated(str2, limit) { - return Array.from(str2).slice(0, limit).join(""); + function utilUnicodeCharsTruncated(str, limit) { + return Array.from(str).slice(0, limit).join(""); } function toNumericID(id2) { var match = id2.match(/^[cnwr](-?\d+)$/); @@ -28761,8 +31503,8 @@ bothways }; } - function parseTurnLanes(tag) { - if (!tag) + function parseTurnLanes(tag2) { + if (!tag2) return; var validValues = [ "left", @@ -28777,7 +31519,7 @@ "merge_to_right", "none" ]; - return tag.split("|").map(function(s2) { + return tag2.split("|").map(function(s2) { if (s2 === "") s2 = "none"; return s2.split(";").map(function(d2) { @@ -28785,10 +31527,10 @@ }); }); } - function parseMaxspeedLanes(tag, maxspeed) { - if (!tag) + function parseMaxspeedLanes(tag2, maxspeed) { + if (!tag2) return; - return tag.split("|").map(function(s2) { + return tag2.split("|").map(function(s2) { if (s2 === "none") return s2; var m2 = parseInt(s2, 10); @@ -28797,22 +31539,22 @@ return isNaN(m2) ? "unknown" : m2; }); } - function parseMiscLanes(tag) { - if (!tag) + function parseMiscLanes(tag2) { + if (!tag2) return; var validValues = [ "yes", "no", "designated" ]; - return tag.split("|").map(function(s2) { + return tag2.split("|").map(function(s2) { if (s2 === "") s2 = "no"; return validValues.indexOf(s2) === -1 ? "unknown" : s2; }); } - function parseBicycleWay(tag) { - if (!tag) + function parseBicycleWay(tag2) { + if (!tag2) return; var validValues = [ "yes", @@ -28820,7 +31562,7 @@ "designated", "lane" ]; - return tag.split("|").map(function(s2) { + return tag2.split("|").map(function(s2) { if (s2 === "") s2 = "no"; return validValues.indexOf(s2) === -1 ? "unknown" : s2; @@ -28952,6 +31694,7 @@ road: 4, living_street: 4, bus_guideway: 4, + busway: 4, pedestrian: 4, residential: 3.5, service: 3.5, @@ -29483,7 +32226,7 @@ return graph; }; function addWayMember(relation, graph) { - var groups, tempWay, insertPairIsReversed, item, i3, j3, k2; + var groups, tempWay, insertPairIsReversed, item, i3, j2, k2; var PTv2members = []; var members = []; for (i3 = 0; i3 < relation.members.length; i3++) { @@ -29516,8 +32259,8 @@ var segment = joined[i3]; var nodes = segment.nodes.slice(); var startIndex = segment[0].index; - for (j3 = 0; j3 < members.length; j3++) { - if (members[j3].index === startIndex) { + for (j2 = 0; j2 < members.length; j2++) { + if (members[j2].index === startIndex) { break; } } @@ -29539,8 +32282,8 @@ } } if (k2 > 0) { - if (j3 + k2 >= members.length || item.index !== members[j3 + k2].index) { - moveMember(members, item.index, j3 + k2); + if (j2 + k2 >= members.length || item.index !== members[j2 + k2].index) { + moveMember(members, item.index, j2 + k2); } } nodes.splice(0, way.nodes.length - 1); @@ -29634,7 +32377,7 @@ preserveKeys = preserveKeys.concat(Object.keys(newPreset.addTags)); } if (oldPreset && !oldPreset.id.startsWith(newPreset.id)) { - newPreset.fields(loc).concat(newPreset.moreFields(loc)).filter((f3) => f3.matchGeometry(geometry)).map((f3) => f3.key).filter(Boolean).forEach((key) => preserveKeys.push(key)); + newPreset.fields(loc).concat(newPreset.moreFields(loc)).filter((f2) => f2.matchGeometry(geometry)).map((f2) => f2.key).filter(Boolean).forEach((key) => preserveKeys.push(key)); } } if (oldPreset) @@ -29878,7 +32621,7 @@ return geoVecLength(centroid, p2); }); var sign2 = area_default3(points) > 0 ? 1 : -1; - var ids, i3, j3, k2; + var ids, i3, j2, k2; if (!keyNodes.length) { keyNodes = [nodes[0]]; keyPoints = [points[0]]; @@ -29924,20 +32667,20 @@ numberNewPoints++; eachAngle = totalAngle / (indexRange + numberNewPoints); } while (Math.abs(eachAngle) > maxAngle); - for (j3 = 1; j3 < indexRange; j3++) { - angle2 = startAngle + j3 * eachAngle; + for (j2 = 1; j2 < indexRange; j2++) { + angle2 = startAngle + j2 * eachAngle; loc = projection2.invert([ centroid[0] + Math.cos(angle2) * radius, centroid[1] + Math.sin(angle2) * radius ]); - node = nodes[(j3 + startNodeIndex) % nodes.length]; + node = nodes[(j2 + startNodeIndex) % nodes.length]; origNode = origNodes[node.id]; nearNodes[node.id] = angle2; node = node.move(geoVecInterp(origNode.loc, loc, t2)); graph = graph.replace(node); } - for (j3 = 0; j3 < numberNewPoints; j3++) { - angle2 = startAngle + (indexRange + j3) * eachAngle; + for (j2 = 0; j2 < numberNewPoints; j2++) { + angle2 = startAngle + (indexRange + j2) * eachAngle; loc = projection2.invert([ centroid[0] + Math.cos(angle2) * radius, centroid[1] + Math.sin(angle2) * radius @@ -29953,7 +32696,7 @@ } node = osmNode({ loc: geoVecInterp(origNode.loc, loc, t2) }); graph = graph.replace(node); - nodes.splice(endNodeIndex + j3, 0, node); + nodes.splice(endNodeIndex + j2, 0, node); inBetweenNodes.push(node.id); } if (indexRange === 1 && inBetweenNodes.length) { @@ -29964,8 +32707,8 @@ wayDirection1 = 1; } var parentWays = graph.parentWays(keyNodes[i3]); - for (j3 = 0; j3 < parentWays.length; j3++) { - var sharedWay = parentWays[j3]; + for (j2 = 0; j2 < parentWays.length; j2++) { + var sharedWay = parentWays[j2]; if (sharedWay === way) continue; if (sharedWay.areAdjacent(startNode.id, endNode.id)) { @@ -30004,7 +32747,7 @@ }); var sign2 = area_default3(points) > 0 ? 1 : -1; var hull = hull_default(points); - var i3, j3; + var i3, j2; if (sign2 === -1) { nodes.reverse(); points.reverse(); @@ -30016,9 +32759,9 @@ if (indexRange < 0) { indexRange += nodes.length; } - for (j3 = 1; j3 < indexRange; j3++) { - var point2 = geoVecInterp(hull[i3], hull[i3 + 1], j3 / indexRange); - var node = nodes[(j3 + startIndex) % nodes.length].move(projection2.invert(point2)); + for (j2 = 1; j2 < indexRange; j2++) { + var point2 = geoVecInterp(hull[i3], hull[i3 + 1], j2 / indexRange); + var node = nodes[(j2 + startIndex) % nodes.length].move(projection2.invert(point2)); graph = graph.replace(node); } } @@ -30180,7 +32923,7 @@ var survivor; var node; var parents; - var i3, j3; + var i3, j2; nodeIDs.reverse(); var interestingIDs = []; for (i3 = 0; i3 < nodeIDs.length; i3++) { @@ -30197,12 +32940,12 @@ if (node.id === survivor.id) continue; parents = graph.parentWays(node); - for (j3 = 0; j3 < parents.length; j3++) { - graph = graph.replace(parents[j3].replaceNode(node.id, survivor.id)); + for (j2 = 0; j2 < parents.length; j2++) { + graph = graph.replace(parents[j2].replaceNode(node.id, survivor.id)); } parents = graph.parentRelations(node); - for (j3 = 0; j3 < parents.length; j3++) { - graph = graph.replace(parents[j3].replaceMember(node, survivor)); + for (j2 = 0; j2 < parents.length; j2++) { + graph = graph.replace(parents[j2].replaceMember(node, survivor)); } survivor = survivor.mergeTags(node.tags); graph = actionDeleteNode(node.id)(graph); @@ -30222,13 +32965,13 @@ var survivor; var node, way; var relations, relation, role; - var i3, j3, k2; + var i3, j2, k2; survivor = graph.entity(utilOldestID(nodeIDs)); for (i3 = 0; i3 < nodeIDs.length; i3++) { node = graph.entity(nodeIDs[i3]); relations = graph.parentRelations(node); - for (j3 = 0; j3 < relations.length; j3++) { - relation = relations[j3]; + for (j2 = 0; j2 < relations.length; j2++) { + relation = relations[j2]; role = relation.memberById(node.id).role || ""; if (relation.hasFromViaTo()) { restrictionIDs.push(relation.id); @@ -30243,8 +32986,8 @@ for (i3 = 0; i3 < nodeIDs.length; i3++) { node = graph.entity(nodeIDs[i3]); var parents = graph.parentWays(node); - for (j3 = 0; j3 < parents.length; j3++) { - var parent = parents[j3]; + for (j2 = 0; j2 < parents.length; j2++) { + var parent = parents[j2]; relations = graph.parentRelations(parent); for (k2 = 0; k2 < relations.length; k2++) { relation = relations[k2]; @@ -30265,12 +33008,12 @@ return graph.entity(m2.id); }); memberWays = utilArrayUniq(memberWays); - var f3 = relation.memberByRole("from"); + var f2 = relation.memberByRole("from"); var t2 = relation.memberByRole("to"); - var isUturn = f3.id === t2.id; + var isUturn = f2.id === t2.id; var nodes = { from: [], via: [], to: [], keyfrom: [], keyto: [] }; - for (j3 = 0; j3 < relation.members.length; j3++) { - collectNodes(relation.members[j3], nodes); + for (j2 = 0; j2 < relation.members.length; j2++) { + collectNodes(relation.members[j2], nodes); } nodes.keyfrom = utilArrayUniq(nodes.keyfrom.filter(hasDuplicates)); nodes.keyto = utilArrayUniq(nodes.keyto.filter(hasDuplicates)); @@ -30283,8 +33026,8 @@ var connectTo = false; var connectKeyFrom = false; var connectKeyTo = false; - for (j3 = 0; j3 < nodeIDs.length; j3++) { - var n3 = nodeIDs[j3]; + for (j2 = 0; j2 < nodeIDs.length; j2++) { + var n3 = nodeIDs[j2]; if (nodes.from.indexOf(n3) !== -1) { connectFrom = true; } @@ -30316,8 +33059,8 @@ } var n0 = null; var n1 = null; - for (j3 = 0; j3 < memberWays.length; j3++) { - way = memberWays[j3]; + for (j2 = 0; j2 < memberWays.length; j2++) { + way = memberWays[j2]; if (way.contains(nodeIDs[0])) { n0 = nodeIDs[0]; } @@ -30327,8 +33070,8 @@ } if (n0 && n1) { var ok = false; - for (j3 = 0; j3 < memberWays.length; j3++) { - way = memberWays[j3]; + for (j2 = 0; j2 < memberWays.length; j2++) { + way = memberWays[j2]; if (way.areAdjacent(n0, n1)) { ok = true; break; @@ -30339,8 +33082,8 @@ } } } - for (j3 = 0; j3 < memberWays.length; j3++) { - way = memberWays[j3].update({}); + for (j2 = 0; j2 < memberWays.length; j2++) { + way = memberWays[j2].update({}); for (k2 = 0; k2 < nodeIDs.length; k2++) { if (nodeIDs[k2] === survivor.id) continue; @@ -30425,11 +33168,11 @@ } // modules/actions/discard_tags.js - function actionDiscardTags(difference, discardTags) { + function actionDiscardTags(difference2, discardTags) { discardTags = discardTags || {}; return (graph) => { - difference.modified().forEach(checkTags); - difference.created().forEach(checkTags); + difference2.modified().forEach(checkTags); + difference2.created().forEach(checkTags); return graph; function checkTags(entity) { const keys2 = Object.keys(entity.tags); @@ -30489,13 +33232,13 @@ if (way.isArea() && way.nodes[0] === nodeId) { candidates.push({ wayID: way.id, index: 0 }); } else { - for (var j3 = 0; j3 < way.nodes.length; j3++) { - waynode = way.nodes[j3]; + for (var j2 = 0; j2 < way.nodes.length; j2++) { + waynode = way.nodes[j2]; if (waynode === nodeId) { - if (way.isClosed() && parentWays.length > 1 && wayIds && wayIds.indexOf(way.id) !== -1 && j3 === way.nodes.length - 1) { + if (way.isClosed() && parentWays.length > 1 && wayIds && wayIds.indexOf(way.id) !== -1 && j2 === way.nodes.length - 1) { continue; } - candidates.push({ wayID: way.id, index: j3 }); + candidates.push({ wayID: way.id, index: j2 }); } } } @@ -30562,7 +33305,7 @@ var fromGeometry = entity.geometry(graph); var keysToCopyAndRetain = ["source", "wheelchair"]; var keysToRetain = ["area"]; - var buildingKeysToRetain = ["architect", "building", "height", "layer"]; + var buildingKeysToRetain = ["architect", "building", "height", "layer", "nycdoitt:bin"]; var extractedLoc = path_default(projection2).centroid(entity.asGeoJSON(graph)); extractedLoc = extractedLoc && projection2.invert(extractedLoc); if (!extractedLoc || !isFinite(extractedLoc[0]) || !isFinite(extractedLoc[1])) { @@ -30714,11 +33457,11 @@ } } for (i3 = 0; i3 < ids.length - 1; i3++) { - for (var j3 = i3 + 1; j3 < ids.length; j3++) { + for (var j2 = i3 + 1; j2 < ids.length; j2++) { var path1 = graph.childNodes(graph.entity(ids[i3])).map(function(e3) { return e3.loc; }); - var path2 = graph.childNodes(graph.entity(ids[j3])).map(function(e3) { + var path2 = graph.childNodes(graph.entity(ids[j2])).map(function(e3) { return e3.loc; }); var intersections = geoPathIntersections(path1, path2); @@ -30983,16 +33726,16 @@ changes2.relation = Object.values(sorted); return changes2; } - function rep2(entity) { + function rep(entity) { return entity.asJXON(changeset_id); } return { osmChange: { "@version": 0.6, "@generator": "iD", - "create": sort(nest(changes.created.map(rep2), ["node", "way", "relation"])), - "modify": nest(changes.modified.map(rep2), ["node", "way", "relation"]), - "delete": Object.assign(nest(changes.deleted.map(rep2), ["relation", "way", "node"]), { "@if-unused": true }) + "create": sort(nest(changes.created.map(rep), ["node", "way", "relation"])), + "modify": nest(changes.modified.map(rep), ["node", "way", "relation"]), + "delete": Object.assign(nest(changes.deleted.map(rep), ["relation", "way", "node"]), { "@if-unused": true }) } }; }, @@ -31403,23 +34146,23 @@ } function splitArea(nodes, idxA, graph) { var lengths = new Array(nodes.length); - var length; + var length2; var i3; var best = 0; var idxB; function wrap2(index) { return utilWrap(index, nodes.length); } - length = 0; + length2 = 0; for (i3 = wrap2(idxA + 1); i3 !== idxA; i3 = wrap2(i3 + 1)) { - length += dist(graph, nodes[i3], nodes[wrap2(i3 - 1)]); - lengths[i3] = length; + length2 += dist(graph, nodes[i3], nodes[wrap2(i3 - 1)]); + lengths[i3] = length2; } - length = 0; + length2 = 0; for (i3 = wrap2(idxA - 1); i3 !== idxA; i3 = wrap2(i3 - 1)) { - length += dist(graph, nodes[i3], nodes[wrap2(i3 + 1)]); - if (length < lengths[i3]) { - lengths[i3] = length; + length2 += dist(graph, nodes[i3], nodes[wrap2(i3 + 1)]); + if (length2 < lengths[i3]) { + lengths[i3] = length2; } } for (i3 = 0; i3 < nodes.length; i3++) { @@ -31494,11 +34237,11 @@ graph.parentRelations(wayA).forEach(function(relation) { var member; if (relation.hasFromViaTo()) { - var f3 = relation.memberByRole("from"); + var f2 = relation.memberByRole("from"); var v2 = relation.membersByRole("via"); var t2 = relation.memberByRole("to"); var i3; - if (f3.id === wayA.id || t2.id === wayA.id) { + if (f2.id === wayA.id || t2.id === wayA.id) { var keepB = false; if (v2.length === 1 && v2[0].type === "node") { keepB = wayB.contains(v2[0].id); @@ -31570,8 +34313,8 @@ for (var i3 = 0; i3 < nodeIds.length; i3++) { var nodeId = nodeIds[i3]; var candidates = action.waysForNode(nodeId, graph); - for (var j3 = 0; j3 < candidates.length; j3++) { - graph = split(graph, nodeId, candidates[j3], newWayIds && newWayIds[newWayIndex]); + for (var j2 = 0; j2 < candidates.length; j2++) { + graph = split(graph, nodeId, candidates[j2], newWayIds && newWayIds[newWayIndex]); newWayIndex += 1; } } @@ -31740,7 +34483,7 @@ // graph always contained the newly downloaded data. rebase: function(entities, stack, force) { var base = this.base(); - var i3, j3, k2, id2; + var i3, j2, k2, id2; for (i3 = 0; i3 < entities.length; i3++) { var entity = entities[i3]; if (!entity.visible || !force && base.entities[entity.id]) @@ -31748,8 +34491,8 @@ base.entities[entity.id] = entity; this._updateCalculated(void 0, entity, base.parentWays, base.parentRels); if (entity.type === "way") { - for (j3 = 0; j3 < entity.nodes.length; j3++) { - id2 = entity.nodes[j3]; + for (j2 = 0; j2 < entity.nodes.length; j2++) { + id2 = entity.nodes[j2]; for (k2 = 1; k2 < stack.length; k2++) { var ents = stack[k2].entities; if (ents.hasOwnProperty(id2) && ents[id2] === void 0) { @@ -31892,7 +34635,7 @@ function osmIntersection(graph, startVertexId, maxDistance) { maxDistance = maxDistance || 30; var vgraph = coreGraph(); - var i3, j3, k2; + var i3, j2, k2; function memberOfRestriction(entity) { return graph.parentRelations(entity).some(function(r2) { return r2.isRestriction(); @@ -31916,6 +34659,7 @@ "unclassified": true, "living_street": true, "service": true, + "busway": true, "road": true, "track": true }; @@ -31946,8 +34690,8 @@ ways.push(way); hasWays = true; nodes = utilArrayUniq(graph.childNodes(way)); - for (j3 = 0; j3 < nodes.length; j3++) { - node = nodes[j3]; + for (j2 = 0; j2 < nodes.length; j2++) { + node = nodes[j2]; if (node === vertex) continue; if (vertices.indexOf(node) !== -1) @@ -32119,19 +34863,19 @@ }).map(function(way2) { return vgraph.entity(way2.id); }); - var intersection = { + var intersection2 = { graph: vgraph, actions, vertices, ways }; - intersection.turns = function(fromWayId, maxViaWay) { + intersection2.turns = function(fromWayId, maxViaWay) { if (!fromWayId) return []; if (!maxViaWay) maxViaWay = 0; - var vgraph2 = intersection.graph; - var keyVertexIds = intersection.vertices.map(function(v2) { + var vgraph2 = intersection2.graph; + var keyVertexIds = intersection2.vertices.map(function(v2) { return v2.id; }); var start2 = vgraph2.entity(fromWayId); @@ -32154,7 +34898,7 @@ } } function stepNode(entity, currPath, currRestrictions) { - var i4, j4; + var i4, j3; var parents2 = vgraph2.parentWays(entity); var nextWays = []; for (i4 = 0; i4 < parents2.length; i4++) { @@ -32164,9 +34908,9 @@ if (currPath.indexOf(way2.id) !== -1 && currPath.length >= 3) continue; var restrict = null; - for (j4 = 0; j4 < currRestrictions.length; j4++) { - var restriction = currRestrictions[j4]; - var f3 = restriction.memberByRole("from"); + for (j3 = 0; j3 < currRestrictions.length; j3++) { + var restriction = currRestrictions[j3]; + var f2 = restriction.memberByRole("from"); var v2 = restriction.membersByRole("via"); var t2 = restriction.memberByRole("to"); var isNo = /^no_/.test(restriction.tags.restriction); @@ -32174,7 +34918,7 @@ if (!(isNo || isOnly)) { continue; } - var matchesFrom = f3.id === fromWayId; + var matchesFrom = f2.id === fromWayId; var matchesViaTo = false; var isAlongOnlyPath = false; if (t2.id === way2.id) { @@ -32204,15 +34948,15 @@ } if (matchesViaTo) { if (isOnly) { - restrict = { id: restriction.id, direct: matchesFrom, from: f3.id, only: true, end: true }; + restrict = { id: restriction.id, direct: matchesFrom, from: f2.id, only: true, end: true }; } else { - restrict = { id: restriction.id, direct: matchesFrom, from: f3.id, no: true, end: true }; + restrict = { id: restriction.id, direct: matchesFrom, from: f2.id, no: true, end: true }; } } else { if (isAlongOnlyPath) { - restrict = { id: restriction.id, direct: false, from: f3.id, only: true, end: false }; + restrict = { id: restriction.id, direct: false, from: f2.id, only: true, end: false }; } else if (isOnly) { - restrict = { id: restriction.id, direct: false, from: f3.id, no: true, end: true }; + restrict = { id: restriction.id, direct: false, from: f2.id, no: true, end: true }; } } if (restrict && restrict.direct) @@ -32274,8 +35018,8 @@ var fromRestrictions = vgraph2.parentRelations(entity).filter(function(r2) { if (!r2.isRestriction()) return false; - var f3 = r2.memberByRole("from"); - if (!f3 || f3.id !== entity.id) + var f2 = r2.memberByRole("from"); + if (!f2 || f2.id !== entity.id) return false; var isOnly = /^only_/.test(r2.tags.restriction); if (!isOnly) @@ -32344,7 +35088,7 @@ } } }; - return intersection; + return intersection2; } function osmInferRestriction(graph, turn, projection2) { var fromWay = graph.entity(turn.from.way); @@ -32516,12 +35260,12 @@ // node_modules/node-diff3/index.mjs function LCS(buffer1, buffer2) { let equivalenceClasses = {}; - for (let j3 = 0; j3 < buffer2.length; j3++) { - const item = buffer2[j3]; + for (let j2 = 0; j2 < buffer2.length; j2++) { + const item = buffer2[j2]; if (equivalenceClasses[item]) { - equivalenceClasses[item].push(j3); + equivalenceClasses[item].push(j2); } else { - equivalenceClasses[item] = [j3]; + equivalenceClasses[item] = [j2]; } } const NULLRESULT = { buffer1index: -1, buffer2index: -1, chain: null }; @@ -32532,15 +35276,15 @@ let r2 = 0; let c2 = candidates[0]; for (let jx = 0; jx < buffer2indices.length; jx++) { - const j3 = buffer2indices[jx]; + const j2 = buffer2indices[jx]; let s2; for (s2 = r2; s2 < candidates.length; s2++) { - if (candidates[s2].buffer2index < j3 && (s2 === candidates.length - 1 || candidates[s2 + 1].buffer2index > j3)) { + if (candidates[s2].buffer2index < j2 && (s2 === candidates.length - 1 || candidates[s2 + 1].buffer2index > j2)) { break; } } if (s2 < candidates.length) { - const newCandidate = { buffer1index: i3, buffer2index: j3, chain: candidates[s2] }; + const newCandidate = { buffer1index: i3, buffer2index: j2, chain: candidates[s2] }; if (r2 === candidates.length) { candidates.push(c2); } else { @@ -32972,8 +35716,8 @@ for (var i3 = 0; i3 < ids.length; i3++) { var id2 = ids[i3]; var childNodes = graph.childNodes(graph.entity(id2)); - for (var j3 = 0; j3 < childNodes.length; j3++) { - var node = childNodes[j3]; + for (var j2 = 0; j2 < childNodes.length; j2++) { + var node = childNodes[j2]; var parents = graph.parentWays(node); if (parents.length !== 2) continue; @@ -33086,12 +35830,12 @@ } return graph; } - function unZorroIntersection(intersection, graph) { - var vertex = graph.entity(intersection.nodeId); - var way1 = graph.entity(intersection.movedId); - var way2 = graph.entity(intersection.unmovedId); - var isEP1 = intersection.movedIsEP; - var isEP2 = intersection.unmovedIsEP; + function unZorroIntersection(intersection2, graph) { + var vertex = graph.entity(intersection2.nodeId); + var way1 = graph.entity(intersection2.movedId); + var way2 = graph.entity(intersection2.unmovedId); + var isEP1 = intersection2.movedIsEP; + var isEP2 = intersection2.unmovedIsEP; if (isEP1 && isEP2) return graph; var nodes1 = graph.childNodes(way1).filter(function(n3) { @@ -33165,8 +35909,8 @@ return projection2(n3.loc); }); var hits = geoPathIntersections(movedPath, unmovedPath); - for (var j3 = 0; i3 < hits.length; i3++) { - if (geoVecEqual(hits[j3], end)) + for (var j2 = 0; i3 < hits.length; i3++) { + if (geoVecEqual(hits[j2], end)) continue; var edge = geoChooseEdge(unmovedNodes, end, projection2); _delta = geoVecSubtract(projection2(edge.loc), start2); @@ -33256,7 +36000,7 @@ var nodeCount = {}; var points = []; var corner = { i: 0, dotp: 1 }; - var node, point2, loc, score, motions, i3, j3; + var node, point2, loc, score, motions, i3, j2; for (i3 = 0; i3 < nodes.length; i3++) { node = nodes[i3]; nodeCount[node.id] = (nodeCount[node.id] || 0) + 1; @@ -33296,8 +36040,8 @@ score = Infinity; for (i3 = 0; i3 < 1e3; i3++) { motions = simplified.map(calcMotion); - for (j3 = 0; j3 < motions.length; j3++) { - simplified[j3].coord = geoVecAdd(simplified[j3].coord, motions[j3]); + for (j2 = 0; j2 < motions.length; j2++) { + simplified[j2].coord = geoVecAdd(simplified[j2].coord, motions[j2]); } var newScore = geoOrthoCalcScore(simplified, isClosed, epsilon3, threshold); if (newScore < score) { @@ -33926,8 +36670,8 @@ } else if (datum2 instanceof osmEntity) { selector += ", ." + datum2.id; if (datum2.type === "relation") { - for (var j3 in datum2.members) { - selector += ", ." + datum2.members[j3].id; + for (var j2 in datum2.members) { + selector += ", ." + datum2.members[j2].id; } } } @@ -34161,15 +36905,15 @@ var import_fast_deep_equal2 = __toESM(require_fast_deep_equal()); // node_modules/d3-scale/src/init.js - function initRange(domain2, range3) { + function initRange(domain, range3) { switch (arguments.length) { case 0: break; case 1: - this.range(domain2); + this.range(domain); break; default: - this.range(range3).domain(domain2); + this.range(range3).domain(domain); break; } return this; @@ -34205,8 +36949,8 @@ return Math.max(a2, Math.min(b2, x2)); }; } - function bimap(domain2, range3, interpolate) { - var d0 = domain2[0], d1 = domain2[1], r0 = range3[0], r1 = range3[1]; + function bimap(domain, range3, interpolate) { + var d0 = domain[0], d1 = domain[1], r0 = range3[0], r1 = range3[1]; if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0); else @@ -34215,18 +36959,18 @@ return r0(d0(x2)); }; } - function polymap(domain2, range3, interpolate) { - var j3 = Math.min(domain2.length, range3.length) - 1, d2 = new Array(j3), r2 = new Array(j3), i3 = -1; - if (domain2[j3] < domain2[0]) { - domain2 = domain2.slice().reverse(); + function polymap(domain, range3, interpolate) { + var j2 = Math.min(domain.length, range3.length) - 1, d2 = new Array(j2), r2 = new Array(j2), i3 = -1; + if (domain[j2] < domain[0]) { + domain = domain.slice().reverse(); range3 = range3.slice().reverse(); } - while (++i3 < j3) { - d2[i3] = normalize(domain2[i3], domain2[i3 + 1]); + while (++i3 < j2) { + d2[i3] = normalize(domain[i3], domain[i3 + 1]); r2[i3] = interpolate(range3[i3], range3[i3 + 1]); } return function(x2) { - var i4 = bisect_default(domain2, x2, 1, j3) - 1; + var i4 = bisect_default(domain, x2, 1, j2) - 1; return r2[i4](d2[i4](x2)); }; } @@ -34234,23 +36978,23 @@ return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown()); } function transformer2() { - var domain2 = unit, range3 = unit, interpolate = value_default, transform2, untransform, unknown, clamp3 = identity3, piecewise, output, input; + var domain = unit, range3 = unit, interpolate = value_default, transform2, untransform, unknown, clamp3 = identity3, piecewise, output, input; function rescale() { - var n3 = Math.min(domain2.length, range3.length); + var n3 = Math.min(domain.length, range3.length); if (clamp3 !== identity3) - clamp3 = clamper(domain2[0], domain2[n3 - 1]); + clamp3 = clamper(domain[0], domain[n3 - 1]); piecewise = n3 > 2 ? polymap : bimap; output = input = null; return scale; } function scale(x2) { - return x2 == null || isNaN(x2 = +x2) ? unknown : (output || (output = piecewise(domain2.map(transform2), range3, interpolate)))(transform2(clamp3(x2))); + return x2 == null || isNaN(x2 = +x2) ? unknown : (output || (output = piecewise(domain.map(transform2), range3, interpolate)))(transform2(clamp3(x2))); } scale.invert = function(y2) { - return clamp3(untransform((input || (input = piecewise(range3, domain2.map(transform2), number_default)))(y2))); + return clamp3(untransform((input || (input = piecewise(range3, domain.map(transform2), number_default)))(y2))); }; scale.domain = function(_2) { - return arguments.length ? (domain2 = Array.from(_2, number2), rescale()) : domain2.slice(); + return arguments.length ? (domain = Array.from(_2, number2), rescale()) : domain.slice(); }; scale.range = function(_2) { return arguments.length ? (range3 = Array.from(_2), rescale()) : range3.slice(); @@ -34298,14 +37042,14 @@ // node_modules/d3-format/src/formatGroup.js function formatGroup_default(grouping, thousands) { return function(value, width) { - var i3 = value.length, t2 = [], j3 = 0, g3 = grouping[0], length = 0; + var i3 = value.length, t2 = [], j2 = 0, g3 = grouping[0], length2 = 0; while (i3 > 0 && g3 > 0) { - if (length + g3 + 1 > width) - g3 = Math.max(1, width - length); + if (length2 + g3 + 1 > width) + g3 = Math.max(1, width - length2); t2.push(value.substring(i3 -= g3, i3 + g3)); - if ((length += g3 + 1) > width) + if ((length2 += g3 + 1) > width) break; - g3 = grouping[j3 = (j3 + 1) % grouping.length]; + g3 = grouping[j2 = (j2 + 1) % grouping.length]; } return t2.reverse().join(thousands); }; @@ -34417,7 +37161,7 @@ }; // node_modules/d3-format/src/identity.js - function identity_default3(x2) { + function identity_default4(x2) { return x2; } @@ -34425,19 +37169,19 @@ var map = Array.prototype.map; var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"]; function locale_default(locale2) { - var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity_default3 : formatGroup_default(map.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity_default3 : formatNumerals_default(map.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "\u2212" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + ""; + var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity_default4 : formatGroup_default(map.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity_default4 : formatNumerals_default(map.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "\u2212" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + ""; function newFormat(specifier) { specifier = formatSpecifier(specifier); - var fill = specifier.fill, align = specifier.align, sign2 = specifier.sign, symbol = specifier.symbol, zero3 = specifier.zero, width = specifier.width, comma = specifier.comma, precision2 = specifier.precision, trim = specifier.trim, type2 = specifier.type; + var fill = specifier.fill, align = specifier.align, sign2 = specifier.sign, symbol = specifier.symbol, zero3 = specifier.zero, width = specifier.width, comma = specifier.comma, precision3 = specifier.precision, trim = specifier.trim, type2 = specifier.type; if (type2 === "n") comma = true, type2 = "g"; else if (!formatTypes_default[type2]) - precision2 === void 0 && (precision2 = 12), trim = true, type2 = "g"; + precision3 === void 0 && (precision3 = 12), trim = true, type2 = "g"; if (zero3 || fill === "0" && align === "=") zero3 = true, fill = "0", align = "="; var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type2) ? "0" + type2.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type2) ? percent : ""; var formatType = formatTypes_default[type2], maybeSuffix = /[defgprs%]/.test(type2); - precision2 = precision2 === void 0 ? 6 : /[gprs]/.test(type2) ? Math.max(1, Math.min(21, precision2)) : Math.max(0, Math.min(20, precision2)); + precision3 = precision3 === void 0 ? 6 : /[gprs]/.test(type2) ? Math.max(1, Math.min(21, precision3)) : Math.max(0, Math.min(20, precision3)); function format2(value) { var valuePrefix = prefix, valueSuffix = suffix, i3, n3, c2; if (type2 === "c") { @@ -34446,7 +37190,7 @@ } else { value = +value; var valueNegative = value < 0 || 1 / value < 0; - value = isNaN(value) ? nan : formatType(Math.abs(value), precision2); + value = isNaN(value) ? nan : formatType(Math.abs(value), precision3); if (trim) value = formatTrim_default(value); if (valueNegative && +value === 0 && sign2 !== "+") @@ -34466,7 +37210,7 @@ } if (comma && !zero3) value = group(value, Infinity); - var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : ""; + var length2 = valuePrefix.length + value.length + valueSuffix.length, padding = length2 < width ? new Array(width - length2 + 1).join(fill) : ""; if (comma && zero3) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = ""; switch (align) { @@ -34477,7 +37221,7 @@ value = valuePrefix + padding + value + valueSuffix; break; case "^": - value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); + value = padding.slice(0, length2 = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length2); break; default: value = padding + valuePrefix + value + valueSuffix; @@ -34491,9 +37235,9 @@ return format2; } function formatPrefix2(specifier, value) { - var f3 = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e3 = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k2 = Math.pow(10, -e3), prefix = prefixes[8 + e3 / 3]; + var f2 = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e3 = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k2 = Math.pow(10, -e3), prefix = prefixes[8 + e3 / 3]; return function(value2) { - return f3(k2 * value2) + prefix; + return f2(k2 * value2) + prefix; }; } return { @@ -34536,13 +37280,13 @@ // node_modules/d3-scale/src/tickFormat.js function tickFormat(start2, stop, count, specifier) { - var step = tickStep(start2, stop, count), precision2; + var step = tickStep(start2, stop, count), precision3; specifier = formatSpecifier(specifier == null ? ",f" : specifier); switch (specifier.type) { case "s": { var value = Math.max(Math.abs(start2), Math.abs(stop)); - if (specifier.precision == null && !isNaN(precision2 = precisionPrefix_default(step, value))) - specifier.precision = precision2; + if (specifier.precision == null && !isNaN(precision3 = precisionPrefix_default(step, value))) + specifier.precision = precision3; return formatPrefix(specifier, value); } case "": @@ -34550,14 +37294,14 @@ case "g": case "p": case "r": { - if (specifier.precision == null && !isNaN(precision2 = precisionRound_default(step, Math.max(Math.abs(start2), Math.abs(stop))))) - specifier.precision = precision2 - (specifier.type === "e"); + if (specifier.precision == null && !isNaN(precision3 = precisionRound_default(step, Math.max(Math.abs(start2), Math.abs(stop))))) + specifier.precision = precision3 - (specifier.type === "e"); break; } case "f": case "%": { - if (specifier.precision == null && !isNaN(precision2 = precisionFixed_default(step))) - specifier.precision = precision2 - (specifier.type === "%") * 2; + if (specifier.precision == null && !isNaN(precision3 = precisionFixed_default(step))) + specifier.precision = precision3 - (specifier.type === "%") * 2; break; } } @@ -34566,19 +37310,19 @@ // node_modules/d3-scale/src/linear.js function linearish(scale) { - var domain2 = scale.domain; + var domain = scale.domain; scale.ticks = function(count) { - var d2 = domain2(); + var d2 = domain(); return ticks(d2[0], d2[d2.length - 1], count == null ? 10 : count); }; scale.tickFormat = function(count, specifier) { - var d2 = domain2(); + var d2 = domain(); return tickFormat(d2[0], d2[d2.length - 1], count == null ? 10 : count, specifier); }; scale.nice = function(count) { if (count == null) count = 10; - var d2 = domain2(); + var d2 = domain(); var i0 = 0; var i1 = d2.length - 1; var start2 = d2[i0]; @@ -34595,7 +37339,7 @@ if (step === prestep) { d2[i0] = start2; d2[i1] = stop; - return domain2(d2); + return domain(d2); } else if (step > 0) { start2 = Math.floor(start2 / step) * step; stop = Math.ceil(stop / step) * step; @@ -34622,15 +37366,15 @@ // node_modules/d3-scale/src/quantize.js function quantize() { - var x05 = 0, x12 = 1, n3 = 1, domain2 = [0.5], range3 = [0, 1], unknown; + var x05 = 0, x12 = 1, n3 = 1, domain = [0.5], range3 = [0, 1], unknown; function scale(x2) { - return x2 != null && x2 <= x2 ? range3[bisect_default(domain2, x2, 0, n3)] : unknown; + return x2 != null && x2 <= x2 ? range3[bisect_default(domain, x2, 0, n3)] : unknown; } function rescale() { var i3 = -1; - domain2 = new Array(n3); + domain = new Array(n3); while (++i3 < n3) - domain2[i3] = ((i3 + 1) * x12 - (i3 - n3) * x05) / (n3 + 1); + domain[i3] = ((i3 + 1) * x12 - (i3 - n3) * x05) / (n3 + 1); return scale; } scale.domain = function(_2) { @@ -34641,13 +37385,13 @@ }; scale.invertExtent = function(y2) { var i3 = range3.indexOf(y2); - return i3 < 0 ? [NaN, NaN] : i3 < 1 ? [x05, domain2[0]] : i3 >= n3 ? [domain2[n3 - 1], x12] : [domain2[i3 - 1], domain2[i3]]; + return i3 < 0 ? [NaN, NaN] : i3 < 1 ? [x05, domain[0]] : i3 >= n3 ? [domain[n3 - 1], x12] : [domain[i3 - 1], domain[i3]]; }; scale.unknown = function(_2) { return arguments.length ? (unknown = _2, scale) : scale; }; scale.thresholds = function() { - return domain2.slice(); + return domain.slice(); }; scale.copy = function() { return quantize().domain([x05, x12]).range(range3).unknown(unknown); @@ -34709,22 +37453,22 @@ function calcAnimationParams(selection2) { selection2.call(reset).each(function(d2) { var s2 = select_default2(this); - var tag = s2.node().tagName; + var tag2 = s2.node().tagName; var p2 = { "from": {}, "to": {} }; var opacity; var width; - if (tag === "circle") { + if (tag2 === "circle") { opacity = Number(s2.style("fill-opacity") || 0.5); width = Number(s2.style("r") || 15.5); } else { opacity = Number(s2.style("stroke-opacity") || 0.7); width = Number(s2.style("stroke-width") || 10); } - p2.tag = tag; + p2.tag = tag2; p2.from.opacity = opacity * 0.6; p2.to.opacity = opacity * 1.25; p2.from.width = width * 0.7; - p2.to.width = width * (tag === "circle" ? 1.5 : 1); + p2.to.width = width * (tag2 === "circle" ? 1.5 : 1); _params[d2.id] = p2; }); } @@ -34838,7 +37582,7 @@ } return actionCircularize(entityID, context.projection); } - var operation = function() { + var operation2 = function() { if (!_actions.length) return; var combinedAction = function(graph, t2) { @@ -34850,15 +37594,15 @@ return graph; }; combinedAction.transitionable = true; - context.perform(combinedAction, operation.annotation()); + context.perform(combinedAction, operation2.annotation()); window.setTimeout(function() { context.validator().validate(); }, 300); }; - operation.available = function() { + operation2.available = function() { return _actions.length && selectedIDs.length === _actions.length; }; - operation.disabled = function() { + operation2.disabled = function() { if (!_actions.length) return ""; var actionDisableds = _actions.map(function(action) { @@ -34895,18 +37639,18 @@ return false; } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.circularize." + disable + "." + _amount) : _t.append("operations.circularize.description." + _amount); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.circularize.annotation.feature", { n: _actions.length }); }; - operation.id = "circularize"; - operation.keys = [_t("operations.circularize.key")]; - operation.title = _t.append("operations.circularize.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "circularize"; + operation2.keys = [_t("operations.circularize.key")]; + operation2.title = _t.append("operations.circularize.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/ui/cmd.js @@ -34967,7 +37711,7 @@ return n3.loc; }); var extent = utilTotalExtent(selectedIDs, context.graph()); - var operation = function() { + var operation2 = function() { var nextSelectedID; var nextSelectedLoc; if (selectedIDs.length === 1) { @@ -34992,7 +37736,7 @@ nextSelectedLoc = context.entity(nextSelectedID).loc; } } - context.perform(action, operation.annotation()); + context.perform(action, operation2.annotation()); context.validator().validate(); if (nextSelectedID && nextSelectedLoc) { if (context.hasEntity(nextSelectedID)) { @@ -35005,10 +37749,10 @@ context.enter(modeBrowse(context)); } }; - operation.available = function() { + operation2.available = function() { return true; }; - operation.disabled = function() { + operation2.disabled = function() { if (extent.percentContainedIn(context.map().extent()) < 0.8) { return "too_large"; } else if (someMissing()) { @@ -35064,18 +37808,18 @@ return false; } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.delete." + disable + "." + multi) : _t.append("operations.delete.description." + multi); }; - operation.annotation = function() { + operation2.annotation = function() { return selectedIDs.length === 1 ? _t("operations.delete.annotation." + context.graph().geometry(selectedIDs[0])) : _t("operations.delete.annotation.feature", { n: selectedIDs.length }); }; - operation.id = "delete"; - operation.keys = [uiCmd("\u2318\u232B"), uiCmd("\u2318\u2326"), uiCmd("\u2326")]; - operation.title = _t.append("operations.delete.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "delete"; + operation2.keys = [uiCmd("\u2318\u232B"), uiCmd("\u2318\u2326"), uiCmd("\u2326")]; + operation2.title = _t.append("operations.delete.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/orthogonalize.js @@ -35115,7 +37859,7 @@ } return null; } - var operation = function() { + var operation2 = function() { if (!_actions.length) return; var combinedAction = function(graph, t2) { @@ -35127,15 +37871,15 @@ return graph; }; combinedAction.transitionable = true; - context.perform(combinedAction, operation.annotation()); + context.perform(combinedAction, operation2.annotation()); window.setTimeout(function() { context.validator().validate(); }, 300); }; - operation.available = function() { + operation2.available = function() { return _actions.length && selectedIDs.length === _actions.length; }; - operation.disabled = function() { + operation2.disabled = function() { if (!_actions.length) return ""; var actionDisableds = _actions.map(function(action) { @@ -35172,18 +37916,18 @@ return false; } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.orthogonalize." + disable + "." + _amount) : _t.append("operations.orthogonalize.description." + _type + "." + _amount); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.orthogonalize.annotation." + _type, { n: _actions.length }); }; - operation.id = "orthogonalize"; - operation.keys = [_t("operations.orthogonalize.key")]; - operation.title = _t.append("operations.orthogonalize.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "orthogonalize"; + operation2.keys = [_t("operations.orthogonalize.key")]; + operation2.title = _t.append("operations.orthogonalize.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/reflect.js @@ -35201,17 +37945,17 @@ return n3.loc; }); var extent = utilTotalExtent(selectedIDs, context.graph()); - var operation = function() { + var operation2 = function() { var action = actionReflect(selectedIDs, context.projection).useLongAxis(Boolean(axis === "long")); - context.perform(action, operation.annotation()); + context.perform(action, operation2.annotation()); window.setTimeout(function() { context.validator().validate(); }, 300); }; - operation.available = function() { + operation2.available = function() { return nodes.length >= 3; }; - operation.disabled = function() { + operation2.disabled = function() { if (extent.percentContainedIn(context.map().extent()) < 0.8) { return "too_large"; } else if (someMissing()) { @@ -35244,18 +37988,18 @@ return entity.type === "relation" && !entity.isComplete(context.graph()); } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.reflect." + disable + "." + multi) : _t.append("operations.reflect.description." + axis + "." + multi); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.reflect.annotation." + axis + ".feature", { n: selectedIDs.length }); }; - operation.id = "reflect-" + axis; - operation.keys = [_t("operations.reflect.key." + axis)]; - operation.title = _t.append("operations.reflect.title." + axis); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "reflect-" + axis; + operation2.keys = [_t("operations.reflect.key." + axis)]; + operation2.title = _t.append("operations.reflect.title." + axis); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/move.js @@ -35266,13 +38010,13 @@ return n3.loc; }); var extent = utilTotalExtent(selectedIDs, context.graph()); - var operation = function() { + var operation2 = function() { context.enter(modeMove(context, selectedIDs)); }; - operation.available = function() { + operation2.available = function() { return selectedIDs.length > 0; }; - operation.disabled = function() { + operation2.disabled = function() { if (extent.percentContainedIn(context.map().extent()) < 0.8) { return "too_large"; } else if (someMissing()) { @@ -35305,19 +38049,19 @@ return entity.type === "relation" && !entity.isComplete(context.graph()); } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.move." + disable + "." + multi) : _t.append("operations.move.description." + multi); }; - operation.annotation = function() { + operation2.annotation = function() { return selectedIDs.length === 1 ? _t("operations.move.annotation." + context.graph().geometry(selectedIDs[0])) : _t("operations.move.annotation.feature", { n: selectedIDs.length }); }; - operation.id = "move"; - operation.keys = [_t("operations.move.key")]; - operation.title = _t.append("operations.move.title"); - operation.behavior = behaviorOperation(context).which(operation); - operation.mouseOnly = true; - return operation; + operation2.id = "move"; + operation2.keys = [_t("operations.move.key")]; + operation2.title = _t.append("operations.move.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + operation2.mouseOnly = true; + return operation2; } // modules/modes/rotate.js @@ -35447,13 +38191,13 @@ return n3.loc; }); var extent = utilTotalExtent(selectedIDs, context.graph()); - var operation = function() { + var operation2 = function() { context.enter(modeRotate(context, selectedIDs)); }; - operation.available = function() { + operation2.available = function() { return nodes.length >= 2; }; - operation.disabled = function() { + operation2.disabled = function() { if (extent.percentContainedIn(context.map().extent()) < 0.8) { return "too_large"; } else if (someMissing()) { @@ -35486,19 +38230,19 @@ return entity.type === "relation" && !entity.isComplete(context.graph()); } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.rotate." + disable + "." + multi) : _t.append("operations.rotate.description." + multi); }; - operation.annotation = function() { + operation2.annotation = function() { return selectedIDs.length === 1 ? _t("operations.rotate.annotation." + context.graph().geometry(selectedIDs[0])) : _t("operations.rotate.annotation.feature", { n: selectedIDs.length }); }; - operation.id = "rotate"; - operation.keys = [_t("operations.rotate.key")]; - operation.title = _t.append("operations.rotate.title"); - operation.behavior = behaviorOperation(context).which(operation); - operation.mouseOnly = true; - return operation; + operation2.id = "rotate"; + operation2.keys = [_t("operations.rotate.key")]; + operation2.title = _t.append("operations.rotate.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + operation2.mouseOnly = true; + return operation2; } // modules/modes/move.js @@ -35988,16 +38732,16 @@ } function hasInvalidGeometry(entity, graph) { var parents = graph.parentWays(entity); - var i3, j3, k2; + var i3, j2, k2; for (i3 = 0; i3 < parents.length; i3++) { var parent = parents[i3]; var nodes = []; var activeIndex = null; var relations = graph.parentRelations(parent); - for (j3 = 0; j3 < relations.length; j3++) { - if (!relations[j3].isMultipolygon()) + for (j2 = 0; j2 < relations.length; j2++) { + if (!relations[j2].isMultipolygon()) continue; - var rings = osmJoinWays(relations[j3].members, graph); + var rings = osmJoinWays(relations[j2].members, graph); for (k2 = 0; k2 < rings.length; k2++) { nodes = rings[k2].nodes; if (nodes.find(function(n3) { @@ -36172,7 +38916,7 @@ // node_modules/d3-fetch/src/xml.js function parser(type2) { - return (input, init2) => text_default3(input, init2).then((text2) => new DOMParser().parseFromString(text2, type2)); + return (input, init2) => text_default3(input, init2).then((text) => new DOMParser().parseFromString(text, type2)); } var xml_default = parser("application/xml"); var html = parser("text/html"); @@ -36309,9 +39053,9 @@ if (idType && capture) { capture = parseError(capture, idType); } else { - const compare = capture.toLowerCase(); - if (_krData.localizeStrings[compare]) { - capture = _t("QA.keepRight.error_parts." + _krData.localizeStrings[compare]); + const compare2 = capture.toLowerCase(); + if (_krData.localizeStrings[compare2]) { + capture = _t("QA.keepRight.error_parts." + _krData.localizeStrings[compare2]); } else { capture = unescape_default(capture); } @@ -36321,9 +39065,9 @@ return replacements; } function parseError(capture, idType) { - const compare = capture.toLowerCase(); - if (_krData.localizeStrings[compare]) { - capture = _t("QA.keepRight.error_parts." + _krData.localizeStrings[compare]); + const compare2 = capture.toLowerCase(); + if (_krData.localizeStrings[compare2]) { + capture = _t("QA.keepRight.error_parts." + _krData.localizeStrings[compare2]); } switch (idType) { case "this": @@ -36972,25 +39716,15 @@ function _getDefaults() { return { async: false, - baseUrl: null, breaks: false, extensions: null, gfm: true, - headerIds: false, - headerPrefix: "", - highlight: null, hooks: null, - langPrefix: "language-", - mangle: false, pedantic: false, renderer: null, - sanitize: false, - sanitizer: null, silent: false, - smartypants: false, tokenizer: null, - walkTokens: null, - xhtml: false + walkTokens: null }; } var _defaults = _getDefaults(); @@ -37009,21 +39743,21 @@ "'": "'" }; var getEscapeReplacement = (ch) => escapeReplacements[ch]; - function escape4(html2, encode) { + function escape$1(html3, encode) { if (encode) { - if (escapeTest.test(html2)) { - return html2.replace(escapeReplace, getEscapeReplacement); + if (escapeTest.test(html3)) { + return html3.replace(escapeReplace, getEscapeReplacement); } } else { - if (escapeTestNoEncode.test(html2)) { - return html2.replace(escapeReplaceNoEncode, getEscapeReplacement); + if (escapeTestNoEncode.test(html3)) { + return html3.replace(escapeReplaceNoEncode, getEscapeReplacement); } } - return html2; + return html3; } var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; - function unescape3(html2) { - return html2.replace(unescapeTest, (_2, n3) => { + function unescape2(html3) { + return html3.replace(unescapeTest, (_2, n3) => { n3 = n3.toLowerCase(); if (n3 === "colon") return ":"; @@ -37035,38 +39769,22 @@ } var caret = /(^|[^\[])\^/g; function edit(regex, opt) { - regex = typeof regex === "string" ? regex : regex.source; + let source = typeof regex === "string" ? regex : regex.source; opt = opt || ""; const obj = { replace: (name, val) => { - val = typeof val === "object" && "source" in val ? val.source : val; - val = val.replace(caret, "$1"); - regex = regex.replace(name, val); + let valSource = typeof val === "string" ? val : val.source; + valSource = valSource.replace(caret, "$1"); + source = source.replace(name, valSource); return obj; }, getRegex: () => { - return new RegExp(regex, opt); + return new RegExp(source, opt); } }; return obj; } - var nonWordAndColonTest = /[^\w:]/g; - var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; - function cleanUrl(sanitize, base, href) { - if (sanitize) { - let prot; - try { - prot = decodeURIComponent(unescape3(href)).replace(nonWordAndColonTest, "").toLowerCase(); - } catch (e3) { - return null; - } - if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) { - return null; - } - } - if (base && !originIndependentUrl.test(href)) { - href = resolveUrl(base, href); - } + function cleanUrl(href) { try { href = encodeURI(href).replace(/%25/g, "%"); } catch (e3) { @@ -37074,39 +39792,12 @@ } return href; } - var baseUrls = {}; - var justDomain = /^[^:]+:\/*[^/]*$/; - var protocol = /^([^:]+:)[\s\S]*$/; - var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/; - function resolveUrl(base, href) { - if (!baseUrls[" " + base]) { - if (justDomain.test(base)) { - baseUrls[" " + base] = base + "/"; - } else { - baseUrls[" " + base] = rtrim(base, "/", true); - } - } - base = baseUrls[" " + base]; - const relativeBase = base.indexOf(":") === -1; - if (href.substring(0, 2) === "//") { - if (relativeBase) { - return href; - } - return base.replace(protocol, "$1") + href; - } else if (href.charAt(0) === "/") { - if (relativeBase) { - return href; - } - return base.replace(domain, "$1") + href; - } else { - return base + href; - } - } var noopTest = { exec: () => null }; function splitCells(tableRow, count) { - const row = tableRow.replace(/\|/g, (match, offset, str2) => { - let escaped = false, curr = offset; - while (--curr >= 0 && str2[curr] === "\\") + const row = tableRow.replace(/\|/g, (match, offset, str) => { + let escaped = false; + let curr = offset; + while (--curr >= 0 && str[curr] === "\\") escaped = !escaped; if (escaped) { return "|"; @@ -37134,14 +39825,14 @@ } return cells; } - function rtrim(str2, c2, invert) { - const l2 = str2.length; + function rtrim(str, c2, invert) { + const l2 = str.length; if (l2 === 0) { return ""; } let suffLen = 0; while (suffLen < l2) { - const currChar = str2.charAt(l2 - suffLen - 1); + const currChar = str.charAt(l2 - suffLen - 1); if (currChar === c2 && !invert) { suffLen++; } else if (currChar !== c2 && invert) { @@ -37150,20 +39841,19 @@ break; } } - return str2.slice(0, l2 - suffLen); + return str.slice(0, l2 - suffLen); } - function findClosingBracket(str2, b2) { - if (str2.indexOf(b2[1]) === -1) { + function findClosingBracket(str, b2) { + if (str.indexOf(b2[1]) === -1) { return -1; } - const l2 = str2.length; - let level = 0, i3 = 0; - for (; i3 < l2; i3++) { - if (str2[i3] === "\\") { + let level = 0; + for (let i3 = 0; i3 < str.length; i3++) { + if (str[i3] === "\\") { i3++; - } else if (str2[i3] === b2[0]) { + } else if (str[i3] === b2[0]) { level++; - } else if (str2[i3] === b2[1]) { + } else if (str[i3] === b2[1]) { level--; if (level < 0) { return i3; @@ -37172,39 +39862,10 @@ } return -1; } - function checkDeprecations(opt, callback) { - if (!opt || opt.silent) { - return; - } - if (callback) { - console.warn("marked(): callback is deprecated since version 5.0.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/using_pro#async"); - } - if (opt.sanitize || opt.sanitizer) { - console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options"); - } - if (opt.highlight || opt.langPrefix !== "language-") { - console.warn("marked(): highlight and langPrefix parameters are deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-highlight."); - } - if (opt.mangle) { - console.warn("marked(): mangle parameter is enabled by default, but is deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-mangle, or disable by setting `{mangle: false}`."); - } - if (opt.baseUrl) { - console.warn("marked(): baseUrl parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-base-url."); - } - if (opt.smartypants) { - console.warn("marked(): smartypants parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-smartypants."); - } - if (opt.xhtml) { - console.warn("marked(): xhtml parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-xhtml."); - } - if (opt.headerIds || opt.headerPrefix) { - console.warn("marked(): headerIds and headerPrefix parameters enabled by default, but are deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-gfm-heading-id, or disable by setting `{headerIds: false}`."); - } - } - function outputLink(cap, link2, raw, lexer2) { - const href = link2.href; - const title = link2.title ? escape4(link2.title) : null; - const text2 = cap[1].replace(/\\([\[\]])/g, "$1"); + function outputLink(cap, link3, raw, lexer2) { + const href = link3.href; + const title = link3.title ? escape$1(link3.title) : null; + const text = cap[1].replace(/\\([\[\]])/g, "$1"); if (cap[0].charAt(0) !== "!") { lexer2.state.inLink = true; const token = { @@ -37212,8 +39873,8 @@ raw, href, title, - text: text2, - tokens: lexer2.inlineTokens(text2) + text, + tokens: lexer2.inlineTokens(text) }; lexer2.state.inLink = false; return token; @@ -37223,16 +39884,16 @@ raw, href, title, - text: escape4(text2) + text: escape$1(text) }; } - function indentCodeCompensation(raw, text2) { + function indentCodeCompensation(raw, text) { const matchIndentToCode = raw.match(/^(\s+)(?:```)/); if (matchIndentToCode === null) { - return text2; + return text; } const indentToCode = matchIndentToCode[1]; - return text2.split("\n").map((node) => { + return text.split("\n").map((node) => { const matchIndentInNode = node.match(/^\s+/); if (matchIndentInNode === null) { return node; @@ -37245,9 +39906,11 @@ }).join("\n"); } var _Tokenizer = class { + // set by the lexer constructor(options2) { __publicField(this, "options"); __publicField(this, "rules"); + // set by the lexer __publicField(this, "lexer"); this.options = options2 || _defaults; } @@ -37263,12 +39926,12 @@ code(src) { const cap = this.rules.block.code.exec(src); if (cap) { - const text2 = cap[0].replace(/^ {1,4}/gm, ""); + const text = cap[0].replace(/^ {1,4}/gm, ""); return { type: "code", raw: cap[0], codeBlockStyle: "indented", - text: !this.options.pedantic ? rtrim(text2, "\n") : text2 + text: !this.options.pedantic ? rtrim(text, "\n") : text }; } } @@ -37276,33 +39939,33 @@ const cap = this.rules.block.fences.exec(src); if (cap) { const raw = cap[0]; - const text2 = indentCodeCompensation(raw, cap[3] || ""); + const text = indentCodeCompensation(raw, cap[3] || ""); return { type: "code", raw, - lang: cap[2] ? cap[2].trim().replace(this.rules.inline._escapes, "$1") : cap[2], - text: text2 + lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2], + text }; } } heading(src) { const cap = this.rules.block.heading.exec(src); if (cap) { - let text2 = cap[2].trim(); - if (/#$/.test(text2)) { - const trimmed = rtrim(text2, "#"); + let text = cap[2].trim(); + if (/#$/.test(text)) { + const trimmed = rtrim(text, "#"); if (this.options.pedantic) { - text2 = trimmed.trim(); + text = trimmed.trim(); } else if (!trimmed || / $/.test(trimmed)) { - text2 = trimmed.trim(); + text = trimmed.trim(); } } return { type: "heading", raw: cap[0], depth: cap[1].length, - text: text2, - tokens: this.lexer.inline(text2) + text, + tokens: this.lexer.inline(text) }; } } @@ -37318,26 +39981,25 @@ blockquote(src) { const cap = this.rules.block.blockquote.exec(src); if (cap) { - const text2 = cap[0].replace(/^ *>[ \t]?/gm, ""); + const text = rtrim(cap[0].replace(/^ *>[ \t]?/gm, ""), "\n"); const top = this.lexer.state.top; this.lexer.state.top = true; - const tokens = this.lexer.blockTokens(text2); + const tokens = this.lexer.blockTokens(text); this.lexer.state.top = top; return { type: "blockquote", raw: cap[0], tokens, - text: text2 + text }; } } list(src) { let cap = this.rules.block.list.exec(src); if (cap) { - let raw, istask, ischecked, indent2, i3, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly; let bull = cap[1].trim(); const isordered = bull.length > 1; - const list = { + const list2 = { type: "list", raw: "", ordered: isordered, @@ -37350,8 +40012,11 @@ bull = isordered ? bull : "[*+-]"; } const itemRegex = new RegExp("^( {0,3}".concat(bull, ")((?:[ ][^\\n]*)?(?:\\n|$))")); + let raw = ""; + let itemContents = ""; + let endsWithBlankLine = false; while (src) { - endEarly = false; + let endEarly = false; if (!(cap = itemRegex.exec(src))) { break; } @@ -37360,30 +40025,31 @@ } raw = cap[0]; src = src.substring(raw.length); - line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t2) => " ".repeat(3 * t2.length)); - nextLine = src.split("\n", 1)[0]; + let line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t2) => " ".repeat(3 * t2.length)); + let nextLine = src.split("\n", 1)[0]; + let indent = 0; if (this.options.pedantic) { - indent2 = 2; - itemContents = line.trimLeft(); + indent = 2; + itemContents = line.trimStart(); } else { - indent2 = cap[2].search(/[^ ]/); - indent2 = indent2 > 4 ? 1 : indent2; - itemContents = line.slice(indent2); - indent2 += cap[1].length; + indent = cap[2].search(/[^ ]/); + indent = indent > 4 ? 1 : indent; + itemContents = line.slice(indent); + indent += cap[1].length; } - blankLine = false; + let blankLine = false; if (!line && /^ *$/.test(nextLine)) { raw += nextLine + "\n"; src = src.substring(nextLine.length + 1); endEarly = true; } if (!endEarly) { - const nextBulletRegex = new RegExp("^ {0,".concat(Math.min(3, indent2 - 1), "}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))")); - const hrRegex = new RegExp("^ {0,".concat(Math.min(3, indent2 - 1), "}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)")); - const fencesBeginRegex = new RegExp("^ {0,".concat(Math.min(3, indent2 - 1), "}(?:```|~~~)")); - const headingBeginRegex = new RegExp("^ {0,".concat(Math.min(3, indent2 - 1), "}#")); + const nextBulletRegex = new RegExp("^ {0,".concat(Math.min(3, indent - 1), "}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))")); + const hrRegex = new RegExp("^ {0,".concat(Math.min(3, indent - 1), "}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)")); + const fencesBeginRegex = new RegExp("^ {0,".concat(Math.min(3, indent - 1), "}(?:```|~~~)")); + const headingBeginRegex = new RegExp("^ {0,".concat(Math.min(3, indent - 1), "}#")); while (src) { - rawLine = src.split("\n", 1)[0]; + const rawLine = src.split("\n", 1)[0]; nextLine = rawLine; if (this.options.pedantic) { nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, " "); @@ -37400,8 +40066,8 @@ if (hrRegex.test(src)) { break; } - if (nextLine.search(/[^ ]/) >= indent2 || !nextLine.trim()) { - itemContents += "\n" + nextLine.slice(indent2); + if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { + itemContents += "\n" + nextLine.slice(indent); } else { if (blankLine) { break; @@ -37425,16 +40091,18 @@ } raw += rawLine + "\n"; src = src.substring(rawLine.length + 1); - line = nextLine.slice(indent2); + line = nextLine.slice(indent); } } - if (!list.loose) { + if (!list2.loose) { if (endsWithBlankLine) { - list.loose = true; + list2.loose = true; } else if (/\n *\n *$/.test(raw)) { endsWithBlankLine = true; } } + let istask = null; + let ischecked; if (this.options.gfm) { istask = /^\[[ xX]\] /.exec(itemContents); if (istask) { @@ -37442,35 +40110,35 @@ itemContents = itemContents.replace(/^\[[ xX]\] +/, ""); } } - list.items.push({ + list2.items.push({ type: "list_item", raw, task: !!istask, checked: ischecked, loose: false, - text: itemContents + text: itemContents, + tokens: [] }); - list.raw += raw; + list2.raw += raw; } - list.items[list.items.length - 1].raw = raw.trimRight(); - list.items[list.items.length - 1].text = itemContents.trimRight(); - list.raw = list.raw.trimRight(); - const l2 = list.items.length; - for (i3 = 0; i3 < l2; i3++) { + list2.items[list2.items.length - 1].raw = raw.trimEnd(); + list2.items[list2.items.length - 1].text = itemContents.trimEnd(); + list2.raw = list2.raw.trimEnd(); + for (let i3 = 0; i3 < list2.items.length; i3++) { this.lexer.state.top = false; - list.items[i3].tokens = this.lexer.blockTokens(list.items[i3].text, []); - if (!list.loose) { - const spacers = list.items[i3].tokens.filter((t2) => t2.type === "space"); + list2.items[i3].tokens = this.lexer.blockTokens(list2.items[i3].text, []); + if (!list2.loose) { + const spacers = list2.items[i3].tokens.filter((t2) => t2.type === "space"); const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t2) => /\n.*\n/.test(t2.raw)); - list.loose = hasMultipleLineBreaks; + list2.loose = hasMultipleLineBreaks; } } - if (list.loose) { - for (i3 = 0; i3 < l2; i3++) { - list.items[i3].loose = true; + if (list2.loose) { + for (let i3 = 0; i3 < list2.items.length; i3++) { + list2.items[i3].loose = true; } } - return list; + return list2; } } html(src) { @@ -37480,28 +40148,21 @@ type: "html", block: true, raw: cap[0], - pre: !this.options.sanitizer && (cap[1] === "pre" || cap[1] === "script" || cap[1] === "style"), + pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style", text: cap[0] }; - if (this.options.sanitize) { - const text2 = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape4(cap[0]); - const paragraph = token; - paragraph.type = "paragraph"; - paragraph.text = text2; - paragraph.tokens = this.lexer.inline(text2); - } return token; } } def(src) { const cap = this.rules.block.def.exec(src); if (cap) { - const tag = cap[1].toLowerCase().replace(/\s+/g, " "); - const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline._escapes, "$1") : ""; - const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline._escapes, "$1") : cap[3]; + const tag2 = cap[1].toLowerCase().replace(/\s+/g, " "); + const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline.anyPunctuation, "$1") : ""; + const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3]; return { type: "def", - tag, + tag: tag2, raw: cap[0], href, title @@ -37510,50 +40171,51 @@ } table(src) { const cap = this.rules.block.table.exec(src); - if (cap) { - const item = { - type: "table", - raw: cap[0], - header: splitCells(cap[1]).map((c2) => { - return { text: c2 }; - }), - align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */), - rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : [] - }; - if (item.header.length === item.align.length) { - let l2 = item.align.length; - let i3, j3, k2, row; - for (i3 = 0; i3 < l2; i3++) { - if (/^ *-+: *$/.test(item.align[i3])) { - item.align[i3] = "right"; - } else if (/^ *:-+: *$/.test(item.align[i3])) { - item.align[i3] = "center"; - } else if (/^ *:-+ *$/.test(item.align[i3])) { - item.align[i3] = "left"; - } else { - item.align[i3] = null; - } - } - l2 = item.rows.length; - for (i3 = 0; i3 < l2; i3++) { - item.rows[i3] = splitCells(item.rows[i3], item.header.length).map((c2) => { - return { text: c2 }; - }); - } - l2 = item.header.length; - for (j3 = 0; j3 < l2; j3++) { - item.header[j3].tokens = this.lexer.inline(item.header[j3].text); - } - l2 = item.rows.length; - for (j3 = 0; j3 < l2; j3++) { - row = item.rows[j3]; - for (k2 = 0; k2 < row.length; k2++) { - row[k2].tokens = this.lexer.inline(row[k2].text); - } - } - return item; + if (!cap) { + return; + } + if (!/[:|]/.test(cap[2])) { + return; + } + const headers = splitCells(cap[1]); + const aligns = cap[2].replace(/^\||\| *$/g, "").split("|"); + const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : []; + const item = { + type: "table", + raw: cap[0], + header: [], + align: [], + rows: [] + }; + if (headers.length !== aligns.length) { + return; + } + for (const align of aligns) { + if (/^ *-+: *$/.test(align)) { + item.align.push("right"); + } else if (/^ *:-+: *$/.test(align)) { + item.align.push("center"); + } else if (/^ *:-+ *$/.test(align)) { + item.align.push("left"); + } else { + item.align.push(null); } } + for (const header of headers) { + item.header.push({ + text: header, + tokens: this.lexer.inline(header) + }); + } + for (const row of rows) { + item.rows.push(splitCells(row, item.header.length).map((cell) => { + return { + text: cell, + tokens: this.lexer.inline(cell) + }; + })); + } + return item; } lheading(src) { const cap = this.rules.block.lheading.exec(src); @@ -37570,12 +40232,12 @@ paragraph(src) { const cap = this.rules.block.paragraph.exec(src); if (cap) { - const text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1]; + const text = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1]; return { type: "paragraph", raw: cap[0], - text: text2, - tokens: this.lexer.inline(text2) + text, + tokens: this.lexer.inline(text) }; } } @@ -37596,7 +40258,7 @@ return { type: "escape", raw: cap[0], - text: escape4(cap[1]) + text: escape$1(cap[1]) }; } } @@ -37614,12 +40276,12 @@ this.lexer.state.inRawBlock = false; } return { - type: this.options.sanitize ? "text" : "html", + type: "html", raw: cap[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, - text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape4(cap[0]) : cap[0] + text: cap[0] }; } } @@ -37648,10 +40310,10 @@ let href = cap[2]; let title = ""; if (this.options.pedantic) { - const link2 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); - if (link2) { - href = link2[1]; - title = link2[3]; + const link3 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); + if (link3) { + href = link3[1]; + title = link3[3]; } } else { title = cap[3] ? cap[3].slice(1, -1) : ""; @@ -37665,38 +40327,38 @@ } } return outputLink(cap, { - href: href ? href.replace(this.rules.inline._escapes, "$1") : href, - title: title ? title.replace(this.rules.inline._escapes, "$1") : title + href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href, + title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title }, cap[0], this.lexer); } } reflink(src, links) { let cap; if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) { - let link2 = (cap[2] || cap[1]).replace(/\s+/g, " "); - link2 = links[link2.toLowerCase()]; - if (!link2) { - const text2 = cap[0].charAt(0); + const linkString = (cap[2] || cap[1]).replace(/\s+/g, " "); + const link3 = links[linkString.toLowerCase()]; + if (!link3) { + const text = cap[0].charAt(0); return { type: "text", - raw: text2, - text: text2 + raw: text, + text }; } - return outputLink(cap, link2, cap[0], this.lexer); + return outputLink(cap, link3, cap[0], this.lexer); } } emStrong(src, maskedSrc, prevChar = "") { - let match = this.rules.inline.emStrong.lDelim.exec(src); + let match = this.rules.inline.emStrongLDelim.exec(src); if (!match) return; - if (match[3] && prevChar.match(new RegExp("[\\p{L}\\p{N}]", "u"))) + if (match[3] && prevChar.match(/[\p{L}\p{N}]/u)) return; const nextChar = match[1] || match[2] || ""; if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { const lLength = [...match[0]].length - 1; let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; - const endReg = match[0][0] === "*" ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd; + const endReg = match[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; endReg.lastIndex = 0; maskedSrc = maskedSrc.slice(-1 * src.length + lLength); while ((match = endReg.exec(maskedSrc)) != null) { @@ -37717,22 +40379,23 @@ if (delimTotal > 0) continue; rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); - const raw = [...src].slice(0, lLength + match.index + rLength + 1).join(""); + const lastCharLength = [...match[0]][0].length; + const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); if (Math.min(lLength, rLength) % 2) { - const text3 = raw.slice(1, -1); + const text2 = raw.slice(1, -1); return { type: "em", raw, - text: text3, - tokens: this.lexer.inlineTokens(text3) + text: text2, + tokens: this.lexer.inlineTokens(text2) }; } - const text2 = raw.slice(2, -2); + const text = raw.slice(2, -2); return { type: "strong", raw, - text: text2, - tokens: this.lexer.inlineTokens(text2) + text, + tokens: this.lexer.inlineTokens(text) }; } } @@ -37740,17 +40403,17 @@ codespan(src) { const cap = this.rules.inline.code.exec(src); if (cap) { - let text2 = cap[2].replace(/\n/g, " "); - const hasNonSpaceChars = /[^ ]/.test(text2); - const hasSpaceCharsOnBothEnds = /^ /.test(text2) && / $/.test(text2); + let text = cap[2].replace(/\n/g, " "); + const hasNonSpaceChars = /[^ ]/.test(text); + const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text); if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { - text2 = text2.substring(1, text2.length - 1); + text = text.substring(1, text.length - 1); } - text2 = escape4(text2, true); + text = escape$1(text, true); return { type: "codespan", raw: cap[0], - text: text2 + text }; } } @@ -37774,46 +40437,47 @@ }; } } - autolink(src, mangle2) { + autolink(src) { const cap = this.rules.inline.autolink.exec(src); if (cap) { - let text2, href; + let text, href; if (cap[2] === "@") { - text2 = escape4(this.options.mangle ? mangle2(cap[1]) : cap[1]); - href = "mailto:" + text2; + text = escape$1(cap[1]); + href = "mailto:" + text; } else { - text2 = escape4(cap[1]); - href = text2; + text = escape$1(cap[1]); + href = text; } return { type: "link", raw: cap[0], - text: text2, + text, href, tokens: [ { type: "text", - raw: text2, - text: text2 + raw: text, + text } ] }; } } - url(src, mangle2) { + url(src) { + var _a2, _b; let cap; if (cap = this.rules.inline.url.exec(src)) { - let text2, href; + let text, href; if (cap[2] === "@") { - text2 = escape4(this.options.mangle ? mangle2(cap[0]) : cap[0]); - href = "mailto:" + text2; + text = escape$1(cap[0]); + href = "mailto:" + text; } else { let prevCapZero; do { prevCapZero = cap[0]; - cap[0] = this.rules.inline._backpedal.exec(cap[0])[0]; + cap[0] = (_b = (_a2 = this.rules.inline._backpedal.exec(cap[0])) == null ? void 0 : _a2[0]) != null ? _b : ""; } while (prevCapZero !== cap[0]); - text2 = escape4(cap[0]); + text = escape$1(cap[0]); if (cap[1] === "www.") { href = "http://" + cap[0]; } else { @@ -37823,170 +40487,153 @@ return { type: "link", raw: cap[0], - text: text2, + text, href, tokens: [ { type: "text", - raw: text2, - text: text2 + raw: text, + text } ] }; } } - inlineText(src, smartypants2) { + inlineText(src) { const cap = this.rules.inline.text.exec(src); if (cap) { - let text2; + let text; if (this.lexer.state.inRawBlock) { - text2 = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape4(cap[0]) : cap[0]; + text = cap[0]; } else { - text2 = escape4(this.options.smartypants ? smartypants2(cap[0]) : cap[0]); + text = escape$1(cap[0]); } return { type: "text", raw: cap[0], - text: text2 + text }; } } }; - var block = { - newline: /^(?: *(?:\n|$))+/, - code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/, - fences: /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, - hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, - heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, - blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, - list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/, - html: "^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", - def: /^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/, + var newline = /^(?: *(?:\n|$))+/; + var blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/; + var fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; + var hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; + var heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; + var bullet = /(?:[*+-]|\d{1,9}[.)])/; + var lheading = edit(/^(?!bull )((?:.|\n(?!\s*?\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet).getRegex(); + var _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; + var blockText = /^[^\n]+/; + var _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; + var def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(); + var list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex(); + var _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; + var _comment = /|$))/; + var html2 = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); + var paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex(); + var blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex(); + var blockNormal = { + blockquote, + code: blockCode, + def, + fences, + heading, + hr, + html: html2, + lheading, + list, + newline, + paragraph, table: noopTest, - lheading: /^((?:(?!^bull ).|\n(?!\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - // regex template, placeholders will be replaced according to different paragraph - // interruption rules of commonmark and the original markdown spec: - _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, - text: /^[^\n]+/ + text: blockText }; - block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/; - block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; - block.def = edit(block.def).replace("label", block._label).replace("title", block._title).getRegex(); - block.bullet = /(?:[*+-]|\d{1,9}[.)])/; - block.listItemStart = edit(/^( *)(bull) */).replace("bull", block.bullet).getRegex(); - block.list = edit(block.list).replace(/bull/g, block.bullet).replace("hr", "\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def", "\\n+(?=" + block.def.source + ")").getRegex(); - block._tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; - block._comment = /|$)/; - block.html = edit(block.html, "i").replace("comment", block._comment).replace("tag", block._tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); - block.lheading = edit(block.lheading).replace(/bull/g, block.bullet).getRegex(); - block.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex(); - block.blockquote = edit(block.blockquote).replace("paragraph", block.paragraph).getRegex(); - block.normal = __spreadValues({}, block); - block.gfm = __spreadProps(__spreadValues({}, block.normal), { - table: "^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)" - // Cells - }); - block.gfm.table = edit(block.gfm.table).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex(); - block.gfm.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("table", block.gfm.table).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex(); - block.pedantic = __spreadProps(__spreadValues({}, block.normal), { - html: edit("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment", block._comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), + var gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex(); + var blockGfm = { + ...blockNormal, + table: gfmTable, + paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex() + }; + var blockPedantic = { + ...blockNormal, + html: edit("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: noopTest, + // fences not supported lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, - paragraph: edit(block.normal._paragraph).replace("hr", block.hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", block.lheading).replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").getRegex() - }); - var inline = { - escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, - autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, - url: noopTest, - tag: "^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^", - link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, - reflink: /^!?\[(label)\]\[(ref)\]/, - nolink: /^!?\[(ref)\](?:\[\])?/, - reflinkSearch: "reflink|nolink(?!\\()", - emStrong: { - lDelim: /^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, - // (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right. - // | Skip orphan inside strong | Consume to delim | (1) #*** | (2) a***#, a*** | (3) #***a, ***a | (4) ***# | (5) #***# | (6) a***a - rDelimAst: /^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\*)[punct](\*+)(?=[\s]|$)|[^punct\s](\*+)(?!\*)(?=[punct\s]|$)|(?!\*)[punct\s](\*+)(?=[^punct\s])|[\s](\*+)(?!\*)(?=[punct])|(?!\*)[punct](\*+)(?!\*)(?=[punct])|[^punct\s](\*+)(?=[^punct\s])/, - rDelimUnd: /^[^_*]*?\*\*[^_*]*?_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\s]|$)|[^punct\s](_+)(?!_)(?=[punct\s]|$)|(?!_)[punct\s](_+)(?=[^punct\s])|[\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])/ - // ^- Not allowed for _ - }, - code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, - br: /^( {2,}|\\)\n(?!\s*$)/, + paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() + }; + var escape4 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; + var inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; + var br = /^( {2,}|\\)\n(?!\s*$)/; + var inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g; + var emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, "u").replace(/punct/g, _punctuation).getRegex(); + var emStrongRDelimAst = edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])", "gu").replace(/punct/g, _punctuation).getRegex(); + var emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])", "gu").replace(/punct/g, _punctuation).getRegex(); + var anyPunctuation = edit(/\\([punct])/, "gu").replace(/punct/g, _punctuation).getRegex(); + var autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(); + var _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex(); + var tag = edit("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(); + var _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; + var link2 = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(); + var reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex(); + var nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex(); + var reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex(); + var inlineNormal = { + _backpedal: noopTest, + // only used for GFM url + anyPunctuation, + autolink, + blockSkip, + br, + code: inlineCode, del: noopTest, - text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`^|~"; - inline.punctuation = edit(inline.punctuation, "u").replace(/punctuation/g, inline._punctuation).getRegex(); - inline.blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g; - inline.anyPunctuation = /\\[punct]/g; - inline._escapes = /\\([punct])/g; - inline._comment = edit(block._comment).replace("(?:-->|$)", "-->").getRegex(); - inline.emStrong.lDelim = edit(inline.emStrong.lDelim, "u").replace(/punct/g, inline._punctuation).getRegex(); - inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, "gu").replace(/punct/g, inline._punctuation).getRegex(); - inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, "gu").replace(/punct/g, inline._punctuation).getRegex(); - inline.anyPunctuation = edit(inline.anyPunctuation, "gu").replace(/punct/g, inline._punctuation).getRegex(); - inline._escapes = edit(inline._escapes, "gu").replace(/punct/g, inline._punctuation).getRegex(); - inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; - inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; - inline.autolink = edit(inline.autolink).replace("scheme", inline._scheme).replace("email", inline._email).getRegex(); - inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; - inline.tag = edit(inline.tag).replace("comment", inline._comment).replace("attribute", inline._attribute).getRegex(); - inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; - inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/; - inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; - inline.link = edit(inline.link).replace("label", inline._label).replace("href", inline._href).replace("title", inline._title).getRegex(); - inline.reflink = edit(inline.reflink).replace("label", inline._label).replace("ref", block._label).getRegex(); - inline.nolink = edit(inline.nolink).replace("ref", block._label).getRegex(); - inline.reflinkSearch = edit(inline.reflinkSearch, "g").replace("reflink", inline.reflink).replace("nolink", inline.nolink).getRegex(); - inline.normal = __spreadValues({}, inline); - inline.pedantic = __spreadProps(__spreadValues({}, inline.normal), { - strong: { - start: /^__|\*\*/, - middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, - endAst: /\*\*(?!\*)/g, - endUnd: /__(?!_)/g - }, - em: { - start: /^_|\*/, - middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/, - endAst: /\*(?!\*)/g, - endUnd: /_(?!_)/g - }, - link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", inline._label).getRegex(), - reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", inline._label).getRegex() - }); - inline.gfm = __spreadProps(__spreadValues({}, inline.normal), { - escape: edit(inline.escape).replace("])", "~|])").getRegex(), - _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, - url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, + var inlinePedantic = { + ...inlineNormal, + link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(), + reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex() + }; + var inlineGfm = { + ...inlineNormal, + escape: edit(escape4).replace("])", "~|])").getRegex(), + url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\ 0.5) { - ch = "x" + ch.toString(16); - } - out += "&#" + ch + ";"; - } - return out; - } + }; + var inlineBreaks = { + ...inlineGfm, + br: edit(br).replace("{2,}", "*").getRegex(), + text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() + }; + var block = { + normal: blockNormal, + gfm: blockGfm, + pedantic: blockPedantic + }; + var inline = { + normal: inlineNormal, + gfm: inlineGfm, + breaks: inlineBreaks, + pedantic: inlinePedantic + }; var _Lexer = class __Lexer { constructor(options2) { __publicField(this, "tokens"); @@ -38053,10 +40700,11 @@ lex(src) { src = src.replace(/\r\n|\r/g, "\n"); this.blockTokens(src, this.tokens); - let next; - while (next = this.inlineQueue.shift()) { + for (let i3 = 0; i3 < this.inlineQueue.length; i3++) { + const next = this.inlineQueue[i3]; this.inlineTokens(next.src, next.tokens); } + this.inlineQueue = []; return this.tokens; } blockTokens(src, tokens = []) { @@ -38308,12 +40956,12 @@ tokens.push(token); continue; } - if (token = this.tokenizer.autolink(src, mangle)) { + if (token = this.tokenizer.autolink(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } - if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) { + if (!this.state.inLink && (token = this.tokenizer.url(src))) { src = src.substring(token.raw.length); tokens.push(token); continue; @@ -38333,7 +40981,7 @@ cutSrc = src.substring(0, startIndex + 1); } } - if (token = this.tokenizer.inlineText(cutSrc, smartypants)) { + if (token = this.tokenizer.inlineText(cutSrc)) { src = src.substring(token.raw.length); if (token.raw.slice(-1) !== "_") { prevChar = token.raw.slice(-1); @@ -38367,48 +41015,39 @@ this.options = options2 || _defaults; } code(code, infostring, escaped) { - const lang = (infostring || "").match(/\S*/)[0]; - if (this.options.highlight) { - const out = this.options.highlight(code, lang); - if (out != null && out !== code) { - escaped = true; - code = out; - } - } + var _a2; + const lang = (_a2 = (infostring || "").match(/^\S*/)) == null ? void 0 : _a2[0]; code = code.replace(/\n$/, "") + "\n"; if (!lang) { - return "
" + (escaped ? code : escape4(code, true)) + "
\n"; + return "
" + (escaped ? code : escape$1(code, true)) + "
\n"; } - return '
' + (escaped ? code : escape4(code, true)) + "
\n"; + return '
' + (escaped ? code : escape$1(code, true)) + "
\n"; } - blockquote(quote2) { - return "
\n".concat(quote2, "
\n"); + blockquote(quote) { + return "
\n".concat(quote, "
\n"); } - html(html2, block2) { - return html2; + html(html3, block2) { + return html3; } - heading(text2, level, raw, slugger) { - if (this.options.headerIds) { - const id2 = this.options.headerPrefix + slugger.slug(raw); - return "').concat(text2, "\n"); - } - return "").concat(text2, "\n"); + heading(text, level, raw) { + return "").concat(text, "\n"); } hr() { - return this.options.xhtml ? "
\n" : "
\n"; + return "
\n"; } list(body, ordered, start2) { - const type2 = ordered ? "ol" : "ul", startatt = ordered && start2 !== 1 ? ' start="' + start2 + '"' : ""; + const type2 = ordered ? "ol" : "ul"; + const startatt = ordered && start2 !== 1 ? ' start="' + start2 + '"' : ""; return "<" + type2 + startatt + ">\n" + body + "\n"; } - listitem(text2, task, checked) { - return "
  • ".concat(text2, "
  • \n"); + listitem(text, task, checked) { + return "
  • ".concat(text, "
  • \n"); } checkbox(checked) { - return " "; + return "'; } - paragraph(text2) { - return "

    ".concat(text2, "

    \n"); + paragraph(text) { + return "

    ".concat(text, "

    \n"); } table(header, body) { if (body) @@ -38420,132 +41059,97 @@ } tablecell(content, flags) { const type2 = flags.header ? "th" : "td"; - const tag = flags.align ? "<".concat(type2, ' align="').concat(flags.align, '">') : "<".concat(type2, ">"); - return tag + content + "\n"); + const tag2 = flags.align ? "<".concat(type2, ' align="').concat(flags.align, '">') : "<".concat(type2, ">"); + return tag2 + content + "\n"); } /** * span level renderer */ - strong(text2) { - return "".concat(text2, ""); + strong(text) { + return "".concat(text, ""); } - em(text2) { - return "".concat(text2, ""); + em(text) { + return "".concat(text, ""); } - codespan(text2) { - return "".concat(text2, ""); + codespan(text) { + return "".concat(text, ""); } br() { - return this.options.xhtml ? "
    " : "
    "; + return "
    "; } - del(text2) { - return "".concat(text2, ""); + del(text) { + return "".concat(text, ""); } - link(href, title, text2) { - href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); - if (href === null) { - return text2; + link(href, title, text) { + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; } + href = cleanHref; let out = '"; + out += ">" + text + ""; return out; } - image(href, title, text2) { - href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); - if (href === null) { - return text2; + image(href, title, text) { + const cleanHref = cleanUrl(href); + if (cleanHref === null) { + return text; } - let out = '').concat(text2, '" : ">"; + out += ">"; return out; } - text(text2) { - return text2; + text(text) { + return text; } }; var _TextRenderer = class { // no need for block level renderers - strong(text2) { - return text2; + strong(text) { + return text; } - em(text2) { - return text2; + em(text) { + return text; } - codespan(text2) { - return text2; + codespan(text) { + return text; } - del(text2) { - return text2; + del(text) { + return text; } - html(text2) { - return text2; + html(text) { + return text; } - text(text2) { - return text2; + text(text) { + return text; } - link(href, title, text2) { - return "" + text2; + link(href, title, text) { + return "" + text; } - image(href, title, text2) { - return "" + text2; + image(href, title, text) { + return "" + text; } br() { return ""; } }; - var _Slugger = class { - constructor() { - __publicField(this, "seen"); - this.seen = {}; - } - serialize(value) { - return value.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig, "").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, "").replace(/\s/g, "-"); - } - /** - * Finds the next safe (unique) slug to use - */ - getNextSafeSlug(originalSlug, isDryRun) { - let slug = originalSlug; - let occurenceAccumulator = 0; - if (this.seen.hasOwnProperty(slug)) { - occurenceAccumulator = this.seen[originalSlug]; - do { - occurenceAccumulator++; - slug = originalSlug + "-" + occurenceAccumulator; - } while (this.seen.hasOwnProperty(slug)); - } - if (!isDryRun) { - this.seen[originalSlug] = occurenceAccumulator; - this.seen[slug] = 0; - } - return slug; - } - /** - * Convert string to unique id - */ - slug(value, options2 = {}) { - const slug = this.serialize(value); - return this.getNextSafeSlug(slug, options2.dryrun); - } - }; var _Parser = class __Parser { constructor(options2) { __publicField(this, "options"); __publicField(this, "renderer"); __publicField(this, "textRenderer"); - __publicField(this, "slugger"); this.options = options2 || _defaults; this.options.renderer = this.options.renderer || new _Renderer(); this.renderer = this.options.renderer; this.renderer.options = this.options; this.textRenderer = new _TextRenderer(); - this.slugger = new _Slugger(); } /** * Static Parse Method @@ -38565,13 +41169,13 @@ * Parse Loop */ parse(tokens, top = true) { - let out = "", i3, j3, k2, l2, l3, row, cell, header, body, token, ordered, start2, loose, itemBody, item, checked, task, checkbox, ret; - const l4 = tokens.length; - for (i3 = 0; i3 < l4; i3++) { - token = tokens[i3]; + let out = ""; + for (let i3 = 0; i3 < tokens.length; i3++) { + const token = tokens[i3]; if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { - ret = this.options.extensions.renderers[token.type].call({ parser: this }, token); - if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(token.type)) { + const genericToken = token; + const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken); + if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) { out += ret || ""; continue; } @@ -38585,29 +41189,29 @@ continue; } case "heading": { - out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape3(this.parseInline(token.tokens, this.textRenderer)), this.slugger); + const headingToken = token; + out += this.renderer.heading(this.parseInline(headingToken.tokens), headingToken.depth, unescape2(this.parseInline(headingToken.tokens, this.textRenderer))); continue; } case "code": { - out += this.renderer.code(token.text, token.lang, !!token.escaped); + const codeToken = token; + out += this.renderer.code(codeToken.text, codeToken.lang, !!codeToken.escaped); continue; } case "table": { - header = ""; - cell = ""; - l2 = token.header.length; - for (j3 = 0; j3 < l2; j3++) { - cell += this.renderer.tablecell(this.parseInline(token.header[j3].tokens), { header: true, align: token.align[j3] }); + const tableToken = token; + let header = ""; + let cell = ""; + for (let j2 = 0; j2 < tableToken.header.length; j2++) { + cell += this.renderer.tablecell(this.parseInline(tableToken.header[j2].tokens), { header: true, align: tableToken.align[j2] }); } header += this.renderer.tablerow(cell); - body = ""; - l2 = token.rows.length; - for (j3 = 0; j3 < l2; j3++) { - row = token.rows[j3]; + let body = ""; + for (let j2 = 0; j2 < tableToken.rows.length; j2++) { + const row = tableToken.rows[j2]; cell = ""; - l3 = row.length; - for (k2 = 0; k2 < l3; k2++) { - cell += this.renderer.tablecell(this.parseInline(row[k2].tokens), { header: false, align: token.align[k2] }); + for (let k2 = 0; k2 < row.length; k2++) { + cell += this.renderer.tablecell(this.parseInline(row[k2].tokens), { header: false, align: tableToken.align[k2] }); } body += this.renderer.tablerow(cell); } @@ -38615,23 +41219,24 @@ continue; } case "blockquote": { - body = this.parse(token.tokens); + const blockquoteToken = token; + const body = this.parse(blockquoteToken.tokens); out += this.renderer.blockquote(body); continue; } case "list": { - ordered = token.ordered; - start2 = token.start; - loose = token.loose; - l2 = token.items.length; - body = ""; - for (j3 = 0; j3 < l2; j3++) { - item = token.items[j3]; - checked = item.checked; - task = item.task; - itemBody = ""; + const listToken = token; + const ordered = listToken.ordered; + const start2 = listToken.start; + const loose = listToken.loose; + let body = ""; + for (let j2 = 0; j2 < listToken.items.length; j2++) { + const item = listToken.items[j2]; + const checked = item.checked; + const task = item.task; + let itemBody = ""; if (item.task) { - checkbox = this.renderer.checkbox(!!checked); + const checkbox = this.renderer.checkbox(!!checked); if (loose) { if (item.tokens.length > 0 && item.tokens[0].type === "paragraph") { item.tokens[0].text = checkbox + " " + item.tokens[0].text; @@ -38641,11 +41246,11 @@ } else { item.tokens.unshift({ type: "text", - text: checkbox + text: checkbox + " " }); } } else { - itemBody += checkbox; + itemBody += checkbox + " "; } } itemBody += this.parse(item.tokens, loose); @@ -38655,18 +41260,21 @@ continue; } case "html": { - out += this.renderer.html(token.text, token.block); + const htmlToken = token; + out += this.renderer.html(htmlToken.text, htmlToken.block); continue; } case "paragraph": { - out += this.renderer.paragraph(this.parseInline(token.tokens)); + const paragraphToken = token; + out += this.renderer.paragraph(this.parseInline(paragraphToken.tokens)); continue; } case "text": { - body = token.tokens ? this.parseInline(token.tokens) : token.text; - while (i3 + 1 < l4 && tokens[i3 + 1].type === "text") { - token = tokens[++i3]; - body += "\n" + (token.tokens ? this.parseInline(token.tokens) : token.text); + let textToken = token; + let body = textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text; + while (i3 + 1 < tokens.length && tokens[i3 + 1].type === "text") { + textToken = tokens[++i3]; + body += "\n" + (textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text); } out += top ? this.renderer.paragraph(body) : body; continue; @@ -38689,12 +41297,11 @@ */ parseInline(tokens, renderer) { renderer = renderer || this.renderer; - let out = "", i3, token, ret; - const l2 = tokens.length; - for (i3 = 0; i3 < l2; i3++) { - token = tokens[i3]; + let out = ""; + for (let i3 = 0; i3 < tokens.length; i3++) { + const token = tokens[i3]; if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) { - ret = this.options.extensions.renderers[token.type].call({ parser: this }, token); + const ret = this.options.extensions.renderers[token.type].call({ parser: this }, token); if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(token.type)) { out += ret || ""; continue; @@ -38702,31 +41309,38 @@ } switch (token.type) { case "escape": { - out += renderer.text(token.text); + const escapeToken = token; + out += renderer.text(escapeToken.text); break; } case "html": { - out += renderer.html(token.text); + const tagToken = token; + out += renderer.html(tagToken.text); break; } case "link": { - out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer)); + const linkToken = token; + out += renderer.link(linkToken.href, linkToken.title, this.parseInline(linkToken.tokens, renderer)); break; } case "image": { - out += renderer.image(token.href, token.title, token.text); + const imageToken = token; + out += renderer.image(imageToken.href, imageToken.title, imageToken.text); break; } case "strong": { - out += renderer.strong(this.parseInline(token.tokens, renderer)); + const strongToken = token; + out += renderer.strong(this.parseInline(strongToken.tokens, renderer)); break; } case "em": { - out += renderer.em(this.parseInline(token.tokens, renderer)); + const emToken = token; + out += renderer.em(this.parseInline(emToken.tokens, renderer)); break; } case "codespan": { - out += renderer.codespan(token.text); + const codespanToken = token; + out += renderer.codespan(codespanToken.text); break; } case "br": { @@ -38734,11 +41348,13 @@ break; } case "del": { - out += renderer.del(this.parseInline(token.tokens, renderer)); + const delToken = token; + out += renderer.del(this.parseInline(delToken.tokens, renderer)); break; } case "text": { - out += renderer.text(token.text); + const textToken = token; + out += renderer.text(textToken.text); break; } default: { @@ -38769,13 +41385,20 @@ /** * Process HTML after marked is finished */ - postprocess(html2) { - return html2; + postprocess(html3) { + return html3; + } + /** + * Process all tokens before walk tokens + */ + processAllTokens(tokens) { + return tokens; } }; __publicField(_Hooks, "passThroughHooks", /* @__PURE__ */ new Set([ "preprocess", - "postprocess" + "postprocess", + "processAllTokens" ])); var _parseMarkdown, parseMarkdown_fn, _onError, onError_fn; var Marked = class { @@ -38787,13 +41410,10 @@ __publicField(this, "parse", __privateMethod(this, _parseMarkdown, parseMarkdown_fn).call(this, _Lexer.lex, _Parser.parse)); __publicField(this, "parseInline", __privateMethod(this, _parseMarkdown, parseMarkdown_fn).call(this, _Lexer.lexInline, _Parser.parseInline)); __publicField(this, "Parser", _Parser); - __publicField(this, "parser", _Parser.parse); __publicField(this, "Renderer", _Renderer); __publicField(this, "TextRenderer", _TextRenderer); __publicField(this, "Lexer", _Lexer); - __publicField(this, "lexer", _Lexer.lex); __publicField(this, "Tokenizer", _Tokenizer); - __publicField(this, "Slugger", _Slugger); __publicField(this, "Hooks", _Hooks); this.use(...args); } @@ -38801,15 +41421,17 @@ * Run callback for every token */ walkTokens(tokens, callback) { + var _a2, _b; let values = []; for (const token of tokens) { values = values.concat(callback.call(this, token)); switch (token.type) { case "table": { - for (const cell of token.header) { + const tableToken = token; + for (const cell of tableToken.header) { values = values.concat(this.walkTokens(cell.tokens, callback)); } - for (const row of token.rows) { + for (const row of tableToken.rows) { for (const cell of row) { values = values.concat(this.walkTokens(cell.tokens, callback)); } @@ -38817,16 +41439,19 @@ break; } case "list": { - values = values.concat(this.walkTokens(token.items, callback)); + const listToken = token; + values = values.concat(this.walkTokens(listToken.items, callback)); break; } default: { - if (this.defaults.extensions && this.defaults.extensions.childTokens && this.defaults.extensions.childTokens[token.type]) { - this.defaults.extensions.childTokens[token.type].forEach((childTokens) => { - values = values.concat(this.walkTokens(token[childTokens], callback)); + const genericToken = token; + if ((_b = (_a2 = this.defaults.extensions) == null ? void 0 : _a2.childTokens) == null ? void 0 : _b[genericToken.type]) { + this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => { + const tokens2 = genericToken[childTokens].flat(Infinity); + values = values.concat(this.walkTokens(tokens2, callback)); }); - } else if (token.tokens) { - values = values.concat(this.walkTokens(token.tokens, callback)); + } else if (genericToken.tokens) { + values = values.concat(this.walkTokens(genericToken.tokens, callback)); } } } @@ -38836,7 +41461,7 @@ use(...args) { const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; args.forEach((pack) => { - const opts = __spreadValues({}, pack); + const opts = { ...pack }; opts.async = this.defaults.async || opts.async || false; if (pack.extensions) { pack.extensions.forEach((ext) => { @@ -38861,8 +41486,9 @@ if (!ext.level || ext.level !== "block" && ext.level !== "inline") { throw new Error("extension level must be 'block' or 'inline'"); } - if (extensions[ext.level]) { - extensions[ext.level].unshift(ext.tokenizer); + const extLevel = extensions[ext.level]; + if (extLevel) { + extLevel.unshift(ext.tokenizer); } else { extensions[ext.level] = [ext.tokenizer]; } @@ -38891,10 +41517,16 @@ if (pack.renderer) { const renderer = this.defaults.renderer || new _Renderer(this.defaults); for (const prop in pack.renderer) { - const rendererFunc = pack.renderer[prop]; - const rendererKey = prop; - const prevRenderer = renderer[rendererKey]; - renderer[rendererKey] = (...args2) => { + if (!(prop in renderer)) { + throw new Error("renderer '".concat(prop, "' does not exist")); + } + if (prop === "options") { + continue; + } + const rendererProp = prop; + const rendererFunc = pack.renderer[rendererProp]; + const prevRenderer = renderer[rendererProp]; + renderer[rendererProp] = (...args2) => { let ret = rendererFunc.apply(renderer, args2); if (ret === false) { ret = prevRenderer.apply(renderer, args2); @@ -38907,10 +41539,16 @@ if (pack.tokenizer) { const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); for (const prop in pack.tokenizer) { - const tokenizerFunc = pack.tokenizer[prop]; - const tokenizerKey = prop; - const prevTokenizer = tokenizer[tokenizerKey]; - tokenizer[tokenizerKey] = (...args2) => { + if (!(prop in tokenizer)) { + throw new Error("tokenizer '".concat(prop, "' does not exist")); + } + if (["options", "rules", "lexer"].includes(prop)) { + continue; + } + const tokenizerProp = prop; + const tokenizerFunc = pack.tokenizer[tokenizerProp]; + const prevTokenizer = tokenizer[tokenizerProp]; + tokenizer[tokenizerProp] = (...args2) => { let ret = tokenizerFunc.apply(tokenizer, args2); if (ret === false) { ret = prevTokenizer.apply(tokenizer, args2); @@ -38923,11 +41561,17 @@ if (pack.hooks) { const hooks = this.defaults.hooks || new _Hooks(); for (const prop in pack.hooks) { - const hooksFunc = pack.hooks[prop]; - const hooksKey = prop; - const prevHook = hooks[hooksKey]; + if (!(prop in hooks)) { + throw new Error("hook '".concat(prop, "' does not exist")); + } + if (prop === "options") { + continue; + } + const hooksProp = prop; + const hooksFunc = pack.hooks[hooksProp]; + const prevHook = hooks[hooksProp]; if (_Hooks.passThroughHooks.has(prop)) { - hooks[hooksKey] = (arg) => { + hooks[hooksProp] = (arg) => { if (this.defaults.async) { return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => { return prevHook.call(hooks, ret2); @@ -38937,7 +41581,7 @@ return prevHook.call(hooks, ret); }; } else { - hooks[hooksKey] = (...args2) => { + hooks[hooksProp] = (...args2) => { let ret = hooksFunc.apply(hooks, args2); if (ret === false) { ret = prevHook.apply(hooks, args2); @@ -38950,154 +41594,96 @@ } if (pack.walkTokens) { const walkTokens2 = this.defaults.walkTokens; + const packWalktokens = pack.walkTokens; opts.walkTokens = function(token) { let values = []; - values.push(pack.walkTokens.call(this, token)); + values.push(packWalktokens.call(this, token)); if (walkTokens2) { values = values.concat(walkTokens2.call(this, token)); } return values; }; } - this.defaults = __spreadValues(__spreadValues({}, this.defaults), opts); + this.defaults = { ...this.defaults, ...opts }; }); return this; } setOptions(opt) { - this.defaults = __spreadValues(__spreadValues({}, this.defaults), opt); + this.defaults = { ...this.defaults, ...opt }; return this; } + lexer(src, options2) { + return _Lexer.lex(src, options2 != null ? options2 : this.defaults); + } + parser(tokens, options2) { + return _Parser.parse(tokens, options2 != null ? options2 : this.defaults); + } }; _parseMarkdown = new WeakSet(); parseMarkdown_fn = function(lexer2, parser3) { - return (src, optOrCallback, callback) => { - if (typeof optOrCallback === "function") { - callback = optOrCallback; - optOrCallback = null; - } - const origOpt = __spreadValues({}, optOrCallback); - const opt = __spreadValues(__spreadValues({}, this.defaults), origOpt); - const throwError = __privateMethod(this, _onError, onError_fn).call(this, !!opt.silent, !!opt.async, callback); + return (src, options2) => { + const origOpt = { ...options2 }; + const opt = { ...this.defaults, ...origOpt }; + if (this.defaults.async === true && origOpt.async === false) { + if (!opt.silent) { + console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."); + } + opt.async = true; + } + const throwError = __privateMethod(this, _onError, onError_fn).call(this, !!opt.silent, !!opt.async); if (typeof src === "undefined" || src === null) { return throwError(new Error("marked(): input parameter is undefined or null")); } if (typeof src !== "string") { return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected")); } - checkDeprecations(opt, callback); if (opt.hooks) { opt.hooks.options = opt; } - if (callback) { - const highlight = opt.highlight; - let tokens; - try { - if (opt.hooks) { - src = opt.hooks.preprocess(src); - } - tokens = lexer2(src, opt); - } catch (e3) { - return throwError(e3); - } - const done = (err) => { - let out; - if (!err) { - try { - if (opt.walkTokens) { - this.walkTokens(tokens, opt.walkTokens); - } - out = parser3(tokens, opt); - if (opt.hooks) { - out = opt.hooks.postprocess(out); - } - } catch (e3) { - err = e3; - } - } - opt.highlight = highlight; - return err ? throwError(err) : callback(null, out); - }; - if (!highlight || highlight.length < 3) { - return done(); - } - delete opt.highlight; - if (!tokens.length) - return done(); - let pending = 0; - this.walkTokens(tokens, (token) => { - if (token.type === "code") { - pending++; - setTimeout(() => { - highlight(token.text, token.lang, (err, code) => { - if (err) { - return done(err); - } - if (code != null && code !== token.text) { - token.text = code; - token.escaped = true; - } - pending--; - if (pending === 0) { - done(); - } - }); - }, 0); - } - }); - if (pending === 0) { - done(); - } - return; - } if (opt.async) { - return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser3(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError); + return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser3(tokens, opt)).then((html3) => opt.hooks ? opt.hooks.postprocess(html3) : html3).catch(throwError); } try { if (opt.hooks) { src = opt.hooks.preprocess(src); } - const tokens = lexer2(src, opt); + let tokens = lexer2(src, opt); + if (opt.hooks) { + tokens = opt.hooks.processAllTokens(tokens); + } if (opt.walkTokens) { this.walkTokens(tokens, opt.walkTokens); } - let html2 = parser3(tokens, opt); + let html3 = parser3(tokens, opt); if (opt.hooks) { - html2 = opt.hooks.postprocess(html2); + html3 = opt.hooks.postprocess(html3); } - return html2; + return html3; } catch (e3) { return throwError(e3); } }; }; _onError = new WeakSet(); - onError_fn = function(silent, async, callback) { + onError_fn = function(silent, async) { return (e3) => { e3.message += "\nPlease report this to https://github.com/markedjs/marked."; if (silent) { - const msg = "

    An error occurred:

    " + escape4(e3.message + "", true) + "
    "; + const msg = "

    An error occurred:

    " + escape$1(e3.message + "", true) + "
    "; if (async) { return Promise.resolve(msg); } - if (callback) { - callback(null, msg); - return; - } return msg; } if (async) { return Promise.reject(e3); } - if (callback) { - callback(e3); - return; - } throw e3; }; }; var markedInstance = new Marked(); - function marked(src, opt, callback) { - return markedInstance.parse(src, opt, callback); + function marked(src, opt) { + return markedInstance.parse(src, opt); } marked.options = marked.setOptions = function(options2) { markedInstance.setOptions(options2); @@ -39124,7 +41710,6 @@ marked.Lexer = _Lexer; marked.lexer = _Lexer.lex; marked.Tokenizer = _Tokenizer; - marked.Slugger = _Slugger; marked.Hooks = _Hooks; marked.parse = marked; var options = marked.options; @@ -39905,9 +42490,9 @@ function showDetections(detections) { const tagComponent = _mlyViewer.getComponent("tag"); detections.forEach(function(data) { - const tag = makeTag(data); - if (tag) { - tagComponent.add([tag]); + const tag2 = makeTag(data); + if (tag2) { + tagComponent.add([tag2]); } }); } @@ -39915,17 +42500,17 @@ const valueParts = data.value.split("--"); if (!valueParts.length) return; - let tag; - let text2; + let tag2; + let text; let color2 = 16777215; if (_mlyHighlightedDetection === data.id) { color2 = 16776960; - text2 = valueParts[1]; - if (text2 === "flat" || text2 === "discrete" || text2 === "sign") { - text2 = valueParts[2]; + text = valueParts[1]; + if (text === "flat" || text === "discrete" || text === "sign") { + text = valueParts[2]; } - text2 = text2.replace(/-/g, " "); - text2 = text2.charAt(0).toUpperCase() + text2.slice(1); + text = text.replace(/-/g, " "); + text = text.charAt(0).toUpperCase() + text.slice(1); _mlyHighlightedDetection = null; } var decodedGeometry = window.atob(data.geometry); @@ -39937,11 +42522,11 @@ const layer = tile.layers["mpy-or"]; const geometries = layer.feature(0).loadGeometry(); const polygon2 = geometries.map((ring) => ring.map((point2) => [point2.x / layer.extent, point2.y / layer.extent])); - tag = new mapillary.OutlineTag( + tag2 = new mapillary.OutlineTag( data.id, new mapillary.PolygonGeometry(polygon2[0]), { - text: text2, + text, textColor: color2, lineColor: color2, lineWidth: 2, @@ -39949,7 +42534,7 @@ fillOpacity: 0.3 } ); - return tag; + return tag2; } }, // Return the current cache @@ -40302,7 +42887,7 @@ } } load(); - _diff.length = function length() { + _diff.length = function length2() { return Object.keys(_changes).length; }; _diff.changes = function changes() { @@ -40395,8 +42980,8 @@ } function addParents(entity) { var parents = head.parentWays(entity); - for (var j3 = parents.length - 1; j3 >= 0; j3--) { - var parent = parents[j3]; + for (var j2 = parents.length - 1; j2 >= 0; j2--) { + var parent = parents[j2]; if (!(parent.id in relevant)) { addEntity(parent, head, "modified"); } @@ -40742,11 +43327,11 @@ return change(previous); } function change(previous) { - var difference = coreDifference(previous, history.graph()); + var difference2 = coreDifference(previous, history.graph()); if (!_pausedGraph) { - dispatch14.call("change", this, difference); + dispatch14.call("change", this, difference2); } - return difference; + return difference2; } function getKey(n3) { return "iD_" + window.location.origin + "_" + n3; @@ -40886,11 +43471,11 @@ if (action) { head = action(head); } - var difference = coreDifference(base, head); + var difference2 = coreDifference(base, head); return { - modified: difference.modified(), - created: difference.created(), - deleted: difference.deleted() + modified: difference2.modified(), + created: difference2.created(), + deleted: difference2.deleted() }; }, hasChanges: function() { @@ -41251,6 +43836,7 @@ validationMismatchedGeometry: () => validationMismatchedGeometry, validationMissingRole: () => validationMissingRole, validationMissingTag: () => validationMissingTag, + validationMutuallyExclusiveTags: () => validationMutuallyExclusiveTags, validationOutdatedTags: () => validationOutdatedTags, validationPrivateData: () => validationPrivateData, validationSuspiciousName: () => validationSuspiciousName, @@ -41578,15 +44164,15 @@ if (!shouldCheckWay(parentWay)) continue; var lastIndex = parentWay.nodes.length - 1; - for (var j3 = 0; j3 < parentWay.nodes.length; j3++) { - if (j3 !== 0) { - if (parentWay.nodes[j3 - 1] === node.id) { - checkForCloseness(node, graph.entity(parentWay.nodes[j3]), parentWay); + for (var j2 = 0; j2 < parentWay.nodes.length; j2++) { + if (j2 !== 0) { + if (parentWay.nodes[j2 - 1] === node.id) { + checkForCloseness(node, graph.entity(parentWay.nodes[j2]), parentWay); } } - if (j3 !== lastIndex) { - if (parentWay.nodes[j3 + 1] === node.id) { - checkForCloseness(graph.entity(parentWay.nodes[j3]), node, parentWay); + if (j2 !== lastIndex) { + if (parentWay.nodes[j2 + 1] === node.id) { + checkForCloseness(graph.entity(parentWay.nodes[j2]), node, parentWay); } } } @@ -41618,8 +44204,8 @@ [lon + lon_range, lat + lat_range] ]); var intersected = context.history().tree().intersects(queryExtent, graph); - for (var j3 = 0; j3 < intersected.length; j3++) { - var nearby = intersected[j3]; + for (var j2 = 0; j2 < intersected.length; j2++) { + var nearby = intersected[j2]; if (nearby.id === node.id) continue; if (nearby.type !== "node" || nearby.geometry(graph) !== "point") @@ -41903,7 +44489,7 @@ if (way1FeatureType === null) return edgeCrossInfos; var checkedSingleCrossingWays = {}; - var i3, j3; + var i3, j2; var extent; var n1, n22, nA, nB, nAId, nBId; var segment1, segment2; @@ -41925,8 +44511,8 @@ ] ]); segmentInfos = tree.waySegments(extent, graph); - for (j3 = 0; j3 < segmentInfos.length; j3++) { - segment2Info = segmentInfos[j3]; + for (j2 = 0; j2 < segmentInfos.length; j2++) { + segment2Info = segmentInfos[j2]; if (segment2Info.wayId === way1.id) continue; if (checkedSingleCrossingWays[segment2Info.wayId]) @@ -42757,9 +45343,9 @@ entityIds: [singleEntity.id], onClick: function(context2) { var id2 = this.issue.entityIds[0]; - var operation = operationDelete(context2, [id2]); - if (!operation.disabled()) { - operation(); + var operation2 = operationDelete(context2, [id2]); + if (!operation2.disabled()) { + operation2(); } } })); @@ -43736,14 +46322,14 @@ })); var deleteOnClick; var id2 = this.entityIds[0]; - var operation = operationDelete(context2, [id2]); - var disabledReasonID = operation.disabled(); + var operation2 = operationDelete(context2, [id2]); + var disabledReasonID = operation2.disabled(); if (!disabledReasonID) { deleteOnClick = function(context3) { var id3 = this.issue.entityIds[0]; - var operation2 = operationDelete(context3, [id3]); - if (!operation2.disabled()) { - operation2(); + var operation3 = operationDelete(context3, [id3]); + if (!operation3.disabled()) { + operation3(); } }; } @@ -43766,6 +46352,72 @@ return validation; } + // modules/validations/mutually_exclusive_tags.js + function validationMutuallyExclusiveTags() { + const type2 = "mutually_exclusive_tags"; + const tagKeyPairs = osmMutuallyExclusiveTagPairs; + const validation = function checkMutuallyExclusiveTags(entity) { + let pairsFounds = tagKeyPairs.filter((pair3) => { + return pair3[0] in entity.tags && pair3[1] in entity.tags; + }).filter((pair3) => { + return !(pair3[0].match(/^(addr:)?no[a-z]/) && entity.tags[pair3[0]] === "no" || pair3[1].match(/^(addr:)?no[a-z]/) && entity.tags[pair3[1]] === "no"); + }); + Object.keys(entity.tags).forEach((key) => { + let negative_key = "not:" + key; + if (negative_key in entity.tags && entity.tags[negative_key].split(";").includes(entity.tags[key])) { + pairsFounds.push([negative_key, key, "same_value"]); + } + if (key.match(/^name:[a-z]+/)) { + negative_key = "not:name"; + if (negative_key in entity.tags && entity.tags[negative_key].split(";").includes(entity.tags[key])) { + pairsFounds.push([negative_key, key, "same_value"]); + } + } + }); + let issues = pairsFounds.map((pair3) => { + const subtype = pair3[2] || "default"; + return new validationIssue({ + type: type2, + subtype, + severity: "warning", + message: function(context) { + let entity2 = context.hasEntity(this.entityIds[0]); + return entity2 ? _t.append("issues.".concat(type2, ".").concat(subtype, ".message"), { + feature: utilDisplayLabel(entity2, context.graph()), + tag1: pair3[0], + tag2: pair3[1] + }) : ""; + }, + reference: (selection2) => showReference(selection2, pair3, subtype), + entityIds: [entity.id], + dynamicFixes: () => pair3.slice(0, 2).map((tagToRemove) => createIssueFix(tagToRemove)) + }); + }); + function createIssueFix(tagToRemove) { + return new validationIssueFix({ + icon: "iD-operation-delete", + title: _t.append("issues.fix.remove_named_tag.title", { tag: tagToRemove }), + onClick: function(context) { + const entityId = this.issue.entityIds[0]; + const entity2 = context.entity(entityId); + let tags = Object.assign({}, entity2.tags); + delete tags[tagToRemove]; + context.perform( + actionChangeTags(entityId, tags), + _t("issues.fix.remove_named_tag.annotation", { tag: tagToRemove }) + ); + } + }); + } + function showReference(selection2, pair3, subtype) { + selection2.selectAll(".issue-reference").data([0]).enter().append("div").attr("class", "issue-reference").call(_t.append("issues.".concat(type2, ".").concat(subtype, ".reference"), { tag1: pair3[0], tag2: pair3[1] })); + } + return issues; + }; + validation.type = type2; + return validation; + } + // modules/validations/outdated_tags.js function validationOutdatedTags() { const type2 = "outdated_tags"; @@ -43796,8 +46448,8 @@ if (_dataDeprecated) { const deprecatedTags = entity.deprecatedTags(_dataDeprecated); if (deprecatedTags.length) { - deprecatedTags.forEach((tag) => { - graph = actionUpgradeTags(entity.id, tag.old, tag.replace)(graph); + deprecatedTags.forEach((tag2) => { + graph = actionUpgradeTags(entity.id, tag2.old, tag2.replace)(graph); }); entity = graph.entity(entity.id); } @@ -44194,70 +46846,18 @@ selection2.selectAll(".issue-reference").data([0]).enter().append("div").attr("class", "issue-reference").call(_t.append("issues.generic_name.reference")); } } - function makeIncorrectNameIssue(entityId, nameKey, incorrectName, langCode) { - return new validationIssue({ - type: type2, - subtype: "not_name", - severity: "warning", - message: function(context) { - const entity = context.hasEntity(this.entityIds[0]); - if (!entity) - return ""; - const preset = _mainPresetIndex.match(entity, context.graph()); - const langName = langCode && _mainLocalizer.languageName(langCode); - return _t.append( - "issues.incorrect_name.message" + (langName ? "_language" : ""), - { feature: preset.name(), name: incorrectName, language: langName } - ); - }, - reference: showReference, - entityIds: [entityId], - hash: "".concat(nameKey, "=").concat(incorrectName), - dynamicFixes: function() { - return [ - new validationIssueFix({ - icon: "iD-operation-delete", - title: _t.append("issues.fix.remove_the_name.title"), - onClick: function(context) { - const entityId2 = this.issue.entityIds[0]; - const entity = context.entity(entityId2); - let tags = Object.assign({}, entity.tags); - delete tags[nameKey]; - context.perform( - actionChangeTags(entityId2, tags), - _t("issues.fix.remove_mistaken_name.annotation") - ); - } - }) - ]; - } - }); - function showReference(selection2) { - selection2.selectAll(".issue-reference").data([0]).enter().append("div").attr("class", "issue-reference").call(_t.append("issues.generic_name.reference")); - } - } let validation = function checkGenericName(entity) { const tags = entity.tags; const hasWikidata = !!tags.wikidata || !!tags["brand:wikidata"] || !!tags["operator:wikidata"]; if (hasWikidata) return []; let issues = []; - const notNames2 = (tags["not:name"] || "").split(";"); for (let key in tags) { const m2 = key.match(/^name(?:(?::)([a-zA-Z_-]+))?$/); if (!m2) continue; const langCode = m2.length >= 2 ? m2[1] : null; const value = tags[key]; - if (notNames2.length) { - for (let i3 in notNames2) { - const notName = notNames2[i3]; - if (notName && value === notName) { - issues.push(makeIncorrectNameIssue(entity.id, key, value, langCode)); - continue; - } - } - } if (isGenericName(value, tags)) { issues.provisional = _waitingForNsi; issues.push(makeGenericNameIssue(entity.id, key, value, langCode)); @@ -44410,8 +47010,8 @@ result.push({ type: makeRegExp(type2), subtype: makeRegExp(subtype) }); }); return result; - function makeRegExp(str2) { - const escaped = str2.replace(/[-\/\\^$+?.()|[\]{}]/g, "\\$&").replace(/\*/g, ".*"); + function makeRegExp(str) { + const escaped = str.replace(/[-\/\\^$+?.()|[\]{}]/g, "\\$&").replace(/\*/g, ".*"); return new RegExp("^" + escaped + "$"); } } @@ -45028,10 +47628,10 @@ } } function detectConflicts() { - function choice(id2, text2, action) { + function choice(id2, text, action) { return { id: id2, - text: text2, + text, action: function() { history.replace(action); } @@ -45158,8 +47758,8 @@ var entity = context.hasEntity(_conflicts[i3].id); if (entity && entity.type === "way") { var children2 = utilArrayUniq(entity.nodes); - for (var j3 = 0; j3 < children2.length; j3++) { - history.replace(actionRevert(children2[j3])); + for (var j2 = 0; j2 < children2.length; j2++) { + history.replace(actionRevert(children2[j2])); } } history.replace(actionRevert(_conflicts[i3].id)); @@ -45288,7 +47888,7 @@ return source; }; source.url = function(coord2) { - var result = _template.replace(new RegExp("#[\\s\\S]*", "u"), ""); + var result = _template.replace(/#[\s\S]*/u, ""); if (result === "") return result; if (!source.type || source.id === "custom") { @@ -45542,7 +48142,7 @@ inflight[tileID] = true; json_default(url).then(function(result) { delete inflight[tileID]; - result = result.features.map((f3) => f3.attributes).filter((a2) => a2.MinMapLevel <= zoom && a2.MaxMapLevel >= zoom)[0]; + result = result.features.map((f2) => f2.attributes).filter((a2) => a2.MinMapLevel <= zoom && a2.MaxMapLevel >= zoom)[0]; if (!result) { throw new Error("Unknown Error"); } else if (result.features && result.features.length < 1) { @@ -45612,7 +48212,7 @@ if (cleaned.indexOf("?") !== -1) { var parts = cleaned.split("?", 2); var qs = utilStringQs(parts[1]); - ["access_token", "connectId", "token"].forEach(function(param) { + ["access_token", "connectId", "token", "Signature"].forEach(function(param) { if (qs[param]) { qs[param] = "{apikey}"; } @@ -45688,8 +48288,8 @@ if (ring.length < 4) { throw new Error("Each LinearRing of a Polygon must have 4 or more Positions."); } - for (var j3 = 0; j3 < ring[ring.length - 1].length; j3++) { - if (ring[ring.length - 1][j3] !== ring[0][j3]) { + for (var j2 = 0; j2 < ring[ring.length - 1].length; j2++) { + if (ring[ring.length - 1][j2] !== ring[0][j2]) { throw new Error("First and last Position are not equivalent."); } } @@ -45872,7 +48472,7 @@ function coordEach(geojson, callback, excludeWrapCoord) { if (geojson === null) return; - var j3, k2, l2, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, coordIndex = 0, isGeometryCollection, type2 = geojson.type, isFeatureCollection = type2 === "FeatureCollection", isFeature = type2 === "Feature", stop = isFeatureCollection ? geojson.features.length : 1; + var j2, k2, l2, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, coordIndex = 0, isGeometryCollection, type2 = geojson.type, isFeatureCollection = type2 === "FeatureCollection", isFeature = type2 === "Feature", stop = isFeatureCollection ? geojson.features.length : 1; for (var featureIndex = 0; featureIndex < stop; featureIndex++) { geometryMaybeCollection = isFeatureCollection ? geojson.features[featureIndex].geometry : isFeature ? geojson.geometry : geojson; isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === "GeometryCollection" : false; @@ -45903,9 +48503,9 @@ break; case "LineString": case "MultiPoint": - for (j3 = 0; j3 < coords.length; j3++) { + for (j2 = 0; j2 < coords.length; j2++) { if (callback( - coords[j3], + coords[j2], coordIndex, featureIndex, multiFeatureIndex, @@ -45921,10 +48521,10 @@ break; case "Polygon": case "MultiLineString": - for (j3 = 0; j3 < coords.length; j3++) { - for (k2 = 0; k2 < coords[j3].length - wrapShrink; k2++) { + for (j2 = 0; j2 < coords.length; j2++) { + for (k2 = 0; k2 < coords[j2].length - wrapShrink; k2++) { if (callback( - coords[j3][k2], + coords[j2][k2], coordIndex, featureIndex, multiFeatureIndex, @@ -45942,12 +48542,12 @@ multiFeatureIndex++; break; case "MultiPolygon": - for (j3 = 0; j3 < coords.length; j3++) { + for (j2 = 0; j2 < coords.length; j2++) { geometryIndex = 0; - for (k2 = 0; k2 < coords[j3].length; k2++) { - for (l2 = 0; l2 < coords[j3][k2].length - wrapShrink; l2++) { + for (k2 = 0; k2 < coords[j2].length; k2++) { + for (l2 = 0; l2 < coords[j2][k2].length - wrapShrink; l2++) { if (callback( - coords[j3][k2][l2], + coords[j2][k2][l2], coordIndex, featureIndex, multiFeatureIndex, @@ -45962,8 +48562,8 @@ } break; case "GeometryCollection": - for (j3 = 0; j3 < geometry.geometries.length; j3++) - if (coordEach(geometry.geometries[j3], callback, excludeWrapCoord) === false) + for (j2 = 0; j2 < geometry.geometries.length; j2++) + if (coordEach(geometry.geometries[j2], callback, excludeWrapCoord) === false) return false; break; default: @@ -46708,12486 +49308,10820 @@ if (osmLifecyclePrefixes[s2] || osmLifecyclePrefixes[tags[s2]]) return true; } - return false; - }); - defineRule("others", function isOther(tags, geometry) { - return geometry === "line" || geometry === "area"; - }); - features.features = function() { - return _rules; - }; - features.keys = function() { - return _keys; - }; - features.enabled = function(k2) { - if (!arguments.length) { - return _keys.filter(function(k3) { - return _rules[k3].enabled; - }); - } - return _rules[k2] && _rules[k2].enabled; - }; - features.disabled = function(k2) { - if (!arguments.length) { - return _keys.filter(function(k3) { - return !_rules[k3].enabled; - }); - } - return _rules[k2] && !_rules[k2].enabled; - }; - features.hidden = function(k2) { - if (!arguments.length) { - return _keys.filter(function(k3) { - return _rules[k3].hidden(); - }); - } - return _rules[k2] && _rules[k2].hidden(); - }; - features.autoHidden = function(k2) { - if (!arguments.length) { - return _keys.filter(function(k3) { - return _rules[k3].autoHidden(); - }); - } - return _rules[k2] && _rules[k2].autoHidden(); - }; - features.enable = function(k2) { - if (_rules[k2] && !_rules[k2].enabled) { - _rules[k2].enable(); - update(); - } - }; - features.enableAll = function() { - var didEnable = false; - for (var k2 in _rules) { - if (!_rules[k2].enabled) { - didEnable = true; - _rules[k2].enable(); - } - } - if (didEnable) - update(); - }; - features.disable = function(k2) { - if (_rules[k2] && _rules[k2].enabled) { - _rules[k2].disable(); - update(); - } - }; - features.disableAll = function() { - var didDisable = false; - for (var k2 in _rules) { - if (_rules[k2].enabled) { - didDisable = true; - _rules[k2].disable(); - } - } - if (didDisable) - update(); - }; - features.toggle = function(k2) { - if (_rules[k2]) { - (function(f3) { - return f3.enabled ? f3.disable() : f3.enable(); - })(_rules[k2]); - update(); - } - }; - features.resetStats = function() { - for (var i3 = 0; i3 < _keys.length; i3++) { - _rules[_keys[i3]].count = 0; - } - dispatch14.call("change"); - }; - features.gatherStats = function(d2, resolver, dimensions) { - var needsRedraw = false; - var types = utilArrayGroupBy(d2, "type"); - var entities = [].concat(types.relation || [], types.way || [], types.node || []); - var currHidden, geometry, matches, i3, j3; - for (i3 = 0; i3 < _keys.length; i3++) { - _rules[_keys[i3]].count = 0; - } - _cullFactor = dimensions[0] * dimensions[1] / 1e6; - for (i3 = 0; i3 < entities.length; i3++) { - geometry = entities[i3].geometry(resolver); - matches = Object.keys(features.getMatches(entities[i3], resolver, geometry)); - for (j3 = 0; j3 < matches.length; j3++) { - _rules[matches[j3]].count++; - } - } - currHidden = features.hidden(); - if (currHidden !== _hidden) { - _hidden = currHidden; - needsRedraw = true; - dispatch14.call("change"); - } - return needsRedraw; - }; - features.stats = function() { - for (var i3 = 0; i3 < _keys.length; i3++) { - _stats[_keys[i3]] = _rules[_keys[i3]].count; - } - return _stats; - }; - features.clear = function(d2) { - for (var i3 = 0; i3 < d2.length; i3++) { - features.clearEntity(d2[i3]); - } - }; - features.clearEntity = function(entity) { - delete _cache5[osmEntity.key(entity)]; - }; - features.reset = function() { - Array.from(_deferred2).forEach(function(handle) { - window.cancelIdleCallback(handle); - _deferred2.delete(handle); - }); - _cache5 = {}; - }; - function relationShouldBeChecked(relation) { - return relation.tags.type === "boundary"; - } - features.getMatches = function(entity, resolver, geometry) { - if (geometry === "vertex" || geometry === "relation" && !relationShouldBeChecked(entity)) - return {}; - var ent = osmEntity.key(entity); - if (!_cache5[ent]) { - _cache5[ent] = {}; - } - if (!_cache5[ent].matches) { - var matches = {}; - var hasMatch = false; - for (var i3 = 0; i3 < _keys.length; i3++) { - if (_keys[i3] === "others") { - if (hasMatch) - continue; - if (entity.type === "way") { - var parents = features.getParents(entity, resolver, geometry); - if (parents.length === 1 && parents[0].isMultipolygon() || // 2b. or belongs only to boundary relations - parents.length > 0 && parents.every(function(parent) { - return parent.tags.type === "boundary"; - })) { - var pkey = osmEntity.key(parents[0]); - if (_cache5[pkey] && _cache5[pkey].matches) { - matches = Object.assign({}, _cache5[pkey].matches); - continue; - } - } - } - } - if (_rules[_keys[i3]].filter(entity.tags, geometry)) { - matches[_keys[i3]] = hasMatch = true; - } - } - _cache5[ent].matches = matches; - } - return _cache5[ent].matches; - }; - features.getParents = function(entity, resolver, geometry) { - if (geometry === "point") - return []; - var ent = osmEntity.key(entity); - if (!_cache5[ent]) { - _cache5[ent] = {}; - } - if (!_cache5[ent].parents) { - var parents = []; - if (geometry === "vertex") { - parents = resolver.parentWays(entity); - } else { - parents = resolver.parentRelations(entity); - } - _cache5[ent].parents = parents; - } - return _cache5[ent].parents; - }; - features.isHiddenPreset = function(preset, geometry) { - if (!_hidden.length) - return false; - if (!preset.tags) - return false; - var test = preset.setTags({}, geometry); - for (var key in _rules) { - if (_rules[key].filter(test, geometry)) { - if (_hidden.indexOf(key) !== -1) { - return key; - } - return false; - } - } - return false; - }; - features.isHiddenFeature = function(entity, resolver, geometry) { - if (!_hidden.length) - return false; - if (!entity.version) - return false; - if (_forceVisible[entity.id]) - return false; - var matches = Object.keys(features.getMatches(entity, resolver, geometry)); - return matches.length && matches.every(function(k2) { - return features.hidden(k2); - }); - }; - features.isHiddenChild = function(entity, resolver, geometry) { - if (!_hidden.length) - return false; - if (!entity.version || geometry === "point") - return false; - if (_forceVisible[entity.id]) - return false; - var parents = features.getParents(entity, resolver, geometry); - if (!parents.length) - return false; - for (var i3 = 0; i3 < parents.length; i3++) { - if (!features.isHidden(parents[i3], resolver, parents[i3].geometry(resolver))) { - return false; - } - } - return true; - }; - features.hasHiddenConnections = function(entity, resolver) { - if (!_hidden.length) - return false; - var childNodes, connections; - if (entity.type === "midpoint") { - childNodes = [resolver.entity(entity.edge[0]), resolver.entity(entity.edge[1])]; - connections = []; - } else { - childNodes = entity.nodes ? resolver.childNodes(entity) : []; - connections = features.getParents(entity, resolver, entity.geometry(resolver)); - } - connections = childNodes.reduce(function(result, e3) { - return resolver.isShared(e3) ? utilArrayUnion(result, resolver.parentWays(e3)) : result; - }, connections); - return connections.some(function(e3) { - return features.isHidden(e3, resolver, e3.geometry(resolver)); - }); - }; - features.isHidden = function(entity, resolver, geometry) { - if (!_hidden.length) - return false; - if (!entity.version) - return false; - var fn = geometry === "vertex" ? features.isHiddenChild : features.isHiddenFeature; - return fn(entity, resolver, geometry); - }; - features.filter = function(d2, resolver) { - if (!_hidden.length) - return d2; - var result = []; - for (var i3 = 0; i3 < d2.length; i3++) { - var entity = d2[i3]; - if (!features.isHidden(entity, resolver, entity.geometry(resolver))) { - result.push(entity); - } - } - return result; - }; - features.forceVisible = function(entityIDs) { - if (!arguments.length) - return Object.keys(_forceVisible); - _forceVisible = {}; - for (var i3 = 0; i3 < entityIDs.length; i3++) { - _forceVisible[entityIDs[i3]] = true; - var entity = context.hasEntity(entityIDs[i3]); - if (entity && entity.type === "relation") { - for (var j3 in entity.members) { - _forceVisible[entity.members[j3].id] = true; - } - } - } - return features; - }; - features.init = function() { - var storage = corePreferences("disabled-features"); - if (storage) { - var storageDisabled = storage.replace(/;/g, ",").split(","); - storageDisabled.forEach(features.disable); - } - var hash = utilStringQs(window.location.hash); - if (hash.disable_features) { - var hashDisabled = hash.disable_features.replace(/;/g, ",").split(","); - hashDisabled.forEach(features.disable); - } - }; - context.history().on("merge.features", function(newEntities) { - if (!newEntities) - return; - var handle = window.requestIdleCallback(function() { - var graph = context.graph(); - var types = utilArrayGroupBy(newEntities, "type"); - var entities = [].concat(types.relation || [], types.way || [], types.node || []); - for (var i3 = 0; i3 < entities.length; i3++) { - var geometry = entities[i3].geometry(graph); - features.getMatches(entities[i3], graph, geometry); - } - }); - _deferred2.add(handle); - }); - return features; - } - - // modules/svg/areas.js - var import_fast_deep_equal5 = __toESM(require_fast_deep_equal()); - - // modules/svg/helpers.js - function svgPassiveVertex(node, graph, activeID) { - if (!activeID) - return 1; - if (activeID === node.id) - return 0; - var parents = graph.parentWays(node); - var i3, j3, nodes, isClosed, ix1, ix2, ix3, ix4, max3; - for (i3 = 0; i3 < parents.length; i3++) { - nodes = parents[i3].nodes; - isClosed = parents[i3].isClosed(); - for (j3 = 0; j3 < nodes.length; j3++) { - if (nodes[j3] === node.id) { - ix1 = j3 - 2; - ix2 = j3 - 1; - ix3 = j3 + 1; - ix4 = j3 + 2; - if (isClosed) { - max3 = nodes.length - 1; - if (ix1 < 0) - ix1 = max3 + ix1; - if (ix2 < 0) - ix2 = max3 + ix2; - if (ix3 > max3) - ix3 = ix3 - max3; - if (ix4 > max3) - ix4 = ix4 - max3; - } - if (nodes[ix1] === activeID) - return 0; - else if (nodes[ix2] === activeID) - return 2; - else if (nodes[ix3] === activeID) - return 2; - else if (nodes[ix4] === activeID) - return 0; - else if (isClosed && nodes.indexOf(activeID) !== -1) - return 0; - } - } - } - return 1; - } - function svgMarkerSegments(projection2, graph, dt2, shouldReverse, bothDirections) { - return function(entity) { - var i3 = 0; - var offset = dt2; - var segments = []; - var clip = identity_default2().clipExtent(projection2.clipExtent()).stream; - var coordinates = graph.childNodes(entity).map(function(n3) { - return n3.loc; - }); - var a2, b2; - if (shouldReverse(entity)) { - coordinates.reverse(); - } - stream_default({ - type: "LineString", - coordinates - }, projection2.stream(clip({ - lineStart: function() { - }, - lineEnd: function() { - a2 = null; - }, - point: function(x2, y2) { - b2 = [x2, y2]; - if (a2) { - var span = geoVecLength(a2, b2) - offset; - if (span >= 0) { - var heading = geoVecAngle(a2, b2); - var dx = dt2 * Math.cos(heading); - var dy = dt2 * Math.sin(heading); - var p2 = [ - a2[0] + offset * Math.cos(heading), - a2[1] + offset * Math.sin(heading) - ]; - var coord2 = [a2, p2]; - for (span -= dt2; span >= 0; span -= dt2) { - p2 = geoVecAdd(p2, [dx, dy]); - coord2.push(p2); - } - coord2.push(b2); - var segment = ""; - var j3; - for (j3 = 0; j3 < coord2.length; j3++) { - segment += (j3 === 0 ? "M" : "L") + coord2[j3][0] + "," + coord2[j3][1]; - } - segments.push({ id: entity.id, index: i3++, d: segment }); - if (bothDirections(entity)) { - segment = ""; - for (j3 = coord2.length - 1; j3 >= 0; j3--) { - segment += (j3 === coord2.length - 1 ? "M" : "L") + coord2[j3][0] + "," + coord2[j3][1]; - } - segments.push({ id: entity.id, index: i3++, d: segment }); - } - } - offset = -span; - } - a2 = b2; - } - }))); - return segments; - }; - } - function svgPath(projection2, graph, isArea) { - var cache = {}; - var padding = isArea ? 65 : 5; - var viewport = projection2.clipExtent(); - var paddedExtent = [ - [viewport[0][0] - padding, viewport[0][1] - padding], - [viewport[1][0] + padding, viewport[1][1] + padding] - ]; - var clip = identity_default2().clipExtent(paddedExtent).stream; - var project = projection2.stream; - var path = path_default().projection({ stream: function(output) { - return project(clip(output)); - } }); - var svgpath = function(entity) { - if (entity.id in cache) { - return cache[entity.id]; - } else { - return cache[entity.id] = path(entity.asGeoJSON(graph)); - } - }; - svgpath.geojson = function(d2) { - if (d2.__featurehash__ !== void 0) { - if (d2.__featurehash__ in cache) { - return cache[d2.__featurehash__]; - } else { - return cache[d2.__featurehash__] = path(d2); - } - } else { - return path(d2); - } - }; - return svgpath; - } - function svgPointTransform(projection2) { - var svgpoint = function(entity) { - var pt2 = projection2(entity.loc); - return "translate(" + pt2[0] + "," + pt2[1] + ")"; + return false; + }); + defineRule("others", function isOther(tags, geometry) { + return geometry === "line" || geometry === "area"; + }); + features.features = function() { + return _rules; }; - svgpoint.geojson = function(d2) { - return svgpoint(d2.properties.entity); + features.keys = function() { + return _keys; }; - return svgpoint; - } - function svgRelationMemberTags(graph) { - return function(entity) { - var tags = entity.tags; - var shouldCopyMultipolygonTags = !entity.hasInterestingTags(); - graph.parentRelations(entity).forEach(function(relation) { - var type2 = relation.tags.type; - if (type2 === "multipolygon" && shouldCopyMultipolygonTags || type2 === "boundary") { - tags = Object.assign({}, relation.tags, tags); - } - }); - return tags; + features.enabled = function(k2) { + if (!arguments.length) { + return _keys.filter(function(k3) { + return _rules[k3].enabled; + }); + } + return _rules[k2] && _rules[k2].enabled; }; - } - function svgSegmentWay(way, graph, activeID) { - if (activeID === void 0) { - return graph.transient(way, "waySegments", getWaySegments); - } else { - return getWaySegments(); - } - function getWaySegments() { - var isActiveWay = way.nodes.indexOf(activeID) !== -1; - var features = { passive: [], active: [] }; - var start2 = {}; - var end = {}; - var node, type2; - for (var i3 = 0; i3 < way.nodes.length; i3++) { - node = graph.entity(way.nodes[i3]); - type2 = svgPassiveVertex(node, graph, activeID); - end = { node, type: type2 }; - if (start2.type !== void 0) { - if (start2.node.id === activeID || end.node.id === activeID) { - } else if (isActiveWay && (start2.type === 2 || end.type === 2)) { - pushActive(start2, end, i3); - } else if (start2.type === 0 && end.type === 0) { - pushActive(start2, end, i3); - } else { - pushPassive(start2, end, i3); - } - } - start2 = end; + features.disabled = function(k2) { + if (!arguments.length) { + return _keys.filter(function(k3) { + return !_rules[k3].enabled; + }); } - return features; - function pushActive(start3, end2, index) { - features.active.push({ - type: "Feature", - id: way.id + "-" + index + "-nope", - properties: { - nope: true, - target: true, - entity: way, - nodes: [start3.node, end2.node], - index - }, - geometry: { - type: "LineString", - coordinates: [start3.node.loc, end2.node.loc] - } + return _rules[k2] && !_rules[k2].enabled; + }; + features.hidden = function(k2) { + if (!arguments.length) { + return _keys.filter(function(k3) { + return _rules[k3].hidden(); }); } - function pushPassive(start3, end2, index) { - features.passive.push({ - type: "Feature", - id: way.id + "-" + index, - properties: { - target: true, - entity: way, - nodes: [start3.node, end2.node], - index - }, - geometry: { - type: "LineString", - coordinates: [start3.node.loc, end2.node.loc] - } + return _rules[k2] && _rules[k2].hidden(); + }; + features.autoHidden = function(k2) { + if (!arguments.length) { + return _keys.filter(function(k3) { + return _rules[k3].autoHidden(); }); } - } - } - - // modules/svg/tag_classes.js - function svgTagClasses() { - var primaries = [ - "building", - "highway", - "railway", - "waterway", - "aeroway", - "aerialway", - "piste:type", - "boundary", - "power", - "amenity", - "natural", - "landuse", - "leisure", - "military", - "place", - "man_made", - "route", - "attraction", - "building:part", - "indoor" - ]; - var statuses = Object.keys(osmLifecyclePrefixes); - var secondaries = [ - "oneway", - "bridge", - "tunnel", - "embankment", - "cutting", - "barrier", - "surface", - "tracktype", - "footway", - "crossing", - "service", - "sport", - "public_transport", - "location", - "parking", - "golf", - "type", - "leisure", - "man_made", - "indoor", - "construction", - "proposed" - ]; - var _tags = function(entity) { - return entity.tags; + return _rules[k2] && _rules[k2].autoHidden(); }; - var tagClasses = function(selection2) { - selection2.each(function tagClassesEach(entity) { - var value = this.className; - if (value.baseVal !== void 0) { - value = value.baseVal; - } - var t2 = _tags(entity); - var computed = tagClasses.getClassesString(t2, value); - if (computed !== value) { - select_default2(this).attr("class", computed); - } - }); + features.enable = function(k2) { + if (_rules[k2] && !_rules[k2].enabled) { + _rules[k2].enable(); + update(); + } }; - tagClasses.getClassesString = function(t2, value) { - var primary, status; - var i3, j3, k2, v2; - var overrideGeometry; - if (/\bstroke\b/.test(value)) { - if (!!t2.barrier && t2.barrier !== "no") { - overrideGeometry = "line"; + features.enableAll = function() { + var didEnable = false; + for (var k2 in _rules) { + if (!_rules[k2].enabled) { + didEnable = true; + _rules[k2].enable(); } } - var classes = value.trim().split(/\s+/).filter(function(klass) { - return klass.length && !/^tag-/.test(klass); - }).map(function(klass) { - return klass === "line" || klass === "area" ? overrideGeometry || klass : klass; - }); - for (i3 = 0; i3 < primaries.length; i3++) { - k2 = primaries[i3]; - v2 = t2[k2]; - if (!v2 || v2 === "no") - continue; - if (k2 === "piste:type") { - k2 = "piste"; - } else if (k2 === "building:part") { - k2 = "building_part"; - } - primary = k2; - if (statuses.indexOf(v2) !== -1) { - status = v2; - classes.push("tag-" + k2); - } else { - classes.push("tag-" + k2); - classes.push("tag-" + k2 + "-" + v2); - } - break; + if (didEnable) + update(); + }; + features.disable = function(k2) { + if (_rules[k2] && _rules[k2].enabled) { + _rules[k2].disable(); + update(); } - if (!primary) { - for (i3 = 0; i3 < statuses.length; i3++) { - for (j3 = 0; j3 < primaries.length; j3++) { - k2 = statuses[i3] + ":" + primaries[j3]; - v2 = t2[k2]; - if (!v2 || v2 === "no") - continue; - status = statuses[i3]; - break; - } + }; + features.disableAll = function() { + var didDisable = false; + for (var k2 in _rules) { + if (_rules[k2].enabled) { + didDisable = true; + _rules[k2].disable(); } } - if (!status) { - for (i3 = 0; i3 < statuses.length; i3++) { - k2 = statuses[i3]; - v2 = t2[k2]; - if (!v2 || v2 === "no") - continue; - if (v2 === "yes") { - status = k2; - } else if (primary && primary === v2) { - status = k2; - } else if (!primary && primaries.indexOf(v2) !== -1) { - status = k2; - primary = v2; - classes.push("tag-" + v2); - } - if (status) - break; - } + if (didDisable) + update(); + }; + features.toggle = function(k2) { + if (_rules[k2]) { + (function(f2) { + return f2.enabled ? f2.disable() : f2.enable(); + })(_rules[k2]); + update(); } - if (status) { - classes.push("tag-status"); - classes.push("tag-status-" + status); + }; + features.resetStats = function() { + for (var i3 = 0; i3 < _keys.length; i3++) { + _rules[_keys[i3]].count = 0; } - for (i3 = 0; i3 < secondaries.length; i3++) { - k2 = secondaries[i3]; - v2 = t2[k2]; - if (!v2 || v2 === "no" || k2 === primary) - continue; - classes.push("tag-" + k2); - classes.push("tag-" + k2 + "-" + v2); + dispatch14.call("change"); + }; + features.gatherStats = function(d2, resolver, dimensions) { + var needsRedraw = false; + var types = utilArrayGroupBy(d2, "type"); + var entities = [].concat(types.relation || [], types.way || [], types.node || []); + var currHidden, geometry, matches, i3, j2; + for (i3 = 0; i3 < _keys.length; i3++) { + _rules[_keys[i3]].count = 0; } - if (primary === "highway" && !osmPathHighwayTagValues[t2.highway] || primary === "aeroway") { - var surface = t2.highway === "track" ? "unpaved" : "paved"; - for (k2 in t2) { - v2 = t2[k2]; - if (k2 in osmPavedTags) { - surface = osmPavedTags[k2][v2] ? "paved" : "unpaved"; - } - if (k2 in osmSemipavedTags && !!osmSemipavedTags[k2][v2]) { - surface = "semipaved"; - } + _cullFactor = dimensions[0] * dimensions[1] / 1e6; + for (i3 = 0; i3 < entities.length; i3++) { + geometry = entities[i3].geometry(resolver); + matches = Object.keys(features.getMatches(entities[i3], resolver, geometry)); + for (j2 = 0; j2 < matches.length; j2++) { + _rules[matches[j2]].count++; } - classes.push("tag-" + surface); } - var qid = t2.wikidata || t2["flag:wikidata"] || t2["brand:wikidata"] || t2["network:wikidata"] || t2["operator:wikidata"]; - if (qid) { - classes.push("tag-wikidata"); + currHidden = features.hidden(); + if (currHidden !== _hidden) { + _hidden = currHidden; + needsRedraw = true; + dispatch14.call("change"); } - return classes.filter((klass) => /^[-_a-z0-9]+$/.test(klass)).join(" ").trim(); + return needsRedraw; }; - tagClasses.tags = function(val) { - if (!arguments.length) - return _tags; - _tags = val; - return tagClasses; + features.stats = function() { + for (var i3 = 0; i3 < _keys.length; i3++) { + _stats[_keys[i3]] = _rules[_keys[i3]].count; + } + return _stats; }; - return tagClasses; - } - - // modules/svg/tag_pattern.js - var patterns = { - // tag - pattern name - // -or- - // tag - value - pattern name - // -or- - // tag - value - rules (optional tag-values, pattern name) - // (matches earlier rules first, so fallback should be last entry) - amenity: { - grave_yard: "cemetery", - fountain: "water_standing" - }, - landuse: { - cemetery: [ - { religion: "christian", pattern: "cemetery_christian" }, - { religion: "buddhist", pattern: "cemetery_buddhist" }, - { religion: "muslim", pattern: "cemetery_muslim" }, - { religion: "jewish", pattern: "cemetery_jewish" }, - { pattern: "cemetery" } - ], - construction: "construction", - farmland: "farmland", - farmyard: "farmyard", - forest: [ - { leaf_type: "broadleaved", pattern: "forest_broadleaved" }, - { leaf_type: "needleleaved", pattern: "forest_needleleaved" }, - { leaf_type: "leafless", pattern: "forest_leafless" }, - { pattern: "forest" } - // same as 'leaf_type:mixed' - ], - grave_yard: "cemetery", - grass: "grass", - landfill: "landfill", - meadow: "meadow", - military: "construction", - orchard: "orchard", - quarry: "quarry", - vineyard: "vineyard" - }, - leisure: { - horse_riding: "farmyard" - }, - natural: { - beach: "beach", - grassland: "grass", - sand: "beach", - scrub: "scrub", - water: [ - { water: "pond", pattern: "pond" }, - { water: "reservoir", pattern: "water_standing" }, - { pattern: "waves" } - ], - wetland: [ - { wetland: "marsh", pattern: "wetland_marsh" }, - { wetland: "swamp", pattern: "wetland_swamp" }, - { wetland: "bog", pattern: "wetland_bog" }, - { wetland: "reedbed", pattern: "wetland_reedbed" }, - { pattern: "wetland" } - ], - wood: [ - { leaf_type: "broadleaved", pattern: "forest_broadleaved" }, - { leaf_type: "needleleaved", pattern: "forest_needleleaved" }, - { leaf_type: "leafless", pattern: "forest_leafless" }, - { pattern: "forest" } - // same as 'leaf_type:mixed' - ] - }, - golf: { - green: "golf_green", - tee: "grass", - fairway: "grass", - rough: "scrub" - }, - surface: { - grass: "grass", - sand: "beach" - } - }; - function svgTagPattern(tags) { - if (tags.building && tags.building !== "no") { - return null; + features.clear = function(d2) { + for (var i3 = 0; i3 < d2.length; i3++) { + features.clearEntity(d2[i3]); + } + }; + features.clearEntity = function(entity) { + delete _cache5[osmEntity.key(entity)]; + }; + features.reset = function() { + Array.from(_deferred2).forEach(function(handle) { + window.cancelIdleCallback(handle); + _deferred2.delete(handle); + }); + _cache5 = {}; + }; + function relationShouldBeChecked(relation) { + return relation.tags.type === "boundary"; } - for (var tag in patterns) { - var entityValue = tags[tag]; - if (!entityValue) - continue; - if (typeof patterns[tag] === "string") { - return "pattern-" + patterns[tag]; - } else { - var values = patterns[tag]; - for (var value in values) { - if (entityValue !== value) - continue; - var rules = values[value]; - if (typeof rules === "string") { - return "pattern-" + rules; - } - for (var ruleKey in rules) { - var rule = rules[ruleKey]; - var pass = true; - for (var criterion in rule) { - if (criterion !== "pattern") { - var v2 = tags[criterion]; - if (!v2 || v2 !== rule[criterion]) { - pass = false; - break; + features.getMatches = function(entity, resolver, geometry) { + if (geometry === "vertex" || geometry === "relation" && !relationShouldBeChecked(entity)) + return {}; + var ent = osmEntity.key(entity); + if (!_cache5[ent]) { + _cache5[ent] = {}; + } + if (!_cache5[ent].matches) { + var matches = {}; + var hasMatch = false; + for (var i3 = 0; i3 < _keys.length; i3++) { + if (_keys[i3] === "others") { + if (hasMatch) + continue; + if (entity.type === "way") { + var parents = features.getParents(entity, resolver, geometry); + if (parents.length === 1 && parents[0].isMultipolygon() || // 2b. or belongs only to boundary relations + parents.length > 0 && parents.every(function(parent) { + return parent.tags.type === "boundary"; + })) { + var pkey = osmEntity.key(parents[0]); + if (_cache5[pkey] && _cache5[pkey].matches) { + matches = Object.assign({}, _cache5[pkey].matches); + continue; } } } - if (pass) { - return "pattern-" + rule.pattern; - } + } + if (_rules[_keys[i3]].filter(entity.tags, geometry)) { + matches[_keys[i3]] = hasMatch = true; } } + _cache5[ent].matches = matches; } - } - return null; - } - - // modules/svg/areas.js - function svgAreas(projection2, context) { - function getPatternStyle(tags) { - var imageID = svgTagPattern(tags); - if (imageID) { - return 'url("#ideditor-' + imageID + '")'; + return _cache5[ent].matches; + }; + features.getParents = function(entity, resolver, geometry) { + if (geometry === "point") + return []; + var ent = osmEntity.key(entity); + if (!_cache5[ent]) { + _cache5[ent] = {}; + } + if (!_cache5[ent].parents) { + var parents = []; + if (geometry === "vertex") { + parents = resolver.parentWays(entity); + } else { + parents = resolver.parentRelations(entity); + } + _cache5[ent].parents = parents; + } + return _cache5[ent].parents; + }; + features.isHiddenPreset = function(preset, geometry) { + if (!_hidden.length) + return false; + if (!preset.tags) + return false; + var test = preset.setTags({}, geometry); + for (var key in _rules) { + if (_rules[key].filter(test, geometry)) { + if (_hidden.indexOf(key) !== -1) { + return key; + } + return false; + } } - return ""; - } - function drawTargets(selection2, graph, entities, filter2) { - var targetClass = context.getDebug("target") ? "pink " : "nocolor "; - var nopeClass = context.getDebug("target") ? "red " : "nocolor "; - var getPath = svgPath(projection2).geojson; - var activeID = context.activeID(); - var base = context.history().base(); - var data = { targets: [], nopes: [] }; - entities.forEach(function(way) { - var features = svgSegmentWay(way, graph, activeID); - data.targets.push.apply(data.targets, features.passive); - data.nopes.push.apply(data.nopes, features.active); - }); - var targetData = data.targets.filter(getPath); - var targets = selection2.selectAll(".area.target-allowed").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(targetData, function key(d2) { - return d2.id; + return false; + }; + features.isHiddenFeature = function(entity, resolver, geometry) { + if (!_hidden.length) + return false; + if (!entity.version) + return false; + if (_forceVisible[entity.id]) + return false; + var matches = Object.keys(features.getMatches(entity, resolver, geometry)); + return matches.length && matches.every(function(k2) { + return features.hidden(k2); }); - targets.exit().remove(); - var segmentWasEdited = function(d2) { - var wayID = d2.properties.entity.id; - if (!base.entities[wayID] || !(0, import_fast_deep_equal5.default)(graph.entities[wayID].nodes, base.entities[wayID].nodes)) { + }; + features.isHiddenChild = function(entity, resolver, geometry) { + if (!_hidden.length) + return false; + if (!entity.version || geometry === "point") + return false; + if (_forceVisible[entity.id]) + return false; + var parents = features.getParents(entity, resolver, geometry); + if (!parents.length) + return false; + for (var i3 = 0; i3 < parents.length; i3++) { + if (!features.isHidden(parents[i3], resolver, parents[i3].geometry(resolver))) { return false; } - return d2.properties.nodes.some(function(n3) { - return !base.entities[n3.id] || !(0, import_fast_deep_equal5.default)(graph.entities[n3.id].loc, base.entities[n3.id].loc); - }); - }; - targets.enter().append("path").merge(targets).attr("d", getPath).attr("class", function(d2) { - return "way area target target-allowed " + targetClass + d2.id; - }).classed("segment-edited", segmentWasEdited); - var nopeData = data.nopes.filter(getPath); - var nopes = selection2.selectAll(".area.target-nope").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(nopeData, function key(d2) { - return d2.id; + } + return true; + }; + features.hasHiddenConnections = function(entity, resolver) { + if (!_hidden.length) + return false; + var childNodes, connections; + if (entity.type === "midpoint") { + childNodes = [resolver.entity(entity.edge[0]), resolver.entity(entity.edge[1])]; + connections = []; + } else { + childNodes = entity.nodes ? resolver.childNodes(entity) : []; + connections = features.getParents(entity, resolver, entity.geometry(resolver)); + } + connections = childNodes.reduce(function(result, e3) { + return resolver.isShared(e3) ? utilArrayUnion(result, resolver.parentWays(e3)) : result; + }, connections); + return connections.some(function(e3) { + return features.isHidden(e3, resolver, e3.geometry(resolver)); }); - nopes.exit().remove(); - nopes.enter().append("path").merge(nopes).attr("d", getPath).attr("class", function(d2) { - return "way area target target-nope " + nopeClass + d2.id; - }).classed("segment-edited", segmentWasEdited); - } - function drawAreas(selection2, graph, entities, filter2) { - var path = svgPath(projection2, graph, true); - var areas = {}; - var multipolygon; - var base = context.history().base(); - for (var i3 = 0; i3 < entities.length; i3++) { - var entity = entities[i3]; - if (entity.geometry(graph) !== "area") - continue; - multipolygon = osmIsOldMultipolygonOuterMember(entity, graph); - if (multipolygon) { - areas[multipolygon.id] = { - entity: multipolygon.mergeTags(entity.tags), - area: Math.abs(entity.area(graph)) - }; - } else if (!areas[entity.id]) { - areas[entity.id] = { - entity, - area: Math.abs(entity.area(graph)) - }; + }; + features.isHidden = function(entity, resolver, geometry) { + if (!_hidden.length) + return false; + if (!entity.version) + return false; + var fn = geometry === "vertex" ? features.isHiddenChild : features.isHiddenFeature; + return fn(entity, resolver, geometry); + }; + features.filter = function(d2, resolver) { + if (!_hidden.length) + return d2; + var result = []; + for (var i3 = 0; i3 < d2.length; i3++) { + var entity = d2[i3]; + if (!features.isHidden(entity, resolver, entity.geometry(resolver))) { + result.push(entity); } } - var fills = Object.values(areas).filter(function hasPath(a2) { - return path(a2.entity); - }); - fills.sort(function areaSort(a2, b2) { - return b2.area - a2.area; - }); - fills = fills.map(function(a2) { - return a2.entity; - }); - var strokes = fills.filter(function(area) { - return area.type === "way"; - }); - var data = { - clip: fills, - shadow: strokes, - stroke: strokes, - fill: fills - }; - var clipPaths = context.surface().selectAll("defs").selectAll(".clipPath-osm").filter(filter2).data(data.clip, osmEntity.key); - clipPaths.exit().remove(); - var clipPathsEnter = clipPaths.enter().append("clipPath").attr("class", "clipPath-osm").attr("id", function(entity2) { - return "ideditor-" + entity2.id + "-clippath"; - }); - clipPathsEnter.append("path"); - clipPaths.merge(clipPathsEnter).selectAll("path").attr("d", path); - var drawLayer = selection2.selectAll(".layer-osm.areas"); - var touchLayer = selection2.selectAll(".layer-touch.areas"); - var areagroup = drawLayer.selectAll("g.areagroup").data(["fill", "shadow", "stroke"]); - areagroup = areagroup.enter().append("g").attr("class", function(d2) { - return "areagroup area-" + d2; - }).merge(areagroup); - var paths = areagroup.selectAll("path").filter(filter2).data(function(layer) { - return data[layer]; - }, osmEntity.key); - paths.exit().remove(); - var fillpaths = selection2.selectAll(".area-fill path.area").nodes(); - var bisect = bisector(function(node) { - return -node.__data__.area(graph); - }).left; - function sortedByArea(entity2) { - if (this._parent.__data__ === "fill") { - return fillpaths[bisect(fillpaths, -entity2.area(graph))]; + return result; + }; + features.forceVisible = function(entityIDs) { + if (!arguments.length) + return Object.keys(_forceVisible); + _forceVisible = {}; + for (var i3 = 0; i3 < entityIDs.length; i3++) { + _forceVisible[entityIDs[i3]] = true; + var entity = context.hasEntity(entityIDs[i3]); + if (entity && entity.type === "relation") { + for (var j2 in entity.members) { + _forceVisible[entity.members[j2].id] = true; + } } } - paths = paths.enter().insert("path", sortedByArea).merge(paths).each(function(entity2) { - var layer = this.parentNode.__data__; - this.setAttribute("class", entity2.type + " area " + layer + " " + entity2.id); - if (layer === "fill") { - this.setAttribute("clip-path", "url(#ideditor-" + entity2.id + "-clippath)"); - this.style.fill = this.style.stroke = getPatternStyle(entity2.tags); + return features; + }; + features.init = function() { + var storage = corePreferences("disabled-features"); + if (storage) { + var storageDisabled = storage.replace(/;/g, ",").split(","); + storageDisabled.forEach(features.disable); + } + var hash = utilStringQs(window.location.hash); + if (hash.disable_features) { + var hashDisabled = hash.disable_features.replace(/;/g, ",").split(","); + hashDisabled.forEach(features.disable); + } + }; + context.history().on("merge.features", function(newEntities) { + if (!newEntities) + return; + var handle = window.requestIdleCallback(function() { + var graph = context.graph(); + var types = utilArrayGroupBy(newEntities, "type"); + var entities = [].concat(types.relation || [], types.way || [], types.node || []); + for (var i3 = 0; i3 < entities.length; i3++) { + var geometry = entities[i3].geometry(graph); + features.getMatches(entities[i3], graph, geometry); } - }).classed("added", function(d2) { - return !base.entities[d2.id]; - }).classed("geometry-edited", function(d2) { - return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal5.default)(graph.entities[d2.id].nodes, base.entities[d2.id].nodes); - }).classed("retagged", function(d2) { - return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal5.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); - }).call(svgTagClasses()).attr("d", path); - touchLayer.call(drawTargets, graph, data.stroke, filter2); - } - return drawAreas; + }); + _deferred2.add(handle); + }); + return features; } - // modules/svg/data.js - var import_fast_json_stable_stringify = __toESM(require_fast_json_stable_stringify()); + // modules/svg/areas.js + var import_fast_deep_equal5 = __toESM(require_fast_deep_equal()); - // node_modules/@tmcw/togeojson/dist/togeojson.es.mjs - function $(element, tagName) { - return Array.from(element.getElementsByTagName(tagName)); - } - function normalizeId(id2) { - return id2[0] === "#" ? id2 : "#".concat(id2); - } - function $ns(element, tagName, ns) { - return Array.from(element.getElementsByTagNameNS(ns, tagName)); - } - function nodeVal(node) { - node == null ? void 0 : node.normalize(); - return node && node.textContent || ""; - } - function get1(node, tagName, callback) { - const n3 = node.getElementsByTagName(tagName); - const result = n3.length ? n3[0] : null; - if (result && callback) - callback(result); - return result; - } - function get3(node, tagName, callback) { - const properties = {}; - if (!node) - return properties; - const n3 = node.getElementsByTagName(tagName); - const result = n3.length ? n3[0] : null; - if (result && callback) { - return callback(result, properties); + // modules/svg/helpers.js + function svgPassiveVertex(node, graph, activeID) { + if (!activeID) + return 1; + if (activeID === node.id) + return 0; + var parents = graph.parentWays(node); + var i3, j2, nodes, isClosed, ix1, ix2, ix3, ix4, max3; + for (i3 = 0; i3 < parents.length; i3++) { + nodes = parents[i3].nodes; + isClosed = parents[i3].isClosed(); + for (j2 = 0; j2 < nodes.length; j2++) { + if (nodes[j2] === node.id) { + ix1 = j2 - 2; + ix2 = j2 - 1; + ix3 = j2 + 1; + ix4 = j2 + 2; + if (isClosed) { + max3 = nodes.length - 1; + if (ix1 < 0) + ix1 = max3 + ix1; + if (ix2 < 0) + ix2 = max3 + ix2; + if (ix3 > max3) + ix3 = ix3 - max3; + if (ix4 > max3) + ix4 = ix4 - max3; + } + if (nodes[ix1] === activeID) + return 0; + else if (nodes[ix2] === activeID) + return 2; + else if (nodes[ix3] === activeID) + return 2; + else if (nodes[ix4] === activeID) + return 0; + else if (isClosed && nodes.indexOf(activeID) !== -1) + return 0; + } + } } - return properties; - } - function val1(node, tagName, callback) { - const val = nodeVal(get1(node, tagName)); - if (val && callback) - return callback(val) || {}; - return {}; - } - function $num(node, tagName, callback) { - const val = parseFloat(nodeVal(get1(node, tagName))); - if (isNaN(val)) - return void 0; - if (val && callback) - return callback(val) || {}; - return {}; - } - function num1(node, tagName, callback) { - const val = parseFloat(nodeVal(get1(node, tagName))); - if (isNaN(val)) - return void 0; - if (callback) - callback(val); - return val; + return 1; } - function getMulti(node, propertyNames) { - const properties = {}; - for (const property of propertyNames) { - val1(node, property, (val) => { - properties[property] = val; + function svgMarkerSegments(projection2, graph, dt2, shouldReverse, bothDirections) { + return function(entity) { + var i3 = 0; + var offset = dt2; + var segments = []; + var clip = identity_default2().clipExtent(projection2.clipExtent()).stream; + var coordinates = graph.childNodes(entity).map(function(n3) { + return n3.loc; }); - } - return properties; - } - function isElement(node) { - return (node == null ? void 0 : node.nodeType) === 1; - } - function getLineStyle(node) { - return get3(node, "line", (lineStyle) => { - const val = Object.assign({}, val1(lineStyle, "color", (color2) => { - return { stroke: "#".concat(color2) }; - }), $num(lineStyle, "opacity", (opacity) => { - return { "stroke-opacity": opacity }; - }), $num(lineStyle, "width", (width) => { - return { "stroke-width": width * 96 / 25.4 }; - })); - return val; - }); + var a2, b2; + if (shouldReverse(entity)) { + coordinates.reverse(); + } + stream_default({ + type: "LineString", + coordinates + }, projection2.stream(clip({ + lineStart: function() { + }, + lineEnd: function() { + a2 = null; + }, + point: function(x2, y2) { + b2 = [x2, y2]; + if (a2) { + var span = geoVecLength(a2, b2) - offset; + if (span >= 0) { + var heading2 = geoVecAngle(a2, b2); + var dx = dt2 * Math.cos(heading2); + var dy = dt2 * Math.sin(heading2); + var p2 = [ + a2[0] + offset * Math.cos(heading2), + a2[1] + offset * Math.sin(heading2) + ]; + var coord2 = [a2, p2]; + for (span -= dt2; span >= 0; span -= dt2) { + p2 = geoVecAdd(p2, [dx, dy]); + coord2.push(p2); + } + coord2.push(b2); + var segment = ""; + var j2; + for (j2 = 0; j2 < coord2.length; j2++) { + segment += (j2 === 0 ? "M" : "L") + coord2[j2][0] + "," + coord2[j2][1]; + } + segments.push({ id: entity.id, index: i3++, d: segment }); + if (bothDirections(entity)) { + segment = ""; + for (j2 = coord2.length - 1; j2 >= 0; j2--) { + segment += (j2 === coord2.length - 1 ? "M" : "L") + coord2[j2][0] + "," + coord2[j2][1]; + } + segments.push({ id: entity.id, index: i3++, d: segment }); + } + } + offset = -span; + } + a2 = b2; + } + }))); + return segments; + }; } - function getExtensions(node) { - let values = []; - if (node === null) - return values; - for (const child of Array.from(node.childNodes)) { - if (!isElement(child)) - continue; - const name = abbreviateName(child.nodeName); - if (name === "gpxtpx:TrackPointExtension") { - values = values.concat(getExtensions(child)); + function svgPath(projection2, graph, isArea) { + var cache = {}; + var padding = isArea ? 65 : 5; + var viewport = projection2.clipExtent(); + var paddedExtent = [ + [viewport[0][0] - padding, viewport[0][1] - padding], + [viewport[1][0] + padding, viewport[1][1] + padding] + ]; + var clip = identity_default2().clipExtent(paddedExtent).stream; + var project = projection2.stream; + var path = path_default().projection({ stream: function(output) { + return project(clip(output)); + } }); + var svgpath = function(entity) { + if (entity.id in cache) { + return cache[entity.id]; } else { - const val = nodeVal(child); - values.push([name, parseNumeric(val)]); + return cache[entity.id] = path(entity.asGeoJSON(graph)); } - } - return values; - } - function abbreviateName(name) { - return ["heart", "gpxtpx:hr", "hr"].includes(name) ? "heart" : name; + }; + svgpath.geojson = function(d2) { + if (d2.__featurehash__ !== void 0) { + if (d2.__featurehash__ in cache) { + return cache[d2.__featurehash__]; + } else { + return cache[d2.__featurehash__] = path(d2); + } + } else { + return path(d2); + } + }; + return svgpath; } - function parseNumeric(val) { - const num = parseFloat(val); - return isNaN(num) ? val : num; + function svgPointTransform(projection2) { + var svgpoint = function(entity) { + var pt2 = projection2(entity.loc); + return "translate(" + pt2[0] + "," + pt2[1] + ")"; + }; + svgpoint.geojson = function(d2) { + return svgpoint(d2.properties.entity); + }; + return svgpoint; } - function coordPair$1(node) { - const ll = [ - parseFloat(node.getAttribute("lon") || ""), - parseFloat(node.getAttribute("lat") || "") - ]; - if (isNaN(ll[0]) || isNaN(ll[1])) { - return null; - } - num1(node, "ele", (val) => { - ll.push(val); - }); - const time = get1(node, "time"); - return { - coordinates: ll, - time: time ? nodeVal(time) : null, - extendedValues: getExtensions(get1(node, "extensions")) + function svgRelationMemberTags(graph) { + return function(entity) { + var tags = entity.tags; + var shouldCopyMultipolygonTags = !entity.hasInterestingTags(); + graph.parentRelations(entity).forEach(function(relation) { + var type2 = relation.tags.type; + if (type2 === "multipolygon" && shouldCopyMultipolygonTags || type2 === "boundary") { + tags = Object.assign({}, relation.tags, tags); + } + }); + return tags; }; } - function extractProperties(node) { - var _a; - const properties = getMulti(node, [ - "name", - "cmt", - "desc", - "type", - "time", - "keywords" - ]); - const extensions = Array.from(node.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3", "*")); - for (const child of extensions) { - if (((_a = child.parentNode) == null ? void 0 : _a.parentNode) === node) { - properties[child.tagName.replace(":", "_")] = nodeVal(child); + function svgSegmentWay(way, graph, activeID) { + if (activeID === void 0) { + return graph.transient(way, "waySegments", getWaySegments); + } else { + return getWaySegments(); + } + function getWaySegments() { + var isActiveWay = way.nodes.indexOf(activeID) !== -1; + var features = { passive: [], active: [] }; + var start2 = {}; + var end = {}; + var node, type2; + for (var i3 = 0; i3 < way.nodes.length; i3++) { + node = graph.entity(way.nodes[i3]); + type2 = svgPassiveVertex(node, graph, activeID); + end = { node, type: type2 }; + if (start2.type !== void 0) { + if (start2.node.id === activeID || end.node.id === activeID) { + } else if (isActiveWay && (start2.type === 2 || end.type === 2)) { + pushActive(start2, end, i3); + } else if (start2.type === 0 && end.type === 0) { + pushActive(start2, end, i3); + } else { + pushPassive(start2, end, i3); + } + } + start2 = end; } - } - const links = $(node, "link"); - if (links.length) { - properties.links = links.map((link2) => Object.assign({ href: link2.getAttribute("href") }, getMulti(link2, ["text", "type"]))); - } - return properties; - } - function getPoints$1(node, pointname) { - const pts = $(node, pointname); - const line = []; - const times = []; - const extendedValues = {}; - for (let i3 = 0; i3 < pts.length; i3++) { - const c2 = coordPair$1(pts[i3]); - if (!c2) { - continue; + return features; + function pushActive(start3, end2, index) { + features.active.push({ + type: "Feature", + id: way.id + "-" + index + "-nope", + properties: { + nope: true, + target: true, + entity: way, + nodes: [start3.node, end2.node], + index + }, + geometry: { + type: "LineString", + coordinates: [start3.node.loc, end2.node.loc] + } + }); } - line.push(c2.coordinates); - if (c2.time) - times.push(c2.time); - for (const [name, val] of c2.extendedValues) { - const plural = name === "heart" ? name : name.replace("gpxtpx:", "") + "s"; - if (!extendedValues[plural]) { - extendedValues[plural] = Array(pts.length).fill(null); - } - extendedValues[plural][i3] = val; + function pushPassive(start3, end2, index) { + features.passive.push({ + type: "Feature", + id: way.id + "-" + index, + properties: { + target: true, + entity: way, + nodes: [start3.node, end2.node], + index + }, + geometry: { + type: "LineString", + coordinates: [start3.node.loc, end2.node.loc] + } + }); } } - if (line.length < 2) - return; - return { - line, - times, - extendedValues - }; } - function getRoute(node) { - const line = getPoints$1(node, "rtept"); - if (!line) - return; - return { - type: "Feature", - properties: Object.assign({ _gpxType: "rte" }, extractProperties(node), getLineStyle(get1(node, "extensions"))), - geometry: { - type: "LineString", - coordinates: line.line - } + + // modules/svg/tag_classes.js + function svgTagClasses() { + var primaries = [ + "building", + "highway", + "railway", + "waterway", + "aeroway", + "aerialway", + "piste:type", + "boundary", + "power", + "amenity", + "natural", + "landuse", + "leisure", + "military", + "place", + "man_made", + "route", + "attraction", + "roller_coaster", + "building:part", + "indoor" + ]; + var statuses = Object.keys(osmLifecyclePrefixes); + var secondaries = [ + "oneway", + "bridge", + "tunnel", + "embankment", + "cutting", + "barrier", + "surface", + "tracktype", + "footway", + "crossing", + "service", + "sport", + "public_transport", + "location", + "parking", + "golf", + "type", + "leisure", + "man_made", + "indoor", + "construction", + "proposed" + ]; + var _tags = function(entity) { + return entity.tags; }; - } - function getTrack(node) { - const segments = $(node, "trkseg"); - const track = []; - const times = []; - const extractedLines = []; - for (const segment of segments) { - const line = getPoints$1(segment, "trkpt"); - if (line) { - extractedLines.push(line); - if (line.times && line.times.length) - times.push(line.times); + var tagClasses = function(selection2) { + selection2.each(function tagClassesEach(entity) { + var value = this.className; + if (value.baseVal !== void 0) { + value = value.baseVal; + } + var t2 = _tags(entity); + var computed = tagClasses.getClassesString(t2, value); + if (computed !== value) { + select_default2(this).attr("class", computed); + } + }); + }; + tagClasses.getClassesString = function(t2, value) { + var primary, status; + var i3, j2, k2, v2; + var overrideGeometry; + if (/\bstroke\b/.test(value)) { + if (!!t2.barrier && t2.barrier !== "no") { + overrideGeometry = "line"; + } } - } - if (extractedLines.length === 0) - return null; - const multi = extractedLines.length > 1; - const properties = Object.assign({ _gpxType: "trk" }, extractProperties(node), getLineStyle(get1(node, "extensions")), times.length ? { - coordinateProperties: { - times: multi ? times : times[0] + var classes = value.trim().split(/\s+/).filter(function(klass) { + return klass.length && !/^tag-/.test(klass); + }).map(function(klass) { + return klass === "line" || klass === "area" ? overrideGeometry || klass : klass; + }); + for (i3 = 0; i3 < primaries.length; i3++) { + k2 = primaries[i3]; + v2 = t2[k2]; + if (!v2 || v2 === "no") + continue; + if (k2 === "piste:type") { + k2 = "piste"; + } else if (k2 === "building:part") { + k2 = "building_part"; + } + primary = k2; + if (statuses.indexOf(v2) !== -1) { + status = v2; + classes.push("tag-" + k2); + } else { + classes.push("tag-" + k2); + classes.push("tag-" + k2 + "-" + v2); + } + break; } - } : {}); - for (const line of extractedLines) { - track.push(line.line); - if (!properties.coordinateProperties) { - properties.coordinateProperties = {}; + if (!primary) { + for (i3 = 0; i3 < statuses.length; i3++) { + for (j2 = 0; j2 < primaries.length; j2++) { + k2 = statuses[i3] + ":" + primaries[j2]; + v2 = t2[k2]; + if (!v2 || v2 === "no") + continue; + status = statuses[i3]; + break; + } + } } - const props = properties.coordinateProperties; - const entries = Object.entries(line.extendedValues); - for (let i3 = 0; i3 < entries.length; i3++) { - const [name, val] = entries[i3]; - if (multi) { - if (!props[name]) { - props[name] = extractedLines.map((line2) => new Array(line2.line.length).fill(null)); + if (!status) { + for (i3 = 0; i3 < statuses.length; i3++) { + k2 = statuses[i3]; + v2 = t2[k2]; + if (!v2 || v2 === "no") + continue; + if (v2 === "yes") { + status = k2; + } else if (primary && primary === v2) { + status = k2; + } else if (!primary && primaries.indexOf(v2) !== -1) { + status = k2; + primary = v2; + classes.push("tag-" + v2); } - props[name][i3] = val; - } else { - props[name] = val; + if (status) + break; } } - } - return { - type: "Feature", - properties, - geometry: multi ? { - type: "MultiLineString", - coordinates: track - } : { - type: "LineString", - coordinates: track[0] + if (status) { + classes.push("tag-status"); + classes.push("tag-status-" + status); } - }; - } - function getPoint(node) { - const properties = Object.assign(extractProperties(node), getMulti(node, ["sym"])); - const pair3 = coordPair$1(node); - if (!pair3) - return null; - return { - type: "Feature", - properties, - geometry: { - type: "Point", - coordinates: pair3.coordinates + for (i3 = 0; i3 < secondaries.length; i3++) { + k2 = secondaries[i3]; + v2 = t2[k2]; + if (!v2 || v2 === "no" || k2 === primary) + continue; + classes.push("tag-" + k2); + classes.push("tag-" + k2 + "-" + v2); + } + if (primary === "highway" && !osmPathHighwayTagValues[t2.highway] || primary === "aeroway") { + var surface = t2.highway === "track" ? "unpaved" : "paved"; + for (k2 in t2) { + v2 = t2[k2]; + if (k2 in osmPavedTags) { + surface = osmPavedTags[k2][v2] ? "paved" : "unpaved"; + } + if (k2 in osmSemipavedTags && !!osmSemipavedTags[k2][v2]) { + surface = "semipaved"; + } + } + classes.push("tag-" + surface); + } + var qid = t2.wikidata || t2["flag:wikidata"] || t2["brand:wikidata"] || t2["network:wikidata"] || t2["operator:wikidata"]; + if (qid) { + classes.push("tag-wikidata"); } + return classes.filter((klass) => /^[-_a-z0-9]+$/.test(klass)).join(" ").trim(); }; - } - function* gpxGen(node) { - for (const track of $(node, "trk")) { - const feature3 = getTrack(track); - if (feature3) - yield feature3; - } - for (const route of $(node, "rte")) { - const feature3 = getRoute(route); - if (feature3) - yield feature3; - } - for (const waypoint of $(node, "wpt")) { - const point2 = getPoint(waypoint); - if (point2) - yield point2; - } - } - function gpx(node) { - return { - type: "FeatureCollection", - features: Array.from(gpxGen(node)) + tagClasses.tags = function(val) { + if (!arguments.length) + return _tags; + _tags = val; + return tagClasses; }; + return tagClasses; } - function fixColor(v2, prefix) { - const properties = {}; - const colorProp = prefix == "stroke" || prefix === "fill" ? prefix : prefix + "-color"; - if (v2[0] === "#") { - v2 = v2.substring(1); - } - if (v2.length === 6 || v2.length === 3) { - properties[colorProp] = "#" + v2; - } else if (v2.length === 8) { - properties[prefix + "-opacity"] = parseInt(v2.substring(0, 2), 16) / 255; - properties[colorProp] = "#" + v2.substring(6, 8) + v2.substring(4, 6) + v2.substring(2, 4); + + // modules/svg/tag_pattern.js + var patterns = { + // tag - pattern name + // -or- + // tag - value - pattern name + // -or- + // tag - value - rules (optional tag-values, pattern name) + // (matches earlier rules first, so fallback should be last entry) + amenity: { + grave_yard: "cemetery", + fountain: "water_standing" + }, + landuse: { + cemetery: [ + { religion: "christian", pattern: "cemetery_christian" }, + { religion: "buddhist", pattern: "cemetery_buddhist" }, + { religion: "muslim", pattern: "cemetery_muslim" }, + { religion: "jewish", pattern: "cemetery_jewish" }, + { pattern: "cemetery" } + ], + construction: "construction", + farmland: "farmland", + farmyard: "farmyard", + forest: [ + { leaf_type: "broadleaved", pattern: "forest_broadleaved" }, + { leaf_type: "needleleaved", pattern: "forest_needleleaved" }, + { leaf_type: "leafless", pattern: "forest_leafless" }, + { pattern: "forest" } + // same as 'leaf_type:mixed' + ], + grave_yard: "cemetery", + grass: "grass", + landfill: "landfill", + meadow: "meadow", + military: "construction", + orchard: "orchard", + quarry: "quarry", + vineyard: "vineyard" + }, + leisure: { + horse_riding: "farmyard" + }, + natural: { + beach: "beach", + grassland: "grass", + sand: "beach", + scrub: "scrub", + water: [ + { water: "pond", pattern: "pond" }, + { water: "reservoir", pattern: "water_standing" }, + { pattern: "waves" } + ], + wetland: [ + { wetland: "marsh", pattern: "wetland_marsh" }, + { wetland: "swamp", pattern: "wetland_swamp" }, + { wetland: "bog", pattern: "wetland_bog" }, + { wetland: "reedbed", pattern: "wetland_reedbed" }, + { pattern: "wetland" } + ], + wood: [ + { leaf_type: "broadleaved", pattern: "forest_broadleaved" }, + { leaf_type: "needleleaved", pattern: "forest_needleleaved" }, + { leaf_type: "leafless", pattern: "forest_leafless" }, + { pattern: "forest" } + // same as 'leaf_type:mixed' + ] + }, + golf: { + green: "golf_green", + tee: "grass", + fairway: "grass", + rough: "scrub" + }, + surface: { + grass: "grass", + sand: "beach" } - return properties; - } - function numericProperty(node, source, target) { - const properties = {}; - num1(node, source, (val) => { - properties[target] = val; - }); - return properties; - } - function getColor(node, output) { - return get3(node, "color", (elem) => fixColor(nodeVal(elem), output)); - } - function extractIconHref(node) { - return get3(node, "Icon", (icon2, properties) => { - val1(icon2, "href", (href) => { - properties.icon = href; - }); - return properties; - }); - } - function extractIcon(node) { - return get3(node, "IconStyle", (iconStyle) => { - return Object.assign(getColor(iconStyle, "icon"), numericProperty(iconStyle, "scale", "icon-scale"), numericProperty(iconStyle, "heading", "icon-heading"), get3(iconStyle, "hotSpot", (hotspot) => { - const left = parseFloat(hotspot.getAttribute("x") || ""); - const top = parseFloat(hotspot.getAttribute("y") || ""); - const xunits = hotspot.getAttribute("xunits") || ""; - const yunits = hotspot.getAttribute("yunits") || ""; - if (!isNaN(left) && !isNaN(top)) - return { - "icon-offset": [left, top], - "icon-offset-units": [xunits, yunits] - }; - return {}; - }), extractIconHref(iconStyle)); - }); - } - function extractLabel(node) { - return get3(node, "LabelStyle", (labelStyle) => { - return Object.assign(getColor(labelStyle, "label"), numericProperty(labelStyle, "scale", "label-scale")); - }); - } - function extractLine(node) { - return get3(node, "LineStyle", (lineStyle) => { - return Object.assign(getColor(lineStyle, "stroke"), numericProperty(lineStyle, "width", "stroke-width")); - }); - } - function extractPoly(node) { - return get3(node, "PolyStyle", (polyStyle, properties) => { - return Object.assign(properties, get3(polyStyle, "color", (elem) => fixColor(nodeVal(elem), "fill")), val1(polyStyle, "fill", (fill) => { - if (fill === "0") - return { "fill-opacity": 0 }; - }), val1(polyStyle, "outline", (outline) => { - if (outline === "0") - return { "stroke-opacity": 0 }; - })); - }); - } - function extractStyle(node) { - return Object.assign({}, extractPoly(node), extractLine(node), extractLabel(node), extractIcon(node)); - } - var toNumber2 = (x2) => Number(x2); - var typeConverters = { - string: (x2) => x2, - int: toNumber2, - uint: toNumber2, - short: toNumber2, - ushort: toNumber2, - float: toNumber2, - double: toNumber2, - bool: (x2) => Boolean(x2) }; - function extractExtendedData(node, schema) { - return get3(node, "ExtendedData", (extendedData, properties) => { - for (const data of $(extendedData, "Data")) { - properties[data.getAttribute("name") || ""] = nodeVal(get1(data, "value")); - } - for (const simpleData of $(extendedData, "SimpleData")) { - const name = simpleData.getAttribute("name") || ""; - const typeConverter = schema[name] || typeConverters.string; - properties[name] = typeConverter(nodeVal(simpleData)); - } - return properties; - }); - } - function getMaybeHTMLDescription(node) { - const descriptionNode = get1(node, "description"); - for (const c2 of Array.from((descriptionNode == null ? void 0 : descriptionNode.childNodes) || [])) { - if (c2.nodeType === 4) { - return { - description: { - "@type": "html", - value: nodeVal(c2) + function svgTagPattern(tags) { + if (tags.building && tags.building !== "no") { + return null; + } + for (var tag2 in patterns) { + var entityValue = tags[tag2]; + if (!entityValue) + continue; + if (typeof patterns[tag2] === "string") { + return "pattern-" + patterns[tag2]; + } else { + var values = patterns[tag2]; + for (var value in values) { + if (entityValue !== value) + continue; + var rules = values[value]; + if (typeof rules === "string") { + return "pattern-" + rules; + } + for (var ruleKey in rules) { + var rule = rules[ruleKey]; + var pass = true; + for (var criterion in rule) { + if (criterion !== "pattern") { + var v2 = tags[criterion]; + if (!v2 || v2 !== rule[criterion]) { + pass = false; + break; + } + } + } + if (pass) { + return "pattern-" + rule.pattern; + } } - }; + } } } - return {}; + return null; } - function extractTimeSpan(node) { - return get3(node, "TimeSpan", (timeSpan) => { - return { - timespan: { - begin: nodeVal(get1(timeSpan, "begin")), - end: nodeVal(get1(timeSpan, "end")) + + // modules/svg/areas.js + function svgAreas(projection2, context) { + function getPatternStyle(tags) { + var imageID = svgTagPattern(tags); + if (imageID) { + return 'url("#ideditor-' + imageID + '")'; + } + return ""; + } + function drawTargets(selection2, graph, entities, filter2) { + var targetClass = context.getDebug("target") ? "pink " : "nocolor "; + var nopeClass = context.getDebug("target") ? "red " : "nocolor "; + var getPath = svgPath(projection2).geojson; + var activeID = context.activeID(); + var base = context.history().base(); + var data = { targets: [], nopes: [] }; + entities.forEach(function(way) { + var features = svgSegmentWay(way, graph, activeID); + data.targets.push.apply(data.targets, features.passive); + data.nopes.push.apply(data.nopes, features.active); + }); + var targetData = data.targets.filter(getPath); + var targets = selection2.selectAll(".area.target-allowed").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(targetData, function key(d2) { + return d2.id; + }); + targets.exit().remove(); + var segmentWasEdited = function(d2) { + var wayID = d2.properties.entity.id; + if (!base.entities[wayID] || !(0, import_fast_deep_equal5.default)(graph.entities[wayID].nodes, base.entities[wayID].nodes)) { + return false; } + return d2.properties.nodes.some(function(n3) { + return !base.entities[n3.id] || !(0, import_fast_deep_equal5.default)(graph.entities[n3.id].loc, base.entities[n3.id].loc); + }); }; - }); + targets.enter().append("path").merge(targets).attr("d", getPath).attr("class", function(d2) { + return "way area target target-allowed " + targetClass + d2.id; + }).classed("segment-edited", segmentWasEdited); + var nopeData = data.nopes.filter(getPath); + var nopes = selection2.selectAll(".area.target-nope").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(nopeData, function key(d2) { + return d2.id; + }); + nopes.exit().remove(); + nopes.enter().append("path").merge(nopes).attr("d", getPath).attr("class", function(d2) { + return "way area target target-nope " + nopeClass + d2.id; + }).classed("segment-edited", segmentWasEdited); + } + function drawAreas(selection2, graph, entities, filter2) { + var path = svgPath(projection2, graph, true); + var areas = {}; + var multipolygon; + var base = context.history().base(); + for (var i3 = 0; i3 < entities.length; i3++) { + var entity = entities[i3]; + if (entity.geometry(graph) !== "area") + continue; + multipolygon = osmIsOldMultipolygonOuterMember(entity, graph); + if (multipolygon) { + areas[multipolygon.id] = { + entity: multipolygon.mergeTags(entity.tags), + area: Math.abs(entity.area(graph)) + }; + } else if (!areas[entity.id]) { + areas[entity.id] = { + entity, + area: Math.abs(entity.area(graph)) + }; + } + } + var fills = Object.values(areas).filter(function hasPath(a2) { + return path(a2.entity); + }); + fills.sort(function areaSort(a2, b2) { + return b2.area - a2.area; + }); + fills = fills.map(function(a2) { + return a2.entity; + }); + var strokes = fills.filter(function(area) { + return area.type === "way"; + }); + var data = { + clip: fills, + shadow: strokes, + stroke: strokes, + fill: fills + }; + var clipPaths = context.surface().selectAll("defs").selectAll(".clipPath-osm").filter(filter2).data(data.clip, osmEntity.key); + clipPaths.exit().remove(); + var clipPathsEnter = clipPaths.enter().append("clipPath").attr("class", "clipPath-osm").attr("id", function(entity2) { + return "ideditor-" + entity2.id + "-clippath"; + }); + clipPathsEnter.append("path"); + clipPaths.merge(clipPathsEnter).selectAll("path").attr("d", path); + var drawLayer = selection2.selectAll(".layer-osm.areas"); + var touchLayer = selection2.selectAll(".layer-touch.areas"); + var areagroup = drawLayer.selectAll("g.areagroup").data(["fill", "shadow", "stroke"]); + areagroup = areagroup.enter().append("g").attr("class", function(d2) { + return "areagroup area-" + d2; + }).merge(areagroup); + var paths = areagroup.selectAll("path").filter(filter2).data(function(layer) { + return data[layer]; + }, osmEntity.key); + paths.exit().remove(); + var fillpaths = selection2.selectAll(".area-fill path.area").nodes(); + var bisect = bisector(function(node) { + return -node.__data__.area(graph); + }).left; + function sortedByArea(entity2) { + if (this._parent.__data__ === "fill") { + return fillpaths[bisect(fillpaths, -entity2.area(graph))]; + } + } + paths = paths.enter().insert("path", sortedByArea).merge(paths).each(function(entity2) { + var layer = this.parentNode.__data__; + this.setAttribute("class", entity2.type + " area " + layer + " " + entity2.id); + if (layer === "fill") { + this.setAttribute("clip-path", "url(#ideditor-" + entity2.id + "-clippath)"); + this.style.fill = this.style.stroke = getPatternStyle(entity2.tags); + } + }).classed("added", function(d2) { + return !base.entities[d2.id]; + }).classed("geometry-edited", function(d2) { + return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal5.default)(graph.entities[d2.id].nodes, base.entities[d2.id].nodes); + }).classed("retagged", function(d2) { + return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal5.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); + }).call(svgTagClasses()).attr("d", path); + touchLayer.call(drawTargets, graph, data.stroke, filter2); + } + return drawAreas; } - function extractTimeStamp(node) { - return get3(node, "TimeStamp", (timeStamp) => { - return { timestamp: nodeVal(get1(timeStamp, "when")) }; - }); + + // modules/svg/data.js + var import_fast_json_stable_stringify = __toESM(require_fast_json_stable_stringify()); + + // node_modules/@tmcw/togeojson/dist/togeojson.es.mjs + function $(element, tagName) { + return Array.from(element.getElementsByTagName(tagName)); } - function extractCascadedStyle(node, styleMap) { - return val1(node, "styleUrl", (styleUrl) => { - styleUrl = normalizeId(styleUrl); - if (styleMap[styleUrl]) { - return Object.assign({ styleUrl }, styleMap[styleUrl]); - } - return { styleUrl }; - }); + function normalizeId(id2) { + return id2[0] === "#" ? id2 : "#".concat(id2); } - var removeSpace = /\s*/g; - var trimSpace = /^\s*|\s*$/g; - var splitSpace = /\s+/; - function coord1(value) { - return value.replace(removeSpace, "").split(",").map(parseFloat).filter((num) => !isNaN(num)).slice(0, 3); + function $ns(element, tagName, ns) { + return Array.from(element.getElementsByTagNameNS(ns, tagName)); } - function coord(value) { - return value.replace(trimSpace, "").split(splitSpace).map(coord1).filter((coord2) => { - return coord2.length >= 2; - }); + function nodeVal(node) { + node == null ? void 0 : node.normalize(); + return node && node.textContent || ""; } - function gxCoords(node) { - let elems = $(node, "coord"); - if (elems.length === 0) { - elems = $ns(node, "coord", "*"); - } - const coordinates = elems.map((elem) => { - return nodeVal(elem).split(" ").map(parseFloat); - }); - if (coordinates.length === 0) { - return null; - } - return { - geometry: coordinates.length > 2 ? { - type: "LineString", - coordinates - } : { - type: "Point", - coordinates: coordinates[0] - }, - times: $(node, "when").map((elem) => nodeVal(elem)) - }; + function get1(node, tagName, callback) { + const n3 = node.getElementsByTagName(tagName); + const result = n3.length ? n3[0] : null; + if (result && callback) + callback(result); + return result; } - function fixRing(ring) { - if (ring.length === 0) - return ring; - const first = ring[0]; - const last = ring[ring.length - 1]; - let equal = true; - for (let i3 = 0; i3 < Math.max(first.length, last.length); i3++) { - if (first[i3] !== last[i3]) { - equal = false; - break; - } - } - if (!equal) { - return ring.concat([ring[0]]); + function get3(node, tagName, callback) { + const properties = {}; + if (!node) + return properties; + const n3 = node.getElementsByTagName(tagName); + const result = n3.length ? n3[0] : null; + if (result && callback) { + return callback(result, properties); } - return ring; + return properties; } - function getCoordinates(node) { - return nodeVal(get1(node, "coordinates")); + function val1(node, tagName, callback) { + const val = nodeVal(get1(node, tagName)); + if (val && callback) + return callback(val) || {}; + return {}; } - function getGeometry(node) { - let geometries = []; - let coordTimes = []; - for (let i3 = 0; i3 < node.childNodes.length; i3++) { - const child = node.childNodes.item(i3); - if (isElement(child)) { - switch (child.tagName) { - case "MultiGeometry": - case "MultiTrack": - case "gx:MultiTrack": { - const childGeometries = getGeometry(child); - geometries = geometries.concat(childGeometries.geometries); - coordTimes = coordTimes.concat(childGeometries.coordTimes); - break; - } - case "Point": { - const coordinates = coord1(getCoordinates(child)); - if (coordinates.length >= 2) { - geometries.push({ - type: "Point", - coordinates - }); - } - break; - } - case "LinearRing": - case "LineString": { - const coordinates = coord(getCoordinates(child)); - if (coordinates.length >= 2) { - geometries.push({ - type: "LineString", - coordinates - }); - } - break; - } - case "Polygon": { - const coords = []; - for (const linearRing of $(child, "LinearRing")) { - const ring = fixRing(coord(getCoordinates(linearRing))); - if (ring.length >= 4) { - coords.push(ring); - } - } - if (coords.length) { - geometries.push({ - type: "Polygon", - coordinates: coords - }); - } - break; - } - case "Track": - case "gx:Track": { - const gx = gxCoords(child); - if (!gx) - break; - const { times, geometry } = gx; - geometries.push(geometry); - if (times.length) - coordTimes.push(times); - break; - } - } - } - } - return { - geometries, - coordTimes - }; + function $num(node, tagName, callback) { + const val = parseFloat(nodeVal(get1(node, tagName))); + if (isNaN(val)) + return void 0; + if (val && callback) + return callback(val) || {}; + return {}; } - function geometryListToGeometry(geometries) { - return geometries.length === 0 ? null : geometries.length === 1 ? geometries[0] : { - type: "GeometryCollection", - geometries - }; + function num1(node, tagName, callback) { + const val = parseFloat(nodeVal(get1(node, tagName))); + if (isNaN(val)) + return void 0; + if (callback) + callback(val); + return val; } - function getPlacemark(node, styleMap, schema, options2) { - var _a; - const { coordTimes, geometries } = getGeometry(node); - const geometry = geometryListToGeometry(geometries); - if (!geometry && options2.skipNullGeometry) { - return null; - } - const feature3 = { - type: "Feature", - geometry, - properties: Object.assign(getMulti(node, [ - "name", - "address", - "visibility", - "open", - "phoneNumber", - "description" - ]), getMaybeHTMLDescription(node), extractCascadedStyle(node, styleMap), extractStyle(node), extractExtendedData(node, schema), extractTimeSpan(node), extractTimeStamp(node), coordTimes.length ? { - coordinateProperties: { - times: coordTimes.length === 1 ? coordTimes[0] : coordTimes - } - } : {}) - }; - if (((_a = feature3.properties) == null ? void 0 : _a.visibility) !== void 0) { - feature3.properties.visibility = feature3.properties.visibility !== "0"; + function getMulti(node, propertyNames) { + const properties = {}; + for (const property of propertyNames) { + val1(node, property, (val) => { + properties[property] = val; + }); } - const id2 = node.getAttribute("id"); - if (id2 !== null && id2 !== "") - feature3.id = id2; - return feature3; + return properties; } - function getGroundOverlayBox(node) { - const latLonQuad = get1(node, "gx:LatLonQuad"); - if (latLonQuad) { - const ring = fixRing(coord(getCoordinates(node))); - return { - geometry: { - type: "Polygon", - coordinates: [ring] - } - }; - } - return getLatLonBox(node); + function isElement(node) { + return (node == null ? void 0 : node.nodeType) === 1; } - var DEGREES_TO_RADIANS = Math.PI / 180; - function rotateBox(bbox2, coordinates, rotation) { - const center = [(bbox2[0] + bbox2[2]) / 2, (bbox2[1] + bbox2[3]) / 2]; - return [ - coordinates[0].map((coordinate) => { - const dy = coordinate[1] - center[1]; - const dx = coordinate[0] - center[0]; - const distance = Math.sqrt(Math.pow(dy, 2) + Math.pow(dx, 2)); - const angle2 = Math.atan2(dy, dx) + rotation * DEGREES_TO_RADIANS; - return [ - center[0] + Math.cos(angle2) * distance, - center[1] + Math.sin(angle2) * distance - ]; - }) - ]; + function getLineStyle(node) { + return get3(node, "line", (lineStyle) => { + const val = Object.assign({}, val1(lineStyle, "color", (color2) => { + return { stroke: "#".concat(color2) }; + }), $num(lineStyle, "opacity", (opacity) => { + return { "stroke-opacity": opacity }; + }), $num(lineStyle, "width", (width) => { + return { "stroke-width": width * 96 / 25.4 }; + })); + return val; + }); } - function getLatLonBox(node) { - const latLonBox = get1(node, "LatLonBox"); - if (latLonBox) { - const north = num1(latLonBox, "north"); - const west = num1(latLonBox, "west"); - const east = num1(latLonBox, "east"); - const south = num1(latLonBox, "south"); - const rotation = num1(latLonBox, "rotation"); - if (typeof north === "number" && typeof south === "number" && typeof west === "number" && typeof east === "number") { - const bbox2 = [west, south, east, north]; - let coordinates = [ - [ - [west, north], - [east, north], - [east, south], - [west, south], - [west, north] - // top left (again) - ] - ]; - if (typeof rotation === "number") { - coordinates = rotateBox(bbox2, coordinates, rotation); - } - return { - bbox: bbox2, - geometry: { - type: "Polygon", - coordinates - } - }; + function getExtensions(node) { + let values = []; + if (node === null) + return values; + for (const child of Array.from(node.childNodes)) { + if (!isElement(child)) + continue; + const name = abbreviateName(child.nodeName); + if (name === "gpxtpx:TrackPointExtension") { + values = values.concat(getExtensions(child)); + } else { + const val = nodeVal(child); + values.push([name, parseNumeric(val)]); } } - return null; + return values; } - function getGroundOverlay(node, styleMap, schema, options2) { - var _a; - const box = getGroundOverlayBox(node); - const geometry = (box == null ? void 0 : box.geometry) || null; - if (!geometry && options2.skipNullGeometry) { + function abbreviateName(name) { + return ["heart", "gpxtpx:hr", "hr"].includes(name) ? "heart" : name; + } + function parseNumeric(val) { + const num = parseFloat(val); + return isNaN(num) ? val : num; + } + function coordPair$1(node) { + const ll = [ + parseFloat(node.getAttribute("lon") || ""), + parseFloat(node.getAttribute("lat") || "") + ]; + if (isNaN(ll[0]) || isNaN(ll[1])) { return null; } - const feature3 = { - type: "Feature", - geometry, - properties: Object.assign( - /** - * Related to - * https://gist.github.com/tmcw/037a1cb6660d74a392e9da7446540f46 - */ - { "@geometry-type": "groundoverlay" }, - getMulti(node, [ - "name", - "address", - "visibility", - "open", - "phoneNumber", - "description" - ]), - getMaybeHTMLDescription(node), - extractCascadedStyle(node, styleMap), - extractStyle(node), - extractIconHref(node), - extractExtendedData(node, schema), - extractTimeSpan(node), - extractTimeStamp(node) - ) + num1(node, "ele", (val) => { + ll.push(val); + }); + const time = get1(node, "time"); + return { + coordinates: ll, + time: time ? nodeVal(time) : null, + extendedValues: getExtensions(get1(node, "extensions")) }; - if (box == null ? void 0 : box.bbox) { - feature3.bbox = box.bbox; + } + function extractProperties(node) { + var _a2; + const properties = getMulti(node, [ + "name", + "cmt", + "desc", + "type", + "time", + "keywords" + ]); + const extensions = Array.from(node.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3", "*")); + for (const child of extensions) { + if (((_a2 = child.parentNode) == null ? void 0 : _a2.parentNode) === node) { + properties[child.tagName.replace(":", "_")] = nodeVal(child); + } } - if (((_a = feature3.properties) == null ? void 0 : _a.visibility) !== void 0) { - feature3.properties.visibility = feature3.properties.visibility !== "0"; + const links = $(node, "link"); + if (links.length) { + properties.links = links.map((link3) => Object.assign({ href: link3.getAttribute("href") }, getMulti(link3, ["text", "type"]))); } - const id2 = node.getAttribute("id"); - if (id2 !== null && id2 !== "") - feature3.id = id2; - return feature3; + return properties; } - function getStyleId(style) { - let id2 = style.getAttribute("id"); - const parentNode = style.parentNode; - if (!id2 && isElement(parentNode) && parentNode.localName === "CascadingStyle") { - id2 = parentNode.getAttribute("kml:id") || parentNode.getAttribute("id"); + function getPoints$1(node, pointname) { + const pts = $(node, pointname); + const line = []; + const times = []; + const extendedValues = {}; + for (let i3 = 0; i3 < pts.length; i3++) { + const c2 = coordPair$1(pts[i3]); + if (!c2) { + continue; + } + line.push(c2.coordinates); + if (c2.time) + times.push(c2.time); + for (const [name, val] of c2.extendedValues) { + const plural = name === "heart" ? name : name.replace("gpxtpx:", "") + "s"; + if (!extendedValues[plural]) { + extendedValues[plural] = Array(pts.length).fill(null); + } + extendedValues[plural][i3] = val; + } } - return normalizeId(id2 || ""); + if (line.length < 2) + return; + return { + line, + times, + extendedValues + }; } - function buildStyleMap(node) { - const styleMap = {}; - for (const style of $(node, "Style")) { - styleMap[getStyleId(style)] = extractStyle(style); + function getRoute(node) { + const line = getPoints$1(node, "rtept"); + if (!line) + return; + return { + type: "Feature", + properties: Object.assign({ _gpxType: "rte" }, extractProperties(node), getLineStyle(get1(node, "extensions"))), + geometry: { + type: "LineString", + coordinates: line.line + } + }; + } + function getTrack(node) { + const segments = $(node, "trkseg"); + const track = []; + const times = []; + const extractedLines = []; + for (const segment of segments) { + const line = getPoints$1(segment, "trkpt"); + if (line) { + extractedLines.push(line); + if (line.times && line.times.length) + times.push(line.times); + } } - for (const map2 of $(node, "StyleMap")) { - const id2 = normalizeId(map2.getAttribute("id") || ""); - val1(map2, "styleUrl", (styleUrl) => { - styleUrl = normalizeId(styleUrl); - if (styleMap[styleUrl]) { - styleMap[id2] = styleMap[styleUrl]; + if (extractedLines.length === 0) + return null; + const multi = extractedLines.length > 1; + const properties = Object.assign({ _gpxType: "trk" }, extractProperties(node), getLineStyle(get1(node, "extensions")), times.length ? { + coordinateProperties: { + times: multi ? times : times[0] + } + } : {}); + for (const line of extractedLines) { + track.push(line.line); + if (!properties.coordinateProperties) { + properties.coordinateProperties = {}; + } + const props = properties.coordinateProperties; + const entries = Object.entries(line.extendedValues); + for (let i3 = 0; i3 < entries.length; i3++) { + const [name, val] = entries[i3]; + if (multi) { + if (!props[name]) { + props[name] = extractedLines.map((line2) => new Array(line2.line.length).fill(null)); + } + props[name][i3] = val; + } else { + props[name] = val; } - }); + } } - return styleMap; + return { + type: "Feature", + properties, + geometry: multi ? { + type: "MultiLineString", + coordinates: track + } : { + type: "LineString", + coordinates: track[0] + } + }; } - function buildSchema(node) { - const schema = {}; - for (const field of $(node, "SimpleField")) { - schema[field.getAttribute("name") || ""] = typeConverters[field.getAttribute("type") || ""] || typeConverters["string"]; - } - return schema; + function getPoint(node) { + const properties = Object.assign(extractProperties(node), getMulti(node, ["sym"])); + const pair3 = coordPair$1(node); + if (!pair3) + return null; + return { + type: "Feature", + properties, + geometry: { + type: "Point", + coordinates: pair3.coordinates + } + }; } - function* kmlGen(node, options2 = { - skipNullGeometry: false - }) { - const styleMap = buildStyleMap(node); - const schema = buildSchema(node); - for (const placemark of $(node, "Placemark")) { - const feature3 = getPlacemark(placemark, styleMap, schema, options2); + function* gpxGen(node) { + for (const track of $(node, "trk")) { + const feature3 = getTrack(track); if (feature3) yield feature3; } - for (const groundOverlay of $(node, "GroundOverlay")) { - const feature3 = getGroundOverlay(groundOverlay, styleMap, schema, options2); + for (const route of $(node, "rte")) { + const feature3 = getRoute(route); if (feature3) yield feature3; } + for (const waypoint of $(node, "wpt")) { + const point2 = getPoint(waypoint); + if (point2) + yield point2; + } } - function kml(node, options2 = { - skipNullGeometry: false - }) { + function gpx(node) { return { type: "FeatureCollection", - features: Array.from(kmlGen(node, options2)) + features: Array.from(gpxGen(node)) }; } - - // modules/svg/data.js - var _initialized = false; - var _enabled = false; - var _geojson; - function svgData(projection2, context, dispatch14) { - var throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - var _showLabels = true; - var detected = utilDetect(); - var layer = select_default2(null); - var _vtService; - var _fileList; - var _template; - var _src; - const supportedFormats = [ - ".gpx", - ".kml", - ".geojson", - ".json" - ]; - function init2() { - if (_initialized) - return; - _geojson = {}; - _enabled = true; - function over(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - d3_event.dataTransfer.dropEffect = "copy"; - } - context.container().attr("dropzone", "copy").on("drop.svgData", function(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - if (!detected.filedrop) - return; - var f3 = d3_event.dataTransfer.files[0]; - var extension = getExtension(f3.name); - if (!supportedFormats.includes(extension)) - return; - drawData.fileList(d3_event.dataTransfer.files); - }).on("dragenter.svgData", over).on("dragexit.svgData", over).on("dragover.svgData", over); - _initialized = true; - } - function getService() { - if (services.vectorTile && !_vtService) { - _vtService = services.vectorTile; - _vtService.event.on("loadedData", throttledRedraw); - } else if (!services.vectorTile && _vtService) { - _vtService = null; - } - return _vtService; - } - function showLayer() { - layerOn(); - layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { - dispatch14.call("change"); - }); - } - function hideLayer() { - throttledRedraw.cancel(); - layer.transition().duration(250).style("opacity", 0).on("end", layerOff); - } - function layerOn() { - layer.style("display", "block"); - } - function layerOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); - } - function ensureIDs(gj) { - if (!gj) - return null; - if (gj.type === "FeatureCollection") { - for (var i3 = 0; i3 < gj.features.length; i3++) { - ensureFeatureID(gj.features[i3]); - } - } else { - ensureFeatureID(gj); - } - return gj; - } - function ensureFeatureID(feature3) { - if (!feature3) - return; - feature3.__featurehash__ = utilHashcode((0, import_fast_json_stable_stringify.default)(feature3)); - return feature3; - } - function getFeatures(gj) { - if (!gj) - return []; - if (gj.type === "FeatureCollection") { - return gj.features; - } else { - return [gj]; - } - } - function featureKey(d2) { - return d2.__featurehash__; - } - function isPolygon(d2) { - return d2.geometry.type === "Polygon" || d2.geometry.type === "MultiPolygon"; - } - function clipPathID(d2) { - return "ideditor-data-" + d2.__featurehash__ + "-clippath"; + function fixColor(v2, prefix) { + const properties = {}; + const colorProp = prefix == "stroke" || prefix === "fill" ? prefix : prefix + "-color"; + if (v2[0] === "#") { + v2 = v2.substring(1); } - function featureClasses(d2) { - return [ - "data" + d2.__featurehash__, - d2.geometry.type, - isPolygon(d2) ? "area" : "", - d2.__layerID__ || "" - ].filter(Boolean).join(" "); + if (v2.length === 6 || v2.length === 3) { + properties[colorProp] = "#" + v2; + } else if (v2.length === 8) { + properties[prefix + "-opacity"] = parseInt(v2.substring(0, 2), 16) / 255; + properties[colorProp] = "#" + v2.substring(6, 8) + v2.substring(4, 6) + v2.substring(2, 4); } - function drawData(selection2) { - var vtService = getService(); - var getPath = svgPath(projection2).geojson; - var getAreaPath = svgPath(projection2, null, true).geojson; - var hasData = drawData.hasData(); - layer = selection2.selectAll(".layer-mapdata").data(_enabled && hasData ? [0] : []); - layer.exit().remove(); - layer = layer.enter().append("g").attr("class", "layer-mapdata").merge(layer); - var surface = context.surface(); - if (!surface || surface.empty()) - return; - var geoData, polygonData; - if (_template && vtService) { - var sourceID = _template; - vtService.loadTiles(sourceID, _template, projection2); - geoData = vtService.data(sourceID, projection2); - } else { - geoData = getFeatures(_geojson); - } - geoData = geoData.filter(getPath); - polygonData = geoData.filter(isPolygon); - var clipPaths = surface.selectAll("defs").selectAll(".clipPath-data").data(polygonData, featureKey); - clipPaths.exit().remove(); - var clipPathsEnter = clipPaths.enter().append("clipPath").attr("class", "clipPath-data").attr("id", clipPathID); - clipPathsEnter.append("path"); - clipPaths.merge(clipPathsEnter).selectAll("path").attr("d", getAreaPath); - var datagroups = layer.selectAll("g.datagroup").data(["fill", "shadow", "stroke"]); - datagroups = datagroups.enter().append("g").attr("class", function(d2) { - return "datagroup datagroup-" + d2; - }).merge(datagroups); - var pathData = { - fill: polygonData, - shadow: geoData, - stroke: geoData - }; - var paths = datagroups.selectAll("path").data(function(layer2) { - return pathData[layer2]; - }, featureKey); - paths.exit().remove(); - paths = paths.enter().append("path").attr("class", function(d2) { - var datagroup = this.parentNode.__data__; - return "pathdata " + datagroup + " " + featureClasses(d2); - }).attr("clip-path", function(d2) { - var datagroup = this.parentNode.__data__; - return datagroup === "fill" ? "url(#" + clipPathID(d2) + ")" : null; - }).merge(paths).attr("d", function(d2) { - var datagroup = this.parentNode.__data__; - return datagroup === "fill" ? getAreaPath(d2) : getPath(d2); + return properties; + } + function numericProperty(node, source, target) { + const properties = {}; + num1(node, source, (val) => { + properties[target] = val; + }); + return properties; + } + function getColor(node, output) { + return get3(node, "color", (elem) => fixColor(nodeVal(elem), output)); + } + function extractIconHref(node) { + return get3(node, "Icon", (icon2, properties) => { + val1(icon2, "href", (href) => { + properties.icon = href; }); - layer.call(drawLabels, "label-halo", geoData).call(drawLabels, "label", geoData); - function drawLabels(selection3, textClass, data) { - var labelPath = path_default(projection2); - var labelData = data.filter(function(d2) { - return _showLabels && d2.properties && (d2.properties.desc || d2.properties.name); - }); - var labels = selection3.selectAll("text." + textClass).data(labelData, featureKey); - labels.exit().remove(); - labels = labels.enter().append("text").attr("class", function(d2) { - return textClass + " " + featureClasses(d2); - }).merge(labels).text(function(d2) { - return d2.properties.desc || d2.properties.name; - }).attr("x", function(d2) { - var centroid = labelPath.centroid(d2); - return centroid[0] + 11; - }).attr("y", function(d2) { - var centroid = labelPath.centroid(d2); - return centroid[1]; - }); - } - } - function getExtension(fileName) { - if (!fileName) - return; - var re3 = /\.(gpx|kml|(geo)?json|png)$/i; - var match = fileName.toLowerCase().match(re3); - return match && match.length && match[0]; - } - function xmlToDom(textdata) { - return new DOMParser().parseFromString(textdata, "text/xml"); - } - function stringifyGeojsonProperties(feature3) { - const properties = feature3.properties; - for (const key in properties) { - const property = properties[key]; - if (typeof property === "number" || typeof property === "boolean" || Array.isArray(property)) { - properties[key] = property.toString(); - } else if (property === null) { - properties[key] = "null"; - } else if (typeof property === "object") { - properties[key] = JSON.stringify(property); - } - } - } - drawData.setFile = function(extension, data) { - _template = null; - _fileList = null; - _geojson = null; - _src = null; - var gj; - switch (extension) { - case ".gpx": - gj = gpx(xmlToDom(data)); - break; - case ".kml": - gj = kml(xmlToDom(data)); - break; - case ".geojson": - case ".json": - gj = JSON.parse(data); - if (gj.type === "FeatureCollection") { - gj.features.forEach(stringifyGeojsonProperties); - } else if (gj.type === "Feature") { - stringifyGeojsonProperties(gj); - } - break; - } - gj = gj || {}; - if (Object.keys(gj).length) { - _geojson = ensureIDs(gj); - _src = extension + " data file"; - this.fitZoom(); - } - dispatch14.call("change"); - return this; - }; - drawData.showLabels = function(val) { - if (!arguments.length) - return _showLabels; - _showLabels = val; - return this; - }; - drawData.enabled = function(val) { - if (!arguments.length) - return _enabled; - _enabled = val; - if (_enabled) { - showLayer(); - } else { - hideLayer(); - } - dispatch14.call("change"); - return this; - }; - drawData.hasData = function() { - var gj = _geojson || {}; - return !!(_template || Object.keys(gj).length); - }; - drawData.template = function(val, src) { - if (!arguments.length) - return _template; - var osm = context.connection(); - if (osm) { - var blocklists = osm.imageryBlocklists(); - var fail = false; - var tested = 0; - var regex; - for (var i3 = 0; i3 < blocklists.length; i3++) { - regex = blocklists[i3]; - fail = regex.test(val); - tested++; - if (fail) - break; - } - if (!tested) { - regex = /.*\.google(apis)?\..*\/(vt|kh)[\?\/].*([xyz]=.*){3}.*/; - fail = regex.test(val); - } + return properties; + }); + } + function extractIcon(node) { + return get3(node, "IconStyle", (iconStyle) => { + return Object.assign(getColor(iconStyle, "icon"), numericProperty(iconStyle, "scale", "icon-scale"), numericProperty(iconStyle, "heading", "icon-heading"), get3(iconStyle, "hotSpot", (hotspot) => { + const left = parseFloat(hotspot.getAttribute("x") || ""); + const top = parseFloat(hotspot.getAttribute("y") || ""); + const xunits = hotspot.getAttribute("xunits") || ""; + const yunits = hotspot.getAttribute("yunits") || ""; + if (!isNaN(left) && !isNaN(top)) + return { + "icon-offset": [left, top], + "icon-offset-units": [xunits, yunits] + }; + return {}; + }), extractIconHref(iconStyle)); + }); + } + function extractLabel(node) { + return get3(node, "LabelStyle", (labelStyle) => { + return Object.assign(getColor(labelStyle, "label"), numericProperty(labelStyle, "scale", "label-scale")); + }); + } + function extractLine(node) { + return get3(node, "LineStyle", (lineStyle) => { + return Object.assign(getColor(lineStyle, "stroke"), numericProperty(lineStyle, "width", "stroke-width")); + }); + } + function extractPoly(node) { + return get3(node, "PolyStyle", (polyStyle, properties) => { + return Object.assign(properties, get3(polyStyle, "color", (elem) => fixColor(nodeVal(elem), "fill")), val1(polyStyle, "fill", (fill) => { + if (fill === "0") + return { "fill-opacity": 0 }; + }), val1(polyStyle, "outline", (outline) => { + if (outline === "0") + return { "stroke-opacity": 0 }; + })); + }); + } + function extractStyle(node) { + return Object.assign({}, extractPoly(node), extractLine(node), extractLabel(node), extractIcon(node)); + } + var toNumber2 = (x2) => Number(x2); + var typeConverters = { + string: (x2) => x2, + int: toNumber2, + uint: toNumber2, + short: toNumber2, + ushort: toNumber2, + float: toNumber2, + double: toNumber2, + bool: (x2) => Boolean(x2) + }; + function extractExtendedData(node, schema) { + return get3(node, "ExtendedData", (extendedData, properties) => { + for (const data of $(extendedData, "Data")) { + properties[data.getAttribute("name") || ""] = nodeVal(get1(data, "value")); } - _template = val; - _fileList = null; - _geojson = null; - _src = src || "vectortile:" + val.split(/[?#]/)[0]; - dispatch14.call("change"); - return this; - }; - drawData.geojson = function(gj, src) { - if (!arguments.length) - return _geojson; - _template = null; - _fileList = null; - _geojson = null; - _src = null; - gj = gj || {}; - if (Object.keys(gj).length) { - _geojson = ensureIDs(gj); - _src = src || "unknown.geojson"; + for (const simpleData of $(extendedData, "SimpleData")) { + const name = simpleData.getAttribute("name") || ""; + const typeConverter = schema[name] || typeConverters.string; + properties[name] = typeConverter(nodeVal(simpleData)); } - dispatch14.call("change"); - return this; - }; - drawData.fileList = function(fileList) { - if (!arguments.length) - return _fileList; - _template = null; - _geojson = null; - _src = null; - _fileList = fileList; - if (!fileList || !fileList.length) - return this; - var f3 = fileList[0]; - var extension = getExtension(f3.name); - var reader = new FileReader(); - reader.onload = function() { - return function(e3) { - drawData.setFile(extension, e3.target.result); + return properties; + }); + } + function getMaybeHTMLDescription(node) { + const descriptionNode = get1(node, "description"); + for (const c2 of Array.from((descriptionNode == null ? void 0 : descriptionNode.childNodes) || [])) { + if (c2.nodeType === 4) { + return { + description: { + "@type": "html", + value: nodeVal(c2) + } }; - }(f3); - reader.readAsText(f3); - return this; - }; - drawData.url = function(url, defaultExtension) { - _template = null; - _fileList = null; - _geojson = null; - _src = null; - var testUrl = url.split(/[?#]/)[0]; - var extension = getExtension(testUrl) || defaultExtension; - if (extension) { - _template = null; - text_default3(url).then(function(data) { - drawData.setFile(extension, data); - }).catch(function() { - }); - } else { - drawData.template(url); } - return this; - }; - drawData.getSrc = function() { - return _src || ""; - }; - drawData.fitZoom = function() { - var features = getFeatures(_geojson); - if (!features.length) - return; - var map2 = context.map(); - var viewport = map2.trimmedExtent().polygon(); - var coords = features.reduce(function(coords2, feature3) { - var geom = feature3.geometry; - if (!geom) - return coords2; - var c2 = geom.coordinates; - switch (geom.type) { - case "Point": - c2 = [c2]; - case "MultiPoint": - case "LineString": - break; - case "MultiPolygon": - c2 = utilArrayFlatten(c2); - case "Polygon": - case "MultiLineString": - c2 = utilArrayFlatten(c2); - break; + } + return {}; + } + function extractTimeSpan(node) { + return get3(node, "TimeSpan", (timeSpan) => { + return { + timespan: { + begin: nodeVal(get1(timeSpan, "begin")), + end: nodeVal(get1(timeSpan, "end")) } - return utilArrayUnion(coords2, c2); - }, []); - if (!geoPolygonIntersectsPolygon(viewport, coords, true)) { - var extent = geoExtent(bounds_default({ type: "LineString", coordinates: coords })); - map2.centerZoom(extent.center(), map2.trimmedExtentZoom(extent)); + }; + }); + } + function extractTimeStamp(node) { + return get3(node, "TimeStamp", (timeStamp) => { + return { timestamp: nodeVal(get1(timeStamp, "when")) }; + }); + } + function extractCascadedStyle(node, styleMap) { + return val1(node, "styleUrl", (styleUrl) => { + styleUrl = normalizeId(styleUrl); + if (styleMap[styleUrl]) { + return Object.assign({ styleUrl }, styleMap[styleUrl]); } - return this; + return { styleUrl }; + }); + } + var removeSpace = /\s*/g; + var trimSpace = /^\s*|\s*$/g; + var splitSpace = /\s+/; + function coord1(value) { + return value.replace(removeSpace, "").split(",").map(parseFloat).filter((num) => !isNaN(num)).slice(0, 3); + } + function coord(value) { + return value.replace(trimSpace, "").split(splitSpace).map(coord1).filter((coord2) => { + return coord2.length >= 2; + }); + } + function gxCoords(node) { + let elems = $(node, "coord"); + if (elems.length === 0) { + elems = $ns(node, "coord", "*"); + } + const coordinates = elems.map((elem) => { + return nodeVal(elem).split(" ").map(parseFloat); + }); + if (coordinates.length === 0) { + return null; + } + return { + geometry: coordinates.length > 2 ? { + type: "LineString", + coordinates + } : { + type: "Point", + coordinates: coordinates[0] + }, + times: $(node, "when").map((elem) => nodeVal(elem)) }; - init2(); - return drawData; } - - // modules/svg/debug.js - function svgDebug(projection2, context) { - function drawDebug(selection2) { - const showTile = context.getDebug("tile"); - const showCollision = context.getDebug("collision"); - const showImagery = context.getDebug("imagery"); - const showTouchTargets = context.getDebug("target"); - const showDownloaded = context.getDebug("downloaded"); - let debugData = []; - if (showTile) { - debugData.push({ class: "red", label: "tile" }); - } - if (showCollision) { - debugData.push({ class: "yellow", label: "collision" }); - } - if (showImagery) { - debugData.push({ class: "orange", label: "imagery" }); - } - if (showTouchTargets) { - debugData.push({ class: "pink", label: "touchTargets" }); - } - if (showDownloaded) { - debugData.push({ class: "purple", label: "downloaded" }); + function fixRing(ring) { + if (ring.length === 0) + return ring; + const first = ring[0]; + const last = ring[ring.length - 1]; + let equal = true; + for (let i3 = 0; i3 < Math.max(first.length, last.length); i3++) { + if (first[i3] !== last[i3]) { + equal = false; + break; } - let legend = context.container().select(".main-content").selectAll(".debug-legend").data(debugData.length ? [0] : []); - legend.exit().remove(); - legend = legend.enter().append("div").attr("class", "fillD debug-legend").merge(legend); - let legendItems = legend.selectAll(".debug-legend-item").data(debugData, (d2) => d2.label); - legendItems.exit().remove(); - legendItems.enter().append("span").attr("class", (d2) => "debug-legend-item ".concat(d2.class)).text((d2) => d2.label); - let layer = selection2.selectAll(".layer-debug").data(showImagery || showDownloaded ? [0] : []); - layer.exit().remove(); - layer = layer.enter().append("g").attr("class", "layer-debug").merge(layer); - const extent = context.map().extent(); - _mainFileFetcher.get("imagery").then((d2) => { - const hits = showImagery && d2.query.bbox(extent.rectangle(), true) || []; - const features = hits.map((d4) => d4.features[d4.id]); - let imagery = layer.selectAll("path.debug-imagery").data(features); - imagery.exit().remove(); - imagery.enter().append("path").attr("class", "debug-imagery debug orange"); - }).catch(() => { - }); - const osm = context.connection(); - let dataDownloaded = []; - if (osm && showDownloaded) { - const rtree = osm.caches("get").tile.rtree; - dataDownloaded = rtree.all().map((bbox2) => { - return { - type: "Feature", - properties: { id: bbox2.id }, - geometry: { - type: "Polygon", - coordinates: [[ - [bbox2.minX, bbox2.minY], - [bbox2.minX, bbox2.maxY], - [bbox2.maxX, bbox2.maxY], - [bbox2.maxX, bbox2.minY], - [bbox2.minX, bbox2.minY] - ]] + } + if (!equal) { + return ring.concat([ring[0]]); + } + return ring; + } + function getCoordinates(node) { + return nodeVal(get1(node, "coordinates")); + } + function getGeometry(node) { + let geometries = []; + let coordTimes = []; + for (let i3 = 0; i3 < node.childNodes.length; i3++) { + const child = node.childNodes.item(i3); + if (isElement(child)) { + switch (child.tagName) { + case "MultiGeometry": + case "MultiTrack": + case "gx:MultiTrack": { + const childGeometries = getGeometry(child); + geometries = geometries.concat(childGeometries.geometries); + coordTimes = coordTimes.concat(childGeometries.coordTimes); + break; + } + case "Point": { + const coordinates = coord1(getCoordinates(child)); + if (coordinates.length >= 2) { + geometries.push({ + type: "Point", + coordinates + }); } - }; - }); + break; + } + case "LinearRing": + case "LineString": { + const coordinates = coord(getCoordinates(child)); + if (coordinates.length >= 2) { + geometries.push({ + type: "LineString", + coordinates + }); + } + break; + } + case "Polygon": { + const coords = []; + for (const linearRing of $(child, "LinearRing")) { + const ring = fixRing(coord(getCoordinates(linearRing))); + if (ring.length >= 4) { + coords.push(ring); + } + } + if (coords.length) { + geometries.push({ + type: "Polygon", + coordinates: coords + }); + } + break; + } + case "Track": + case "gx:Track": { + const gx = gxCoords(child); + if (!gx) + break; + const { times, geometry } = gx; + geometries.push(geometry); + if (times.length) + coordTimes.push(times); + break; + } + } } - let downloaded = layer.selectAll("path.debug-downloaded").data(showDownloaded ? dataDownloaded : []); - downloaded.exit().remove(); - downloaded.enter().append("path").attr("class", "debug-downloaded debug purple"); - layer.selectAll("path").attr("d", svgPath(projection2).geojson); } - drawDebug.enabled = function() { - if (!arguments.length) { - return context.getDebug("tile") || context.getDebug("collision") || context.getDebug("imagery") || context.getDebug("target") || context.getDebug("downloaded"); - } else { - return this; - } + return { + geometries, + coordTimes }; - return drawDebug; } - - // modules/svg/defs.js - function svgDefs(context) { - var _defsSelection = select_default2(null); - var _spritesheetIds = [ - "iD-sprite", - "maki-sprite", - "temaki-sprite", - "fa-sprite", - "roentgen-sprite", - "community-sprite" - ]; - function drawDefs(selection2) { - _defsSelection = selection2.append("defs"); - _defsSelection.append("marker").attr("id", "ideditor-oneway-marker").attr("viewBox", "0 0 10 5").attr("refX", 2.5).attr("refY", 2.5).attr("markerWidth", 2).attr("markerHeight", 2).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "oneway-marker-path").attr("d", "M 5,3 L 0,3 L 0,2 L 5,2 L 5,0 L 10,2.5 L 5,5 z").attr("stroke", "none").attr("fill", "#000").attr("opacity", "0.75"); - function addSidedMarker(name, color2, offset) { - _defsSelection.append("marker").attr("id", "ideditor-sided-marker-" + name).attr("viewBox", "0 0 2 2").attr("refX", 1).attr("refY", -offset).attr("markerWidth", 1.5).attr("markerHeight", 1.5).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "sided-marker-path sided-marker-" + name + "-path").attr("d", "M 0,0 L 1,1 L 2,0 z").attr("stroke", "none").attr("fill", color2); - } - addSidedMarker("natural", "rgb(170, 170, 170)", 0); - addSidedMarker("coastline", "#77dede", 1); - addSidedMarker("waterway", "#77dede", 1); - addSidedMarker("barrier", "#ddd", 1); - addSidedMarker("man_made", "#fff", 0); - _defsSelection.append("marker").attr("id", "ideditor-viewfield-marker").attr("viewBox", "0 0 16 16").attr("refX", 8).attr("refY", 16).attr("markerWidth", 4).attr("markerHeight", 4).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "viewfield-marker-path").attr("d", "M 6,14 C 8,13.4 8,13.4 10,14 L 16,3 C 12,0 4,0 0,3 z").attr("fill", "#333").attr("fill-opacity", "0.75").attr("stroke", "#fff").attr("stroke-width", "0.5px").attr("stroke-opacity", "0.75"); - _defsSelection.append("marker").attr("id", "ideditor-viewfield-marker-wireframe").attr("viewBox", "0 0 16 16").attr("refX", 8).attr("refY", 16).attr("markerWidth", 4).attr("markerHeight", 4).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "viewfield-marker-path").attr("d", "M 6,14 C 8,13.4 8,13.4 10,14 L 16,3 C 12,0 4,0 0,3 z").attr("fill", "none").attr("stroke", "#fff").attr("stroke-width", "0.5px").attr("stroke-opacity", "0.75"); - var patterns2 = _defsSelection.selectAll("pattern").data([ - // pattern name, pattern image name - ["beach", "dots"], - ["construction", "construction"], - ["cemetery", "cemetery"], - ["cemetery_christian", "cemetery_christian"], - ["cemetery_buddhist", "cemetery_buddhist"], - ["cemetery_muslim", "cemetery_muslim"], - ["cemetery_jewish", "cemetery_jewish"], - ["farmland", "farmland"], - ["farmyard", "farmyard"], - ["forest", "forest"], - ["forest_broadleaved", "forest_broadleaved"], - ["forest_needleleaved", "forest_needleleaved"], - ["forest_leafless", "forest_leafless"], - ["golf_green", "grass"], - ["grass", "grass"], - ["landfill", "landfill"], - ["meadow", "grass"], - ["orchard", "orchard"], - ["pond", "pond"], - ["quarry", "quarry"], - ["scrub", "bushes"], - ["vineyard", "vineyard"], - ["water_standing", "lines"], - ["waves", "waves"], - ["wetland", "wetland"], - ["wetland_marsh", "wetland_marsh"], - ["wetland_swamp", "wetland_swamp"], - ["wetland_bog", "wetland_bog"], - ["wetland_reedbed", "wetland_reedbed"] - ]).enter().append("pattern").attr("id", function(d2) { - return "ideditor-pattern-" + d2[0]; - }).attr("width", 32).attr("height", 32).attr("patternUnits", "userSpaceOnUse"); - patterns2.append("rect").attr("x", 0).attr("y", 0).attr("width", 32).attr("height", 32).attr("class", function(d2) { - return "pattern-color-" + d2[0]; - }); - patterns2.append("image").attr("x", 0).attr("y", 0).attr("width", 32).attr("height", 32).attr("xlink:href", function(d2) { - return context.imagePath("pattern/" + d2[1] + ".png"); - }); - _defsSelection.selectAll("clipPath").data([12, 18, 20, 32, 45]).enter().append("clipPath").attr("id", function(d2) { - return "ideditor-clip-square-" + d2; - }).append("rect").attr("x", 0).attr("y", 0).attr("width", function(d2) { - return d2; - }).attr("height", function(d2) { - return d2; - }); - addSprites(_spritesheetIds, true); + function geometryListToGeometry(geometries) { + return geometries.length === 0 ? null : geometries.length === 1 ? geometries[0] : { + type: "GeometryCollection", + geometries + }; + } + function getPlacemark(node, styleMap, schema, options2) { + var _a2; + const { coordTimes, geometries } = getGeometry(node); + const geometry = geometryListToGeometry(geometries); + if (!geometry && options2.skipNullGeometry) { + return null; } - function addSprites(ids, overrideColors) { - _spritesheetIds = utilArrayUniq(_spritesheetIds.concat(ids)); - var spritesheets = _defsSelection.selectAll(".spritesheet").data(_spritesheetIds); - spritesheets.enter().append("g").attr("class", function(d2) { - return "spritesheet spritesheet-" + d2; - }).each(function(d2) { - var url = context.imagePath(d2 + ".svg"); - var node = select_default2(this).node(); - svg(url).then(function(svg2) { - node.appendChild( - select_default2(svg2.documentElement).attr("id", "ideditor-" + d2).node() - ); - if (overrideColors && d2 !== "iD-sprite") { - select_default2(node).selectAll("path").attr("fill", "currentColor"); + const feature3 = { + type: "Feature", + geometry, + properties: Object.assign(getMulti(node, [ + "name", + "address", + "visibility", + "open", + "phoneNumber", + "description" + ]), getMaybeHTMLDescription(node), extractCascadedStyle(node, styleMap), extractStyle(node), extractExtendedData(node, schema), extractTimeSpan(node), extractTimeStamp(node), coordTimes.length ? { + coordinateProperties: { + times: coordTimes.length === 1 ? coordTimes[0] : coordTimes + } + } : {}) + }; + if (((_a2 = feature3.properties) == null ? void 0 : _a2.visibility) !== void 0) { + feature3.properties.visibility = feature3.properties.visibility !== "0"; + } + const id2 = node.getAttribute("id"); + if (id2 !== null && id2 !== "") + feature3.id = id2; + return feature3; + } + function getGroundOverlayBox(node) { + const latLonQuad = get1(node, "gx:LatLonQuad"); + if (latLonQuad) { + const ring = fixRing(coord(getCoordinates(node))); + return { + geometry: { + type: "Polygon", + coordinates: [ring] + } + }; + } + return getLatLonBox(node); + } + var DEGREES_TO_RADIANS = Math.PI / 180; + function rotateBox(bbox2, coordinates, rotation) { + const center = [(bbox2[0] + bbox2[2]) / 2, (bbox2[1] + bbox2[3]) / 2]; + return [ + coordinates[0].map((coordinate) => { + const dy = coordinate[1] - center[1]; + const dx = coordinate[0] - center[0]; + const distance = Math.sqrt(Math.pow(dy, 2) + Math.pow(dx, 2)); + const angle2 = Math.atan2(dy, dx) + rotation * DEGREES_TO_RADIANS; + return [ + center[0] + Math.cos(angle2) * distance, + center[1] + Math.sin(angle2) * distance + ]; + }) + ]; + } + function getLatLonBox(node) { + const latLonBox = get1(node, "LatLonBox"); + if (latLonBox) { + const north = num1(latLonBox, "north"); + const west = num1(latLonBox, "west"); + const east = num1(latLonBox, "east"); + const south = num1(latLonBox, "south"); + const rotation = num1(latLonBox, "rotation"); + if (typeof north === "number" && typeof south === "number" && typeof west === "number" && typeof east === "number") { + const bbox2 = [west, south, east, north]; + let coordinates = [ + [ + [west, north], + [east, north], + [east, south], + [west, south], + [west, north] + // top left (again) + ] + ]; + if (typeof rotation === "number") { + coordinates = rotateBox(bbox2, coordinates, rotation); + } + return { + bbox: bbox2, + geometry: { + type: "Polygon", + coordinates } - }).catch(function() { - }); - }); - spritesheets.exit().remove(); + }; + } } - drawDefs.addSprites = addSprites; - return drawDefs; + return null; } - - // modules/svg/keepRight.js - var _layerEnabled = false; - var _qaService; - function svgKeepRight(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); - const minZoom4 = 12; - let touchLayer = select_default2(null); - let drawLayer = select_default2(null); - let layerVisible = false; - function markerPath(selection2, klass) { - selection2.attr("class", klass).attr("transform", "translate(-4, -24)").attr("d", "M11.6,6.2H7.1l1.4-5.1C8.6,0.6,8.1,0,7.5,0H2.2C1.7,0,1.3,0.3,1.3,0.8L0,10.2c-0.1,0.6,0.4,1.1,0.9,1.1h4.6l-1.8,7.6C3.6,19.4,4.1,20,4.7,20c0.3,0,0.6-0.2,0.8-0.5l6.9-11.9C12.7,7,12.3,6.2,11.6,6.2z"); + function getGroundOverlay(node, styleMap, schema, options2) { + var _a2; + const box = getGroundOverlayBox(node); + const geometry = (box == null ? void 0 : box.geometry) || null; + if (!geometry && options2.skipNullGeometry) { + return null; } - function getService() { - if (services.keepRight && !_qaService) { - _qaService = services.keepRight; - _qaService.on("loaded", throttledRedraw); - } else if (!services.keepRight && _qaService) { - _qaService = null; - } - return _qaService; + const feature3 = { + type: "Feature", + geometry, + properties: Object.assign( + /** + * Related to + * https://gist.github.com/tmcw/037a1cb6660d74a392e9da7446540f46 + */ + { "@geometry-type": "groundoverlay" }, + getMulti(node, [ + "name", + "address", + "visibility", + "open", + "phoneNumber", + "description" + ]), + getMaybeHTMLDescription(node), + extractCascadedStyle(node, styleMap), + extractStyle(node), + extractIconHref(node), + extractExtendedData(node, schema), + extractTimeSpan(node), + extractTimeStamp(node) + ) + }; + if (box == null ? void 0 : box.bbox) { + feature3.bbox = box.bbox; } - function editOn() { - if (!layerVisible) { - layerVisible = true; - drawLayer.style("display", "block"); - } + if (((_a2 = feature3.properties) == null ? void 0 : _a2.visibility) !== void 0) { + feature3.properties.visibility = feature3.properties.visibility !== "0"; } - function editOff() { - if (layerVisible) { - layerVisible = false; - drawLayer.style("display", "none"); - drawLayer.selectAll(".qaItem.keepRight").remove(); - touchLayer.selectAll(".qaItem.keepRight").remove(); - } + const id2 = node.getAttribute("id"); + if (id2 !== null && id2 !== "") + feature3.id = id2; + return feature3; + } + function getStyleId(style) { + let id2 = style.getAttribute("id"); + const parentNode = style.parentNode; + if (!id2 && isElement(parentNode) && parentNode.localName === "CascadingStyle") { + id2 = parentNode.getAttribute("kml:id") || parentNode.getAttribute("id"); } - function layerOn() { - editOn(); - drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", () => dispatch14.call("change")); + return normalizeId(id2 || ""); + } + function buildStyleMap(node) { + const styleMap = {}; + for (const style of $(node, "Style")) { + styleMap[getStyleId(style)] = extractStyle(style); } - function layerOff() { - throttledRedraw.cancel(); - drawLayer.interrupt(); - touchLayer.selectAll(".qaItem.keepRight").remove(); - drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", () => { - editOff(); - dispatch14.call("change"); + for (const map2 of $(node, "StyleMap")) { + const id2 = normalizeId(map2.getAttribute("id") || ""); + val1(map2, "styleUrl", (styleUrl) => { + styleUrl = normalizeId(styleUrl); + if (styleMap[styleUrl]) { + styleMap[id2] = styleMap[styleUrl]; + } }); } - function updateMarkers() { - if (!layerVisible || !_layerEnabled) - return; - const service = getService(); - const selectedID = context.selectedErrorID(); - const data = service ? service.getItems(projection2) : []; - const getTransform = svgPointTransform(projection2); - const markers = drawLayer.selectAll(".qaItem.keepRight").data(data, (d2) => d2.id); - markers.exit().remove(); - const markersEnter = markers.enter().append("g").attr("class", (d2) => "qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.parentIssueType)); - markersEnter.append("ellipse").attr("cx", 0.5).attr("cy", 1).attr("rx", 6.5).attr("ry", 3).attr("class", "stroke"); - markersEnter.append("path").call(markerPath, "shadow"); - markersEnter.append("use").attr("class", "qaItem-fill").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").attr("xlink:href", "#iD-icon-bolt"); - markers.merge(markersEnter).sort(sortY).classed("selected", (d2) => d2.id === selectedID).attr("transform", getTransform); - if (touchLayer.empty()) - return; - const fillClass = context.getDebug("target") ? "pink " : "nocolor "; - const targets = touchLayer.selectAll(".qaItem.keepRight").data(data, (d2) => d2.id); - targets.exit().remove(); - targets.enter().append("rect").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").merge(targets).sort(sortY).attr("class", (d2) => "qaItem ".concat(d2.service, " target ").concat(fillClass, " itemId-").concat(d2.id)).attr("transform", getTransform); - function sortY(a2, b2) { - return a2.id === selectedID ? 1 : b2.id === selectedID ? -1 : a2.severity === "error" && b2.severity !== "error" ? 1 : b2.severity === "error" && a2.severity !== "error" ? -1 : b2.loc[1] - a2.loc[1]; - } + return styleMap; + } + function buildSchema(node) { + const schema = {}; + for (const field of $(node, "SimpleField")) { + schema[field.getAttribute("name") || ""] = typeConverters[field.getAttribute("type") || ""] || typeConverters["string"]; } - function drawKeepRight(selection2) { - const service = getService(); - const surface = context.surface(); - if (surface && !surface.empty()) { - touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); - } - drawLayer = selection2.selectAll(".layer-keepRight").data(service ? [0] : []); - drawLayer.exit().remove(); - drawLayer = drawLayer.enter().append("g").attr("class", "layer-keepRight").style("display", _layerEnabled ? "block" : "none").merge(drawLayer); - if (_layerEnabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - service.loadIssues(projection2); - updateMarkers(); - } else { - editOff(); - } - } + return schema; + } + function* kmlGen(node, options2 = { + skipNullGeometry: false + }) { + const styleMap = buildStyleMap(node); + const schema = buildSchema(node); + for (const placemark of $(node, "Placemark")) { + const feature3 = getPlacemark(placemark, styleMap, schema, options2); + if (feature3) + yield feature3; } - drawKeepRight.enabled = function(val) { - if (!arguments.length) - return _layerEnabled; - _layerEnabled = val; - if (_layerEnabled) { - layerOn(); - } else { - layerOff(); - if (context.selectedErrorID()) { - context.enter(modeBrowse(context)); - } - } - dispatch14.call("change"); - return this; + for (const groundOverlay of $(node, "GroundOverlay")) { + const feature3 = getGroundOverlay(groundOverlay, styleMap, schema, options2); + if (feature3) + yield feature3; + } + } + function kml(node, options2 = { + skipNullGeometry: false + }) { + return { + type: "FeatureCollection", + features: Array.from(kmlGen(node, options2)) }; - drawKeepRight.supported = () => !!getService(); - return drawKeepRight; } - // modules/svg/geolocate.js - function svgGeolocate(projection2) { + // modules/svg/data.js + var _initialized = false; + var _enabled = false; + var _geojson; + function svgData(projection2, context, dispatch14) { + var throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + var _showLabels = true; + var detected = utilDetect(); var layer = select_default2(null); - var _position; + var _vtService; + var _fileList; + var _template; + var _src; + const supportedFormats = [ + ".gpx", + ".kml", + ".geojson", + ".json" + ]; function init2() { - if (svgGeolocate.initialized) + if (_initialized) return; - svgGeolocate.enabled = false; - svgGeolocate.initialized = true; + _geojson = {}; + _enabled = true; + function over(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + d3_event.dataTransfer.dropEffect = "copy"; + } + context.container().attr("dropzone", "copy").on("drop.svgData", function(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + if (!detected.filedrop) + return; + var f2 = d3_event.dataTransfer.files[0]; + var extension = getExtension(f2.name); + if (!supportedFormats.includes(extension)) + return; + drawData.fileList(d3_event.dataTransfer.files); + }).on("dragenter.svgData", over).on("dragexit.svgData", over).on("dragover.svgData", over); + _initialized = true; + } + function getService() { + if (services.vectorTile && !_vtService) { + _vtService = services.vectorTile; + _vtService.event.on("loadedData", throttledRedraw); + } else if (!services.vectorTile && _vtService) { + _vtService = null; + } + return _vtService; } function showLayer() { - layer.style("display", "block"); + layerOn(); + layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { + dispatch14.call("change"); + }); } function hideLayer() { - layer.transition().duration(250).style("opacity", 0); + throttledRedraw.cancel(); + layer.transition().duration(250).style("opacity", 0).on("end", layerOff); } function layerOn() { - layer.style("opacity", 0).transition().duration(250).style("opacity", 1); + layer.style("display", "block"); } function layerOff() { + layer.selectAll(".viewfield-group").remove(); layer.style("display", "none"); } - function transform2(d2) { - return svgPointTransform(projection2)(d2); - } - function accuracy(accuracy2, loc) { - var degreesRadius = geoMetersToLat(accuracy2), tangentLoc = [loc[0], loc[1] + degreesRadius], projectedTangent = projection2(tangentLoc), projectedLoc = projection2([loc[0], loc[1]]); - return Math.round(projectedLoc[1] - projectedTangent[1]).toString(); - } - function update() { - var geolocation = { loc: [_position.coords.longitude, _position.coords.latitude] }; - var groups = layer.selectAll(".geolocations").selectAll(".geolocation").data([geolocation]); - groups.exit().remove(); - var pointsEnter = groups.enter().append("g").attr("class", "geolocation"); - pointsEnter.append("circle").attr("class", "geolocate-radius").attr("dx", "0").attr("dy", "0").attr("fill", "rgb(15,128,225)").attr("fill-opacity", "0.3").attr("r", "0"); - pointsEnter.append("circle").attr("dx", "0").attr("dy", "0").attr("fill", "rgb(15,128,225)").attr("stroke", "white").attr("stroke-width", "1.5").attr("r", "6"); - groups.merge(pointsEnter).attr("transform", transform2); - layer.select(".geolocate-radius").attr("r", accuracy(_position.coords.accuracy, geolocation.loc)); - } - function drawLocation(selection2) { - var enabled = svgGeolocate.enabled; - layer = selection2.selectAll(".layer-geolocate").data([0]); - layer.exit().remove(); - var layerEnter = layer.enter().append("g").attr("class", "layer-geolocate").style("display", enabled ? "block" : "none"); - layerEnter.append("g").attr("class", "geolocations"); - layer = layerEnter.merge(layer); - if (enabled) { - update(); - } else { - layerOff(); - } - } - drawLocation.enabled = function(position, enabled) { - if (!arguments.length) - return svgGeolocate.enabled; - _position = position; - svgGeolocate.enabled = enabled; - if (svgGeolocate.enabled) { - showLayer(); - layerOn(); + function ensureIDs(gj) { + if (!gj) + return null; + if (gj.type === "FeatureCollection") { + for (var i3 = 0; i3 < gj.features.length; i3++) { + ensureFeatureID(gj.features[i3]); + } } else { - hideLayer(); + ensureFeatureID(gj); } - return this; - }; - init2(); - return drawLocation; - } - - // modules/svg/labels.js - var import_rbush6 = __toESM(require_rbush_min()); - function svgLabels(projection2, context) { - var path = path_default(projection2); - var detected = utilDetect(); - var baselineHack = detected.ie || detected.browser.toLowerCase() === "edge" || detected.browser.toLowerCase() === "firefox" && detected.version >= 70; - var _rdrawn = new import_rbush6.default(); - var _rskipped = new import_rbush6.default(); - var _textWidthCache = {}; - var _entitybboxes = {}; - var labelStack = [ - ["line", "aeroway", "*", 12], - ["line", "highway", "motorway", 12], - ["line", "highway", "trunk", 12], - ["line", "highway", "primary", 12], - ["line", "highway", "secondary", 12], - ["line", "highway", "tertiary", 12], - ["line", "highway", "*", 12], - ["line", "railway", "*", 12], - ["line", "waterway", "*", 12], - ["area", "aeroway", "*", 12], - ["area", "amenity", "*", 12], - ["area", "building", "*", 12], - ["area", "historic", "*", 12], - ["area", "leisure", "*", 12], - ["area", "man_made", "*", 12], - ["area", "natural", "*", 12], - ["area", "shop", "*", 12], - ["area", "tourism", "*", 12], - ["area", "camp_site", "*", 12], - ["point", "aeroway", "*", 10], - ["point", "amenity", "*", 10], - ["point", "building", "*", 10], - ["point", "historic", "*", 10], - ["point", "leisure", "*", 10], - ["point", "man_made", "*", 10], - ["point", "natural", "*", 10], - ["point", "shop", "*", 10], - ["point", "tourism", "*", 10], - ["point", "camp_site", "*", 10], - ["line", "ref", "*", 12], - ["area", "ref", "*", 12], - ["point", "ref", "*", 10], - ["line", "name", "*", 12], - ["area", "name", "*", 12], - ["point", "name", "*", 10] - ]; - function shouldSkipIcon(preset) { - var noIcons = ["building", "landuse", "natural"]; - return noIcons.some(function(s2) { - return preset.id.indexOf(s2) >= 0; - }); + return gj; } - function get4(array2, prop) { - return function(d2, i3) { - return array2[i3][prop]; - }; + function ensureFeatureID(feature3) { + if (!feature3) + return; + feature3.__featurehash__ = utilHashcode((0, import_fast_json_stable_stringify.default)(feature3)); + return feature3; } - function textWidth(text2, size, elem) { - var c2 = _textWidthCache[size]; - if (!c2) - c2 = _textWidthCache[size] = {}; - if (c2[text2]) { - return c2[text2]; - } else if (elem) { - c2[text2] = elem.getComputedTextLength(); - return c2[text2]; + function getFeatures(gj) { + if (!gj) + return []; + if (gj.type === "FeatureCollection") { + return gj.features; } else { - var str2 = encodeURIComponent(text2).match(/%[CDEFcdef]/g); - if (str2 === null) { - return size / 3 * 2 * text2.length; - } else { - return size / 3 * (2 * text2.length + str2.length); - } + return [gj]; } } - function drawLinePaths(selection2, entities, filter2, classes, labels) { - var paths = selection2.selectAll("path").filter(filter2).data(entities, osmEntity.key); - paths.exit().remove(); - paths.enter().append("path").style("stroke-width", get4(labels, "font-size")).attr("id", function(d2) { - return "ideditor-labelpath-" + d2.id; - }).attr("class", classes).merge(paths).attr("d", get4(labels, "lineString")); + function featureKey(d2) { + return d2.__featurehash__; } - function drawLineLabels(selection2, entities, filter2, classes, labels) { - var texts = selection2.selectAll("text." + classes).filter(filter2).data(entities, osmEntity.key); - texts.exit().remove(); - texts.enter().append("text").attr("class", function(d2, i3) { - return classes + " " + labels[i3].classes + " " + d2.id; - }).attr("dy", baselineHack ? "0.35em" : null).append("textPath").attr("class", "textpath"); - selection2.selectAll("text." + classes).selectAll(".textpath").filter(filter2).data(entities, osmEntity.key).attr("startOffset", "50%").attr("xlink:href", function(d2) { - return "#ideditor-labelpath-" + d2.id; - }).text(utilDisplayNameForPath); + function isPolygon(d2) { + return d2.geometry.type === "Polygon" || d2.geometry.type === "MultiPolygon"; } - function drawPointLabels(selection2, entities, filter2, classes, labels) { - var texts = selection2.selectAll("text." + classes).filter(filter2).data(entities, osmEntity.key); - texts.exit().remove(); - texts.enter().append("text").attr("class", function(d2, i3) { - return classes + " " + labels[i3].classes + " " + d2.id; - }).merge(texts).attr("x", get4(labels, "x")).attr("y", get4(labels, "y")).style("text-anchor", get4(labels, "textAnchor")).text(utilDisplayName).each(function(d2, i3) { - textWidth(utilDisplayName(d2), labels[i3].height, this); - }); + function clipPathID(d2) { + return "ideditor-data-" + d2.__featurehash__ + "-clippath"; } - function drawAreaLabels(selection2, entities, filter2, classes, labels) { - entities = entities.filter(hasText); - labels = labels.filter(hasText); - drawPointLabels(selection2, entities, filter2, classes, labels); - function hasText(d2, i3) { - return labels[i3].hasOwnProperty("x") && labels[i3].hasOwnProperty("y"); - } + function featureClasses(d2) { + return [ + "data" + d2.__featurehash__, + d2.geometry.type, + isPolygon(d2) ? "area" : "", + d2.__layerID__ || "" + ].filter(Boolean).join(" "); } - function drawAreaIcons(selection2, entities, filter2, classes, labels) { - var icons = selection2.selectAll("use." + classes).filter(filter2).data(entities, osmEntity.key); - icons.exit().remove(); - icons.enter().append("use").attr("class", "icon " + classes).attr("width", "17px").attr("height", "17px").merge(icons).attr("transform", get4(labels, "transform")).attr("xlink:href", function(d2) { - var preset = _mainPresetIndex.match(d2, context.graph()); - var picon = preset && preset.icon; - return picon ? "#" + picon : ""; + function drawData(selection2) { + var vtService = getService(); + var getPath = svgPath(projection2).geojson; + var getAreaPath = svgPath(projection2, null, true).geojson; + var hasData = drawData.hasData(); + layer = selection2.selectAll(".layer-mapdata").data(_enabled && hasData ? [0] : []); + layer.exit().remove(); + layer = layer.enter().append("g").attr("class", "layer-mapdata").merge(layer); + var surface = context.surface(); + if (!surface || surface.empty()) + return; + var geoData, polygonData; + if (_template && vtService) { + var sourceID = _template; + vtService.loadTiles(sourceID, _template, projection2); + geoData = vtService.data(sourceID, projection2); + } else { + geoData = getFeatures(_geojson); + } + geoData = geoData.filter(getPath); + polygonData = geoData.filter(isPolygon); + var clipPaths = surface.selectAll("defs").selectAll(".clipPath-data").data(polygonData, featureKey); + clipPaths.exit().remove(); + var clipPathsEnter = clipPaths.enter().append("clipPath").attr("class", "clipPath-data").attr("id", clipPathID); + clipPathsEnter.append("path"); + clipPaths.merge(clipPathsEnter).selectAll("path").attr("d", getAreaPath); + var datagroups = layer.selectAll("g.datagroup").data(["fill", "shadow", "stroke"]); + datagroups = datagroups.enter().append("g").attr("class", function(d2) { + return "datagroup datagroup-" + d2; + }).merge(datagroups); + var pathData = { + fill: polygonData, + shadow: geoData, + stroke: geoData + }; + var paths = datagroups.selectAll("path").data(function(layer2) { + return pathData[layer2]; + }, featureKey); + paths.exit().remove(); + paths = paths.enter().append("path").attr("class", function(d2) { + var datagroup = this.parentNode.__data__; + return "pathdata " + datagroup + " " + featureClasses(d2); + }).attr("clip-path", function(d2) { + var datagroup = this.parentNode.__data__; + return datagroup === "fill" ? "url(#" + clipPathID(d2) + ")" : null; + }).merge(paths).attr("d", function(d2) { + var datagroup = this.parentNode.__data__; + return datagroup === "fill" ? getAreaPath(d2) : getPath(d2); }); - } - function drawCollisionBoxes(selection2, rtree, which) { - var classes = "debug " + which + " " + (which === "debug-skipped" ? "orange" : "yellow"); - var gj = []; - if (context.getDebug("collision")) { - gj = rtree.all().map(function(d2) { - return { type: "Polygon", coordinates: [[ - [d2.minX, d2.minY], - [d2.maxX, d2.minY], - [d2.maxX, d2.maxY], - [d2.minX, d2.maxY], - [d2.minX, d2.minY] - ]] }; + layer.call(drawLabels, "label-halo", geoData).call(drawLabels, "label", geoData); + function drawLabels(selection3, textClass, data) { + var labelPath = path_default(projection2); + var labelData = data.filter(function(d2) { + return _showLabels && d2.properties && (d2.properties.desc || d2.properties.name); + }); + var labels = selection3.selectAll("text." + textClass).data(labelData, featureKey); + labels.exit().remove(); + labels = labels.enter().append("text").attr("class", function(d2) { + return textClass + " " + featureClasses(d2); + }).merge(labels).text(function(d2) { + return d2.properties.desc || d2.properties.name; + }).attr("x", function(d2) { + var centroid = labelPath.centroid(d2); + return centroid[0] + 11; + }).attr("y", function(d2) { + var centroid = labelPath.centroid(d2); + return centroid[1]; }); } - var boxes = selection2.selectAll("." + which).data(gj); - boxes.exit().remove(); - boxes.enter().append("path").attr("class", classes).merge(boxes).attr("d", path_default()); } - function drawLabels(selection2, graph, entities, filter2, dimensions, fullRedraw) { - var wireframe = context.surface().classed("fill-wireframe"); - var zoom = geoScaleToZoom(projection2.scale()); - var labelable = []; - var renderNodeAs = {}; - var i3, j3, k2, entity, geometry; - for (i3 = 0; i3 < labelStack.length; i3++) { - labelable.push([]); + function getExtension(fileName) { + if (!fileName) + return; + var re3 = /\.(gpx|kml|(geo)?json|png)$/i; + var match = fileName.toLowerCase().match(re3); + return match && match.length && match[0]; + } + function xmlToDom(textdata) { + return new DOMParser().parseFromString(textdata, "text/xml"); + } + function stringifyGeojsonProperties(feature3) { + const properties = feature3.properties; + for (const key in properties) { + const property = properties[key]; + if (typeof property === "number" || typeof property === "boolean" || Array.isArray(property)) { + properties[key] = property.toString(); + } else if (property === null) { + properties[key] = "null"; + } else if (typeof property === "object") { + properties[key] = JSON.stringify(property); + } + } + } + drawData.setFile = function(extension, data) { + _template = null; + _fileList = null; + _geojson = null; + _src = null; + var gj; + switch (extension) { + case ".gpx": + gj = gpx(xmlToDom(data)); + break; + case ".kml": + gj = kml(xmlToDom(data)); + break; + case ".geojson": + case ".json": + gj = JSON.parse(data); + if (gj.type === "FeatureCollection") { + gj.features.forEach(stringifyGeojsonProperties); + } else if (gj.type === "Feature") { + stringifyGeojsonProperties(gj); + } + break; } - if (fullRedraw) { - _rdrawn.clear(); - _rskipped.clear(); - _entitybboxes = {}; + gj = gj || {}; + if (Object.keys(gj).length) { + _geojson = ensureIDs(gj); + _src = extension + " data file"; + this.fitZoom(); + } + dispatch14.call("change"); + return this; + }; + drawData.showLabels = function(val) { + if (!arguments.length) + return _showLabels; + _showLabels = val; + return this; + }; + drawData.enabled = function(val) { + if (!arguments.length) + return _enabled; + _enabled = val; + if (_enabled) { + showLayer(); } else { - for (i3 = 0; i3 < entities.length; i3++) { - entity = entities[i3]; - var toRemove = [].concat(_entitybboxes[entity.id] || []).concat(_entitybboxes[entity.id + "I"] || []); - for (j3 = 0; j3 < toRemove.length; j3++) { - _rdrawn.remove(toRemove[j3]); - _rskipped.remove(toRemove[j3]); - } - } + hideLayer(); } - for (i3 = 0; i3 < entities.length; i3++) { - entity = entities[i3]; - geometry = entity.geometry(graph); - if (geometry === "point" || geometry === "vertex" && isInterestingVertex(entity)) { - var hasDirections = entity.directions(graph, projection2).length; - var markerPadding; - if (!wireframe && geometry === "point" && !(zoom >= 18 && hasDirections)) { - renderNodeAs[entity.id] = "point"; - markerPadding = 20; - } else { - renderNodeAs[entity.id] = "vertex"; - markerPadding = 0; - } - var coord2 = projection2(entity.loc); - var nodePadding = 10; - var bbox2 = { - minX: coord2[0] - nodePadding, - minY: coord2[1] - nodePadding - markerPadding, - maxX: coord2[0] + nodePadding, - maxY: coord2[1] + nodePadding - }; - doInsert(bbox2, entity.id + "P"); - } - if (geometry === "vertex") { - geometry = "point"; - } - var preset = geometry === "area" && _mainPresetIndex.match(entity, graph); - var icon2 = preset && !shouldSkipIcon(preset) && preset.icon; - if (!icon2 && !utilDisplayName(entity)) - continue; - for (k2 = 0; k2 < labelStack.length; k2++) { - var matchGeom = labelStack[k2][0]; - var matchKey = labelStack[k2][1]; - var matchVal = labelStack[k2][2]; - var hasVal = entity.tags[matchKey]; - if (geometry === matchGeom && hasVal && (matchVal === "*" || matchVal === hasVal)) { - labelable[k2].push(entity); + dispatch14.call("change"); + return this; + }; + drawData.hasData = function() { + var gj = _geojson || {}; + return !!(_template || Object.keys(gj).length); + }; + drawData.template = function(val, src) { + if (!arguments.length) + return _template; + var osm = context.connection(); + if (osm) { + var blocklists = osm.imageryBlocklists(); + var fail = false; + var tested = 0; + var regex; + for (var i3 = 0; i3 < blocklists.length; i3++) { + regex = blocklists[i3]; + fail = regex.test(val); + tested++; + if (fail) break; - } } - } - var positions = { - point: [], - line: [], - area: [] - }; - var labelled = { - point: [], - line: [], - area: [] - }; - for (k2 = 0; k2 < labelable.length; k2++) { - var fontSize = labelStack[k2][3]; - for (i3 = 0; i3 < labelable[k2].length; i3++) { - entity = labelable[k2][i3]; - geometry = entity.geometry(graph); - var getName = geometry === "line" ? utilDisplayNameForPath : utilDisplayName; - var name = getName(entity); - var width = name && textWidth(name, fontSize); - var p2 = null; - if (geometry === "point" || geometry === "vertex") { - if (wireframe) - continue; - var renderAs = renderNodeAs[entity.id]; - if (renderAs === "vertex" && zoom < 17) - continue; - p2 = getPointLabel(entity, width, fontSize, renderAs); - } else if (geometry === "line") { - p2 = getLineLabel(entity, width, fontSize); - } else if (geometry === "area") { - p2 = getAreaLabel(entity, width, fontSize); - } - if (p2) { - if (geometry === "vertex") { - geometry = "point"; - } - p2.classes = geometry + " tag-" + labelStack[k2][1]; - positions[geometry].push(p2); - labelled[geometry].push(entity); - } + if (!tested) { + regex = /.*\.google(apis)?\..*\/(vt|kh)[\?\/].*([xyz]=.*){3}.*/; + fail = regex.test(val); } } - function isInterestingVertex(entity2) { - var selectedIDs = context.selectedIDs(); - return entity2.hasInterestingTags() || entity2.isEndpoint(graph) || entity2.isConnected(graph) || selectedIDs.indexOf(entity2.id) !== -1 || graph.parentWays(entity2).some(function(parent) { - return selectedIDs.indexOf(parent.id) !== -1; - }); + _template = val; + _fileList = null; + _geojson = null; + _src = src || "vectortile:" + val.split(/[?#]/)[0]; + dispatch14.call("change"); + return this; + }; + drawData.geojson = function(gj, src) { + if (!arguments.length) + return _geojson; + _template = null; + _fileList = null; + _geojson = null; + _src = null; + gj = gj || {}; + if (Object.keys(gj).length) { + _geojson = ensureIDs(gj); + _src = src || "unknown.geojson"; } - function getPointLabel(entity2, width2, height, geometry2) { - var y2 = geometry2 === "point" ? -12 : 0; - var pointOffsets = { - ltr: [15, y2, "start"], - rtl: [-15, y2, "end"] - }; - var textDirection = _mainLocalizer.textDirection(); - var coord3 = projection2(entity2.loc); - var textPadding = 2; - var offset = pointOffsets[textDirection]; - var p3 = { - height, - width: width2, - x: coord3[0] + offset[0], - y: coord3[1] + offset[1], - textAnchor: offset[2] + dispatch14.call("change"); + return this; + }; + drawData.fileList = function(fileList) { + if (!arguments.length) + return _fileList; + _template = null; + _geojson = null; + _src = null; + _fileList = fileList; + if (!fileList || !fileList.length) + return this; + var f2 = fileList[0]; + var extension = getExtension(f2.name); + var reader = new FileReader(); + reader.onload = /* @__PURE__ */ function() { + return function(e3) { + drawData.setFile(extension, e3.target.result); }; - var bbox3; - if (textDirection === "rtl") { - bbox3 = { - minX: p3.x - width2 - textPadding, - minY: p3.y - height / 2 - textPadding, - maxX: p3.x + textPadding, - maxY: p3.y + height / 2 + textPadding - }; - } else { - bbox3 = { - minX: p3.x - textPadding, - minY: p3.y - height / 2 - textPadding, - maxX: p3.x + width2 + textPadding, - maxY: p3.y + height / 2 + textPadding - }; - } - if (tryInsert([bbox3], entity2.id, true)) { - return p3; - } - } - function getLineLabel(entity2, width2, height) { - var viewport = geoExtent(context.projection.clipExtent()).polygon(); - var points = graph.childNodes(entity2).map(function(node) { - return projection2(node.loc); + }(f2); + reader.readAsText(f2); + return this; + }; + drawData.url = function(url, defaultExtension) { + _template = null; + _fileList = null; + _geojson = null; + _src = null; + var testUrl = url.split(/[?#]/)[0]; + var extension = getExtension(testUrl) || defaultExtension; + if (extension) { + _template = null; + text_default3(url).then(function(data) { + drawData.setFile(extension, data); + }).catch(function() { }); - var length = geoPathLength(points); - if (length < width2 + 20) - return; - var lineOffsets = [ - 50, - 45, - 55, - 40, - 60, - 35, - 65, - 30, - 70, - 25, - 75, - 20, - 80, - 15, - 95, - 10, - 90, - 5, - 95 - ]; - var padding = 3; - for (var i4 = 0; i4 < lineOffsets.length; i4++) { - var offset = lineOffsets[i4]; - var middle = offset / 100 * length; - var start2 = middle - width2 / 2; - if (start2 < 0 || start2 + width2 > length) - continue; - var sub = subpath(points, start2, start2 + width2); - if (!sub || !geoPolygonIntersectsPolygon(viewport, sub, true)) { - continue; - } - var isReverse = reverse(sub); - if (isReverse) { - sub = sub.reverse(); - } - var bboxes = []; - var boxsize = (height + 2) / 2; - for (var j4 = 0; j4 < sub.length - 1; j4++) { - var a2 = sub[j4]; - var b2 = sub[j4 + 1]; - var num = Math.max(1, Math.floor(geoVecLength(a2, b2) / boxsize / 2)); - for (var box = 0; box < num; box++) { - var p3 = geoVecInterp(a2, b2, box / num); - var x05 = p3[0] - boxsize - padding; - var y05 = p3[1] - boxsize - padding; - var x12 = p3[0] + boxsize + padding; - var y12 = p3[1] + boxsize + padding; - bboxes.push({ - minX: Math.min(x05, x12), - minY: Math.min(y05, y12), - maxX: Math.max(x05, x12), - maxY: Math.max(y05, y12) - }); - } - } - if (tryInsert(bboxes, entity2.id, false)) { - return { - "font-size": height + 2, - lineString: lineString2(sub), - startOffset: offset + "%" - }; - } - } - function reverse(p4) { - var angle2 = Math.atan2(p4[1][1] - p4[0][1], p4[1][0] - p4[0][0]); - return !(p4[0][0] < p4[p4.length - 1][0] && angle2 < Math.PI / 2 && angle2 > -Math.PI / 2); - } - function lineString2(points2) { - return "M" + points2.join("L"); - } - function subpath(points2, from, to) { - var sofar = 0; - var start3, end, i0, i1; - for (var i5 = 0; i5 < points2.length - 1; i5++) { - var a3 = points2[i5]; - var b3 = points2[i5 + 1]; - var current = geoVecLength(a3, b3); - var portion; - if (!start3 && sofar + current >= from) { - portion = (from - sofar) / current; - start3 = [ - a3[0] + portion * (b3[0] - a3[0]), - a3[1] + portion * (b3[1] - a3[1]) - ]; - i0 = i5 + 1; - } - if (!end && sofar + current >= to) { - portion = (to - sofar) / current; - end = [ - a3[0] + portion * (b3[0] - a3[0]), - a3[1] + portion * (b3[1] - a3[1]) - ]; - i1 = i5 + 1; - } - sofar += current; - } - var result = points2.slice(i0, i1); - result.unshift(start3); - result.push(end); - return result; - } - } - function getAreaLabel(entity2, width2, height) { - var centroid = path.centroid(entity2.asGeoJSON(graph)); - var extent = entity2.extent(graph); - var areaWidth = projection2(extent[1])[0] - projection2(extent[0])[0]; - if (isNaN(centroid[0]) || areaWidth < 20) - return; - var preset2 = _mainPresetIndex.match(entity2, context.graph()); - var picon = preset2 && preset2.icon; - var iconSize = 17; - var padding = 2; - var p3 = {}; - if (picon) { - if (addIcon()) { - addLabel(iconSize + padding); - return p3; - } - } else { - if (addLabel(0)) { - return p3; - } - } - function addIcon() { - var iconX = centroid[0] - iconSize / 2; - var iconY = centroid[1] - iconSize / 2; - var bbox3 = { - minX: iconX, - minY: iconY, - maxX: iconX + iconSize, - maxY: iconY + iconSize - }; - if (tryInsert([bbox3], entity2.id + "I", true)) { - p3.transform = "translate(" + iconX + "," + iconY + ")"; - return true; - } - return false; - } - function addLabel(yOffset) { - if (width2 && areaWidth >= width2 + 20) { - var labelX = centroid[0]; - var labelY = centroid[1] + yOffset; - var bbox3 = { - minX: labelX - width2 / 2 - padding, - minY: labelY - height / 2 - padding, - maxX: labelX + width2 / 2 + padding, - maxY: labelY + height / 2 + padding - }; - if (tryInsert([bbox3], entity2.id, true)) { - p3.x = labelX; - p3.y = labelY; - p3.textAnchor = "middle"; - p3.height = height; - return true; - } - } - return false; - } - } - function doInsert(bbox3, id2) { - bbox3.id = id2; - var oldbox = _entitybboxes[id2]; - if (oldbox) { - _rdrawn.remove(oldbox); - } - _entitybboxes[id2] = bbox3; - _rdrawn.insert(bbox3); + } else { + drawData.template(url); } - function tryInsert(bboxes, id2, saveSkipped) { - var skipped = false; - for (var i4 = 0; i4 < bboxes.length; i4++) { - var bbox3 = bboxes[i4]; - bbox3.id = id2; - if (bbox3.minX < 0 || bbox3.minY < 0 || bbox3.maxX > dimensions[0] || bbox3.maxY > dimensions[1]) { - skipped = true; + return this; + }; + drawData.getSrc = function() { + return _src || ""; + }; + drawData.fitZoom = function() { + var features = getFeatures(_geojson); + if (!features.length) + return; + var map2 = context.map(); + var viewport = map2.trimmedExtent().polygon(); + var coords = features.reduce(function(coords2, feature3) { + var geom = feature3.geometry; + if (!geom) + return coords2; + var c2 = geom.coordinates; + switch (geom.type) { + case "Point": + c2 = [c2]; + case "MultiPoint": + case "LineString": break; - } - if (_rdrawn.collides(bbox3)) { - skipped = true; + case "MultiPolygon": + c2 = utilArrayFlatten(c2); + case "Polygon": + case "MultiLineString": + c2 = utilArrayFlatten(c2); break; - } - } - _entitybboxes[id2] = bboxes; - if (skipped) { - if (saveSkipped) { - _rskipped.load(bboxes); - } - } else { - _rdrawn.load(bboxes); } - return !skipped; + return utilArrayUnion(coords2, c2); + }, []); + if (!geoPolygonIntersectsPolygon(viewport, coords, true)) { + var extent = geoExtent(bounds_default({ type: "LineString", coordinates: coords })); + map2.centerZoom(extent.center(), map2.trimmedExtentZoom(extent)); + } + return this; + }; + init2(); + return drawData; + } + + // modules/svg/debug.js + function svgDebug(projection2, context) { + function drawDebug(selection2) { + const showTile = context.getDebug("tile"); + const showCollision = context.getDebug("collision"); + const showImagery = context.getDebug("imagery"); + const showTouchTargets = context.getDebug("target"); + const showDownloaded = context.getDebug("downloaded"); + let debugData = []; + if (showTile) { + debugData.push({ class: "red", label: "tile" }); + } + if (showCollision) { + debugData.push({ class: "yellow", label: "collision" }); } - var layer = selection2.selectAll(".layer-osm.labels"); - layer.selectAll(".labels-group").data(["halo", "label", "debug"]).enter().append("g").attr("class", function(d2) { - return "labels-group " + d2; - }); - var halo = layer.selectAll(".labels-group.halo"); - var label = layer.selectAll(".labels-group.label"); - var debug2 = layer.selectAll(".labels-group.debug"); - drawPointLabels(label, labelled.point, filter2, "pointlabel", positions.point); - drawPointLabels(halo, labelled.point, filter2, "pointlabel-halo", positions.point); - drawLinePaths(layer, labelled.line, filter2, "", positions.line); - drawLineLabels(label, labelled.line, filter2, "linelabel", positions.line); - drawLineLabels(halo, labelled.line, filter2, "linelabel-halo", positions.line); - drawAreaLabels(label, labelled.area, filter2, "arealabel", positions.area); - drawAreaLabels(halo, labelled.area, filter2, "arealabel-halo", positions.area); - drawAreaIcons(label, labelled.area, filter2, "areaicon", positions.area); - drawAreaIcons(halo, labelled.area, filter2, "areaicon-halo", positions.area); - drawCollisionBoxes(debug2, _rskipped, "debug-skipped"); - drawCollisionBoxes(debug2, _rdrawn, "debug-drawn"); - layer.call(filterLabels); - } - function filterLabels(selection2) { - var drawLayer = selection2.selectAll(".layer-osm.labels"); - var layers = drawLayer.selectAll(".labels-group.halo, .labels-group.label"); - layers.selectAll(".nolabel").classed("nolabel", false); - var mouse = context.map().mouse(); - var graph = context.graph(); - var selectedIDs = context.selectedIDs(); - var ids = []; - var pad2, bbox2; - if (mouse) { - pad2 = 20; - bbox2 = { minX: mouse[0] - pad2, minY: mouse[1] - pad2, maxX: mouse[0] + pad2, maxY: mouse[1] + pad2 }; - var nearMouse = _rdrawn.search(bbox2).map(function(entity2) { - return entity2.id; - }); - ids.push.apply(ids, nearMouse); + if (showImagery) { + debugData.push({ class: "orange", label: "imagery" }); } - for (var i3 = 0; i3 < selectedIDs.length; i3++) { - var entity = graph.hasEntity(selectedIDs[i3]); - if (entity && entity.type === "node") { - ids.push(selectedIDs[i3]); - } + if (showTouchTargets) { + debugData.push({ class: "pink", label: "touchTargets" }); } - layers.selectAll(utilEntitySelector(ids)).classed("nolabel", true); - var debug2 = selection2.selectAll(".labels-group.debug"); - var gj = []; - if (context.getDebug("collision")) { - gj = bbox2 ? [{ - type: "Polygon", - coordinates: [[ - [bbox2.minX, bbox2.minY], - [bbox2.maxX, bbox2.minY], - [bbox2.maxX, bbox2.maxY], - [bbox2.minX, bbox2.maxY], - [bbox2.minX, bbox2.minY] - ]] - }] : []; + if (showDownloaded) { + debugData.push({ class: "purple", label: "downloaded" }); } - var box = debug2.selectAll(".debug-mouse").data(gj); - box.exit().remove(); - box.enter().append("path").attr("class", "debug debug-mouse yellow").merge(box).attr("d", path_default()); + let legend = context.container().select(".main-content").selectAll(".debug-legend").data(debugData.length ? [0] : []); + legend.exit().remove(); + legend = legend.enter().append("div").attr("class", "fillD debug-legend").merge(legend); + let legendItems = legend.selectAll(".debug-legend-item").data(debugData, (d2) => d2.label); + legendItems.exit().remove(); + legendItems.enter().append("span").attr("class", (d2) => "debug-legend-item ".concat(d2.class)).text((d2) => d2.label); + let layer = selection2.selectAll(".layer-debug").data(showImagery || showDownloaded ? [0] : []); + layer.exit().remove(); + layer = layer.enter().append("g").attr("class", "layer-debug").merge(layer); + const extent = context.map().extent(); + _mainFileFetcher.get("imagery").then((d2) => { + const hits = showImagery && d2.query.bbox(extent.rectangle(), true) || []; + const features = hits.map((d4) => d4.features[d4.id]); + let imagery = layer.selectAll("path.debug-imagery").data(features); + imagery.exit().remove(); + imagery.enter().append("path").attr("class", "debug-imagery debug orange"); + }).catch(() => { + }); + const osm = context.connection(); + let dataDownloaded = []; + if (osm && showDownloaded) { + const rtree = osm.caches("get").tile.rtree; + dataDownloaded = rtree.all().map((bbox2) => { + return { + type: "Feature", + properties: { id: bbox2.id }, + geometry: { + type: "Polygon", + coordinates: [[ + [bbox2.minX, bbox2.minY], + [bbox2.minX, bbox2.maxY], + [bbox2.maxX, bbox2.maxY], + [bbox2.maxX, bbox2.minY], + [bbox2.minX, bbox2.minY] + ]] + } + }; + }); + } + let downloaded = layer.selectAll("path.debug-downloaded").data(showDownloaded ? dataDownloaded : []); + downloaded.exit().remove(); + downloaded.enter().append("path").attr("class", "debug-downloaded debug purple"); + layer.selectAll("path").attr("d", svgPath(projection2).geojson); } - var throttleFilterLabels = throttle_default(filterLabels, 100); - drawLabels.observe = function(selection2) { - var listener = function() { - throttleFilterLabels(selection2); - }; - selection2.on("mousemove.hidelabels", listener); - context.on("enter.hidelabels", listener); - }; - drawLabels.off = function(selection2) { - throttleFilterLabels.cancel(); - selection2.on("mousemove.hidelabels", null); - context.on("enter.hidelabels", null); + drawDebug.enabled = function() { + if (!arguments.length) { + return context.getDebug("tile") || context.getDebug("collision") || context.getDebug("imagery") || context.getDebug("target") || context.getDebug("downloaded"); + } else { + return this; + } }; - return drawLabels; + return drawDebug; } - // node_modules/exifr/dist/full.esm.mjs - var e = "undefined" != typeof self ? self : global; - var t = "undefined" != typeof navigator; - var i2 = t && "undefined" == typeof HTMLImageElement; - var n2 = !("undefined" == typeof global || "undefined" == typeof process || !process.versions || !process.versions.node); - var s = e.Buffer; - var r = e.BigInt; - var a = !!s; - var o = (e3) => e3; - function l(e3, t2 = o) { - if (n2) - try { - return "function" == typeof __require ? Promise.resolve(t2(__require(e3))) : Promise.resolve().then(() => ( - /* webpackIgnore: true */ - __toESM(__require(e3)) - )).then(t2); - } catch (t3) { - console.warn("Couldn't load ".concat(e3)); + // modules/svg/defs.js + function svgDefs(context) { + var _defsSelection = select_default2(null); + var _spritesheetIds = [ + "iD-sprite", + "maki-sprite", + "temaki-sprite", + "fa-sprite", + "roentgen-sprite", + "community-sprite" + ]; + function drawDefs(selection2) { + _defsSelection = selection2.append("defs"); + _defsSelection.append("marker").attr("id", "ideditor-oneway-marker").attr("viewBox", "0 0 10 5").attr("refX", 2.5).attr("refY", 2.5).attr("markerWidth", 2).attr("markerHeight", 2).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "oneway-marker-path").attr("d", "M 5,3 L 0,3 L 0,2 L 5,2 L 5,0 L 10,2.5 L 5,5 z").attr("stroke", "none").attr("fill", "#000").attr("opacity", "0.75"); + function addSidedMarker(name, color2, offset) { + _defsSelection.append("marker").attr("id", "ideditor-sided-marker-" + name).attr("viewBox", "0 0 2 2").attr("refX", 1).attr("refY", -offset).attr("markerWidth", 1.5).attr("markerHeight", 1.5).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "sided-marker-path sided-marker-" + name + "-path").attr("d", "M 0,0 L 1,1 L 2,0 z").attr("stroke", "none").attr("fill", color2); } - } - var h = e.fetch; - var u = (e3) => h = e3; - if (!e.fetch) { - const e3 = l("http", (e4) => e4), t2 = l("https", (e4) => e4), i3 = (n3, { headers: s2 } = {}) => new Promise(async (r2, a2) => { - let { port: o2, hostname: l2, pathname: h2, protocol: u2, search: c2 } = new URL(n3); - const f3 = { method: "GET", hostname: l2, path: encodeURI(h2) + c2, headers: s2 }; - "" !== o2 && (f3.port = Number(o2)); - const d2 = ("https:" === u2 ? await t2 : await e3).request(f3, (e4) => { - if (301 === e4.statusCode || 302 === e4.statusCode) { - let t3 = new URL(e4.headers.location, n3).toString(); - return i3(t3, { headers: s2 }).then(r2).catch(a2); - } - r2({ status: e4.statusCode, arrayBuffer: () => new Promise((t3) => { - let i4 = []; - e4.on("data", (e6) => i4.push(e6)), e4.on("end", () => t3(Buffer.concat(i4))); - }) }); + addSidedMarker("natural", "rgb(170, 170, 170)", 0); + addSidedMarker("coastline", "#77dede", 1); + addSidedMarker("waterway", "#77dede", 1); + addSidedMarker("barrier", "#ddd", 1); + addSidedMarker("man_made", "#fff", 0); + _defsSelection.append("marker").attr("id", "ideditor-viewfield-marker").attr("viewBox", "0 0 16 16").attr("refX", 8).attr("refY", 16).attr("markerWidth", 4).attr("markerHeight", 4).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "viewfield-marker-path").attr("d", "M 6,14 C 8,13.4 8,13.4 10,14 L 16,3 C 12,0 4,0 0,3 z").attr("fill", "#333").attr("fill-opacity", "0.75").attr("stroke", "#fff").attr("stroke-width", "0.5px").attr("stroke-opacity", "0.75"); + _defsSelection.append("marker").attr("id", "ideditor-viewfield-marker-wireframe").attr("viewBox", "0 0 16 16").attr("refX", 8).attr("refY", 16).attr("markerWidth", 4).attr("markerHeight", 4).attr("markerUnits", "strokeWidth").attr("orient", "auto").append("path").attr("class", "viewfield-marker-path").attr("d", "M 6,14 C 8,13.4 8,13.4 10,14 L 16,3 C 12,0 4,0 0,3 z").attr("fill", "none").attr("stroke", "#fff").attr("stroke-width", "0.5px").attr("stroke-opacity", "0.75"); + var patterns2 = _defsSelection.selectAll("pattern").data([ + // pattern name, pattern image name + ["beach", "dots"], + ["construction", "construction"], + ["cemetery", "cemetery"], + ["cemetery_christian", "cemetery_christian"], + ["cemetery_buddhist", "cemetery_buddhist"], + ["cemetery_muslim", "cemetery_muslim"], + ["cemetery_jewish", "cemetery_jewish"], + ["farmland", "farmland"], + ["farmyard", "farmyard"], + ["forest", "forest"], + ["forest_broadleaved", "forest_broadleaved"], + ["forest_needleleaved", "forest_needleleaved"], + ["forest_leafless", "forest_leafless"], + ["golf_green", "grass"], + ["grass", "grass"], + ["landfill", "landfill"], + ["meadow", "grass"], + ["orchard", "orchard"], + ["pond", "pond"], + ["quarry", "quarry"], + ["scrub", "bushes"], + ["vineyard", "vineyard"], + ["water_standing", "lines"], + ["waves", "waves"], + ["wetland", "wetland"], + ["wetland_marsh", "wetland_marsh"], + ["wetland_swamp", "wetland_swamp"], + ["wetland_bog", "wetland_bog"], + ["wetland_reedbed", "wetland_reedbed"] + ]).enter().append("pattern").attr("id", function(d2) { + return "ideditor-pattern-" + d2[0]; + }).attr("width", 32).attr("height", 32).attr("patternUnits", "userSpaceOnUse"); + patterns2.append("rect").attr("x", 0).attr("y", 0).attr("width", 32).attr("height", 32).attr("class", function(d2) { + return "pattern-color-" + d2[0]; }); - d2.on("error", a2), d2.end(); - }); - u(i3); - } - function c(e3, t2, i3) { - return t2 in e3 ? Object.defineProperty(e3, t2, { value: i3, enumerable: true, configurable: true, writable: true }) : e3[t2] = i3, e3; - } - var f2 = (e3) => p(e3) ? void 0 : e3; - var d = (e3) => void 0 !== e3; - function p(e3) { - return void 0 === e3 || (e3 instanceof Map ? 0 === e3.size : 0 === Object.values(e3).filter(d).length); - } - function g2(e3) { - let t2 = new Error(e3); - throw delete t2.stack, t2; - } - function m(e3) { - return "" === (e3 = function(e4) { - for (; e4.endsWith("\0"); ) - e4 = e4.slice(0, -1); - return e4; - }(e3).trim()) ? void 0 : e3; - } - function S(e3) { - let t2 = function(e4) { - let t3 = 0; - return e4.ifd0.enabled && (t3 += 1024), e4.exif.enabled && (t3 += 2048), e4.makerNote && (t3 += 2048), e4.userComment && (t3 += 1024), e4.gps.enabled && (t3 += 512), e4.interop.enabled && (t3 += 100), e4.ifd1.enabled && (t3 += 1024), t3 + 2048; - }(e3); - return e3.jfif.enabled && (t2 += 50), e3.xmp.enabled && (t2 += 2e4), e3.iptc.enabled && (t2 += 14e3), e3.icc.enabled && (t2 += 6e3), t2; - } - var C = (e3) => String.fromCharCode.apply(null, e3); - var y = "undefined" != typeof TextDecoder ? new TextDecoder("utf-8") : void 0; - function b(e3) { - return y ? y.decode(e3) : a ? Buffer.from(e3).toString("utf8") : decodeURIComponent(escape(C(e3))); - } - var I = class _I { - static from(e3, t2) { - return e3 instanceof this && e3.le === t2 ? e3 : new _I(e3, void 0, void 0, t2); - } - constructor(e3, t2 = 0, i3, n3) { - if ("boolean" == typeof n3 && (this.le = n3), Array.isArray(e3) && (e3 = new Uint8Array(e3)), 0 === e3) - this.byteOffset = 0, this.byteLength = 0; - else if (e3 instanceof ArrayBuffer) { - void 0 === i3 && (i3 = e3.byteLength - t2); - let n4 = new DataView(e3, t2, i3); - this._swapDataView(n4); - } else if (e3 instanceof Uint8Array || e3 instanceof DataView || e3 instanceof _I) { - void 0 === i3 && (i3 = e3.byteLength - t2), (t2 += e3.byteOffset) + i3 > e3.byteOffset + e3.byteLength && g2("Creating view outside of available memory in ArrayBuffer"); - let n4 = new DataView(e3.buffer, t2, i3); - this._swapDataView(n4); - } else if ("number" == typeof e3) { - let t3 = new DataView(new ArrayBuffer(e3)); - this._swapDataView(t3); - } else - g2("Invalid input argument for BufferView: " + e3); - } - _swapArrayBuffer(e3) { - this._swapDataView(new DataView(e3)); - } - _swapBuffer(e3) { - this._swapDataView(new DataView(e3.buffer, e3.byteOffset, e3.byteLength)); - } - _swapDataView(e3) { - this.dataView = e3, this.buffer = e3.buffer, this.byteOffset = e3.byteOffset, this.byteLength = e3.byteLength; - } - _lengthToEnd(e3) { - return this.byteLength - e3; - } - set(e3, t2, i3 = _I) { - return e3 instanceof DataView || e3 instanceof _I ? e3 = new Uint8Array(e3.buffer, e3.byteOffset, e3.byteLength) : e3 instanceof ArrayBuffer && (e3 = new Uint8Array(e3)), e3 instanceof Uint8Array || g2("BufferView.set(): Invalid data argument."), this.toUint8().set(e3, t2), new i3(this, t2, e3.byteLength); - } - subarray(e3, t2) { - return t2 = t2 || this._lengthToEnd(e3), new _I(this, e3, t2); - } - toUint8() { - return new Uint8Array(this.buffer, this.byteOffset, this.byteLength); - } - getUint8Array(e3, t2) { - return new Uint8Array(this.buffer, this.byteOffset + e3, t2); - } - getString(e3 = 0, t2 = this.byteLength) { - return b(this.getUint8Array(e3, t2)); - } - getLatin1String(e3 = 0, t2 = this.byteLength) { - let i3 = this.getUint8Array(e3, t2); - return C(i3); - } - getUnicodeString(e3 = 0, t2 = this.byteLength) { - const i3 = []; - for (let n3 = 0; n3 < t2 && e3 + n3 < this.byteLength; n3 += 2) - i3.push(this.getUint16(e3 + n3)); - return C(i3); - } - getInt8(e3) { - return this.dataView.getInt8(e3); - } - getUint8(e3) { - return this.dataView.getUint8(e3); - } - getInt16(e3, t2 = this.le) { - return this.dataView.getInt16(e3, t2); - } - getInt32(e3, t2 = this.le) { - return this.dataView.getInt32(e3, t2); - } - getUint16(e3, t2 = this.le) { - return this.dataView.getUint16(e3, t2); - } - getUint32(e3, t2 = this.le) { - return this.dataView.getUint32(e3, t2); - } - getFloat32(e3, t2 = this.le) { - return this.dataView.getFloat32(e3, t2); - } - getFloat64(e3, t2 = this.le) { - return this.dataView.getFloat64(e3, t2); + patterns2.append("image").attr("x", 0).attr("y", 0).attr("width", 32).attr("height", 32).attr("xlink:href", function(d2) { + return context.imagePath("pattern/" + d2[1] + ".png"); + }); + _defsSelection.selectAll("clipPath").data([12, 18, 20, 32, 45]).enter().append("clipPath").attr("id", function(d2) { + return "ideditor-clip-square-" + d2; + }).append("rect").attr("x", 0).attr("y", 0).attr("width", function(d2) { + return d2; + }).attr("height", function(d2) { + return d2; + }); + addSprites(_spritesheetIds, true); } - getFloat(e3, t2 = this.le) { - return this.dataView.getFloat32(e3, t2); + function addSprites(ids, overrideColors) { + _spritesheetIds = utilArrayUniq(_spritesheetIds.concat(ids)); + var spritesheets = _defsSelection.selectAll(".spritesheet").data(_spritesheetIds); + spritesheets.enter().append("g").attr("class", function(d2) { + return "spritesheet spritesheet-" + d2; + }).each(function(d2) { + var url = context.imagePath(d2 + ".svg"); + var node = select_default2(this).node(); + svg(url).then(function(svg2) { + node.appendChild( + select_default2(svg2.documentElement).attr("id", "ideditor-" + d2).node() + ); + if (overrideColors && d2 !== "iD-sprite") { + select_default2(node).selectAll("path").attr("fill", "currentColor"); + } + }).catch(function() { + }); + }); + spritesheets.exit().remove(); } - getDouble(e3, t2 = this.le) { - return this.dataView.getFloat64(e3, t2); + drawDefs.addSprites = addSprites; + return drawDefs; + } + + // modules/svg/keepRight.js + var _layerEnabled = false; + var _qaService; + function svgKeepRight(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); + const minZoom4 = 12; + let touchLayer = select_default2(null); + let drawLayer = select_default2(null); + let layerVisible = false; + function markerPath(selection2, klass) { + selection2.attr("class", klass).attr("transform", "translate(-4, -24)").attr("d", "M11.6,6.2H7.1l1.4-5.1C8.6,0.6,8.1,0,7.5,0H2.2C1.7,0,1.3,0.3,1.3,0.8L0,10.2c-0.1,0.6,0.4,1.1,0.9,1.1h4.6l-1.8,7.6C3.6,19.4,4.1,20,4.7,20c0.3,0,0.6-0.2,0.8-0.5l6.9-11.9C12.7,7,12.3,6.2,11.6,6.2z"); } - getUintBytes(e3, t2, i3) { - switch (t2) { - case 1: - return this.getUint8(e3, i3); - case 2: - return this.getUint16(e3, i3); - case 4: - return this.getUint32(e3, i3); - case 8: - return this.getUint64 && this.getUint64(e3, i3); + function getService() { + if (services.keepRight && !_qaService) { + _qaService = services.keepRight; + _qaService.on("loaded", throttledRedraw); + } else if (!services.keepRight && _qaService) { + _qaService = null; } + return _qaService; } - getUint(e3, t2, i3) { - switch (t2) { - case 8: - return this.getUint8(e3, i3); - case 16: - return this.getUint16(e3, i3); - case 32: - return this.getUint32(e3, i3); - case 64: - return this.getUint64 && this.getUint64(e3, i3); + function editOn() { + if (!layerVisible) { + layerVisible = true; + drawLayer.style("display", "block"); } } - toString(e3) { - return this.dataView.toString(e3, this.constructor.name); + function editOff() { + if (layerVisible) { + layerVisible = false; + drawLayer.style("display", "none"); + drawLayer.selectAll(".qaItem.keepRight").remove(); + touchLayer.selectAll(".qaItem.keepRight").remove(); + } } - ensureChunk() { + function layerOn() { + editOn(); + drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", () => dispatch14.call("change")); } - }; - function P(e3, t2) { - g2("".concat(e3, " '").concat(t2, "' was not loaded, try using full build of exifr.")); - } - var k = class extends Map { - constructor(e3) { - super(), this.kind = e3; + function layerOff() { + throttledRedraw.cancel(); + drawLayer.interrupt(); + touchLayer.selectAll(".qaItem.keepRight").remove(); + drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", () => { + editOff(); + dispatch14.call("change"); + }); } - get(e3, t2) { - return this.has(e3) || P(this.kind, e3), t2 && (e3 in t2 || function(e4, t3) { - g2("Unknown ".concat(e4, " '").concat(t3, "'.")); - }(this.kind, e3), t2[e3].enabled || P(this.kind, e3)), super.get(e3); + function updateMarkers() { + if (!layerVisible || !_layerEnabled) + return; + const service = getService(); + const selectedID = context.selectedErrorID(); + const data = service ? service.getItems(projection2) : []; + const getTransform = svgPointTransform(projection2); + const markers = drawLayer.selectAll(".qaItem.keepRight").data(data, (d2) => d2.id); + markers.exit().remove(); + const markersEnter = markers.enter().append("g").attr("class", (d2) => "qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.parentIssueType)); + markersEnter.append("ellipse").attr("cx", 0.5).attr("cy", 1).attr("rx", 6.5).attr("ry", 3).attr("class", "stroke"); + markersEnter.append("path").call(markerPath, "shadow"); + markersEnter.append("use").attr("class", "qaItem-fill").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").attr("xlink:href", "#iD-icon-bolt"); + markers.merge(markersEnter).sort(sortY).classed("selected", (d2) => d2.id === selectedID).attr("transform", getTransform); + if (touchLayer.empty()) + return; + const fillClass = context.getDebug("target") ? "pink " : "nocolor "; + const targets = touchLayer.selectAll(".qaItem.keepRight").data(data, (d2) => d2.id); + targets.exit().remove(); + targets.enter().append("rect").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").merge(targets).sort(sortY).attr("class", (d2) => "qaItem ".concat(d2.service, " target ").concat(fillClass, " itemId-").concat(d2.id)).attr("transform", getTransform); + function sortY(a2, b2) { + return a2.id === selectedID ? 1 : b2.id === selectedID ? -1 : a2.severity === "error" && b2.severity !== "error" ? 1 : b2.severity === "error" && a2.severity !== "error" ? -1 : b2.loc[1] - a2.loc[1]; + } } - keyList() { - return Array.from(this.keys()); + function drawKeepRight(selection2) { + const service = getService(); + const surface = context.surface(); + if (surface && !surface.empty()) { + touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); + } + drawLayer = selection2.selectAll(".layer-keepRight").data(service ? [0] : []); + drawLayer.exit().remove(); + drawLayer = drawLayer.enter().append("g").attr("class", "layer-keepRight").style("display", _layerEnabled ? "block" : "none").merge(drawLayer); + if (_layerEnabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + service.loadIssues(projection2); + updateMarkers(); + } else { + editOff(); + } + } } - }; - var w = new k("file parser"); - var T = new k("segment parser"); - var A = new k("file reader"); - function D(e3, n3) { - return "string" == typeof e3 ? O(e3, n3) : t && !i2 && e3 instanceof HTMLImageElement ? O(e3.src, n3) : e3 instanceof Uint8Array || e3 instanceof ArrayBuffer || e3 instanceof DataView ? new I(e3) : t && e3 instanceof Blob ? x(e3, n3, "blob", R) : void g2("Invalid input argument"); - } - function O(e3, i3) { - return (s2 = e3).startsWith("data:") || s2.length > 1e4 ? v(e3, i3, "base64") : n2 && e3.includes("://") ? x(e3, i3, "url", M) : n2 ? v(e3, i3, "fs") : t ? x(e3, i3, "url", M) : void g2("Invalid input argument"); - var s2; - } - async function x(e3, t2, i3, n3) { - return A.has(i3) ? v(e3, t2, i3) : n3 ? async function(e4, t3) { - let i4 = await t3(e4); - return new I(i4); - }(e3, n3) : void g2("Parser ".concat(i3, " is not loaded")); - } - async function v(e3, t2, i3) { - let n3 = new (A.get(i3))(e3, t2); - return await n3.read(), n3; + drawKeepRight.enabled = function(val) { + if (!arguments.length) + return _layerEnabled; + _layerEnabled = val; + if (_layerEnabled) { + layerOn(); + } else { + layerOff(); + if (context.selectedErrorID()) { + context.enter(modeBrowse(context)); + } + } + dispatch14.call("change"); + return this; + }; + drawKeepRight.supported = () => !!getService(); + return drawKeepRight; } - var M = (e3) => h(e3).then((e4) => e4.arrayBuffer()); - var R = (e3) => new Promise((t2, i3) => { - let n3 = new FileReader(); - n3.onloadend = () => t2(n3.result || new ArrayBuffer()), n3.onerror = i3, n3.readAsArrayBuffer(e3); - }); - var L = class extends Map { - get tagKeys() { - return this.allKeys || (this.allKeys = Array.from(this.keys())), this.allKeys; + + // modules/svg/geolocate.js + function svgGeolocate(projection2) { + var layer = select_default2(null); + var _position; + function init2() { + if (svgGeolocate.initialized) + return; + svgGeolocate.enabled = false; + svgGeolocate.initialized = true; } - get tagValues() { - return this.allValues || (this.allValues = Array.from(this.values())), this.allValues; + function showLayer() { + layer.style("display", "block"); } - }; - function U(e3, t2, i3) { - let n3 = new L(); - for (let [e4, t3] of i3) - n3.set(e4, t3); - if (Array.isArray(t2)) - for (let i4 of t2) - e3.set(i4, n3); - else - e3.set(t2, n3); - return n3; - } - function F(e3, t2, i3) { - let n3, s2 = e3.get(t2); - for (n3 of i3) - s2.set(n3[0], n3[1]); - } - var E = /* @__PURE__ */ new Map(); - var B = /* @__PURE__ */ new Map(); - var N = /* @__PURE__ */ new Map(); - var G = ["chunked", "firstChunkSize", "firstChunkSizeNode", "firstChunkSizeBrowser", "chunkSize", "chunkLimit"]; - var V = ["jfif", "xmp", "icc", "iptc", "ihdr"]; - var z = ["tiff", ...V]; - var H = ["ifd0", "ifd1", "exif", "gps", "interop"]; - var j2 = [...z, ...H]; - var W = ["makerNote", "userComment"]; - var K = ["translateKeys", "translateValues", "reviveValues", "multiSegment"]; - var X = [...K, "sanitize", "mergeOutput", "silentErrors"]; - var _ = class { - get translate() { - return this.translateKeys || this.translateValues || this.reviveValues; + function hideLayer() { + layer.transition().duration(250).style("opacity", 0); } - }; - var Y = class extends _ { - get needed() { - return this.enabled || this.deps.size > 0; + function layerOn() { + layer.style("opacity", 0).transition().duration(250).style("opacity", 1); } - constructor(e3, t2, i3, n3) { - if (super(), c(this, "enabled", false), c(this, "skip", /* @__PURE__ */ new Set()), c(this, "pick", /* @__PURE__ */ new Set()), c(this, "deps", /* @__PURE__ */ new Set()), c(this, "translateKeys", false), c(this, "translateValues", false), c(this, "reviveValues", false), this.key = e3, this.enabled = t2, this.parse = this.enabled, this.applyInheritables(n3), this.canBeFiltered = H.includes(e3), this.canBeFiltered && (this.dict = E.get(e3)), void 0 !== i3) - if (Array.isArray(i3)) - this.parse = this.enabled = true, this.canBeFiltered && i3.length > 0 && this.translateTagSet(i3, this.pick); - else if ("object" == typeof i3) { - if (this.enabled = true, this.parse = false !== i3.parse, this.canBeFiltered) { - let { pick: e4, skip: t3 } = i3; - e4 && e4.length > 0 && this.translateTagSet(e4, this.pick), t3 && t3.length > 0 && this.translateTagSet(t3, this.skip); - } - this.applyInheritables(i3); - } else - true === i3 || false === i3 ? this.parse = this.enabled = i3 : g2("Invalid options argument: ".concat(i3)); + function layerOff() { + layer.style("display", "none"); } - applyInheritables(e3) { - let t2, i3; - for (t2 of K) - i3 = e3[t2], void 0 !== i3 && (this[t2] = i3); + function transform2(d2) { + return svgPointTransform(projection2)(d2); } - translateTagSet(e3, t2) { - if (this.dict) { - let i3, n3, { tagKeys: s2, tagValues: r2 } = this.dict; - for (i3 of e3) - "string" == typeof i3 ? (n3 = r2.indexOf(i3), -1 === n3 && (n3 = s2.indexOf(Number(i3))), -1 !== n3 && t2.add(Number(s2[n3]))) : t2.add(i3); - } else - for (let i3 of e3) - t2.add(i3); + function accuracy(accuracy2, loc) { + var degreesRadius = geoMetersToLat(accuracy2), tangentLoc = [loc[0], loc[1] + degreesRadius], projectedTangent = projection2(tangentLoc), projectedLoc = projection2([loc[0], loc[1]]); + return Math.round(projectedLoc[1] - projectedTangent[1]).toString(); } - finalizeFilters() { - !this.enabled && this.deps.size > 0 ? (this.enabled = true, ee(this.pick, this.deps)) : this.enabled && this.pick.size > 0 && ee(this.pick, this.deps); + function update() { + var geolocation = { loc: [_position.coords.longitude, _position.coords.latitude] }; + var groups = layer.selectAll(".geolocations").selectAll(".geolocation").data([geolocation]); + groups.exit().remove(); + var pointsEnter = groups.enter().append("g").attr("class", "geolocation"); + pointsEnter.append("circle").attr("class", "geolocate-radius").attr("dx", "0").attr("dy", "0").attr("fill", "rgb(15,128,225)").attr("fill-opacity", "0.3").attr("r", "0"); + pointsEnter.append("circle").attr("dx", "0").attr("dy", "0").attr("fill", "rgb(15,128,225)").attr("stroke", "white").attr("stroke-width", "1.5").attr("r", "6"); + groups.merge(pointsEnter).attr("transform", transform2); + layer.select(".geolocate-radius").attr("r", accuracy(_position.coords.accuracy, geolocation.loc)); } - }; - var $2 = { jfif: false, tiff: true, xmp: false, icc: false, iptc: false, ifd0: true, ifd1: false, exif: true, gps: true, interop: false, ihdr: void 0, makerNote: false, userComment: false, multiSegment: false, skip: [], pick: [], translateKeys: true, translateValues: true, reviveValues: true, sanitize: true, mergeOutput: true, silentErrors: true, chunked: true, firstChunkSize: void 0, firstChunkSizeNode: 512, firstChunkSizeBrowser: 65536, chunkSize: 65536, chunkLimit: 5 }; - var J = /* @__PURE__ */ new Map(); - var q = class extends _ { - static useCached(e3) { - let t2 = J.get(e3); - return void 0 !== t2 || (t2 = new this(e3), J.set(e3, t2)), t2; + function drawLocation(selection2) { + var enabled = svgGeolocate.enabled; + layer = selection2.selectAll(".layer-geolocate").data([0]); + layer.exit().remove(); + var layerEnter = layer.enter().append("g").attr("class", "layer-geolocate").style("display", enabled ? "block" : "none"); + layerEnter.append("g").attr("class", "geolocations"); + layer = layerEnter.merge(layer); + if (enabled) { + update(); + } else { + layerOff(); + } } - constructor(e3) { - super(), true === e3 ? this.setupFromTrue() : void 0 === e3 ? this.setupFromUndefined() : Array.isArray(e3) ? this.setupFromArray(e3) : "object" == typeof e3 ? this.setupFromObject(e3) : g2("Invalid options argument ".concat(e3)), void 0 === this.firstChunkSize && (this.firstChunkSize = t ? this.firstChunkSizeBrowser : this.firstChunkSizeNode), this.mergeOutput && (this.ifd1.enabled = false), this.filterNestedSegmentTags(), this.traverseTiffDependencyTree(), this.checkLoadedPlugins(); + drawLocation.enabled = function(position, enabled) { + if (!arguments.length) + return svgGeolocate.enabled; + _position = position; + svgGeolocate.enabled = enabled; + if (svgGeolocate.enabled) { + showLayer(); + layerOn(); + } else { + hideLayer(); + } + return this; + }; + init2(); + return drawLocation; + } + + // modules/svg/labels.js + var import_rbush6 = __toESM(require_rbush_min()); + function svgLabels(projection2, context) { + var path = path_default(projection2); + var detected = utilDetect(); + var baselineHack = detected.ie || detected.browser.toLowerCase() === "edge" || detected.browser.toLowerCase() === "firefox" && detected.version >= 70; + var _rdrawn = new import_rbush6.default(); + var _rskipped = new import_rbush6.default(); + var _textWidthCache = {}; + var _entitybboxes = {}; + var labelStack = [ + ["line", "aeroway", "*", 12], + ["line", "highway", "motorway", 12], + ["line", "highway", "trunk", 12], + ["line", "highway", "primary", 12], + ["line", "highway", "secondary", 12], + ["line", "highway", "tertiary", 12], + ["line", "highway", "*", 12], + ["line", "railway", "*", 12], + ["line", "waterway", "*", 12], + ["area", "aeroway", "*", 12], + ["area", "amenity", "*", 12], + ["area", "building", "*", 12], + ["area", "historic", "*", 12], + ["area", "leisure", "*", 12], + ["area", "man_made", "*", 12], + ["area", "natural", "*", 12], + ["area", "shop", "*", 12], + ["area", "tourism", "*", 12], + ["area", "camp_site", "*", 12], + ["point", "aeroway", "*", 10], + ["point", "amenity", "*", 10], + ["point", "building", "*", 10], + ["point", "historic", "*", 10], + ["point", "leisure", "*", 10], + ["point", "man_made", "*", 10], + ["point", "natural", "*", 10], + ["point", "shop", "*", 10], + ["point", "tourism", "*", 10], + ["point", "camp_site", "*", 10], + ["line", "ref", "*", 12], + ["area", "ref", "*", 12], + ["point", "ref", "*", 10], + ["line", "name", "*", 12], + ["area", "name", "*", 12], + ["point", "name", "*", 10] + ]; + function shouldSkipIcon(preset) { + var noIcons = ["building", "landuse", "natural"]; + return noIcons.some(function(s2) { + return preset.id.indexOf(s2) >= 0; + }); } - setupFromUndefined() { - let e3; - for (e3 of G) - this[e3] = $2[e3]; - for (e3 of X) - this[e3] = $2[e3]; - for (e3 of W) - this[e3] = $2[e3]; - for (e3 of j2) - this[e3] = new Y(e3, $2[e3], void 0, this); + function get4(array2, prop) { + return function(d2, i3) { + return array2[i3][prop]; + }; } - setupFromTrue() { - let e3; - for (e3 of G) - this[e3] = $2[e3]; - for (e3 of X) - this[e3] = $2[e3]; - for (e3 of W) - this[e3] = true; - for (e3 of j2) - this[e3] = new Y(e3, true, void 0, this); + function textWidth(text, size, elem) { + var c2 = _textWidthCache[size]; + if (!c2) + c2 = _textWidthCache[size] = {}; + if (c2[text]) { + return c2[text]; + } else if (elem) { + c2[text] = elem.getComputedTextLength(); + return c2[text]; + } else { + var str = encodeURIComponent(text).match(/%[CDEFcdef]/g); + if (str === null) { + return size / 3 * 2 * text.length; + } else { + return size / 3 * (2 * text.length + str.length); + } + } } - setupFromArray(e3) { - let t2; - for (t2 of G) - this[t2] = $2[t2]; - for (t2 of X) - this[t2] = $2[t2]; - for (t2 of W) - this[t2] = $2[t2]; - for (t2 of j2) - this[t2] = new Y(t2, false, void 0, this); - this.setupGlobalFilters(e3, void 0, H); + function drawLinePaths(selection2, entities, filter2, classes, labels) { + var paths = selection2.selectAll("path").filter(filter2).data(entities, osmEntity.key); + paths.exit().remove(); + paths.enter().append("path").style("stroke-width", get4(labels, "font-size")).attr("id", function(d2) { + return "ideditor-labelpath-" + d2.id; + }).attr("class", classes).merge(paths).attr("d", get4(labels, "lineString")); } - setupFromObject(e3) { - let t2; - for (t2 of (H.ifd0 = H.ifd0 || H.image, H.ifd1 = H.ifd1 || H.thumbnail, Object.assign(this, e3), G)) - this[t2] = Z(e3[t2], $2[t2]); - for (t2 of X) - this[t2] = Z(e3[t2], $2[t2]); - for (t2 of W) - this[t2] = Z(e3[t2], $2[t2]); - for (t2 of z) - this[t2] = new Y(t2, $2[t2], e3[t2], this); - for (t2 of H) - this[t2] = new Y(t2, $2[t2], e3[t2], this.tiff); - this.setupGlobalFilters(e3.pick, e3.skip, H, j2), true === e3.tiff ? this.batchEnableWithBool(H, true) : false === e3.tiff ? this.batchEnableWithUserValue(H, e3) : Array.isArray(e3.tiff) ? this.setupGlobalFilters(e3.tiff, void 0, H) : "object" == typeof e3.tiff && this.setupGlobalFilters(e3.tiff.pick, e3.tiff.skip, H); + function drawLineLabels(selection2, entities, filter2, classes, labels) { + var texts = selection2.selectAll("text." + classes).filter(filter2).data(entities, osmEntity.key); + texts.exit().remove(); + texts.enter().append("text").attr("class", function(d2, i3) { + return classes + " " + labels[i3].classes + " " + d2.id; + }).attr("dy", baselineHack ? "0.35em" : null).append("textPath").attr("class", "textpath"); + selection2.selectAll("text." + classes).selectAll(".textpath").filter(filter2).data(entities, osmEntity.key).attr("startOffset", "50%").attr("xlink:href", function(d2) { + return "#ideditor-labelpath-" + d2.id; + }).text(utilDisplayNameForPath); } - batchEnableWithBool(e3, t2) { - for (let i3 of e3) - this[i3].enabled = t2; + function drawPointLabels(selection2, entities, filter2, classes, labels) { + var texts = selection2.selectAll("text." + classes).filter(filter2).data(entities, osmEntity.key); + texts.exit().remove(); + texts.enter().append("text").attr("class", function(d2, i3) { + return classes + " " + labels[i3].classes + " " + d2.id; + }).merge(texts).attr("x", get4(labels, "x")).attr("y", get4(labels, "y")).style("text-anchor", get4(labels, "textAnchor")).text(utilDisplayName).each(function(d2, i3) { + textWidth(utilDisplayName(d2), labels[i3].height, this); + }); } - batchEnableWithUserValue(e3, t2) { - for (let i3 of e3) { - let e4 = t2[i3]; - this[i3].enabled = false !== e4 && void 0 !== e4; + function drawAreaLabels(selection2, entities, filter2, classes, labels) { + entities = entities.filter(hasText); + labels = labels.filter(hasText); + drawPointLabels(selection2, entities, filter2, classes, labels); + function hasText(d2, i3) { + return labels[i3].hasOwnProperty("x") && labels[i3].hasOwnProperty("y"); } } - setupGlobalFilters(e3, t2, i3, n3 = i3) { - if (e3 && e3.length) { - for (let e4 of n3) - this[e4].enabled = false; - let t3 = Q(e3, i3); - for (let [e4, i4] of t3) - ee(this[e4].pick, i4), this[e4].enabled = true; - } else if (t2 && t2.length) { - let e4 = Q(t2, i3); - for (let [t3, i4] of e4) - ee(this[t3].skip, i4); + function drawAreaIcons(selection2, entities, filter2, classes, labels) { + var icons = selection2.selectAll("use." + classes).filter(filter2).data(entities, osmEntity.key); + icons.exit().remove(); + icons.enter().append("use").attr("class", "icon " + classes).attr("width", "17px").attr("height", "17px").merge(icons).attr("transform", get4(labels, "transform")).attr("xlink:href", function(d2) { + var preset = _mainPresetIndex.match(d2, context.graph()); + var picon = preset && preset.icon; + return picon ? "#" + picon : ""; + }); + } + function drawCollisionBoxes(selection2, rtree, which) { + var classes = "debug " + which + " " + (which === "debug-skipped" ? "orange" : "yellow"); + var gj = []; + if (context.getDebug("collision")) { + gj = rtree.all().map(function(d2) { + return { type: "Polygon", coordinates: [[ + [d2.minX, d2.minY], + [d2.maxX, d2.minY], + [d2.maxX, d2.maxY], + [d2.minX, d2.maxY], + [d2.minX, d2.minY] + ]] }; + }); + } + var boxes = selection2.selectAll("." + which).data(gj); + boxes.exit().remove(); + boxes.enter().append("path").attr("class", classes).merge(boxes).attr("d", path_default()); + } + function drawLabels(selection2, graph, entities, filter2, dimensions, fullRedraw) { + var wireframe = context.surface().classed("fill-wireframe"); + var zoom = geoScaleToZoom(projection2.scale()); + var labelable = []; + var renderNodeAs = {}; + var i3, j2, k2, entity, geometry; + for (i3 = 0; i3 < labelStack.length; i3++) { + labelable.push([]); + } + if (fullRedraw) { + _rdrawn.clear(); + _rskipped.clear(); + _entitybboxes = {}; + } else { + for (i3 = 0; i3 < entities.length; i3++) { + entity = entities[i3]; + var toRemove = [].concat(_entitybboxes[entity.id] || []).concat(_entitybboxes[entity.id + "I"] || []); + for (j2 = 0; j2 < toRemove.length; j2++) { + _rdrawn.remove(toRemove[j2]); + _rskipped.remove(toRemove[j2]); + } + } + } + for (i3 = 0; i3 < entities.length; i3++) { + entity = entities[i3]; + geometry = entity.geometry(graph); + if (geometry === "point" || geometry === "vertex" && isInterestingVertex(entity)) { + var hasDirections = entity.directions(graph, projection2).length; + var markerPadding; + if (!wireframe && geometry === "point" && !(zoom >= 18 && hasDirections)) { + renderNodeAs[entity.id] = "point"; + markerPadding = 20; + } else { + renderNodeAs[entity.id] = "vertex"; + markerPadding = 0; + } + var coord2 = projection2(entity.loc); + var nodePadding = 10; + var bbox2 = { + minX: coord2[0] - nodePadding, + minY: coord2[1] - nodePadding - markerPadding, + maxX: coord2[0] + nodePadding, + maxY: coord2[1] + nodePadding + }; + doInsert(bbox2, entity.id + "P"); + } + if (geometry === "vertex") { + geometry = "point"; + } + var preset = geometry === "area" && _mainPresetIndex.match(entity, graph); + var icon2 = preset && !shouldSkipIcon(preset) && preset.icon; + if (!icon2 && !utilDisplayName(entity)) + continue; + for (k2 = 0; k2 < labelStack.length; k2++) { + var matchGeom = labelStack[k2][0]; + var matchKey = labelStack[k2][1]; + var matchVal = labelStack[k2][2]; + var hasVal = entity.tags[matchKey]; + if (geometry === matchGeom && hasVal && (matchVal === "*" || matchVal === hasVal)) { + labelable[k2].push(entity); + break; + } + } + } + var positions = { + point: [], + line: [], + area: [] + }; + var labelled = { + point: [], + line: [], + area: [] + }; + for (k2 = 0; k2 < labelable.length; k2++) { + var fontSize = labelStack[k2][3]; + for (i3 = 0; i3 < labelable[k2].length; i3++) { + entity = labelable[k2][i3]; + geometry = entity.geometry(graph); + var getName = geometry === "line" ? utilDisplayNameForPath : utilDisplayName; + var name = getName(entity); + var width = name && textWidth(name, fontSize); + var p2 = null; + if (geometry === "point" || geometry === "vertex") { + if (wireframe) + continue; + var renderAs = renderNodeAs[entity.id]; + if (renderAs === "vertex" && zoom < 17) + continue; + p2 = getPointLabel(entity, width, fontSize, renderAs); + } else if (geometry === "line") { + p2 = getLineLabel(entity, width, fontSize); + } else if (geometry === "area") { + p2 = getAreaLabel(entity, width, fontSize); + } + if (p2) { + if (geometry === "vertex") { + geometry = "point"; + } + p2.classes = geometry + " tag-" + labelStack[k2][1]; + positions[geometry].push(p2); + labelled[geometry].push(entity); + } + } + } + function isInterestingVertex(entity2) { + var selectedIDs = context.selectedIDs(); + return entity2.hasInterestingTags() || entity2.isEndpoint(graph) || entity2.isConnected(graph) || selectedIDs.indexOf(entity2.id) !== -1 || graph.parentWays(entity2).some(function(parent) { + return selectedIDs.indexOf(parent.id) !== -1; + }); + } + function getPointLabel(entity2, width2, height, geometry2) { + var y2 = geometry2 === "point" ? -12 : 0; + var pointOffsets = { + ltr: [15, y2, "start"], + rtl: [-15, y2, "end"] + }; + var textDirection = _mainLocalizer.textDirection(); + var coord3 = projection2(entity2.loc); + var textPadding = 2; + var offset = pointOffsets[textDirection]; + var p3 = { + height, + width: width2, + x: coord3[0] + offset[0], + y: coord3[1] + offset[1], + textAnchor: offset[2] + }; + var bbox3; + if (textDirection === "rtl") { + bbox3 = { + minX: p3.x - width2 - textPadding, + minY: p3.y - height / 2 - textPadding, + maxX: p3.x + textPadding, + maxY: p3.y + height / 2 + textPadding + }; + } else { + bbox3 = { + minX: p3.x - textPadding, + minY: p3.y - height / 2 - textPadding, + maxX: p3.x + width2 + textPadding, + maxY: p3.y + height / 2 + textPadding + }; + } + if (tryInsert([bbox3], entity2.id, true)) { + return p3; + } + } + function getLineLabel(entity2, width2, height) { + var viewport = geoExtent(context.projection.clipExtent()).polygon(); + var points = graph.childNodes(entity2).map(function(node) { + return projection2(node.loc); + }); + var length2 = geoPathLength(points); + if (length2 < width2 + 20) + return; + var lineOffsets = [ + 50, + 45, + 55, + 40, + 60, + 35, + 65, + 30, + 70, + 25, + 75, + 20, + 80, + 15, + 95, + 10, + 90, + 5, + 95 + ]; + var padding = 3; + for (var i4 = 0; i4 < lineOffsets.length; i4++) { + var offset = lineOffsets[i4]; + var middle = offset / 100 * length2; + var start2 = middle - width2 / 2; + if (start2 < 0 || start2 + width2 > length2) + continue; + var sub = subpath(points, start2, start2 + width2); + if (!sub || !geoPolygonIntersectsPolygon(viewport, sub, true)) { + continue; + } + var isReverse = reverse(sub); + if (isReverse) { + sub = sub.reverse(); + } + var bboxes = []; + var boxsize = (height + 2) / 2; + for (var j3 = 0; j3 < sub.length - 1; j3++) { + var a2 = sub[j3]; + var b2 = sub[j3 + 1]; + var num = Math.max(1, Math.floor(geoVecLength(a2, b2) / boxsize / 2)); + for (var box = 0; box < num; box++) { + var p3 = geoVecInterp(a2, b2, box / num); + var x05 = p3[0] - boxsize - padding; + var y05 = p3[1] - boxsize - padding; + var x12 = p3[0] + boxsize + padding; + var y12 = p3[1] + boxsize + padding; + bboxes.push({ + minX: Math.min(x05, x12), + minY: Math.min(y05, y12), + maxX: Math.max(x05, x12), + maxY: Math.max(y05, y12) + }); + } + } + if (tryInsert(bboxes, entity2.id, false)) { + return { + "font-size": height + 2, + lineString: lineString2(sub), + startOffset: offset + "%" + }; + } + } + function reverse(p4) { + var angle2 = Math.atan2(p4[1][1] - p4[0][1], p4[1][0] - p4[0][0]); + return !(p4[0][0] < p4[p4.length - 1][0] && angle2 < Math.PI / 2 && angle2 > -Math.PI / 2); + } + function lineString2(points2) { + return "M" + points2.join("L"); + } + function subpath(points2, from, to) { + var sofar = 0; + var start3, end, i0, i1; + for (var i5 = 0; i5 < points2.length - 1; i5++) { + var a3 = points2[i5]; + var b3 = points2[i5 + 1]; + var current = geoVecLength(a3, b3); + var portion; + if (!start3 && sofar + current >= from) { + portion = (from - sofar) / current; + start3 = [ + a3[0] + portion * (b3[0] - a3[0]), + a3[1] + portion * (b3[1] - a3[1]) + ]; + i0 = i5 + 1; + } + if (!end && sofar + current >= to) { + portion = (to - sofar) / current; + end = [ + a3[0] + portion * (b3[0] - a3[0]), + a3[1] + portion * (b3[1] - a3[1]) + ]; + i1 = i5 + 1; + } + sofar += current; + } + var result = points2.slice(i0, i1); + result.unshift(start3); + result.push(end); + return result; + } } - } - filterNestedSegmentTags() { - let { ifd0: e3, exif: t2, xmp: i3, iptc: n3, icc: s2 } = this; - this.makerNote ? t2.deps.add(37500) : t2.skip.add(37500), this.userComment ? t2.deps.add(37510) : t2.skip.add(37510), i3.enabled || e3.skip.add(700), n3.enabled || e3.skip.add(33723), s2.enabled || e3.skip.add(34675); - } - traverseTiffDependencyTree() { - let { ifd0: e3, exif: t2, gps: i3, interop: n3 } = this; - n3.needed && (t2.deps.add(40965), e3.deps.add(40965)), t2.needed && e3.deps.add(34665), i3.needed && e3.deps.add(34853), this.tiff.enabled = H.some((e4) => true === this[e4].enabled) || this.makerNote || this.userComment; - for (let e4 of H) - this[e4].finalizeFilters(); - } - get onlyTiff() { - return !V.map((e3) => this[e3].enabled).some((e3) => true === e3) && this.tiff.enabled; - } - checkLoadedPlugins() { - for (let e3 of z) - this[e3].enabled && !T.has(e3) && P("segment parser", e3); - } - }; - function Q(e3, t2) { - let i3, n3, s2, r2, a2 = []; - for (s2 of t2) { - for (r2 of (i3 = E.get(s2), n3 = [], i3)) - (e3.includes(r2[0]) || e3.includes(r2[1])) && n3.push(r2[0]); - n3.length && a2.push([s2, n3]); - } - return a2; - } - function Z(e3, t2) { - return void 0 !== e3 ? e3 : void 0 !== t2 ? t2 : void 0; - } - function ee(e3, t2) { - for (let i3 of t2) - e3.add(i3); - } - c(q, "default", $2); - var te = class { - constructor(e3) { - c(this, "parsers", {}), c(this, "output", {}), c(this, "errors", []), c(this, "pushToErrors", (e4) => this.errors.push(e4)), this.options = q.useCached(e3); - } - async read(e3) { - this.file = await D(e3, this.options); - } - setup() { - if (this.fileParser) - return; - let { file: e3 } = this, t2 = e3.getUint16(0); - for (let [i3, n3] of w) - if (n3.canHandle(e3, t2)) - return this.fileParser = new n3(this.options, this.file, this.parsers), e3[i3] = true; - this.file.close && this.file.close(), g2("Unknown file format"); - } - async parse() { - let { output: e3, errors: t2 } = this; - return this.setup(), this.options.silentErrors ? (await this.executeParsers().catch(this.pushToErrors), t2.push(...this.fileParser.errors)) : await this.executeParsers(), this.file.close && this.file.close(), this.options.silentErrors && t2.length > 0 && (e3.errors = t2), f2(e3); - } - async executeParsers() { - let { output: e3 } = this; - await this.fileParser.parse(); - let t2 = Object.values(this.parsers).map(async (t3) => { - let i3 = await t3.parse(); - t3.assignToOutput(e3, i3); - }); - this.options.silentErrors && (t2 = t2.map((e4) => e4.catch(this.pushToErrors))), await Promise.all(t2); - } - async extractThumbnail() { - this.setup(); - let { options: e3, file: t2 } = this, i3 = T.get("tiff", e3); - var n3; - if (t2.tiff ? n3 = { start: 0, type: "tiff" } : t2.jpeg && (n3 = await this.fileParser.getOrFindSegment("tiff")), void 0 === n3) - return; - let s2 = await this.fileParser.ensureSegmentChunk(n3), r2 = this.parsers.tiff = new i3(s2, e3, t2), a2 = await r2.extractThumbnail(); - return t2.close && t2.close(), a2; - } - }; - async function ie(e3, t2) { - let i3 = new te(t2); - return await i3.read(e3), i3.parse(); - } - var ne = Object.freeze({ __proto__: null, parse: ie, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j2, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q }); - var se = class { - constructor(e3, t2, i3) { - c(this, "errors", []), c(this, "ensureSegmentChunk", async (e4) => { - let t3 = e4.start, i4 = e4.size || 65536; - if (this.file.chunked) - if (this.file.available(t3, i4)) - e4.chunk = this.file.subarray(t3, i4); - else - try { - e4.chunk = await this.file.readChunk(t3, i4); - } catch (t4) { - g2("Couldn't read segment: ".concat(JSON.stringify(e4), ". ").concat(t4.message)); + function getAreaLabel(entity2, width2, height) { + var centroid = path.centroid(entity2.asGeoJSON(graph)); + var extent = entity2.extent(graph); + var areaWidth = projection2(extent[1])[0] - projection2(extent[0])[0]; + if (isNaN(centroid[0]) || areaWidth < 20) + return; + var preset2 = _mainPresetIndex.match(entity2, context.graph()); + var picon = preset2 && preset2.icon; + var iconSize = 17; + var padding = 2; + var p3 = {}; + if (picon) { + if (addIcon()) { + addLabel(iconSize + padding); + return p3; + } + } else { + if (addLabel(0)) { + return p3; + } + } + function addIcon() { + var iconX = centroid[0] - iconSize / 2; + var iconY = centroid[1] - iconSize / 2; + var bbox3 = { + minX: iconX, + minY: iconY, + maxX: iconX + iconSize, + maxY: iconY + iconSize + }; + if (tryInsert([bbox3], entity2.id + "I", true)) { + p3.transform = "translate(" + iconX + "," + iconY + ")"; + return true; + } + return false; + } + function addLabel(yOffset) { + if (width2 && areaWidth >= width2 + 20) { + var labelX = centroid[0]; + var labelY = centroid[1] + yOffset; + var bbox3 = { + minX: labelX - width2 / 2 - padding, + minY: labelY - height / 2 - padding, + maxX: labelX + width2 / 2 + padding, + maxY: labelY + height / 2 + padding + }; + if (tryInsert([bbox3], entity2.id, true)) { + p3.x = labelX; + p3.y = labelY; + p3.textAnchor = "middle"; + p3.height = height; + return true; } - else - this.file.byteLength > t3 + i4 ? e4.chunk = this.file.subarray(t3, i4) : void 0 === e4.size ? e4.chunk = this.file.subarray(t3) : g2("Segment unreachable: " + JSON.stringify(e4)); - return e4.chunk; - }), this.extendOptions && this.extendOptions(e3), this.options = e3, this.file = t2, this.parsers = i3; - } - injectSegment(e3, t2) { - this.options[e3].enabled && this.createParser(e3, t2); - } - createParser(e3, t2) { - let i3 = new (T.get(e3))(t2, this.options, this.file); - return this.parsers[e3] = i3; - } - createParsers(e3) { - for (let t2 of e3) { - let { type: e4, chunk: i3 } = t2, n3 = this.options[e4]; - if (n3 && n3.enabled) { - let t3 = this.parsers[e4]; - t3 && t3.append || t3 || this.createParser(e4, i3); + } + return false; } } - } - async readSegments(e3) { - let t2 = e3.map(this.ensureSegmentChunk); - await Promise.all(t2); - } - }; - var re2 = class { - static findPosition(e3, t2) { - let i3 = e3.getUint16(t2 + 2) + 2, n3 = "function" == typeof this.headerLength ? this.headerLength(e3, t2, i3) : this.headerLength, s2 = t2 + n3, r2 = i3 - n3; - return { offset: t2, length: i3, headerLength: n3, start: s2, size: r2, end: s2 + r2 }; - } - static parse(e3, t2 = {}) { - return new this(e3, new q({ [this.type]: t2 }), e3).parse(); - } - normalizeInput(e3) { - return e3 instanceof I ? e3 : new I(e3); - } - constructor(e3, t2 = {}, i3) { - c(this, "errors", []), c(this, "raw", /* @__PURE__ */ new Map()), c(this, "handleError", (e4) => { - if (!this.options.silentErrors) - throw e4; - this.errors.push(e4.message); - }), this.chunk = this.normalizeInput(e3), this.file = i3, this.type = this.constructor.type, this.globalOptions = this.options = t2, this.localOptions = t2[this.type], this.canTranslate = this.localOptions && this.localOptions.translate; - } - translate() { - this.canTranslate && (this.translated = this.translateBlock(this.raw, this.type)); - } - get output() { - return this.translated ? this.translated : this.raw ? Object.fromEntries(this.raw) : void 0; - } - translateBlock(e3, t2) { - let i3 = N.get(t2), n3 = B.get(t2), s2 = E.get(t2), r2 = this.options[t2], a2 = r2.reviveValues && !!i3, o2 = r2.translateValues && !!n3, l2 = r2.translateKeys && !!s2, h2 = {}; - for (let [t3, r3] of e3) - a2 && i3.has(t3) ? r3 = i3.get(t3)(r3) : o2 && n3.has(t3) && (r3 = this.translateValue(r3, n3.get(t3))), l2 && s2.has(t3) && (t3 = s2.get(t3) || t3), h2[t3] = r3; - return h2; - } - translateValue(e3, t2) { - return t2[e3] || t2.DEFAULT || e3; - } - assignToOutput(e3, t2) { - this.assignObjectToOutput(e3, this.constructor.type, t2); - } - assignObjectToOutput(e3, t2, i3) { - if (this.globalOptions.mergeOutput) - return Object.assign(e3, i3); - e3[t2] ? Object.assign(e3[t2], i3) : e3[t2] = i3; - } - }; - c(re2, "headerLength", 4), c(re2, "type", void 0), c(re2, "multiSegment", false), c(re2, "canHandle", () => false); - function ae(e3) { - return 192 === e3 || 194 === e3 || 196 === e3 || 219 === e3 || 221 === e3 || 218 === e3 || 254 === e3; - } - function oe(e3) { - return e3 >= 224 && e3 <= 239; - } - function le(e3, t2, i3) { - for (let [n3, s2] of T) - if (s2.canHandle(e3, t2, i3)) - return n3; - } - var he = class extends se { - constructor(...e3) { - super(...e3), c(this, "appSegments", []), c(this, "jpegSegments", []), c(this, "unknownSegments", []); - } - static canHandle(e3, t2) { - return 65496 === t2; - } - async parse() { - await this.findAppSegments(), await this.readSegments(this.appSegments), this.mergeMultiSegments(), this.createParsers(this.mergedAppSegments || this.appSegments); - } - setupSegmentFinderArgs(e3) { - true === e3 ? (this.findAll = true, this.wanted = new Set(T.keyList())) : (e3 = void 0 === e3 ? T.keyList().filter((e4) => this.options[e4].enabled) : e3.filter((e4) => this.options[e4].enabled && T.has(e4)), this.findAll = false, this.remaining = new Set(e3), this.wanted = new Set(e3)), this.unfinishedMultiSegment = false; - } - async findAppSegments(e3 = 0, t2) { - this.setupSegmentFinderArgs(t2); - let { file: i3, findAll: n3, wanted: s2, remaining: r2 } = this; - if (!n3 && this.file.chunked && (n3 = Array.from(s2).some((e4) => { - let t3 = T.get(e4), i4 = this.options[e4]; - return t3.multiSegment && i4.multiSegment; - }), n3 && await this.file.readWhole()), e3 = this.findAppSegmentsInRange(e3, i3.byteLength), !this.options.onlyTiff && i3.chunked) { - let t3 = false; - for (; r2.size > 0 && !t3 && (i3.canReadNextChunk || this.unfinishedMultiSegment); ) { - let { nextChunkOffset: n4 } = i3, s3 = this.appSegments.some((e4) => !this.file.available(e4.offset || e4.start, e4.length || e4.size)); - if (t3 = e3 > n4 && !s3 ? !await i3.readNextChunk(e3) : !await i3.readNextChunk(n4), void 0 === (e3 = this.findAppSegmentsInRange(e3, i3.byteLength))) - return; + function doInsert(bbox3, id2) { + bbox3.id = id2; + var oldbox = _entitybboxes[id2]; + if (oldbox) { + _rdrawn.remove(oldbox); } + _entitybboxes[id2] = bbox3; + _rdrawn.insert(bbox3); } - } - findAppSegmentsInRange(e3, t2) { - t2 -= 2; - let i3, n3, s2, r2, a2, o2, { file: l2, findAll: h2, wanted: u2, remaining: c2, options: f3 } = this; - for (; e3 < t2; e3++) - if (255 === l2.getUint8(e3)) { - if (i3 = l2.getUint8(e3 + 1), oe(i3)) { - if (n3 = l2.getUint16(e3 + 2), s2 = le(l2, e3, n3), s2 && u2.has(s2) && (r2 = T.get(s2), a2 = r2.findPosition(l2, e3), o2 = f3[s2], a2.type = s2, this.appSegments.push(a2), !h2 && (r2.multiSegment && o2.multiSegment ? (this.unfinishedMultiSegment = a2.chunkNumber < a2.chunkCount, this.unfinishedMultiSegment || c2.delete(s2)) : c2.delete(s2), 0 === c2.size))) - break; - f3.recordUnknownSegments && (a2 = re2.findPosition(l2, e3), a2.marker = i3, this.unknownSegments.push(a2)), e3 += n3 + 1; - } else if (ae(i3)) { - if (n3 = l2.getUint16(e3 + 2), 218 === i3 && false !== f3.stopAfterSos) - return; - f3.recordJpegSegments && this.jpegSegments.push({ offset: e3, length: n3, marker: i3 }), e3 += n3 + 1; + function tryInsert(bboxes, id2, saveSkipped) { + var skipped = false; + for (var i4 = 0; i4 < bboxes.length; i4++) { + var bbox3 = bboxes[i4]; + bbox3.id = id2; + if (bbox3.minX < 0 || bbox3.minY < 0 || bbox3.maxX > dimensions[0] || bbox3.maxY > dimensions[1]) { + skipped = true; + break; + } + if (_rdrawn.collides(bbox3)) { + skipped = true; + break; } } - return e3; - } - mergeMultiSegments() { - if (!this.appSegments.some((e4) => e4.multiSegment)) - return; - let e3 = function(e4, t2) { - let i3, n3, s2, r2 = /* @__PURE__ */ new Map(); - for (let a2 = 0; a2 < e4.length; a2++) - i3 = e4[a2], n3 = i3[t2], r2.has(n3) ? s2 = r2.get(n3) : r2.set(n3, s2 = []), s2.push(i3); - return Array.from(r2); - }(this.appSegments, "type"); - this.mergedAppSegments = e3.map(([e4, t2]) => { - let i3 = T.get(e4, this.options); - if (i3.handleMultiSegments) { - return { type: e4, chunk: i3.handleMultiSegments(t2) }; + _entitybboxes[id2] = bboxes; + if (skipped) { + if (saveSkipped) { + _rskipped.load(bboxes); + } + } else { + _rdrawn.load(bboxes); } - return t2[0]; + return !skipped; + } + var layer = selection2.selectAll(".layer-osm.labels"); + layer.selectAll(".labels-group").data(["halo", "label", "debug"]).enter().append("g").attr("class", function(d2) { + return "labels-group " + d2; }); + var halo = layer.selectAll(".labels-group.halo"); + var label = layer.selectAll(".labels-group.label"); + var debug2 = layer.selectAll(".labels-group.debug"); + drawPointLabels(label, labelled.point, filter2, "pointlabel", positions.point); + drawPointLabels(halo, labelled.point, filter2, "pointlabel-halo", positions.point); + drawLinePaths(layer, labelled.line, filter2, "", positions.line); + drawLineLabels(label, labelled.line, filter2, "linelabel", positions.line); + drawLineLabels(halo, labelled.line, filter2, "linelabel-halo", positions.line); + drawAreaLabels(label, labelled.area, filter2, "arealabel", positions.area); + drawAreaLabels(halo, labelled.area, filter2, "arealabel-halo", positions.area); + drawAreaIcons(label, labelled.area, filter2, "areaicon", positions.area); + drawAreaIcons(halo, labelled.area, filter2, "areaicon-halo", positions.area); + drawCollisionBoxes(debug2, _rskipped, "debug-skipped"); + drawCollisionBoxes(debug2, _rdrawn, "debug-drawn"); + layer.call(filterLabels); } - getSegment(e3) { - return this.appSegments.find((t2) => t2.type === e3); - } - async getOrFindSegment(e3) { - let t2 = this.getSegment(e3); - return void 0 === t2 && (await this.findAppSegments(0, [e3]), t2 = this.getSegment(e3)), t2; - } - }; - c(he, "type", "jpeg"), w.set("jpeg", he); - var ue = [void 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4]; - var ce = class extends re2 { - parseHeader() { - var e3 = this.chunk.getUint16(); - 18761 === e3 ? this.le = true : 19789 === e3 && (this.le = false), this.chunk.le = this.le, this.headerParsed = true; - } - parseTags(e3, t2, i3 = /* @__PURE__ */ new Map()) { - let { pick: n3, skip: s2 } = this.options[t2]; - n3 = new Set(n3); - let r2 = n3.size > 0, a2 = 0 === s2.size, o2 = this.chunk.getUint16(e3); - e3 += 2; - for (let l2 = 0; l2 < o2; l2++) { - let o3 = this.chunk.getUint16(e3); - if (r2) { - if (n3.has(o3) && (i3.set(o3, this.parseTag(e3, o3, t2)), n3.delete(o3), 0 === n3.size)) - break; - } else - !a2 && s2.has(o3) || i3.set(o3, this.parseTag(e3, o3, t2)); - e3 += 12; + function filterLabels(selection2) { + var drawLayer = selection2.selectAll(".layer-osm.labels"); + var layers = drawLayer.selectAll(".labels-group.halo, .labels-group.label"); + layers.selectAll(".nolabel").classed("nolabel", false); + var mouse = context.map().mouse(); + var graph = context.graph(); + var selectedIDs = context.selectedIDs(); + var ids = []; + var pad2, bbox2; + if (mouse) { + pad2 = 20; + bbox2 = { minX: mouse[0] - pad2, minY: mouse[1] - pad2, maxX: mouse[0] + pad2, maxY: mouse[1] + pad2 }; + var nearMouse = _rdrawn.search(bbox2).map(function(entity2) { + return entity2.id; + }); + ids.push.apply(ids, nearMouse); } - return i3; - } - parseTag(e3, t2, i3) { - let { chunk: n3 } = this, s2 = n3.getUint16(e3 + 2), r2 = n3.getUint32(e3 + 4), a2 = ue[s2]; - if (a2 * r2 <= 4 ? e3 += 8 : e3 = n3.getUint32(e3 + 8), (s2 < 1 || s2 > 13) && g2("Invalid TIFF value type. block: ".concat(i3.toUpperCase(), ", tag: ").concat(t2.toString(16), ", type: ").concat(s2, ", offset ").concat(e3)), e3 > n3.byteLength && g2("Invalid TIFF value offset. block: ".concat(i3.toUpperCase(), ", tag: ").concat(t2.toString(16), ", type: ").concat(s2, ", offset ").concat(e3, " is outside of chunk size ").concat(n3.byteLength)), 1 === s2) - return n3.getUint8Array(e3, r2); - if (2 === s2) - return m(n3.getString(e3, r2)); - if (7 === s2) - return n3.getUint8Array(e3, r2); - if (1 === r2) - return this.parseTagValue(s2, e3); - { - let t3 = new (function(e4) { - switch (e4) { - case 1: - return Uint8Array; - case 3: - return Uint16Array; - case 4: - return Uint32Array; - case 5: - return Array; - case 6: - return Int8Array; - case 8: - return Int16Array; - case 9: - return Int32Array; - case 10: - return Array; - case 11: - return Float32Array; - case 12: - return Float64Array; - default: - return Array; - } - }(s2))(r2), i4 = a2; - for (let n4 = 0; n4 < r2; n4++) - t3[n4] = this.parseTagValue(s2, e3), e3 += i4; - return t3; + for (var i3 = 0; i3 < selectedIDs.length; i3++) { + var entity = graph.hasEntity(selectedIDs[i3]); + if (entity && entity.type === "node") { + ids.push(selectedIDs[i3]); + } } - } - parseTagValue(e3, t2) { - let { chunk: i3 } = this; - switch (e3) { - case 1: - return i3.getUint8(t2); - case 3: - return i3.getUint16(t2); - case 4: - return i3.getUint32(t2); - case 5: - return i3.getUint32(t2) / i3.getUint32(t2 + 4); - case 6: - return i3.getInt8(t2); - case 8: - return i3.getInt16(t2); - case 9: - return i3.getInt32(t2); - case 10: - return i3.getInt32(t2) / i3.getInt32(t2 + 4); - case 11: - return i3.getFloat(t2); - case 12: - return i3.getDouble(t2); - case 13: - return i3.getUint32(t2); - default: - g2("Invalid tiff type ".concat(e3)); + layers.selectAll(utilEntitySelector(ids)).classed("nolabel", true); + var debug2 = selection2.selectAll(".labels-group.debug"); + var gj = []; + if (context.getDebug("collision")) { + gj = bbox2 ? [{ + type: "Polygon", + coordinates: [[ + [bbox2.minX, bbox2.minY], + [bbox2.maxX, bbox2.minY], + [bbox2.maxX, bbox2.maxY], + [bbox2.minX, bbox2.maxY], + [bbox2.minX, bbox2.minY] + ]] + }] : []; } + var box = debug2.selectAll(".debug-mouse").data(gj); + box.exit().remove(); + box.enter().append("path").attr("class", "debug debug-mouse yellow").merge(box).attr("d", path_default()); } - }; - var fe = class extends ce { - static canHandle(e3, t2) { - return 225 === e3.getUint8(t2 + 1) && 1165519206 === e3.getUint32(t2 + 4) && 0 === e3.getUint16(t2 + 8); - } - async parse() { - this.parseHeader(); - let { options: e3 } = this; - return e3.ifd0.enabled && await this.parseIfd0Block(), e3.exif.enabled && await this.safeParse("parseExifBlock"), e3.gps.enabled && await this.safeParse("parseGpsBlock"), e3.interop.enabled && await this.safeParse("parseInteropBlock"), e3.ifd1.enabled && await this.safeParse("parseThumbnailBlock"), this.createOutput(); - } - safeParse(e3) { - let t2 = this[e3](); - return void 0 !== t2.catch && (t2 = t2.catch(this.handleError)), t2; - } - findIfd0Offset() { - void 0 === this.ifd0Offset && (this.ifd0Offset = this.chunk.getUint32(4)); - } - findIfd1Offset() { - if (void 0 === this.ifd1Offset) { - this.findIfd0Offset(); - let e3 = this.chunk.getUint16(this.ifd0Offset), t2 = this.ifd0Offset + 2 + 12 * e3; - this.ifd1Offset = this.chunk.getUint32(t2); + var throttleFilterLabels = throttle_default(filterLabels, 100); + drawLabels.observe = function(selection2) { + var listener = function() { + throttleFilterLabels(selection2); + }; + selection2.on("mousemove.hidelabels", listener); + context.on("enter.hidelabels", listener); + }; + drawLabels.off = function(selection2) { + throttleFilterLabels.cancel(); + selection2.on("mousemove.hidelabels", null); + context.on("enter.hidelabels", null); + }; + return drawLabels; + } + + // node_modules/exifr/dist/full.esm.mjs + var e = "undefined" != typeof self ? self : global; + var t = "undefined" != typeof navigator; + var i2 = t && "undefined" == typeof HTMLImageElement; + var n2 = !("undefined" == typeof global || "undefined" == typeof process || !process.versions || !process.versions.node); + var s = e.Buffer; + var r = e.BigInt; + var a = !!s; + var o = (e3) => e3; + function l(e3, t2 = o) { + if (n2) + try { + return "function" == typeof __require ? Promise.resolve(t2(__require(e3))) : import( + /* webpackIgnore: true */ + e3 + ).then(t2); + } catch (t3) { + console.warn("Couldn't load ".concat(e3)); } - } - parseBlock(e3, t2) { - let i3 = /* @__PURE__ */ new Map(); - return this[t2] = i3, this.parseTags(e3, t2, i3), i3; - } - async parseIfd0Block() { - if (this.ifd0) - return; - let { file: e3 } = this; - this.findIfd0Offset(), this.ifd0Offset < 8 && g2("Malformed EXIF data"), !e3.chunked && this.ifd0Offset > e3.byteLength && g2("IFD0 offset points to outside of file.\nthis.ifd0Offset: ".concat(this.ifd0Offset, ", file.byteLength: ").concat(e3.byteLength)), e3.tiff && await e3.ensureChunk(this.ifd0Offset, S(this.options)); - let t2 = this.parseBlock(this.ifd0Offset, "ifd0"); - return 0 !== t2.size ? (this.exifOffset = t2.get(34665), this.interopOffset = t2.get(40965), this.gpsOffset = t2.get(34853), this.xmp = t2.get(700), this.iptc = t2.get(33723), this.icc = t2.get(34675), this.options.sanitize && (t2.delete(34665), t2.delete(40965), t2.delete(34853), t2.delete(700), t2.delete(33723), t2.delete(34675)), t2) : void 0; - } - async parseExifBlock() { - if (this.exif) - return; - if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.exifOffset) - return; - this.file.tiff && await this.file.ensureChunk(this.exifOffset, S(this.options)); - let e3 = this.parseBlock(this.exifOffset, "exif"); - return this.interopOffset || (this.interopOffset = e3.get(40965)), this.makerNote = e3.get(37500), this.userComment = e3.get(37510), this.options.sanitize && (e3.delete(40965), e3.delete(37500), e3.delete(37510)), this.unpack(e3, 41728), this.unpack(e3, 41729), e3; - } - unpack(e3, t2) { - let i3 = e3.get(t2); - i3 && 1 === i3.length && e3.set(t2, i3[0]); - } - async parseGpsBlock() { - if (this.gps) - return; - if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.gpsOffset) - return; - let e3 = this.parseBlock(this.gpsOffset, "gps"); - return e3 && e3.has(2) && e3.has(4) && (e3.set("latitude", de(...e3.get(2), e3.get(1))), e3.set("longitude", de(...e3.get(4), e3.get(3)))), e3; - } - async parseInteropBlock() { - if (!this.interop && (this.ifd0 || await this.parseIfd0Block(), void 0 !== this.interopOffset || this.exif || await this.parseExifBlock(), void 0 !== this.interopOffset)) - return this.parseBlock(this.interopOffset, "interop"); - } - async parseThumbnailBlock(e3 = false) { - if (!this.ifd1 && !this.ifd1Parsed && (!this.options.mergeOutput || e3)) - return this.findIfd1Offset(), this.ifd1Offset > 0 && (this.parseBlock(this.ifd1Offset, "ifd1"), this.ifd1Parsed = true), this.ifd1; - } - async extractThumbnail() { - if (this.headerParsed || this.parseHeader(), this.ifd1Parsed || await this.parseThumbnailBlock(true), void 0 === this.ifd1) - return; - let e3 = this.ifd1.get(513), t2 = this.ifd1.get(514); - return this.chunk.getUint8Array(e3, t2); - } - get image() { - return this.ifd0; - } - get thumbnail() { - return this.ifd1; - } - createOutput() { - let e3, t2, i3, n3 = {}; - for (t2 of H) - if (e3 = this[t2], !p(e3)) - if (i3 = this.canTranslate ? this.translateBlock(e3, t2) : Object.fromEntries(e3), this.options.mergeOutput) { - if ("ifd1" === t2) - continue; - Object.assign(n3, i3); - } else - n3[t2] = i3; - return this.makerNote && (n3.makerNote = this.makerNote), this.userComment && (n3.userComment = this.userComment), n3; - } - assignToOutput(e3, t2) { - if (this.globalOptions.mergeOutput) - Object.assign(e3, t2); - else - for (let [i3, n3] of Object.entries(t2)) - this.assignObjectToOutput(e3, i3, n3); - } - }; - function de(e3, t2, i3, n3) { - var s2 = e3 + t2 / 60 + i3 / 3600; - return "S" !== n3 && "W" !== n3 || (s2 *= -1), s2; } - c(fe, "type", "tiff"), c(fe, "headerLength", 10), T.set("tiff", fe); - var pe = Object.freeze({ __proto__: null, default: ne, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j2, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q, parse: ie }); - var ge = { ifd0: false, ifd1: false, exif: false, gps: false, interop: false, sanitize: false, reviveValues: true, translateKeys: false, translateValues: false, mergeOutput: false }; - var me = Object.assign({}, ge, { firstChunkSize: 4e4, gps: [1, 2, 3, 4] }); - async function Se(e3) { - let t2 = new te(me); - await t2.read(e3); - let i3 = await t2.parse(); - if (i3 && i3.gps) { - let { latitude: e4, longitude: t3 } = i3.gps; - return { latitude: e4, longitude: t3 }; - } + var h = e.fetch; + var u = (e3) => h = e3; + if (!e.fetch) { + const e3 = l("http", (e4) => e4), t2 = l("https", (e4) => e4), i3 = (n3, { headers: s2 } = {}) => new Promise(async (r2, a2) => { + let { port: o2, hostname: l2, pathname: h2, protocol: u2, search: c2 } = new URL(n3); + const f2 = { method: "GET", hostname: l2, path: encodeURI(h2) + c2, headers: s2 }; + "" !== o2 && (f2.port = Number(o2)); + const d2 = ("https:" === u2 ? await t2 : await e3).request(f2, (e4) => { + if (301 === e4.statusCode || 302 === e4.statusCode) { + let t3 = new URL(e4.headers.location, n3).toString(); + return i3(t3, { headers: s2 }).then(r2).catch(a2); + } + r2({ status: e4.statusCode, arrayBuffer: () => new Promise((t3) => { + let i4 = []; + e4.on("data", (e6) => i4.push(e6)), e4.on("end", () => t3(Buffer.concat(i4))); + }) }); + }); + d2.on("error", a2), d2.end(); + }); + u(i3); } - var Ce = Object.assign({}, ge, { tiff: false, ifd1: true, mergeOutput: false }); - async function ye(e3) { - let t2 = new te(Ce); - await t2.read(e3); - let i3 = await t2.extractThumbnail(); - return i3 && a ? s.from(i3) : i3; + function c(e3, t2, i3) { + return t2 in e3 ? Object.defineProperty(e3, t2, { value: i3, enumerable: true, configurable: true, writable: true }) : e3[t2] = i3, e3; } - async function be(e3) { - let t2 = await this.thumbnail(e3); - if (void 0 !== t2) { - let e4 = new Blob([t2]); - return URL.createObjectURL(e4); - } + var f = (e3) => p(e3) ? void 0 : e3; + var d = (e3) => void 0 !== e3; + function p(e3) { + return void 0 === e3 || (e3 instanceof Map ? 0 === e3.size : 0 === Object.values(e3).filter(d).length); } - var Ie = Object.assign({}, ge, { firstChunkSize: 4e4, ifd0: [274] }); - async function Pe(e3) { - let t2 = new te(Ie); - await t2.read(e3); - let i3 = await t2.parse(); - if (i3 && i3.ifd0) - return i3.ifd0[274]; + function g2(e3) { + let t2 = new Error(e3); + throw delete t2.stack, t2; } - var ke = Object.freeze({ 1: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 0, rad: 0 }, 2: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 0, rad: 0 }, 3: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 4: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 5: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 90, rad: 90 * Math.PI / 180 }, 6: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 90, rad: 90 * Math.PI / 180 }, 7: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 270, rad: 270 * Math.PI / 180 }, 8: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 270, rad: 270 * Math.PI / 180 } }); - var we = true; - var Te = true; - if ("object" == typeof navigator) { - let e3 = navigator.userAgent; - if (e3.includes("iPad") || e3.includes("iPhone")) { - let t2 = e3.match(/OS (\d+)_(\d+)/); - if (t2) { - let [, e4, i3] = t2, n3 = Number(e4) + 0.1 * Number(i3); - we = n3 < 13.4, Te = false; - } - } else if (e3.includes("OS X 10")) { - let [, t2] = e3.match(/OS X 10[_.](\d+)/); - we = Te = Number(t2) < 15; - } - if (e3.includes("Chrome/")) { - let [, t2] = e3.match(/Chrome\/(\d+)/); - we = Te = Number(t2) < 81; - } else if (e3.includes("Firefox/")) { - let [, t2] = e3.match(/Firefox\/(\d+)/); - we = Te = Number(t2) < 77; - } + function m(e3) { + return "" === (e3 = function(e4) { + for (; e4.endsWith("\0"); ) + e4 = e4.slice(0, -1); + return e4; + }(e3).trim()) ? void 0 : e3; } - async function Ae(e3) { - let t2 = await Pe(e3); - return Object.assign({ canvas: we, css: Te }, ke[t2]); + function S(e3) { + let t2 = function(e4) { + let t3 = 0; + return e4.ifd0.enabled && (t3 += 1024), e4.exif.enabled && (t3 += 2048), e4.makerNote && (t3 += 2048), e4.userComment && (t3 += 1024), e4.gps.enabled && (t3 += 512), e4.interop.enabled && (t3 += 100), e4.ifd1.enabled && (t3 += 1024), t3 + 2048; + }(e3); + return e3.jfif.enabled && (t2 += 50), e3.xmp.enabled && (t2 += 2e4), e3.iptc.enabled && (t2 += 14e3), e3.icc.enabled && (t2 += 6e3), t2; } - var De = class extends I { - constructor(...e3) { - super(...e3), c(this, "ranges", new Oe()), 0 !== this.byteLength && this.ranges.add(0, this.byteLength); - } - _tryExtend(e3, t2, i3) { - if (0 === e3 && 0 === this.byteLength && i3) { - let e4 = new DataView(i3.buffer || i3, i3.byteOffset, i3.byteLength); - this._swapDataView(e4); - } else { - let i4 = e3 + t2; - if (i4 > this.byteLength) { - let { dataView: e4 } = this._extend(i4); - this._swapDataView(e4); - } - } - } - _extend(e3) { - let t2; - t2 = a ? s.allocUnsafe(e3) : new Uint8Array(e3); - let i3 = new DataView(t2.buffer, t2.byteOffset, t2.byteLength); - return t2.set(new Uint8Array(this.buffer, this.byteOffset, this.byteLength), 0), { uintView: t2, dataView: i3 }; - } - subarray(e3, t2, i3 = false) { - return t2 = t2 || this._lengthToEnd(e3), i3 && this._tryExtend(e3, t2), this.ranges.add(e3, t2), super.subarray(e3, t2); - } - set(e3, t2, i3 = false) { - i3 && this._tryExtend(t2, e3.byteLength, e3); - let n3 = super.set(e3, t2); - return this.ranges.add(t2, n3.byteLength), n3; - } - async ensureChunk(e3, t2) { - this.chunked && (this.ranges.available(e3, t2) || await this.readChunk(e3, t2)); - } - available(e3, t2) { - return this.ranges.available(e3, t2); - } - }; - var Oe = class { - constructor() { - c(this, "list", []); - } - get length() { - return this.list.length; - } - add(e3, t2, i3 = 0) { - let n3 = e3 + t2, s2 = this.list.filter((t3) => xe(e3, t3.offset, n3) || xe(e3, t3.end, n3)); - if (s2.length > 0) { - e3 = Math.min(e3, ...s2.map((e4) => e4.offset)), n3 = Math.max(n3, ...s2.map((e4) => e4.end)), t2 = n3 - e3; - let i4 = s2.shift(); - i4.offset = e3, i4.length = t2, i4.end = n3, this.list = this.list.filter((e4) => !s2.includes(e4)); - } else - this.list.push({ offset: e3, length: t2, end: n3 }); - } - available(e3, t2) { - let i3 = e3 + t2; - return this.list.some((t3) => t3.offset <= e3 && i3 <= t3.end); - } - }; - function xe(e3, t2, i3) { - return e3 <= t2 && t2 <= i3; + var C = (e3) => String.fromCharCode.apply(null, e3); + var y = "undefined" != typeof TextDecoder ? new TextDecoder("utf-8") : void 0; + function b(e3) { + return y ? y.decode(e3) : a ? Buffer.from(e3).toString("utf8") : decodeURIComponent(escape(C(e3))); } - var ve = class extends De { - constructor(e3, t2) { - super(0), c(this, "chunksRead", 0), this.input = e3, this.options = t2; - } - async readWhole() { - this.chunked = false, await this.readChunk(this.nextChunkOffset); - } - async readChunked() { - this.chunked = true, await this.readChunk(0, this.options.firstChunkSize); - } - async readNextChunk(e3 = this.nextChunkOffset) { - if (this.fullyRead) - return this.chunksRead++, false; - let t2 = this.options.chunkSize, i3 = await this.readChunk(e3, t2); - return !!i3 && i3.byteLength === t2; - } - async readChunk(e3, t2) { - if (this.chunksRead++, 0 !== (t2 = this.safeWrapAddress(e3, t2))) - return this._readChunk(e3, t2); - } - safeWrapAddress(e3, t2) { - return void 0 !== this.size && e3 + t2 > this.size ? Math.max(0, this.size - e3) : t2; - } - get nextChunkOffset() { - if (0 !== this.ranges.list.length) - return this.ranges.list[0].length; - } - get canReadNextChunk() { - return this.chunksRead < this.options.chunkLimit; - } - get fullyRead() { - return void 0 !== this.size && this.nextChunkOffset === this.size; - } - read() { - return this.options.chunked ? this.readChunked() : this.readWhole(); - } - close() { - } - }; - A.set("blob", class extends ve { - async readWhole() { - this.chunked = false; - let e3 = await R(this.input); - this._swapArrayBuffer(e3); - } - readChunked() { - return this.chunked = true, this.size = this.input.size, super.readChunked(); - } - async _readChunk(e3, t2) { - let i3 = t2 ? e3 + t2 : void 0, n3 = this.input.slice(e3, i3), s2 = await R(n3); - return this.set(s2, e3, true); - } - }); - var Me = Object.freeze({ __proto__: null, default: pe, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j2, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q, parse: ie, gpsOnlyOptions: me, gps: Se, thumbnailOnlyOptions: Ce, thumbnail: ye, thumbnailUrl: be, orientationOnlyOptions: Ie, orientation: Pe, rotations: ke, get rotateCanvas() { - return we; - }, get rotateCss() { - return Te; - }, rotation: Ae }); - A.set("url", class extends ve { - async readWhole() { - this.chunked = false; - let e3 = await M(this.input); - e3 instanceof ArrayBuffer ? this._swapArrayBuffer(e3) : e3 instanceof Uint8Array && this._swapBuffer(e3); - } - async _readChunk(e3, t2) { - let i3 = t2 ? e3 + t2 - 1 : void 0, n3 = this.options.httpHeaders || {}; - (e3 || i3) && (n3.range = "bytes=".concat([e3, i3].join("-"))); - let s2 = await h(this.input, { headers: n3 }), r2 = await s2.arrayBuffer(), a2 = r2.byteLength; - if (416 !== s2.status) - return a2 !== t2 && (this.size = e3 + a2), this.set(r2, e3, true); - } - }); - I.prototype.getUint64 = function(e3) { - let t2 = this.getUint32(e3), i3 = this.getUint32(e3 + 4); - return t2 < 1048575 ? t2 << 32 | i3 : void 0 !== typeof r ? (console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."), r(t2) << r(32) | r(i3)) : void g2("Trying to read 64b value but JS can only handle 53b numbers."); - }; - var Re = class extends se { - parseBoxes(e3 = 0) { - let t2 = []; - for (; e3 < this.file.byteLength - 4; ) { - let i3 = this.parseBoxHead(e3); - if (t2.push(i3), 0 === i3.length) - break; - e3 += i3.length; - } - return t2; - } - parseSubBoxes(e3) { - e3.boxes = this.parseBoxes(e3.start); - } - findBox(e3, t2) { - return void 0 === e3.boxes && this.parseSubBoxes(e3), e3.boxes.find((e4) => e4.kind === t2); - } - parseBoxHead(e3) { - let t2 = this.file.getUint32(e3), i3 = this.file.getString(e3 + 4, 4), n3 = e3 + 8; - return 1 === t2 && (t2 = this.file.getUint64(e3 + 8), n3 += 8), { offset: e3, length: t2, kind: i3, start: n3 }; - } - parseBoxFullHead(e3) { - if (void 0 !== e3.version) - return; - let t2 = this.file.getUint32(e3.start); - e3.version = t2 >> 24, e3.start += 4; - } - }; - var Le = class extends Re { - static canHandle(e3, t2) { - if (0 !== t2) - return false; - let i3 = e3.getUint16(2); - if (i3 > 50) - return false; - let n3 = 16, s2 = []; - for (; n3 < i3; ) - s2.push(e3.getString(n3, 4)), n3 += 4; - return s2.includes(this.type); - } - async parse() { - let e3 = this.file.getUint32(0), t2 = this.parseBoxHead(e3); - for (; "meta" !== t2.kind; ) - e3 += t2.length, await this.file.ensureChunk(e3, 16), t2 = this.parseBoxHead(e3); - await this.file.ensureChunk(t2.offset, t2.length), this.parseBoxFullHead(t2), this.parseSubBoxes(t2), this.options.icc.enabled && await this.findIcc(t2), this.options.tiff.enabled && await this.findExif(t2); - } - async registerSegment(e3, t2, i3) { - await this.file.ensureChunk(t2, i3); - let n3 = this.file.subarray(t2, i3); - this.createParser(e3, n3); + var I = class _I { + static from(e3, t2) { + return e3 instanceof this && e3.le === t2 ? e3 : new _I(e3, void 0, void 0, t2); } - async findIcc(e3) { - let t2 = this.findBox(e3, "iprp"); - if (void 0 === t2) - return; - let i3 = this.findBox(t2, "ipco"); - if (void 0 === i3) - return; - let n3 = this.findBox(i3, "colr"); - void 0 !== n3 && await this.registerSegment("icc", n3.offset + 12, n3.length); + constructor(e3, t2 = 0, i3, n3) { + if ("boolean" == typeof n3 && (this.le = n3), Array.isArray(e3) && (e3 = new Uint8Array(e3)), 0 === e3) + this.byteOffset = 0, this.byteLength = 0; + else if (e3 instanceof ArrayBuffer) { + void 0 === i3 && (i3 = e3.byteLength - t2); + let n4 = new DataView(e3, t2, i3); + this._swapDataView(n4); + } else if (e3 instanceof Uint8Array || e3 instanceof DataView || e3 instanceof _I) { + void 0 === i3 && (i3 = e3.byteLength - t2), (t2 += e3.byteOffset) + i3 > e3.byteOffset + e3.byteLength && g2("Creating view outside of available memory in ArrayBuffer"); + let n4 = new DataView(e3.buffer, t2, i3); + this._swapDataView(n4); + } else if ("number" == typeof e3) { + let t3 = new DataView(new ArrayBuffer(e3)); + this._swapDataView(t3); + } else + g2("Invalid input argument for BufferView: " + e3); } - async findExif(e3) { - let t2 = this.findBox(e3, "iinf"); - if (void 0 === t2) - return; - let i3 = this.findBox(e3, "iloc"); - if (void 0 === i3) - return; - let n3 = this.findExifLocIdInIinf(t2), s2 = this.findExtentInIloc(i3, n3); - if (void 0 === s2) - return; - let [r2, a2] = s2; - await this.file.ensureChunk(r2, a2); - let o2 = 4 + this.file.getUint32(r2); - r2 += o2, a2 -= o2, await this.registerSegment("tiff", r2, a2); + _swapArrayBuffer(e3) { + this._swapDataView(new DataView(e3)); } - findExifLocIdInIinf(e3) { - this.parseBoxFullHead(e3); - let t2, i3, n3, s2, r2 = e3.start, a2 = this.file.getUint16(r2); - for (r2 += 2; a2--; ) { - if (t2 = this.parseBoxHead(r2), this.parseBoxFullHead(t2), i3 = t2.start, t2.version >= 2 && (n3 = 3 === t2.version ? 4 : 2, s2 = this.file.getString(i3 + n3 + 2, 4), "Exif" === s2)) - return this.file.getUintBytes(i3, n3); - r2 += t2.length; - } + _swapBuffer(e3) { + this._swapDataView(new DataView(e3.buffer, e3.byteOffset, e3.byteLength)); } - get8bits(e3) { - let t2 = this.file.getUint8(e3); - return [t2 >> 4, 15 & t2]; + _swapDataView(e3) { + this.dataView = e3, this.buffer = e3.buffer, this.byteOffset = e3.byteOffset, this.byteLength = e3.byteLength; } - findExtentInIloc(e3, t2) { - this.parseBoxFullHead(e3); - let i3 = e3.start, [n3, s2] = this.get8bits(i3++), [r2, a2] = this.get8bits(i3++), o2 = 2 === e3.version ? 4 : 2, l2 = 1 === e3.version || 2 === e3.version ? 2 : 0, h2 = a2 + n3 + s2, u2 = 2 === e3.version ? 4 : 2, c2 = this.file.getUintBytes(i3, u2); - for (i3 += u2; c2--; ) { - let e4 = this.file.getUintBytes(i3, o2); - i3 += o2 + l2 + 2 + r2; - let u3 = this.file.getUint16(i3); - if (i3 += 2, e4 === t2) - return u3 > 1 && console.warn("ILOC box has more than one extent but we're only processing one\nPlease create an issue at https://github.com/MikeKovarik/exifr with this file"), [this.file.getUintBytes(i3 + a2, n3), this.file.getUintBytes(i3 + a2 + n3, s2)]; - i3 += u3 * h2; - } + _lengthToEnd(e3) { + return this.byteLength - e3; } - }; - var Ue = class extends Le { - }; - c(Ue, "type", "heic"); - var Fe = class extends Le { - }; - c(Fe, "type", "avif"), w.set("heic", Ue), w.set("avif", Fe), U(E, ["ifd0", "ifd1"], [[256, "ImageWidth"], [257, "ImageHeight"], [258, "BitsPerSample"], [259, "Compression"], [262, "PhotometricInterpretation"], [270, "ImageDescription"], [271, "Make"], [272, "Model"], [273, "StripOffsets"], [274, "Orientation"], [277, "SamplesPerPixel"], [278, "RowsPerStrip"], [279, "StripByteCounts"], [282, "XResolution"], [283, "YResolution"], [284, "PlanarConfiguration"], [296, "ResolutionUnit"], [301, "TransferFunction"], [305, "Software"], [306, "ModifyDate"], [315, "Artist"], [316, "HostComputer"], [317, "Predictor"], [318, "WhitePoint"], [319, "PrimaryChromaticities"], [513, "ThumbnailOffset"], [514, "ThumbnailLength"], [529, "YCbCrCoefficients"], [530, "YCbCrSubSampling"], [531, "YCbCrPositioning"], [532, "ReferenceBlackWhite"], [700, "ApplicationNotes"], [33432, "Copyright"], [33723, "IPTC"], [34665, "ExifIFD"], [34675, "ICC"], [34853, "GpsIFD"], [330, "SubIFD"], [40965, "InteropIFD"], [40091, "XPTitle"], [40092, "XPComment"], [40093, "XPAuthor"], [40094, "XPKeywords"], [40095, "XPSubject"]]), U(E, "exif", [[33434, "ExposureTime"], [33437, "FNumber"], [34850, "ExposureProgram"], [34852, "SpectralSensitivity"], [34855, "ISO"], [34858, "TimeZoneOffset"], [34859, "SelfTimerMode"], [34864, "SensitivityType"], [34865, "StandardOutputSensitivity"], [34866, "RecommendedExposureIndex"], [34867, "ISOSpeed"], [34868, "ISOSpeedLatitudeyyy"], [34869, "ISOSpeedLatitudezzz"], [36864, "ExifVersion"], [36867, "DateTimeOriginal"], [36868, "CreateDate"], [36873, "GooglePlusUploadCode"], [36880, "OffsetTime"], [36881, "OffsetTimeOriginal"], [36882, "OffsetTimeDigitized"], [37121, "ComponentsConfiguration"], [37122, "CompressedBitsPerPixel"], [37377, "ShutterSpeedValue"], [37378, "ApertureValue"], [37379, "BrightnessValue"], [37380, "ExposureCompensation"], [37381, "MaxApertureValue"], [37382, "SubjectDistance"], [37383, "MeteringMode"], [37384, "LightSource"], [37385, "Flash"], [37386, "FocalLength"], [37393, "ImageNumber"], [37394, "SecurityClassification"], [37395, "ImageHistory"], [37396, "SubjectArea"], [37500, "MakerNote"], [37510, "UserComment"], [37520, "SubSecTime"], [37521, "SubSecTimeOriginal"], [37522, "SubSecTimeDigitized"], [37888, "AmbientTemperature"], [37889, "Humidity"], [37890, "Pressure"], [37891, "WaterDepth"], [37892, "Acceleration"], [37893, "CameraElevationAngle"], [40960, "FlashpixVersion"], [40961, "ColorSpace"], [40962, "ExifImageWidth"], [40963, "ExifImageHeight"], [40964, "RelatedSoundFile"], [41483, "FlashEnergy"], [41486, "FocalPlaneXResolution"], [41487, "FocalPlaneYResolution"], [41488, "FocalPlaneResolutionUnit"], [41492, "SubjectLocation"], [41493, "ExposureIndex"], [41495, "SensingMethod"], [41728, "FileSource"], [41729, "SceneType"], [41730, "CFAPattern"], [41985, "CustomRendered"], [41986, "ExposureMode"], [41987, "WhiteBalance"], [41988, "DigitalZoomRatio"], [41989, "FocalLengthIn35mmFormat"], [41990, "SceneCaptureType"], [41991, "GainControl"], [41992, "Contrast"], [41993, "Saturation"], [41994, "Sharpness"], [41996, "SubjectDistanceRange"], [42016, "ImageUniqueID"], [42032, "OwnerName"], [42033, "SerialNumber"], [42034, "LensInfo"], [42035, "LensMake"], [42036, "LensModel"], [42037, "LensSerialNumber"], [42080, "CompositeImage"], [42081, "CompositeImageCount"], [42082, "CompositeImageExposureTimes"], [42240, "Gamma"], [59932, "Padding"], [59933, "OffsetSchema"], [65e3, "OwnerName"], [65001, "SerialNumber"], [65002, "Lens"], [65100, "RawFile"], [65101, "Converter"], [65102, "WhiteBalance"], [65105, "Exposure"], [65106, "Shadows"], [65107, "Brightness"], [65108, "Contrast"], [65109, "Saturation"], [65110, "Sharpness"], [65111, "Smoothness"], [65112, "MoireFilter"], [40965, "InteropIFD"]]), U(E, "gps", [[0, "GPSVersionID"], [1, "GPSLatitudeRef"], [2, "GPSLatitude"], [3, "GPSLongitudeRef"], [4, "GPSLongitude"], [5, "GPSAltitudeRef"], [6, "GPSAltitude"], [7, "GPSTimeStamp"], [8, "GPSSatellites"], [9, "GPSStatus"], [10, "GPSMeasureMode"], [11, "GPSDOP"], [12, "GPSSpeedRef"], [13, "GPSSpeed"], [14, "GPSTrackRef"], [15, "GPSTrack"], [16, "GPSImgDirectionRef"], [17, "GPSImgDirection"], [18, "GPSMapDatum"], [19, "GPSDestLatitudeRef"], [20, "GPSDestLatitude"], [21, "GPSDestLongitudeRef"], [22, "GPSDestLongitude"], [23, "GPSDestBearingRef"], [24, "GPSDestBearing"], [25, "GPSDestDistanceRef"], [26, "GPSDestDistance"], [27, "GPSProcessingMethod"], [28, "GPSAreaInformation"], [29, "GPSDateStamp"], [30, "GPSDifferential"], [31, "GPSHPositioningError"]]), U(B, ["ifd0", "ifd1"], [[274, { 1: "Horizontal (normal)", 2: "Mirror horizontal", 3: "Rotate 180", 4: "Mirror vertical", 5: "Mirror horizontal and rotate 270 CW", 6: "Rotate 90 CW", 7: "Mirror horizontal and rotate 90 CW", 8: "Rotate 270 CW" }], [296, { 1: "None", 2: "inches", 3: "cm" }]]); - var Ee = U(B, "exif", [[34850, { 0: "Not defined", 1: "Manual", 2: "Normal program", 3: "Aperture priority", 4: "Shutter priority", 5: "Creative program", 6: "Action program", 7: "Portrait mode", 8: "Landscape mode" }], [37121, { 0: "-", 1: "Y", 2: "Cb", 3: "Cr", 4: "R", 5: "G", 6: "B" }], [37383, { 0: "Unknown", 1: "Average", 2: "CenterWeightedAverage", 3: "Spot", 4: "MultiSpot", 5: "Pattern", 6: "Partial", 255: "Other" }], [37384, { 0: "Unknown", 1: "Daylight", 2: "Fluorescent", 3: "Tungsten (incandescent light)", 4: "Flash", 9: "Fine weather", 10: "Cloudy weather", 11: "Shade", 12: "Daylight fluorescent (D 5700 - 7100K)", 13: "Day white fluorescent (N 4600 - 5400K)", 14: "Cool white fluorescent (W 3900 - 4500K)", 15: "White fluorescent (WW 3200 - 3700K)", 17: "Standard light A", 18: "Standard light B", 19: "Standard light C", 20: "D55", 21: "D65", 22: "D75", 23: "D50", 24: "ISO studio tungsten", 255: "Other" }], [37385, { 0: "Flash did not fire", 1: "Flash fired", 5: "Strobe return light not detected", 7: "Strobe return light detected", 9: "Flash fired, compulsory flash mode", 13: "Flash fired, compulsory flash mode, return light not detected", 15: "Flash fired, compulsory flash mode, return light detected", 16: "Flash did not fire, compulsory flash mode", 24: "Flash did not fire, auto mode", 25: "Flash fired, auto mode", 29: "Flash fired, auto mode, return light not detected", 31: "Flash fired, auto mode, return light detected", 32: "No flash function", 65: "Flash fired, red-eye reduction mode", 69: "Flash fired, red-eye reduction mode, return light not detected", 71: "Flash fired, red-eye reduction mode, return light detected", 73: "Flash fired, compulsory flash mode, red-eye reduction mode", 77: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected", 79: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected", 89: "Flash fired, auto mode, red-eye reduction mode", 93: "Flash fired, auto mode, return light not detected, red-eye reduction mode", 95: "Flash fired, auto mode, return light detected, red-eye reduction mode" }], [41495, { 1: "Not defined", 2: "One-chip color area sensor", 3: "Two-chip color area sensor", 4: "Three-chip color area sensor", 5: "Color sequential area sensor", 7: "Trilinear sensor", 8: "Color sequential linear sensor" }], [41728, { 1: "Film Scanner", 2: "Reflection Print Scanner", 3: "Digital Camera" }], [41729, { 1: "Directly photographed" }], [41985, { 0: "Normal", 1: "Custom", 2: "HDR (no original saved)", 3: "HDR (original saved)", 4: "Original (for HDR)", 6: "Panorama", 7: "Portrait HDR", 8: "Portrait" }], [41986, { 0: "Auto", 1: "Manual", 2: "Auto bracket" }], [41987, { 0: "Auto", 1: "Manual" }], [41990, { 0: "Standard", 1: "Landscape", 2: "Portrait", 3: "Night", 4: "Other" }], [41991, { 0: "None", 1: "Low gain up", 2: "High gain up", 3: "Low gain down", 4: "High gain down" }], [41996, { 0: "Unknown", 1: "Macro", 2: "Close", 3: "Distant" }], [42080, { 0: "Unknown", 1: "Not a Composite Image", 2: "General Composite Image", 3: "Composite Image Captured While Shooting" }]]); - var Be = { 1: "No absolute unit of measurement", 2: "Inch", 3: "Centimeter" }; - Ee.set(37392, Be), Ee.set(41488, Be); - var Ne = { 0: "Normal", 1: "Low", 2: "High" }; - function Ge(e3) { - return "object" == typeof e3 && void 0 !== e3.length ? e3[0] : e3; - } - function Ve(e3) { - let t2 = Array.from(e3).slice(1); - return t2[1] > 15 && (t2 = t2.map((e4) => String.fromCharCode(e4))), "0" !== t2[2] && 0 !== t2[2] || t2.pop(), t2.join("."); - } - function ze(e3) { - if ("string" == typeof e3) { - var [t2, i3, n3, s2, r2, a2] = e3.trim().split(/[-: ]/g).map(Number), o2 = new Date(t2, i3 - 1, n3); - return Number.isNaN(s2) || Number.isNaN(r2) || Number.isNaN(a2) || (o2.setHours(s2), o2.setMinutes(r2), o2.setSeconds(a2)), Number.isNaN(+o2) ? e3 : o2; + set(e3, t2, i3 = _I) { + return e3 instanceof DataView || e3 instanceof _I ? e3 = new Uint8Array(e3.buffer, e3.byteOffset, e3.byteLength) : e3 instanceof ArrayBuffer && (e3 = new Uint8Array(e3)), e3 instanceof Uint8Array || g2("BufferView.set(): Invalid data argument."), this.toUint8().set(e3, t2), new i3(this, t2, e3.byteLength); } - } - function He(e3) { - if ("string" == typeof e3) - return e3; - let t2 = []; - if (0 === e3[1] && 0 === e3[e3.length - 1]) - for (let i3 = 0; i3 < e3.length; i3 += 2) - t2.push(je(e3[i3 + 1], e3[i3])); - else - for (let i3 = 0; i3 < e3.length; i3 += 2) - t2.push(je(e3[i3], e3[i3 + 1])); - return m(String.fromCodePoint(...t2)); - } - function je(e3, t2) { - return e3 << 8 | t2; - } - Ee.set(41992, Ne), Ee.set(41993, Ne), Ee.set(41994, Ne), U(N, ["ifd0", "ifd1"], [[50827, function(e3) { - return "string" != typeof e3 ? b(e3) : e3; - }], [306, ze], [40091, He], [40092, He], [40093, He], [40094, He], [40095, He]]), U(N, "exif", [[40960, Ve], [36864, Ve], [36867, ze], [36868, ze], [40962, Ge], [40963, Ge]]), U(N, "gps", [[0, (e3) => Array.from(e3).join(".")], [7, (e3) => Array.from(e3).join(":")]]); - var We = class extends re2 { - static canHandle(e3, t2) { - return 225 === e3.getUint8(t2 + 1) && 1752462448 === e3.getUint32(t2 + 4) && "http://ns.adobe.com/" === e3.getString(t2 + 4, "http://ns.adobe.com/".length); + subarray(e3, t2) { + return t2 = t2 || this._lengthToEnd(e3), new _I(this, e3, t2); } - static headerLength(e3, t2) { - return "http://ns.adobe.com/xmp/extension/" === e3.getString(t2 + 4, "http://ns.adobe.com/xmp/extension/".length) ? 79 : 4 + "http://ns.adobe.com/xap/1.0/".length + 1; + toUint8() { + return new Uint8Array(this.buffer, this.byteOffset, this.byteLength); } - static findPosition(e3, t2) { - let i3 = super.findPosition(e3, t2); - return i3.multiSegment = i3.extended = 79 === i3.headerLength, i3.multiSegment ? (i3.chunkCount = e3.getUint8(t2 + 72), i3.chunkNumber = e3.getUint8(t2 + 76), 0 !== e3.getUint8(t2 + 77) && i3.chunkNumber++) : (i3.chunkCount = 1 / 0, i3.chunkNumber = -1), i3; + getUint8Array(e3, t2) { + return new Uint8Array(this.buffer, this.byteOffset + e3, t2); } - static handleMultiSegments(e3) { - return e3.map((e4) => e4.chunk.getString()).join(""); + getString(e3 = 0, t2 = this.byteLength) { + return b(this.getUint8Array(e3, t2)); } - normalizeInput(e3) { - return "string" == typeof e3 ? e3 : I.from(e3).getString(); + getLatin1String(e3 = 0, t2 = this.byteLength) { + let i3 = this.getUint8Array(e3, t2); + return C(i3); } - parse(e3 = this.chunk) { - if (!this.localOptions.parse) - return e3; - e3 = function(e4) { - let t3 = {}, i4 = {}; - for (let e6 of Ze) - t3[e6] = [], i4[e6] = 0; - return e4.replace(et, (e6, n4, s2) => { - if ("<" === n4) { - let n5 = ++i4[s2]; - return t3[s2].push(n5), "".concat(e6, "#").concat(n5); - } - return "".concat(e6, "#").concat(t3[s2].pop()); - }); - }(e3); - let t2 = Xe.findAll(e3, "rdf", "Description"); - 0 === t2.length && t2.push(new Xe("rdf", "Description", void 0, e3)); - let i3, n3 = {}; - for (let e4 of t2) - for (let t3 of e4.properties) - i3 = Je(t3.ns, n3), _e(t3, i3); - return function(e4) { - let t3; - for (let i4 in e4) - t3 = e4[i4] = f2(e4[i4]), void 0 === t3 && delete e4[i4]; - return f2(e4); - }(n3); + getUnicodeString(e3 = 0, t2 = this.byteLength) { + const i3 = []; + for (let n3 = 0; n3 < t2 && e3 + n3 < this.byteLength; n3 += 2) + i3.push(this.getUint16(e3 + n3)); + return C(i3); } - assignToOutput(e3, t2) { - if (this.localOptions.parse) - for (let [i3, n3] of Object.entries(t2)) - switch (i3) { - case "tiff": - this.assignObjectToOutput(e3, "ifd0", n3); - break; - case "exif": - this.assignObjectToOutput(e3, "exif", n3); - break; - case "xmlns": - break; - default: - this.assignObjectToOutput(e3, i3, n3); - } - else - e3.xmp = t2; + getInt8(e3) { + return this.dataView.getInt8(e3); } - }; - c(We, "type", "xmp"), c(We, "multiSegment", true), T.set("xmp", We); - var Ke = class _Ke { - static findAll(e3) { - return qe(e3, /([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(_Ke.unpackMatch); + getUint8(e3) { + return this.dataView.getUint8(e3); } - static unpackMatch(e3) { - let t2 = e3[1], i3 = e3[2], n3 = e3[3].slice(1, -1); - return n3 = Qe(n3), new _Ke(t2, i3, n3); + getInt16(e3, t2 = this.le) { + return this.dataView.getInt16(e3, t2); } - constructor(e3, t2, i3) { - this.ns = e3, this.name = t2, this.value = i3; + getInt32(e3, t2 = this.le) { + return this.dataView.getInt32(e3, t2); } - serialize() { - return this.value; + getUint16(e3, t2 = this.le) { + return this.dataView.getUint16(e3, t2); } - }; - var Xe = class _Xe { - static findAll(e3, t2, i3) { - if (void 0 !== t2 || void 0 !== i3) { - t2 = t2 || "[\\w\\d-]+", i3 = i3 || "[\\w\\d-]+"; - var n3 = new RegExp("<(".concat(t2, "):(").concat(i3, ")(#\\d+)?((\\s+?[\\w\\d-:]+=(\"[^\"]*\"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)"), "gm"); - } else - n3 = /<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm; - return qe(e3, n3).map(_Xe.unpackMatch); + getUint32(e3, t2 = this.le) { + return this.dataView.getUint32(e3, t2); } - static unpackMatch(e3) { - let t2 = e3[1], i3 = e3[2], n3 = e3[4], s2 = e3[8]; - return new _Xe(t2, i3, n3, s2); + getFloat32(e3, t2 = this.le) { + return this.dataView.getFloat32(e3, t2); } - constructor(e3, t2, i3, n3) { - this.ns = e3, this.name = t2, this.attrString = i3, this.innerXml = n3, this.attrs = Ke.findAll(i3), this.children = _Xe.findAll(n3), this.value = 0 === this.children.length ? Qe(n3) : void 0, this.properties = [...this.attrs, ...this.children]; + getFloat64(e3, t2 = this.le) { + return this.dataView.getFloat64(e3, t2); } - get isPrimitive() { - return void 0 !== this.value && 0 === this.attrs.length && 0 === this.children.length; + getFloat(e3, t2 = this.le) { + return this.dataView.getFloat32(e3, t2); } - get isListContainer() { - return 1 === this.children.length && this.children[0].isList; + getDouble(e3, t2 = this.le) { + return this.dataView.getFloat64(e3, t2); } - get isList() { - let { ns: e3, name: t2 } = this; - return "rdf" === e3 && ("Seq" === t2 || "Bag" === t2 || "Alt" === t2); + getUintBytes(e3, t2, i3) { + switch (t2) { + case 1: + return this.getUint8(e3, i3); + case 2: + return this.getUint16(e3, i3); + case 4: + return this.getUint32(e3, i3); + case 8: + return this.getUint64 && this.getUint64(e3, i3); + } } - get isListItem() { - return "rdf" === this.ns && "li" === this.name; + getUint(e3, t2, i3) { + switch (t2) { + case 8: + return this.getUint8(e3, i3); + case 16: + return this.getUint16(e3, i3); + case 32: + return this.getUint32(e3, i3); + case 64: + return this.getUint64 && this.getUint64(e3, i3); + } } - serialize() { - if (0 === this.properties.length && void 0 === this.value) - return; - if (this.isPrimitive) - return this.value; - if (this.isListContainer) - return this.children[0].serialize(); - if (this.isList) - return $e(this.children.map(Ye)); - if (this.isListItem && 1 === this.children.length && 0 === this.attrs.length) - return this.children[0].serialize(); - let e3 = {}; - for (let t2 of this.properties) - _e(t2, e3); - return void 0 !== this.value && (e3.value = this.value), f2(e3); + toString(e3) { + return this.dataView.toString(e3, this.constructor.name); + } + ensureChunk() { } }; - function _e(e3, t2) { - let i3 = e3.serialize(); - void 0 !== i3 && (t2[e3.name] = i3); + function P(e3, t2) { + g2("".concat(e3, " '").concat(t2, "' was not loaded, try using full build of exifr.")); } - var Ye = (e3) => e3.serialize(); - var $e = (e3) => 1 === e3.length ? e3[0] : e3; - var Je = (e3, t2) => t2[e3] ? t2[e3] : t2[e3] = {}; - function qe(e3, t2) { - let i3, n3 = []; - if (!e3) - return n3; - for (; null !== (i3 = t2.exec(e3)); ) - n3.push(i3); + var k = class extends Map { + constructor(e3) { + super(), this.kind = e3; + } + get(e3, t2) { + return this.has(e3) || P(this.kind, e3), t2 && (e3 in t2 || function(e4, t3) { + g2("Unknown ".concat(e4, " '").concat(t3, "'.")); + }(this.kind, e3), t2[e3].enabled || P(this.kind, e3)), super.get(e3); + } + keyList() { + return Array.from(this.keys()); + } + }; + var w = new k("file parser"); + var T = new k("segment parser"); + var A = new k("file reader"); + function D(e3, n3) { + return "string" == typeof e3 ? O(e3, n3) : t && !i2 && e3 instanceof HTMLImageElement ? O(e3.src, n3) : e3 instanceof Uint8Array || e3 instanceof ArrayBuffer || e3 instanceof DataView ? new I(e3) : t && e3 instanceof Blob ? x(e3, n3, "blob", R) : void g2("Invalid input argument"); + } + function O(e3, i3) { + return (s2 = e3).startsWith("data:") || s2.length > 1e4 ? v(e3, i3, "base64") : n2 && e3.includes("://") ? x(e3, i3, "url", M) : n2 ? v(e3, i3, "fs") : t ? x(e3, i3, "url", M) : void g2("Invalid input argument"); + var s2; + } + async function x(e3, t2, i3, n3) { + return A.has(i3) ? v(e3, t2, i3) : n3 ? async function(e4, t3) { + let i4 = await t3(e4); + return new I(i4); + }(e3, n3) : void g2("Parser ".concat(i3, " is not loaded")); + } + async function v(e3, t2, i3) { + let n3 = new (A.get(i3))(e3, t2); + return await n3.read(), n3; + } + var M = (e3) => h(e3).then((e4) => e4.arrayBuffer()); + var R = (e3) => new Promise((t2, i3) => { + let n3 = new FileReader(); + n3.onloadend = () => t2(n3.result || new ArrayBuffer()), n3.onerror = i3, n3.readAsArrayBuffer(e3); + }); + var L = class extends Map { + get tagKeys() { + return this.allKeys || (this.allKeys = Array.from(this.keys())), this.allKeys; + } + get tagValues() { + return this.allValues || (this.allValues = Array.from(this.values())), this.allValues; + } + }; + function U(e3, t2, i3) { + let n3 = new L(); + for (let [e4, t3] of i3) + n3.set(e4, t3); + if (Array.isArray(t2)) + for (let i4 of t2) + e3.set(i4, n3); + else + e3.set(t2, n3); return n3; } - function Qe(e3) { - if (function(e4) { - return null == e4 || "null" === e4 || "undefined" === e4 || "" === e4 || "" === e4.trim(); - }(e3)) - return; - let t2 = Number(e3); - if (!Number.isNaN(t2)) - return t2; - let i3 = e3.toLowerCase(); - return "true" === i3 || "false" !== i3 && e3.trim(); + function F(e3, t2, i3) { + let n3, s2 = e3.get(t2); + for (n3 of i3) + s2.set(n3[0], n3[1]); } - var Ze = ["rdf:li", "rdf:Seq", "rdf:Bag", "rdf:Alt", "rdf:Description"]; - var et = new RegExp("(<|\\/)(".concat(Ze.join("|"), ")"), "g"); - var tt = Object.freeze({ __proto__: null, default: Me, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j2, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q, parse: ie, gpsOnlyOptions: me, gps: Se, thumbnailOnlyOptions: Ce, thumbnail: ye, thumbnailUrl: be, orientationOnlyOptions: Ie, orientation: Pe, rotations: ke, get rotateCanvas() { - return we; - }, get rotateCss() { - return Te; - }, rotation: Ae }); - var at = l("fs", (e3) => e3.promises); - A.set("fs", class extends ve { - async readWhole() { - this.chunked = false, this.fs = await at; - let e3 = await this.fs.readFile(this.input); - this._swapBuffer(e3); + var E = /* @__PURE__ */ new Map(); + var B = /* @__PURE__ */ new Map(); + var N = /* @__PURE__ */ new Map(); + var G = ["chunked", "firstChunkSize", "firstChunkSizeNode", "firstChunkSizeBrowser", "chunkSize", "chunkLimit"]; + var V = ["jfif", "xmp", "icc", "iptc", "ihdr"]; + var z = ["tiff", ...V]; + var H = ["ifd0", "ifd1", "exif", "gps", "interop"]; + var j = [...z, ...H]; + var W = ["makerNote", "userComment"]; + var K = ["translateKeys", "translateValues", "reviveValues", "multiSegment"]; + var X = [...K, "sanitize", "mergeOutput", "silentErrors"]; + var _ = class { + get translate() { + return this.translateKeys || this.translateValues || this.reviveValues; } - async readChunked() { - this.chunked = true, this.fs = await at, await this.open(), await this.readChunk(0, this.options.firstChunkSize); + }; + var Y = class extends _ { + get needed() { + return this.enabled || this.deps.size > 0; } - async open() { - void 0 === this.fh && (this.fh = await this.fs.open(this.input, "r"), this.size = (await this.fh.stat(this.input)).size); + constructor(e3, t2, i3, n3) { + if (super(), c(this, "enabled", false), c(this, "skip", /* @__PURE__ */ new Set()), c(this, "pick", /* @__PURE__ */ new Set()), c(this, "deps", /* @__PURE__ */ new Set()), c(this, "translateKeys", false), c(this, "translateValues", false), c(this, "reviveValues", false), this.key = e3, this.enabled = t2, this.parse = this.enabled, this.applyInheritables(n3), this.canBeFiltered = H.includes(e3), this.canBeFiltered && (this.dict = E.get(e3)), void 0 !== i3) + if (Array.isArray(i3)) + this.parse = this.enabled = true, this.canBeFiltered && i3.length > 0 && this.translateTagSet(i3, this.pick); + else if ("object" == typeof i3) { + if (this.enabled = true, this.parse = false !== i3.parse, this.canBeFiltered) { + let { pick: e4, skip: t3 } = i3; + e4 && e4.length > 0 && this.translateTagSet(e4, this.pick), t3 && t3.length > 0 && this.translateTagSet(t3, this.skip); + } + this.applyInheritables(i3); + } else + true === i3 || false === i3 ? this.parse = this.enabled = i3 : g2("Invalid options argument: ".concat(i3)); } - async _readChunk(e3, t2) { - void 0 === this.fh && await this.open(), e3 + t2 > this.size && (t2 = this.size - e3); - var i3 = this.subarray(e3, t2, true); - return await this.fh.read(i3.dataView, 0, t2, e3), i3; + applyInheritables(e3) { + let t2, i3; + for (t2 of K) + i3 = e3[t2], void 0 !== i3 && (this[t2] = i3); } - async close() { - if (this.fh) { - let e3 = this.fh; - this.fh = void 0, await e3.close(); - } + translateTagSet(e3, t2) { + if (this.dict) { + let i3, n3, { tagKeys: s2, tagValues: r2 } = this.dict; + for (i3 of e3) + "string" == typeof i3 ? (n3 = r2.indexOf(i3), -1 === n3 && (n3 = s2.indexOf(Number(i3))), -1 !== n3 && t2.add(Number(s2[n3]))) : t2.add(i3); + } else + for (let i3 of e3) + t2.add(i3); } - }); - A.set("base64", class extends ve { - constructor(...e3) { - super(...e3), this.input = this.input.replace(/^data:([^;]+);base64,/gim, ""), this.size = this.input.length / 4 * 3, this.input.endsWith("==") ? this.size -= 2 : this.input.endsWith("=") && (this.size -= 1); + finalizeFilters() { + !this.enabled && this.deps.size > 0 ? (this.enabled = true, ee(this.pick, this.deps)) : this.enabled && this.pick.size > 0 && ee(this.pick, this.deps); } - async _readChunk(e3, t2) { - let i3, n3, r2 = this.input; - void 0 === e3 ? (e3 = 0, i3 = 0, n3 = 0) : (i3 = 4 * Math.floor(e3 / 3), n3 = e3 - i3 / 4 * 3), void 0 === t2 && (t2 = this.size); - let o2 = e3 + t2, l2 = i3 + 4 * Math.ceil(o2 / 3); - r2 = r2.slice(i3, l2); - let h2 = Math.min(t2, this.size - e3); - if (a) { - let t3 = s.from(r2, "base64").slice(n3, n3 + h2); - return this.set(t3, e3, true); - } - { - let t3 = this.subarray(e3, h2, true), i4 = atob(r2), s2 = t3.toUint8(); - for (let e4 = 0; e4 < h2; e4++) - s2[e4] = i4.charCodeAt(n3 + e4); - return t3; - } + }; + var $2 = { jfif: false, tiff: true, xmp: false, icc: false, iptc: false, ifd0: true, ifd1: false, exif: true, gps: true, interop: false, ihdr: void 0, makerNote: false, userComment: false, multiSegment: false, skip: [], pick: [], translateKeys: true, translateValues: true, reviveValues: true, sanitize: true, mergeOutput: true, silentErrors: true, chunked: true, firstChunkSize: void 0, firstChunkSizeNode: 512, firstChunkSizeBrowser: 65536, chunkSize: 65536, chunkLimit: 5 }; + var J = /* @__PURE__ */ new Map(); + var q = class extends _ { + static useCached(e3) { + let t2 = J.get(e3); + return void 0 !== t2 || (t2 = new this(e3), J.set(e3, t2)), t2; } - }); - var ot = class extends se { - static canHandle(e3, t2) { - return 18761 === t2 || 19789 === t2; + constructor(e3) { + super(), true === e3 ? this.setupFromTrue() : void 0 === e3 ? this.setupFromUndefined() : Array.isArray(e3) ? this.setupFromArray(e3) : "object" == typeof e3 ? this.setupFromObject(e3) : g2("Invalid options argument ".concat(e3)), void 0 === this.firstChunkSize && (this.firstChunkSize = t ? this.firstChunkSizeBrowser : this.firstChunkSizeNode), this.mergeOutput && (this.ifd1.enabled = false), this.filterNestedSegmentTags(), this.traverseTiffDependencyTree(), this.checkLoadedPlugins(); } - extendOptions(e3) { - let { ifd0: t2, xmp: i3, iptc: n3, icc: s2 } = e3; - i3.enabled && t2.deps.add(700), n3.enabled && t2.deps.add(33723), s2.enabled && t2.deps.add(34675), t2.finalizeFilters(); + setupFromUndefined() { + let e3; + for (e3 of G) + this[e3] = $2[e3]; + for (e3 of X) + this[e3] = $2[e3]; + for (e3 of W) + this[e3] = $2[e3]; + for (e3 of j) + this[e3] = new Y(e3, $2[e3], void 0, this); } - async parse() { - let { tiff: e3, xmp: t2, iptc: i3, icc: n3 } = this.options; - if (e3.enabled || t2.enabled || i3.enabled || n3.enabled) { - let e4 = Math.max(S(this.options), this.options.chunkSize); - await this.file.ensureChunk(0, e4), this.createParser("tiff", this.file), this.parsers.tiff.parseHeader(), await this.parsers.tiff.parseIfd0Block(), this.adaptTiffPropAsSegment("xmp"), this.adaptTiffPropAsSegment("iptc"), this.adaptTiffPropAsSegment("icc"); + setupFromTrue() { + let e3; + for (e3 of G) + this[e3] = $2[e3]; + for (e3 of X) + this[e3] = $2[e3]; + for (e3 of W) + this[e3] = true; + for (e3 of j) + this[e3] = new Y(e3, true, void 0, this); + } + setupFromArray(e3) { + let t2; + for (t2 of G) + this[t2] = $2[t2]; + for (t2 of X) + this[t2] = $2[t2]; + for (t2 of W) + this[t2] = $2[t2]; + for (t2 of j) + this[t2] = new Y(t2, false, void 0, this); + this.setupGlobalFilters(e3, void 0, H); + } + setupFromObject(e3) { + let t2; + for (t2 of (H.ifd0 = H.ifd0 || H.image, H.ifd1 = H.ifd1 || H.thumbnail, Object.assign(this, e3), G)) + this[t2] = Z(e3[t2], $2[t2]); + for (t2 of X) + this[t2] = Z(e3[t2], $2[t2]); + for (t2 of W) + this[t2] = Z(e3[t2], $2[t2]); + for (t2 of z) + this[t2] = new Y(t2, $2[t2], e3[t2], this); + for (t2 of H) + this[t2] = new Y(t2, $2[t2], e3[t2], this.tiff); + this.setupGlobalFilters(e3.pick, e3.skip, H, j), true === e3.tiff ? this.batchEnableWithBool(H, true) : false === e3.tiff ? this.batchEnableWithUserValue(H, e3) : Array.isArray(e3.tiff) ? this.setupGlobalFilters(e3.tiff, void 0, H) : "object" == typeof e3.tiff && this.setupGlobalFilters(e3.tiff.pick, e3.tiff.skip, H); + } + batchEnableWithBool(e3, t2) { + for (let i3 of e3) + this[i3].enabled = t2; + } + batchEnableWithUserValue(e3, t2) { + for (let i3 of e3) { + let e4 = t2[i3]; + this[i3].enabled = false !== e4 && void 0 !== e4; } } - adaptTiffPropAsSegment(e3) { - if (this.parsers.tiff[e3]) { - let t2 = this.parsers.tiff[e3]; - this.injectSegment(e3, t2); + setupGlobalFilters(e3, t2, i3, n3 = i3) { + if (e3 && e3.length) { + for (let e4 of n3) + this[e4].enabled = false; + let t3 = Q(e3, i3); + for (let [e4, i4] of t3) + ee(this[e4].pick, i4), this[e4].enabled = true; + } else if (t2 && t2.length) { + let e4 = Q(t2, i3); + for (let [t3, i4] of e4) + ee(this[t3].skip, i4); } } - }; - c(ot, "type", "tiff"), w.set("tiff", ot); - var lt = l("zlib"); - var ht = ["ihdr", "iccp", "text", "itxt", "exif"]; - var ut = class extends se { - constructor(...e3) { - super(...e3), c(this, "catchError", (e4) => this.errors.push(e4)), c(this, "metaChunks", []), c(this, "unknownChunks", []); + filterNestedSegmentTags() { + let { ifd0: e3, exif: t2, xmp: i3, iptc: n3, icc: s2 } = this; + this.makerNote ? t2.deps.add(37500) : t2.skip.add(37500), this.userComment ? t2.deps.add(37510) : t2.skip.add(37510), i3.enabled || e3.skip.add(700), n3.enabled || e3.skip.add(33723), s2.enabled || e3.skip.add(34675); } - static canHandle(e3, t2) { - return 35152 === t2 && 2303741511 === e3.getUint32(0) && 218765834 === e3.getUint32(4); + traverseTiffDependencyTree() { + let { ifd0: e3, exif: t2, gps: i3, interop: n3 } = this; + n3.needed && (t2.deps.add(40965), e3.deps.add(40965)), t2.needed && e3.deps.add(34665), i3.needed && e3.deps.add(34853), this.tiff.enabled = H.some((e4) => true === this[e4].enabled) || this.makerNote || this.userComment; + for (let e4 of H) + this[e4].finalizeFilters(); } - async parse() { - let { file: e3 } = this; - await this.findPngChunksInRange("\x89PNG\r\n\n".length, e3.byteLength), await this.readSegments(this.metaChunks), this.findIhdr(), this.parseTextChunks(), await this.findExif().catch(this.catchError), await this.findXmp().catch(this.catchError), await this.findIcc().catch(this.catchError); + get onlyTiff() { + return !V.map((e3) => this[e3].enabled).some((e3) => true === e3) && this.tiff.enabled; } - async findPngChunksInRange(e3, t2) { - let { file: i3 } = this; - for (; e3 < t2; ) { - let t3 = i3.getUint32(e3), n3 = i3.getUint32(e3 + 4), s2 = i3.getString(e3 + 4, 4).toLowerCase(), r2 = t3 + 4 + 4 + 4, a2 = { type: s2, offset: e3, length: r2, start: e3 + 4 + 4, size: t3, marker: n3 }; - ht.includes(s2) ? this.metaChunks.push(a2) : this.unknownChunks.push(a2), e3 += r2; - } + checkLoadedPlugins() { + for (let e3 of z) + this[e3].enabled && !T.has(e3) && P("segment parser", e3); } - parseTextChunks() { - let e3 = this.metaChunks.filter((e4) => "text" === e4.type); - for (let t2 of e3) { - let [e4, i3] = this.file.getString(t2.start, t2.size).split("\0"); - this.injectKeyValToIhdr(e4, i3); - } + }; + function Q(e3, t2) { + let i3, n3, s2, r2, a2 = []; + for (s2 of t2) { + for (r2 of (i3 = E.get(s2), n3 = [], i3)) + (e3.includes(r2[0]) || e3.includes(r2[1])) && n3.push(r2[0]); + n3.length && a2.push([s2, n3]); } - injectKeyValToIhdr(e3, t2) { - let i3 = this.parsers.ihdr; - i3 && i3.raw.set(e3, t2); + return a2; + } + function Z(e3, t2) { + return void 0 !== e3 ? e3 : void 0 !== t2 ? t2 : void 0; + } + function ee(e3, t2) { + for (let i3 of t2) + e3.add(i3); + } + c(q, "default", $2); + var te = class { + constructor(e3) { + c(this, "parsers", {}), c(this, "output", {}), c(this, "errors", []), c(this, "pushToErrors", (e4) => this.errors.push(e4)), this.options = q.useCached(e3); } - findIhdr() { - let e3 = this.metaChunks.find((e4) => "ihdr" === e4.type); - e3 && false !== this.options.ihdr.enabled && this.createParser("ihdr", e3.chunk); + async read(e3) { + this.file = await D(e3, this.options); + } + setup() { + if (this.fileParser) + return; + let { file: e3 } = this, t2 = e3.getUint16(0); + for (let [i3, n3] of w) + if (n3.canHandle(e3, t2)) + return this.fileParser = new n3(this.options, this.file, this.parsers), e3[i3] = true; + this.file.close && this.file.close(), g2("Unknown file format"); } - async findExif() { - let e3 = this.metaChunks.find((e4) => "exif" === e4.type); - e3 && this.injectSegment("tiff", e3.chunk); + async parse() { + let { output: e3, errors: t2 } = this; + return this.setup(), this.options.silentErrors ? (await this.executeParsers().catch(this.pushToErrors), t2.push(...this.fileParser.errors)) : await this.executeParsers(), this.file.close && this.file.close(), this.options.silentErrors && t2.length > 0 && (e3.errors = t2), f(e3); } - async findXmp() { - let e3 = this.metaChunks.filter((e4) => "itxt" === e4.type); - for (let t2 of e3) { - "XML:com.adobe.xmp" === t2.chunk.getString(0, "XML:com.adobe.xmp".length) && this.injectSegment("xmp", t2.chunk); - } + async executeParsers() { + let { output: e3 } = this; + await this.fileParser.parse(); + let t2 = Object.values(this.parsers).map(async (t3) => { + let i3 = await t3.parse(); + t3.assignToOutput(e3, i3); + }); + this.options.silentErrors && (t2 = t2.map((e4) => e4.catch(this.pushToErrors))), await Promise.all(t2); } - async findIcc() { - let e3 = this.metaChunks.find((e4) => "iccp" === e4.type); - if (!e3) + async extractThumbnail() { + this.setup(); + let { options: e3, file: t2 } = this, i3 = T.get("tiff", e3); + var n3; + if (t2.tiff ? n3 = { start: 0, type: "tiff" } : t2.jpeg && (n3 = await this.fileParser.getOrFindSegment("tiff")), void 0 === n3) return; - let { chunk: t2 } = e3, i3 = t2.getUint8Array(0, 81), s2 = 0; - for (; s2 < 80 && 0 !== i3[s2]; ) - s2++; - let r2 = s2 + 2, a2 = t2.getString(0, s2); - if (this.injectKeyValToIhdr("ProfileName", a2), n2) { - let e4 = await lt, i4 = t2.getUint8Array(r2); - i4 = e4.inflateSync(i4), this.injectSegment("icc", i4); - } + let s2 = await this.fileParser.ensureSegmentChunk(n3), r2 = this.parsers.tiff = new i3(s2, e3, t2), a2 = await r2.extractThumbnail(); + return t2.close && t2.close(), a2; } }; - c(ut, "type", "png"), w.set("png", ut), U(E, "interop", [[1, "InteropIndex"], [2, "InteropVersion"], [4096, "RelatedImageFileFormat"], [4097, "RelatedImageWidth"], [4098, "RelatedImageHeight"]]), F(E, "ifd0", [[11, "ProcessingSoftware"], [254, "SubfileType"], [255, "OldSubfileType"], [263, "Thresholding"], [264, "CellWidth"], [265, "CellLength"], [266, "FillOrder"], [269, "DocumentName"], [280, "MinSampleValue"], [281, "MaxSampleValue"], [285, "PageName"], [286, "XPosition"], [287, "YPosition"], [290, "GrayResponseUnit"], [297, "PageNumber"], [321, "HalftoneHints"], [322, "TileWidth"], [323, "TileLength"], [332, "InkSet"], [337, "TargetPrinter"], [18246, "Rating"], [18249, "RatingPercent"], [33550, "PixelScale"], [34264, "ModelTransform"], [34377, "PhotoshopSettings"], [50706, "DNGVersion"], [50707, "DNGBackwardVersion"], [50708, "UniqueCameraModel"], [50709, "LocalizedCameraModel"], [50736, "DNGLensInfo"], [50739, "ShadowScale"], [50740, "DNGPrivateData"], [33920, "IntergraphMatrix"], [33922, "ModelTiePoint"], [34118, "SEMInfo"], [34735, "GeoTiffDirectory"], [34736, "GeoTiffDoubleParams"], [34737, "GeoTiffAsciiParams"], [50341, "PrintIM"], [50721, "ColorMatrix1"], [50722, "ColorMatrix2"], [50723, "CameraCalibration1"], [50724, "CameraCalibration2"], [50725, "ReductionMatrix1"], [50726, "ReductionMatrix2"], [50727, "AnalogBalance"], [50728, "AsShotNeutral"], [50729, "AsShotWhiteXY"], [50730, "BaselineExposure"], [50731, "BaselineNoise"], [50732, "BaselineSharpness"], [50734, "LinearResponseLimit"], [50735, "CameraSerialNumber"], [50741, "MakerNoteSafety"], [50778, "CalibrationIlluminant1"], [50779, "CalibrationIlluminant2"], [50781, "RawDataUniqueID"], [50827, "OriginalRawFileName"], [50828, "OriginalRawFileData"], [50831, "AsShotICCProfile"], [50832, "AsShotPreProfileMatrix"], [50833, "CurrentICCProfile"], [50834, "CurrentPreProfileMatrix"], [50879, "ColorimetricReference"], [50885, "SRawType"], [50898, "PanasonicTitle"], [50899, "PanasonicTitle2"], [50931, "CameraCalibrationSig"], [50932, "ProfileCalibrationSig"], [50933, "ProfileIFD"], [50934, "AsShotProfileName"], [50936, "ProfileName"], [50937, "ProfileHueSatMapDims"], [50938, "ProfileHueSatMapData1"], [50939, "ProfileHueSatMapData2"], [50940, "ProfileToneCurve"], [50941, "ProfileEmbedPolicy"], [50942, "ProfileCopyright"], [50964, "ForwardMatrix1"], [50965, "ForwardMatrix2"], [50966, "PreviewApplicationName"], [50967, "PreviewApplicationVersion"], [50968, "PreviewSettingsName"], [50969, "PreviewSettingsDigest"], [50970, "PreviewColorSpace"], [50971, "PreviewDateTime"], [50972, "RawImageDigest"], [50973, "OriginalRawFileDigest"], [50981, "ProfileLookTableDims"], [50982, "ProfileLookTableData"], [51043, "TimeCodes"], [51044, "FrameRate"], [51058, "TStop"], [51081, "ReelName"], [51089, "OriginalDefaultFinalSize"], [51090, "OriginalBestQualitySize"], [51091, "OriginalDefaultCropSize"], [51105, "CameraLabel"], [51107, "ProfileHueSatMapEncoding"], [51108, "ProfileLookTableEncoding"], [51109, "BaselineExposureOffset"], [51110, "DefaultBlackRender"], [51111, "NewRawImageDigest"], [51112, "RawToPreviewGain"]]); - var ct = [[273, "StripOffsets"], [279, "StripByteCounts"], [288, "FreeOffsets"], [289, "FreeByteCounts"], [291, "GrayResponseCurve"], [292, "T4Options"], [293, "T6Options"], [300, "ColorResponseUnit"], [320, "ColorMap"], [324, "TileOffsets"], [325, "TileByteCounts"], [326, "BadFaxLines"], [327, "CleanFaxData"], [328, "ConsecutiveBadFaxLines"], [330, "SubIFD"], [333, "InkNames"], [334, "NumberofInks"], [336, "DotRange"], [338, "ExtraSamples"], [339, "SampleFormat"], [340, "SMinSampleValue"], [341, "SMaxSampleValue"], [342, "TransferRange"], [343, "ClipPath"], [344, "XClipPathUnits"], [345, "YClipPathUnits"], [346, "Indexed"], [347, "JPEGTables"], [351, "OPIProxy"], [400, "GlobalParametersIFD"], [401, "ProfileType"], [402, "FaxProfile"], [403, "CodingMethods"], [404, "VersionYear"], [405, "ModeNumber"], [433, "Decode"], [434, "DefaultImageColor"], [435, "T82Options"], [437, "JPEGTables"], [512, "JPEGProc"], [515, "JPEGRestartInterval"], [517, "JPEGLosslessPredictors"], [518, "JPEGPointTransforms"], [519, "JPEGQTables"], [520, "JPEGDCTables"], [521, "JPEGACTables"], [559, "StripRowCounts"], [999, "USPTOMiscellaneous"], [18247, "XP_DIP_XML"], [18248, "StitchInfo"], [28672, "SonyRawFileType"], [28688, "SonyToneCurve"], [28721, "VignettingCorrection"], [28722, "VignettingCorrParams"], [28724, "ChromaticAberrationCorrection"], [28725, "ChromaticAberrationCorrParams"], [28726, "DistortionCorrection"], [28727, "DistortionCorrParams"], [29895, "SonyCropTopLeft"], [29896, "SonyCropSize"], [32781, "ImageID"], [32931, "WangTag1"], [32932, "WangAnnotation"], [32933, "WangTag3"], [32934, "WangTag4"], [32953, "ImageReferencePoints"], [32954, "RegionXformTackPoint"], [32955, "WarpQuadrilateral"], [32956, "AffineTransformMat"], [32995, "Matteing"], [32996, "DataType"], [32997, "ImageDepth"], [32998, "TileDepth"], [33300, "ImageFullWidth"], [33301, "ImageFullHeight"], [33302, "TextureFormat"], [33303, "WrapModes"], [33304, "FovCot"], [33305, "MatrixWorldToScreen"], [33306, "MatrixWorldToCamera"], [33405, "Model2"], [33421, "CFARepeatPatternDim"], [33422, "CFAPattern2"], [33423, "BatteryLevel"], [33424, "KodakIFD"], [33445, "MDFileTag"], [33446, "MDScalePixel"], [33447, "MDColorTable"], [33448, "MDLabName"], [33449, "MDSampleInfo"], [33450, "MDPrepDate"], [33451, "MDPrepTime"], [33452, "MDFileUnits"], [33589, "AdventScale"], [33590, "AdventRevision"], [33628, "UIC1Tag"], [33629, "UIC2Tag"], [33630, "UIC3Tag"], [33631, "UIC4Tag"], [33918, "IntergraphPacketData"], [33919, "IntergraphFlagRegisters"], [33921, "INGRReserved"], [34016, "Site"], [34017, "ColorSequence"], [34018, "IT8Header"], [34019, "RasterPadding"], [34020, "BitsPerRunLength"], [34021, "BitsPerExtendedRunLength"], [34022, "ColorTable"], [34023, "ImageColorIndicator"], [34024, "BackgroundColorIndicator"], [34025, "ImageColorValue"], [34026, "BackgroundColorValue"], [34027, "PixelIntensityRange"], [34028, "TransparencyIndicator"], [34029, "ColorCharacterization"], [34030, "HCUsage"], [34031, "TrapIndicator"], [34032, "CMYKEquivalent"], [34152, "AFCP_IPTC"], [34232, "PixelMagicJBIGOptions"], [34263, "JPLCartoIFD"], [34306, "WB_GRGBLevels"], [34310, "LeafData"], [34687, "TIFF_FXExtensions"], [34688, "MultiProfiles"], [34689, "SharedData"], [34690, "T88Options"], [34732, "ImageLayer"], [34750, "JBIGOptions"], [34856, "Opto-ElectricConvFactor"], [34857, "Interlace"], [34908, "FaxRecvParams"], [34909, "FaxSubAddress"], [34910, "FaxRecvTime"], [34929, "FedexEDR"], [34954, "LeafSubIFD"], [37387, "FlashEnergy"], [37388, "SpatialFrequencyResponse"], [37389, "Noise"], [37390, "FocalPlaneXResolution"], [37391, "FocalPlaneYResolution"], [37392, "FocalPlaneResolutionUnit"], [37397, "ExposureIndex"], [37398, "TIFF-EPStandardID"], [37399, "SensingMethod"], [37434, "CIP3DataFile"], [37435, "CIP3Sheet"], [37436, "CIP3Side"], [37439, "StoNits"], [37679, "MSDocumentText"], [37680, "MSPropertySetStorage"], [37681, "MSDocumentTextPosition"], [37724, "ImageSourceData"], [40965, "InteropIFD"], [40976, "SamsungRawPointersOffset"], [40977, "SamsungRawPointersLength"], [41217, "SamsungRawByteOrder"], [41218, "SamsungRawUnknown"], [41484, "SpatialFrequencyResponse"], [41485, "Noise"], [41489, "ImageNumber"], [41490, "SecurityClassification"], [41491, "ImageHistory"], [41494, "TIFF-EPStandardID"], [41995, "DeviceSettingDescription"], [42112, "GDALMetadata"], [42113, "GDALNoData"], [44992, "ExpandSoftware"], [44993, "ExpandLens"], [44994, "ExpandFilm"], [44995, "ExpandFilterLens"], [44996, "ExpandScanner"], [44997, "ExpandFlashLamp"], [46275, "HasselbladRawImage"], [48129, "PixelFormat"], [48130, "Transformation"], [48131, "Uncompressed"], [48132, "ImageType"], [48256, "ImageWidth"], [48257, "ImageHeight"], [48258, "WidthResolution"], [48259, "HeightResolution"], [48320, "ImageOffset"], [48321, "ImageByteCount"], [48322, "AlphaOffset"], [48323, "AlphaByteCount"], [48324, "ImageDataDiscard"], [48325, "AlphaDataDiscard"], [50215, "OceScanjobDesc"], [50216, "OceApplicationSelector"], [50217, "OceIDNumber"], [50218, "OceImageLogic"], [50255, "Annotations"], [50459, "HasselbladExif"], [50547, "OriginalFileName"], [50560, "USPTOOriginalContentType"], [50656, "CR2CFAPattern"], [50710, "CFAPlaneColor"], [50711, "CFALayout"], [50712, "LinearizationTable"], [50713, "BlackLevelRepeatDim"], [50714, "BlackLevel"], [50715, "BlackLevelDeltaH"], [50716, "BlackLevelDeltaV"], [50717, "WhiteLevel"], [50718, "DefaultScale"], [50719, "DefaultCropOrigin"], [50720, "DefaultCropSize"], [50733, "BayerGreenSplit"], [50737, "ChromaBlurRadius"], [50738, "AntiAliasStrength"], [50752, "RawImageSegmentation"], [50780, "BestQualityScale"], [50784, "AliasLayerMetadata"], [50829, "ActiveArea"], [50830, "MaskedAreas"], [50935, "NoiseReductionApplied"], [50974, "SubTileBlockSize"], [50975, "RowInterleaveFactor"], [51008, "OpcodeList1"], [51009, "OpcodeList2"], [51022, "OpcodeList3"], [51041, "NoiseProfile"], [51114, "CacheVersion"], [51125, "DefaultUserCrop"], [51157, "NikonNEFInfo"], [65024, "KdcIFD"]]; - F(E, "ifd0", ct), F(E, "exif", ct), U(B, "gps", [[23, { M: "Magnetic North", T: "True North" }], [25, { K: "Kilometers", M: "Miles", N: "Nautical Miles" }]]); - var ft = class extends re2 { - static canHandle(e3, t2) { - return 224 === e3.getUint8(t2 + 1) && 1246120262 === e3.getUint32(t2 + 4) && 0 === e3.getUint8(t2 + 8); + async function ie(e3, t2) { + let i3 = new te(t2); + return await i3.read(e3), i3.parse(); + } + var ne = Object.freeze({ __proto__: null, parse: ie, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q }); + var se = class { + constructor(e3, t2, i3) { + c(this, "errors", []), c(this, "ensureSegmentChunk", async (e4) => { + let t3 = e4.start, i4 = e4.size || 65536; + if (this.file.chunked) + if (this.file.available(t3, i4)) + e4.chunk = this.file.subarray(t3, i4); + else + try { + e4.chunk = await this.file.readChunk(t3, i4); + } catch (t4) { + g2("Couldn't read segment: ".concat(JSON.stringify(e4), ". ").concat(t4.message)); + } + else + this.file.byteLength > t3 + i4 ? e4.chunk = this.file.subarray(t3, i4) : void 0 === e4.size ? e4.chunk = this.file.subarray(t3) : g2("Segment unreachable: " + JSON.stringify(e4)); + return e4.chunk; + }), this.extendOptions && this.extendOptions(e3), this.options = e3, this.file = t2, this.parsers = i3; } - parse() { - return this.parseTags(), this.translate(), this.output; + injectSegment(e3, t2) { + this.options[e3].enabled && this.createParser(e3, t2); } - parseTags() { - this.raw = /* @__PURE__ */ new Map([[0, this.chunk.getUint16(0)], [2, this.chunk.getUint8(2)], [3, this.chunk.getUint16(3)], [5, this.chunk.getUint16(5)], [7, this.chunk.getUint8(7)], [8, this.chunk.getUint8(8)]]); + createParser(e3, t2) { + let i3 = new (T.get(e3))(t2, this.options, this.file); + return this.parsers[e3] = i3; } - }; - c(ft, "type", "jfif"), c(ft, "headerLength", 9), T.set("jfif", ft), U(E, "jfif", [[0, "JFIFVersion"], [2, "ResolutionUnit"], [3, "XResolution"], [5, "YResolution"], [7, "ThumbnailWidth"], [8, "ThumbnailHeight"]]); - var dt = class extends re2 { - parse() { - return this.parseTags(), this.translate(), this.output; + createParsers(e3) { + for (let t2 of e3) { + let { type: e4, chunk: i3 } = t2, n3 = this.options[e4]; + if (n3 && n3.enabled) { + let t3 = this.parsers[e4]; + t3 && t3.append || t3 || this.createParser(e4, i3); + } + } } - parseTags() { - this.raw = new Map([[0, this.chunk.getUint32(0)], [4, this.chunk.getUint32(4)], [8, this.chunk.getUint8(8)], [9, this.chunk.getUint8(9)], [10, this.chunk.getUint8(10)], [11, this.chunk.getUint8(11)], [12, this.chunk.getUint8(12)], ...Array.from(this.raw)]); + async readSegments(e3) { + let t2 = e3.map(this.ensureSegmentChunk); + await Promise.all(t2); } }; - c(dt, "type", "ihdr"), T.set("ihdr", dt), U(E, "ihdr", [[0, "ImageWidth"], [4, "ImageHeight"], [8, "BitDepth"], [9, "ColorType"], [10, "Compression"], [11, "Filter"], [12, "Interlace"]]), U(B, "ihdr", [[9, { 0: "Grayscale", 2: "RGB", 3: "Palette", 4: "Grayscale with Alpha", 6: "RGB with Alpha", DEFAULT: "Unknown" }], [10, { 0: "Deflate/Inflate", DEFAULT: "Unknown" }], [11, { 0: "Adaptive", DEFAULT: "Unknown" }], [12, { 0: "Noninterlaced", 1: "Adam7 Interlace", DEFAULT: "Unknown" }]]); - var pt = class extends re2 { - static canHandle(e3, t2) { - return 226 === e3.getUint8(t2 + 1) && 1229144927 === e3.getUint32(t2 + 4); - } + var re2 = class { static findPosition(e3, t2) { - let i3 = super.findPosition(e3, t2); - return i3.chunkNumber = e3.getUint8(t2 + 16), i3.chunkCount = e3.getUint8(t2 + 17), i3.multiSegment = i3.chunkCount > 1, i3; - } - static handleMultiSegments(e3) { - return function(e4) { - let t2 = function(e6) { - let t3 = e6[0].constructor, i3 = 0; - for (let t4 of e6) - i3 += t4.length; - let n3 = new t3(i3), s2 = 0; - for (let t4 of e6) - n3.set(t4, s2), s2 += t4.length; - return n3; - }(e4.map((e6) => e6.chunk.toUint8())); - return new I(t2); - }(e3); + let i3 = e3.getUint16(t2 + 2) + 2, n3 = "function" == typeof this.headerLength ? this.headerLength(e3, t2, i3) : this.headerLength, s2 = t2 + n3, r2 = i3 - n3; + return { offset: t2, length: i3, headerLength: n3, start: s2, size: r2, end: s2 + r2 }; } - parse() { - return this.raw = /* @__PURE__ */ new Map(), this.parseHeader(), this.parseTags(), this.translate(), this.output; + static parse(e3, t2 = {}) { + return new this(e3, new q({ [this.type]: t2 }), e3).parse(); } - parseHeader() { - let { raw: e3 } = this; - this.chunk.byteLength < 84 && g2("ICC header is too short"); - for (let [t2, i3] of Object.entries(gt)) { - t2 = parseInt(t2, 10); - let n3 = i3(this.chunk, t2); - "\0\0\0\0" !== n3 && e3.set(t2, n3); - } + normalizeInput(e3) { + return e3 instanceof I ? e3 : new I(e3); } - parseTags() { - let e3, t2, i3, n3, s2, { raw: r2 } = this, a2 = this.chunk.getUint32(128), o2 = 132, l2 = this.chunk.byteLength; - for (; a2--; ) { - if (e3 = this.chunk.getString(o2, 4), t2 = this.chunk.getUint32(o2 + 4), i3 = this.chunk.getUint32(o2 + 8), n3 = this.chunk.getString(t2, 4), t2 + i3 > l2) - return void console.warn("reached the end of the first ICC chunk. Enable options.tiff.multiSegment to read all ICC segments."); - s2 = this.parseTag(n3, t2, i3), void 0 !== s2 && "\0\0\0\0" !== s2 && r2.set(e3, s2), o2 += 12; - } + constructor(e3, t2 = {}, i3) { + c(this, "errors", []), c(this, "raw", /* @__PURE__ */ new Map()), c(this, "handleError", (e4) => { + if (!this.options.silentErrors) + throw e4; + this.errors.push(e4.message); + }), this.chunk = this.normalizeInput(e3), this.file = i3, this.type = this.constructor.type, this.globalOptions = this.options = t2, this.localOptions = t2[this.type], this.canTranslate = this.localOptions && this.localOptions.translate; } - parseTag(e3, t2, i3) { - switch (e3) { - case "desc": - return this.parseDesc(t2); - case "mluc": - return this.parseMluc(t2); - case "text": - return this.parseText(t2, i3); - case "sig ": - return this.parseSig(t2); - } - if (!(t2 + i3 > this.chunk.byteLength)) - return this.chunk.getUint8Array(t2, i3); + translate() { + this.canTranslate && (this.translated = this.translateBlock(this.raw, this.type)); } - parseDesc(e3) { - let t2 = this.chunk.getUint32(e3 + 8) - 1; - return m(this.chunk.getString(e3 + 12, t2)); + get output() { + return this.translated ? this.translated : this.raw ? Object.fromEntries(this.raw) : void 0; } - parseText(e3, t2) { - return m(this.chunk.getString(e3 + 8, t2 - 8)); + translateBlock(e3, t2) { + let i3 = N.get(t2), n3 = B.get(t2), s2 = E.get(t2), r2 = this.options[t2], a2 = r2.reviveValues && !!i3, o2 = r2.translateValues && !!n3, l2 = r2.translateKeys && !!s2, h2 = {}; + for (let [t3, r3] of e3) + a2 && i3.has(t3) ? r3 = i3.get(t3)(r3) : o2 && n3.has(t3) && (r3 = this.translateValue(r3, n3.get(t3))), l2 && s2.has(t3) && (t3 = s2.get(t3) || t3), h2[t3] = r3; + return h2; } - parseSig(e3) { - return m(this.chunk.getString(e3 + 8, 4)); + translateValue(e3, t2) { + return t2[e3] || t2.DEFAULT || e3; } - parseMluc(e3) { - let { chunk: t2 } = this, i3 = t2.getUint32(e3 + 8), n3 = t2.getUint32(e3 + 12), s2 = e3 + 16, r2 = []; - for (let a2 = 0; a2 < i3; a2++) { - let i4 = t2.getString(s2 + 0, 2), a3 = t2.getString(s2 + 2, 2), o2 = t2.getUint32(s2 + 4), l2 = t2.getUint32(s2 + 8) + e3, h2 = m(t2.getUnicodeString(l2, o2)); - r2.push({ lang: i4, country: a3, text: h2 }), s2 += n3; - } - return 1 === i3 ? r2[0].text : r2; + assignToOutput(e3, t2) { + this.assignObjectToOutput(e3, this.constructor.type, t2); } - translateValue(e3, t2) { - return "string" == typeof e3 ? t2[e3] || t2[e3.toLowerCase()] || e3 : t2[e3] || e3; + assignObjectToOutput(e3, t2, i3) { + if (this.globalOptions.mergeOutput) + return Object.assign(e3, i3); + e3[t2] ? Object.assign(e3[t2], i3) : e3[t2] = i3; } }; - c(pt, "type", "icc"), c(pt, "multiSegment", true), c(pt, "headerLength", 18); - var gt = { 4: mt, 8: function(e3, t2) { - return [e3.getUint8(t2), e3.getUint8(t2 + 1) >> 4, e3.getUint8(t2 + 1) % 16].map((e4) => e4.toString(10)).join("."); - }, 12: mt, 16: mt, 20: mt, 24: function(e3, t2) { - const i3 = e3.getUint16(t2), n3 = e3.getUint16(t2 + 2) - 1, s2 = e3.getUint16(t2 + 4), r2 = e3.getUint16(t2 + 6), a2 = e3.getUint16(t2 + 8), o2 = e3.getUint16(t2 + 10); - return new Date(Date.UTC(i3, n3, s2, r2, a2, o2)); - }, 36: mt, 40: mt, 48: mt, 52: mt, 64: (e3, t2) => e3.getUint32(t2), 80: mt }; - function mt(e3, t2) { - return m(e3.getString(t2, 4)); + c(re2, "headerLength", 4), c(re2, "type", void 0), c(re2, "multiSegment", false), c(re2, "canHandle", () => false); + function ae(e3) { + return 192 === e3 || 194 === e3 || 196 === e3 || 219 === e3 || 221 === e3 || 218 === e3 || 254 === e3; } - T.set("icc", pt), U(E, "icc", [[4, "ProfileCMMType"], [8, "ProfileVersion"], [12, "ProfileClass"], [16, "ColorSpaceData"], [20, "ProfileConnectionSpace"], [24, "ProfileDateTime"], [36, "ProfileFileSignature"], [40, "PrimaryPlatform"], [44, "CMMFlags"], [48, "DeviceManufacturer"], [52, "DeviceModel"], [56, "DeviceAttributes"], [64, "RenderingIntent"], [68, "ConnectionSpaceIlluminant"], [80, "ProfileCreator"], [84, "ProfileID"], ["Header", "ProfileHeader"], ["MS00", "WCSProfiles"], ["bTRC", "BlueTRC"], ["bXYZ", "BlueMatrixColumn"], ["bfd", "UCRBG"], ["bkpt", "MediaBlackPoint"], ["calt", "CalibrationDateTime"], ["chad", "ChromaticAdaptation"], ["chrm", "Chromaticity"], ["ciis", "ColorimetricIntentImageState"], ["clot", "ColorantTableOut"], ["clro", "ColorantOrder"], ["clrt", "ColorantTable"], ["cprt", "ProfileCopyright"], ["crdi", "CRDInfo"], ["desc", "ProfileDescription"], ["devs", "DeviceSettings"], ["dmdd", "DeviceModelDesc"], ["dmnd", "DeviceMfgDesc"], ["dscm", "ProfileDescriptionML"], ["fpce", "FocalPlaneColorimetryEstimates"], ["gTRC", "GreenTRC"], ["gXYZ", "GreenMatrixColumn"], ["gamt", "Gamut"], ["kTRC", "GrayTRC"], ["lumi", "Luminance"], ["meas", "Measurement"], ["meta", "Metadata"], ["mmod", "MakeAndModel"], ["ncl2", "NamedColor2"], ["ncol", "NamedColor"], ["ndin", "NativeDisplayInfo"], ["pre0", "Preview0"], ["pre1", "Preview1"], ["pre2", "Preview2"], ["ps2i", "PS2RenderingIntent"], ["ps2s", "PostScript2CSA"], ["psd0", "PostScript2CRD0"], ["psd1", "PostScript2CRD1"], ["psd2", "PostScript2CRD2"], ["psd3", "PostScript2CRD3"], ["pseq", "ProfileSequenceDesc"], ["psid", "ProfileSequenceIdentifier"], ["psvm", "PS2CRDVMSize"], ["rTRC", "RedTRC"], ["rXYZ", "RedMatrixColumn"], ["resp", "OutputResponse"], ["rhoc", "ReflectionHardcopyOrigColorimetry"], ["rig0", "PerceptualRenderingIntentGamut"], ["rig2", "SaturationRenderingIntentGamut"], ["rpoc", "ReflectionPrintOutputColorimetry"], ["sape", "SceneAppearanceEstimates"], ["scoe", "SceneColorimetryEstimates"], ["scrd", "ScreeningDesc"], ["scrn", "Screening"], ["targ", "CharTarget"], ["tech", "Technology"], ["vcgt", "VideoCardGamma"], ["view", "ViewingConditions"], ["vued", "ViewingCondDesc"], ["wtpt", "MediaWhitePoint"]]); - var St = { "4d2p": "Erdt Systems", AAMA: "Aamazing Technologies", ACER: "Acer", ACLT: "Acolyte Color Research", ACTI: "Actix Sytems", ADAR: "Adara Technology", ADBE: "Adobe", ADI: "ADI Systems", AGFA: "Agfa Graphics", ALMD: "Alps Electric", ALPS: "Alps Electric", ALWN: "Alwan Color Expertise", AMTI: "Amiable Technologies", AOC: "AOC International", APAG: "Apago", APPL: "Apple Computer", AST: "AST", "AT&T": "AT&T", BAEL: "BARBIERI electronic", BRCO: "Barco NV", BRKP: "Breakpoint", BROT: "Brother", BULL: "Bull", BUS: "Bus Computer Systems", "C-IT": "C-Itoh", CAMR: "Intel", CANO: "Canon", CARR: "Carroll Touch", CASI: "Casio", CBUS: "Colorbus PL", CEL: "Crossfield", CELx: "Crossfield", CGS: "CGS Publishing Technologies International", CHM: "Rochester Robotics", CIGL: "Colour Imaging Group, London", CITI: "Citizen", CL00: "Candela", CLIQ: "Color IQ", CMCO: "Chromaco", CMiX: "CHROMiX", COLO: "Colorgraphic Communications", COMP: "Compaq", COMp: "Compeq/Focus Technology", CONR: "Conrac Display Products", CORD: "Cordata Technologies", CPQ: "Compaq", CPRO: "ColorPro", CRN: "Cornerstone", CTX: "CTX International", CVIS: "ColorVision", CWC: "Fujitsu Laboratories", DARI: "Darius Technology", DATA: "Dataproducts", DCP: "Dry Creek Photo", DCRC: "Digital Contents Resource Center, Chung-Ang University", DELL: "Dell Computer", DIC: "Dainippon Ink and Chemicals", DICO: "Diconix", DIGI: "Digital", "DL&C": "Digital Light & Color", DPLG: "Doppelganger", DS: "Dainippon Screen", DSOL: "DOOSOL", DUPN: "DuPont", EPSO: "Epson", ESKO: "Esko-Graphics", ETRI: "Electronics and Telecommunications Research Institute", EVER: "Everex Systems", EXAC: "ExactCODE", Eizo: "Eizo", FALC: "Falco Data Products", FF: "Fuji Photo Film", FFEI: "FujiFilm Electronic Imaging", FNRD: "Fnord Software", FORA: "Fora", FORE: "Forefront Technology", FP: "Fujitsu", FPA: "WayTech Development", FUJI: "Fujitsu", FX: "Fuji Xerox", GCC: "GCC Technologies", GGSL: "Global Graphics Software", GMB: "Gretagmacbeth", GMG: "GMG", GOLD: "GoldStar Technology", GOOG: "Google", GPRT: "Giantprint", GTMB: "Gretagmacbeth", GVC: "WayTech Development", GW2K: "Sony", HCI: "HCI", HDM: "Heidelberger Druckmaschinen", HERM: "Hermes", HITA: "Hitachi America", HP: "Hewlett-Packard", HTC: "Hitachi", HiTi: "HiTi Digital", IBM: "IBM", IDNT: "Scitex", IEC: "Hewlett-Packard", IIYA: "Iiyama North America", IKEG: "Ikegami Electronics", IMAG: "Image Systems", IMI: "Ingram Micro", INTC: "Intel", INTL: "N/A (INTL)", INTR: "Intra Electronics", IOCO: "Iocomm International Technology", IPS: "InfoPrint Solutions Company", IRIS: "Scitex", ISL: "Ichikawa Soft Laboratory", ITNL: "N/A (ITNL)", IVM: "IVM", IWAT: "Iwatsu Electric", Idnt: "Scitex", Inca: "Inca Digital Printers", Iris: "Scitex", JPEG: "Joint Photographic Experts Group", JSFT: "Jetsoft Development", JVC: "JVC Information Products", KART: "Scitex", KFC: "KFC Computek Components", KLH: "KLH Computers", KMHD: "Konica Minolta", KNCA: "Konica", KODA: "Kodak", KYOC: "Kyocera", Kart: "Scitex", LCAG: "Leica", LCCD: "Leeds Colour", LDAK: "Left Dakota", LEAD: "Leading Technology", LEXM: "Lexmark International", LINK: "Link Computer", LINO: "Linotronic", LITE: "Lite-On", Leaf: "Leaf", Lino: "Linotronic", MAGC: "Mag Computronic", MAGI: "MAG Innovision", MANN: "Mannesmann", MICN: "Micron Technology", MICR: "Microtek", MICV: "Microvitec", MINO: "Minolta", MITS: "Mitsubishi Electronics America", MITs: "Mitsuba", MNLT: "Minolta", MODG: "Modgraph", MONI: "Monitronix", MONS: "Monaco Systems", MORS: "Morse Technology", MOTI: "Motive Systems", MSFT: "Microsoft", MUTO: "MUTOH INDUSTRIES", Mits: "Mitsubishi Electric", NANA: "NANAO", NEC: "NEC", NEXP: "NexPress Solutions", NISS: "Nissei Sangyo America", NKON: "Nikon", NONE: "none", OCE: "Oce Technologies", OCEC: "OceColor", OKI: "Oki", OKID: "Okidata", OKIP: "Okidata", OLIV: "Olivetti", OLYM: "Olympus", ONYX: "Onyx Graphics", OPTI: "Optiquest", PACK: "Packard Bell", PANA: "Matsushita Electric Industrial", PANT: "Pantone", PBN: "Packard Bell", PFU: "PFU", PHIL: "Philips Consumer Electronics", PNTX: "HOYA", POne: "Phase One A/S", PREM: "Premier Computer Innovations", PRIN: "Princeton Graphic Systems", PRIP: "Princeton Publishing Labs", QLUX: "Hong Kong", QMS: "QMS", QPCD: "QPcard AB", QUAD: "QuadLaser", QUME: "Qume", RADI: "Radius", RDDx: "Integrated Color Solutions", RDG: "Roland DG", REDM: "REDMS Group", RELI: "Relisys", RGMS: "Rolf Gierling Multitools", RICO: "Ricoh", RNLD: "Edmund Ronald", ROYA: "Royal", RPC: "Ricoh Printing Systems", RTL: "Royal Information Electronics", SAMP: "Sampo", SAMS: "Samsung", SANT: "Jaime Santana Pomares", SCIT: "Scitex", SCRN: "Dainippon Screen", SDP: "Scitex", SEC: "Samsung", SEIK: "Seiko Instruments", SEIk: "Seikosha", SGUY: "ScanGuy.com", SHAR: "Sharp Laboratories", SICC: "International Color Consortium", SONY: "Sony", SPCL: "SpectraCal", STAR: "Star", STC: "Sampo Technology", Scit: "Scitex", Sdp: "Scitex", Sony: "Sony", TALO: "Talon Technology", TAND: "Tandy", TATU: "Tatung", TAXA: "TAXAN America", TDS: "Tokyo Denshi Sekei", TECO: "TECO Information Systems", TEGR: "Tegra", TEKT: "Tektronix", TI: "Texas Instruments", TMKR: "TypeMaker", TOSB: "Toshiba", TOSH: "Toshiba", TOTK: "TOTOKU ELECTRIC", TRIU: "Triumph", TSBT: "Toshiba", TTX: "TTX Computer Products", TVM: "TVM Professional Monitor", TW: "TW Casper", ULSX: "Ulead Systems", UNIS: "Unisys", UTZF: "Utz Fehlau & Sohn", VARI: "Varityper", VIEW: "Viewsonic", VISL: "Visual communication", VIVO: "Vivo Mobile Communication", WANG: "Wang", WLBR: "Wilbur Imaging", WTG2: "Ware To Go", WYSE: "WYSE Technology", XERX: "Xerox", XRIT: "X-Rite", ZRAN: "Zoran", Zebr: "Zebra Technologies", appl: "Apple Computer", bICC: "basICColor", berg: "bergdesign", ceyd: "Integrated Color Solutions", clsp: "MacDermid ColorSpan", ds: "Dainippon Screen", dupn: "DuPont", ffei: "FujiFilm Electronic Imaging", flux: "FluxData", iris: "Scitex", kart: "Scitex", lcms: "Little CMS", lino: "Linotronic", none: "none", ob4d: "Erdt Systems", obic: "Medigraph", quby: "Qubyx Sarl", scit: "Scitex", scrn: "Dainippon Screen", sdp: "Scitex", siwi: "SIWI GRAFIKA", yxym: "YxyMaster" }; - var Ct = { scnr: "Scanner", mntr: "Monitor", prtr: "Printer", link: "Device Link", abst: "Abstract", spac: "Color Space Conversion Profile", nmcl: "Named Color", cenc: "ColorEncodingSpace profile", mid: "MultiplexIdentification profile", mlnk: "MultiplexLink profile", mvis: "MultiplexVisualization profile", nkpf: "Nikon Input Device Profile (NON-STANDARD!)" }; - U(B, "icc", [[4, St], [12, Ct], [40, Object.assign({}, St, Ct)], [48, St], [80, St], [64, { 0: "Perceptual", 1: "Relative Colorimetric", 2: "Saturation", 3: "Absolute Colorimetric" }], ["tech", { amd: "Active Matrix Display", crt: "Cathode Ray Tube Display", kpcd: "Photo CD", pmd: "Passive Matrix Display", dcam: "Digital Camera", dcpj: "Digital Cinema Projector", dmpc: "Digital Motion Picture Camera", dsub: "Dye Sublimation Printer", epho: "Electrophotographic Printer", esta: "Electrostatic Printer", flex: "Flexography", fprn: "Film Writer", fscn: "Film Scanner", grav: "Gravure", ijet: "Ink Jet Printer", imgs: "Photo Image Setter", mpfr: "Motion Picture Film Recorder", mpfs: "Motion Picture Film Scanner", offs: "Offset Lithography", pjtv: "Projection Television", rpho: "Photographic Paper Printer", rscn: "Reflective Scanner", silk: "Silkscreen", twax: "Thermal Wax Printer", vidc: "Video Camera", vidm: "Video Monitor" }]]); - var yt = class extends re2 { - static canHandle(e3, t2, i3) { - return 237 === e3.getUint8(t2 + 1) && "Photoshop" === e3.getString(t2 + 4, 9) && void 0 !== this.containsIptc8bim(e3, t2, i3); + function oe(e3) { + return e3 >= 224 && e3 <= 239; + } + function le(e3, t2, i3) { + for (let [n3, s2] of T) + if (s2.canHandle(e3, t2, i3)) + return n3; + } + var he = class extends se { + constructor(...e3) { + super(...e3), c(this, "appSegments", []), c(this, "jpegSegments", []), c(this, "unknownSegments", []); } - static headerLength(e3, t2, i3) { - let n3, s2 = this.containsIptc8bim(e3, t2, i3); - if (void 0 !== s2) - return n3 = e3.getUint8(t2 + s2 + 7), n3 % 2 != 0 && (n3 += 1), 0 === n3 && (n3 = 4), s2 + 8 + n3; + static canHandle(e3, t2) { + return 65496 === t2; } - static containsIptc8bim(e3, t2, i3) { - for (let n3 = 0; n3 < i3; n3++) - if (this.isIptcSegmentHead(e3, t2 + n3)) - return n3; + async parse() { + await this.findAppSegments(), await this.readSegments(this.appSegments), this.mergeMultiSegments(), this.createParsers(this.mergedAppSegments || this.appSegments); } - static isIptcSegmentHead(e3, t2) { - return 56 === e3.getUint8(t2) && 943868237 === e3.getUint32(t2) && 1028 === e3.getUint16(t2 + 4); + setupSegmentFinderArgs(e3) { + true === e3 ? (this.findAll = true, this.wanted = new Set(T.keyList())) : (e3 = void 0 === e3 ? T.keyList().filter((e4) => this.options[e4].enabled) : e3.filter((e4) => this.options[e4].enabled && T.has(e4)), this.findAll = false, this.remaining = new Set(e3), this.wanted = new Set(e3)), this.unfinishedMultiSegment = false; } - parse() { - let { raw: e3 } = this, t2 = this.chunk.byteLength - 1, i3 = false; - for (let n3 = 0; n3 < t2; n3++) - if (28 === this.chunk.getUint8(n3) && 2 === this.chunk.getUint8(n3 + 1)) { - i3 = true; - let t3 = this.chunk.getUint16(n3 + 3), s2 = this.chunk.getUint8(n3 + 2), r2 = this.chunk.getLatin1String(n3 + 5, t3); - e3.set(s2, this.pluralizeValue(e3.get(s2), r2)), n3 += 4 + t3; - } else if (i3) - break; - return this.translate(), this.output; + async findAppSegments(e3 = 0, t2) { + this.setupSegmentFinderArgs(t2); + let { file: i3, findAll: n3, wanted: s2, remaining: r2 } = this; + if (!n3 && this.file.chunked && (n3 = Array.from(s2).some((e4) => { + let t3 = T.get(e4), i4 = this.options[e4]; + return t3.multiSegment && i4.multiSegment; + }), n3 && await this.file.readWhole()), e3 = this.findAppSegmentsInRange(e3, i3.byteLength), !this.options.onlyTiff && i3.chunked) { + let t3 = false; + for (; r2.size > 0 && !t3 && (i3.canReadNextChunk || this.unfinishedMultiSegment); ) { + let { nextChunkOffset: n4 } = i3, s3 = this.appSegments.some((e4) => !this.file.available(e4.offset || e4.start, e4.length || e4.size)); + if (t3 = e3 > n4 && !s3 ? !await i3.readNextChunk(e3) : !await i3.readNextChunk(n4), void 0 === (e3 = this.findAppSegmentsInRange(e3, i3.byteLength))) + return; + } + } } - pluralizeValue(e3, t2) { - return void 0 !== e3 ? e3 instanceof Array ? (e3.push(t2), e3) : [e3, t2] : t2; + findAppSegmentsInRange(e3, t2) { + t2 -= 2; + let i3, n3, s2, r2, a2, o2, { file: l2, findAll: h2, wanted: u2, remaining: c2, options: f2 } = this; + for (; e3 < t2; e3++) + if (255 === l2.getUint8(e3)) { + if (i3 = l2.getUint8(e3 + 1), oe(i3)) { + if (n3 = l2.getUint16(e3 + 2), s2 = le(l2, e3, n3), s2 && u2.has(s2) && (r2 = T.get(s2), a2 = r2.findPosition(l2, e3), o2 = f2[s2], a2.type = s2, this.appSegments.push(a2), !h2 && (r2.multiSegment && o2.multiSegment ? (this.unfinishedMultiSegment = a2.chunkNumber < a2.chunkCount, this.unfinishedMultiSegment || c2.delete(s2)) : c2.delete(s2), 0 === c2.size))) + break; + f2.recordUnknownSegments && (a2 = re2.findPosition(l2, e3), a2.marker = i3, this.unknownSegments.push(a2)), e3 += n3 + 1; + } else if (ae(i3)) { + if (n3 = l2.getUint16(e3 + 2), 218 === i3 && false !== f2.stopAfterSos) + return; + f2.recordJpegSegments && this.jpegSegments.push({ offset: e3, length: n3, marker: i3 }), e3 += n3 + 1; + } + } + return e3; } - }; - c(yt, "type", "iptc"), c(yt, "translateValues", false), c(yt, "reviveValues", false), T.set("iptc", yt), U(E, "iptc", [[0, "ApplicationRecordVersion"], [3, "ObjectTypeReference"], [4, "ObjectAttributeReference"], [5, "ObjectName"], [7, "EditStatus"], [8, "EditorialUpdate"], [10, "Urgency"], [12, "SubjectReference"], [15, "Category"], [20, "SupplementalCategories"], [22, "FixtureIdentifier"], [25, "Keywords"], [26, "ContentLocationCode"], [27, "ContentLocationName"], [30, "ReleaseDate"], [35, "ReleaseTime"], [37, "ExpirationDate"], [38, "ExpirationTime"], [40, "SpecialInstructions"], [42, "ActionAdvised"], [45, "ReferenceService"], [47, "ReferenceDate"], [50, "ReferenceNumber"], [55, "DateCreated"], [60, "TimeCreated"], [62, "DigitalCreationDate"], [63, "DigitalCreationTime"], [65, "OriginatingProgram"], [70, "ProgramVersion"], [75, "ObjectCycle"], [80, "Byline"], [85, "BylineTitle"], [90, "City"], [92, "Sublocation"], [95, "State"], [100, "CountryCode"], [101, "Country"], [103, "OriginalTransmissionReference"], [105, "Headline"], [110, "Credit"], [115, "Source"], [116, "CopyrightNotice"], [118, "Contact"], [120, "Caption"], [121, "LocalCaption"], [122, "Writer"], [125, "RasterizedCaption"], [130, "ImageType"], [131, "ImageOrientation"], [135, "LanguageIdentifier"], [150, "AudioType"], [151, "AudioSamplingRate"], [152, "AudioSamplingResolution"], [153, "AudioDuration"], [154, "AudioOutcue"], [184, "JobID"], [185, "MasterDocumentID"], [186, "ShortDocumentID"], [187, "UniqueDocumentID"], [188, "OwnerID"], [200, "ObjectPreviewFileFormat"], [201, "ObjectPreviewFileVersion"], [202, "ObjectPreviewData"], [221, "Prefs"], [225, "ClassifyState"], [228, "SimilarityIndex"], [230, "DocumentNotes"], [231, "DocumentHistory"], [232, "ExifCameraInfo"], [255, "CatalogSets"]]), U(B, "iptc", [[10, { 0: "0 (reserved)", 1: "1 (most urgent)", 2: "2", 3: "3", 4: "4", 5: "5 (normal urgency)", 6: "6", 7: "7", 8: "8 (least urgent)", 9: "9 (user-defined priority)" }], [75, { a: "Morning", b: "Both Morning and Evening", p: "Evening" }], [131, { L: "Landscape", P: "Portrait", S: "Square" }]]); - var full_esm_default = tt; - - // modules/services/plane_photo.js - var dispatch6 = dispatch_default("viewerChanged"); - var _photo; - var _wrapper; - var imgZoom; - var _widthOverflow; - function zoomPan(d3_event) { - let t2 = d3_event.transform; - _photo.call(utilSetTransform, t2.x, t2.y, t2.k); - } - function zoomBeahvior() { - const { width: wrapperWidth, height: wrapperHeight } = _wrapper.node().getBoundingClientRect(); - const { naturalHeight, naturalWidth } = _photo.node(); - const intrinsicRatio = naturalWidth / naturalHeight; - _widthOverflow = wrapperHeight * intrinsicRatio - wrapperWidth; - return zoom_default2().extent([[0, 0], [wrapperWidth, wrapperHeight]]).translateExtent([[0, 0], [wrapperWidth + _widthOverflow, wrapperHeight]]).scaleExtent([1, 15]).on("zoom", zoomPan); - } - function loadImage(selection2, path) { - return new Promise((resolve) => { - selection2.attr("src", path); - selection2.on("load", () => { - resolve(selection2); - }); - }); - } - var plane_photo_default = { - init: async function(context, selection2) { - this.event = utilRebind(this, dispatch6, "on"); - _wrapper = selection2.append("div").attr("class", "photo-frame plane-frame").classed("hide", true); - _photo = _wrapper.append("img").attr("class", "plane-photo"); - context.ui().photoviewer.on("resize.plane", () => { - imgZoom = zoomBeahvior(); - _wrapper.call(imgZoom); - }); - await Promise.resolve(); - return this; - }, - showPhotoFrame: function(context) { - const isHidden = context.selectAll(".photo-frame.plane-frame.hide").size(); - if (isHidden) { - context.selectAll(".photo-frame:not(.plane-frame)").classed("hide", true); - context.selectAll(".photo-frame.plane-frame").classed("hide", false); - } - return this; - }, - hidePhotoFrame: function(context) { - context.select("photo-frame.plane-frame").classed("hide", false); - return this; - }, - selectPhoto: function(data, keepOrientation) { - dispatch6.call("viewerChanged"); - loadImage(_photo, ""); - loadImage(_photo, data.image_path).then(() => { - if (!keepOrientation) { - imgZoom = zoomBeahvior(); - _wrapper.call(imgZoom); - _wrapper.call(imgZoom.transform, identity2.translate(-_widthOverflow / 2, 0)); + mergeMultiSegments() { + if (!this.appSegments.some((e4) => e4.multiSegment)) + return; + let e3 = function(e4, t2) { + let i3, n3, s2, r2 = /* @__PURE__ */ new Map(); + for (let a2 = 0; a2 < e4.length; a2++) + i3 = e4[a2], n3 = i3[t2], r2.has(n3) ? s2 = r2.get(n3) : r2.set(n3, s2 = []), s2.push(i3); + return Array.from(r2); + }(this.appSegments, "type"); + this.mergedAppSegments = e3.map(([e4, t2]) => { + let i3 = T.get(e4, this.options); + if (i3.handleMultiSegments) { + return { type: e4, chunk: i3.handleMultiSegments(t2) }; } + return t2[0]; }); - return this; - }, - getYaw: function() { - return 0; + } + getSegment(e3) { + return this.appSegments.find((t2) => t2.type === e3); + } + async getOrFindSegment(e3) { + let t2 = this.getSegment(e3); + return void 0 === t2 && (await this.findAppSegments(0, [e3]), t2 = this.getSegment(e3)), t2; } }; - - // modules/svg/local_photos.js - var _initialized2 = false; - var _enabled2 = false; - var minViewfieldZoom = 16; - function svgLocalPhotos(projection2, context, dispatch14) { - const detected = utilDetect(); - let layer = select_default2(null); - let _fileList; - let _photos = []; - let _idAutoinc = 0; - let _photoFrame; - function init2() { - if (_initialized2) - return; - _enabled2 = true; - function over(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - d3_event.dataTransfer.dropEffect = "copy"; + c(he, "type", "jpeg"), w.set("jpeg", he); + var ue = [void 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4]; + var ce = class extends re2 { + parseHeader() { + var e3 = this.chunk.getUint16(); + 18761 === e3 ? this.le = true : 19789 === e3 && (this.le = false), this.chunk.le = this.le, this.headerParsed = true; + } + parseTags(e3, t2, i3 = /* @__PURE__ */ new Map()) { + let { pick: n3, skip: s2 } = this.options[t2]; + n3 = new Set(n3); + let r2 = n3.size > 0, a2 = 0 === s2.size, o2 = this.chunk.getUint16(e3); + e3 += 2; + for (let l2 = 0; l2 < o2; l2++) { + let o3 = this.chunk.getUint16(e3); + if (r2) { + if (n3.has(o3) && (i3.set(o3, this.parseTag(e3, o3, t2)), n3.delete(o3), 0 === n3.size)) + break; + } else + !a2 && s2.has(o3) || i3.set(o3, this.parseTag(e3, o3, t2)); + e3 += 12; } - context.container().attr("dropzone", "copy").on("drop.svgLocalPhotos", function(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - if (!detected.filedrop) - return; - drawPhotos.fileList(d3_event.dataTransfer.files, (loaded) => { - if (loaded.length > 0) { - drawPhotos.fitZoom(false); - } - }); - }).on("dragenter.svgLocalPhotos", over).on("dragexit.svgLocalPhotos", over).on("dragover.svgLocalPhotos", over); - _initialized2 = true; + return i3; } - function ensureViewerLoaded(context2) { - if (_photoFrame) { - return Promise.resolve(_photoFrame); + parseTag(e3, t2, i3) { + let { chunk: n3 } = this, s2 = n3.getUint16(e3 + 2), r2 = n3.getUint32(e3 + 4), a2 = ue[s2]; + if (a2 * r2 <= 4 ? e3 += 8 : e3 = n3.getUint32(e3 + 8), (s2 < 1 || s2 > 13) && g2("Invalid TIFF value type. block: ".concat(i3.toUpperCase(), ", tag: ").concat(t2.toString(16), ", type: ").concat(s2, ", offset ").concat(e3)), e3 > n3.byteLength && g2("Invalid TIFF value offset. block: ".concat(i3.toUpperCase(), ", tag: ").concat(t2.toString(16), ", type: ").concat(s2, ", offset ").concat(e3, " is outside of chunk size ").concat(n3.byteLength)), 1 === s2) + return n3.getUint8Array(e3, r2); + if (2 === s2) + return m(n3.getString(e3, r2)); + if (7 === s2) + return n3.getUint8Array(e3, r2); + if (1 === r2) + return this.parseTagValue(s2, e3); + { + let t3 = new (function(e4) { + switch (e4) { + case 1: + return Uint8Array; + case 3: + return Uint16Array; + case 4: + return Uint32Array; + case 5: + return Array; + case 6: + return Int8Array; + case 8: + return Int16Array; + case 9: + return Int32Array; + case 10: + return Array; + case 11: + return Float32Array; + case 12: + return Float64Array; + default: + return Array; + } + }(s2))(r2), i4 = a2; + for (let n4 = 0; n4 < r2; n4++) + t3[n4] = this.parseTagValue(s2, e3), e3 += i4; + return t3; } - const viewer = context2.container().select(".photoviewer").selectAll(".local-photos-wrapper").data([0]); - const viewerEnter = viewer.enter().append("div").attr("class", "photo-wrapper local-photos-wrapper").classed("hide", true); - viewerEnter.append("div").attr("class", "photo-attribution fillD"); - return plane_photo_default.init(context2, viewerEnter).then((planePhotoFrame) => { - _photoFrame = planePhotoFrame; - }); } - function click(d3_event, image, zoomTo) { - ensureViewerLoaded(context).then(() => { - const viewer = context.container().select(".photoviewer").datum(image).classed("hide", false); - const viewerWrap = viewer.select(".local-photos-wrapper").classed("hide", false); - const attribution = viewerWrap.selectAll(".photo-attribution").text(""); - if (image.name) { - attribution.append("span").classed("filename", true).text(image.name); - } - _photoFrame.selectPhoto({ image_path: "" }); - image.getSrc().then((src) => { - _photoFrame.selectPhoto({ image_path: src }).showPhotoFrame(viewerWrap); - setStyles(); - }); - }); - if (zoomTo) { - context.map().centerEase(image.loc); + parseTagValue(e3, t2) { + let { chunk: i3 } = this; + switch (e3) { + case 1: + return i3.getUint8(t2); + case 3: + return i3.getUint16(t2); + case 4: + return i3.getUint32(t2); + case 5: + return i3.getUint32(t2) / i3.getUint32(t2 + 4); + case 6: + return i3.getInt8(t2); + case 8: + return i3.getInt16(t2); + case 9: + return i3.getInt32(t2); + case 10: + return i3.getInt32(t2) / i3.getInt32(t2 + 4); + case 11: + return i3.getFloat(t2); + case 12: + return i3.getDouble(t2); + case 13: + return i3.getUint32(t2); + default: + g2("Invalid tiff type ".concat(e3)); } } - function transform2(d2) { - var svgpoint = projection2(d2.loc); - return "translate(" + svgpoint[0] + "," + svgpoint[1] + ")"; + }; + var fe = class extends ce { + static canHandle(e3, t2) { + return 225 === e3.getUint8(t2 + 1) && 1165519206 === e3.getUint32(t2 + 4) && 0 === e3.getUint16(t2 + 8); + } + async parse() { + this.parseHeader(); + let { options: e3 } = this; + return e3.ifd0.enabled && await this.parseIfd0Block(), e3.exif.enabled && await this.safeParse("parseExifBlock"), e3.gps.enabled && await this.safeParse("parseGpsBlock"), e3.interop.enabled && await this.safeParse("parseInteropBlock"), e3.ifd1.enabled && await this.safeParse("parseThumbnailBlock"), this.createOutput(); } - function setStyles(hovered) { - const viewer = context.container().select(".photoviewer"); - const selected = viewer.empty() ? void 0 : viewer.datum(); - context.container().selectAll(".layer-local-photos .viewfield-group").classed("hovered", (d2) => d2.id === (hovered == null ? void 0 : hovered.id)).classed("highlighted", (d2) => d2.id === (hovered == null ? void 0 : hovered.id) || d2.id === (selected == null ? void 0 : selected.id)).classed("currentView", (d2) => d2.id === (selected == null ? void 0 : selected.id)); + safeParse(e3) { + let t2 = this[e3](); + return void 0 !== t2.catch && (t2 = t2.catch(this.handleError)), t2; } - function display_markers(imageList) { - imageList = imageList.filter((image) => isArray_default(image.loc) && isNumber_default(image.loc[0]) && isNumber_default(image.loc[1])); - const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(imageList, function(d2) { - return d2.id; - }); - groups.exit().remove(); - const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", (d3_event, d2) => setStyles(d2)).on("mouseleave", () => setStyles(null)).on("click", click); - groupsEnter.append("g").attr("class", "viewfield-scale"); - const markers = groups.merge(groupsEnter).attr("transform", transform2).select(".viewfield-scale"); - markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - const showViewfields = context.map().zoom() >= minViewfieldZoom; - const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); - viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", function() { - var _a; - const d2 = this.parentNode.__data__; - return "rotate(".concat(Math.round((_a = d2.direction) != null ? _a : 0), ",0,0),scale(1.5,1.5),translate(-8,-13)"); - }).attr("d", "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z").style("visibility", function() { - const d2 = this.parentNode.__data__; - return isNumber_default(d2.direction) ? "visible" : "hidden"; - }); + findIfd0Offset() { + void 0 === this.ifd0Offset && (this.ifd0Offset = this.chunk.getUint32(4)); } - function drawPhotos(selection2) { - layer = selection2.selectAll(".layer-local-photos").data(_photos ? [0] : []); - layer.exit().remove(); - const layerEnter = layer.enter().append("g").attr("class", "layer-local-photos"); - layerEnter.append("g").attr("class", "markers"); - layer = layerEnter.merge(layer); - if (_photos && _photos.length !== 0) { - display_markers(_photos); + findIfd1Offset() { + if (void 0 === this.ifd1Offset) { + this.findIfd0Offset(); + let e3 = this.chunk.getUint16(this.ifd0Offset), t2 = this.ifd0Offset + 2 + 12 * e3; + this.ifd1Offset = this.chunk.getUint32(t2); } } - function readFileAsDataURL(file) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(reader.result); - reader.onerror = (error) => reject(error); - reader.readAsDataURL(file); - }); + parseBlock(e3, t2) { + let i3 = /* @__PURE__ */ new Map(); + return this[t2] = i3, this.parseTags(e3, t2, i3), i3; } - async function readmultifiles(files, callback) { - const loaded = []; - for (const file of files) { - try { - const exifData = await full_esm_default.parse(file); - const photo = { - id: _idAutoinc++, - name: file.name, - getSrc: () => readFileAsDataURL(file), - file, - loc: [exifData.longitude, exifData.latitude], - direction: exifData.GPSImgDirection - }; - loaded.push(photo); - const sameName = _photos.filter((i3) => i3.name === photo.name); - if (sameName.length === 0) { - _photos.push(photo); - } else { - const thisContent = await photo.getSrc(); - const sameNameContent = await Promise.allSettled(sameName.map((i3) => i3.getSrc())); - if (!sameNameContent.some((i3) => i3.value === thisContent)) { - _photos.push(photo); - } - } - } catch (err) { - } - } - if (typeof callback === "function") - callback(loaded); - dispatch14.call("change"); + async parseIfd0Block() { + if (this.ifd0) + return; + let { file: e3 } = this; + this.findIfd0Offset(), this.ifd0Offset < 8 && g2("Malformed EXIF data"), !e3.chunked && this.ifd0Offset > e3.byteLength && g2("IFD0 offset points to outside of file.\nthis.ifd0Offset: ".concat(this.ifd0Offset, ", file.byteLength: ").concat(e3.byteLength)), e3.tiff && await e3.ensureChunk(this.ifd0Offset, S(this.options)); + let t2 = this.parseBlock(this.ifd0Offset, "ifd0"); + return 0 !== t2.size ? (this.exifOffset = t2.get(34665), this.interopOffset = t2.get(40965), this.gpsOffset = t2.get(34853), this.xmp = t2.get(700), this.iptc = t2.get(33723), this.icc = t2.get(34675), this.options.sanitize && (t2.delete(34665), t2.delete(40965), t2.delete(34853), t2.delete(700), t2.delete(33723), t2.delete(34675)), t2) : void 0; } - drawPhotos.setFiles = function(fileList, callback) { - readmultifiles(Array.from(fileList), callback); - return this; - }; - drawPhotos.fileList = function(fileList, callback) { - if (!arguments.length) - return _fileList; - _fileList = fileList; - if (!fileList || !fileList.length) - return this; - drawPhotos.setFiles(_fileList, callback); - return this; - }; - drawPhotos.getPhotos = function() { - return _photos; - }; - drawPhotos.removePhoto = function(id2) { - _photos = _photos.filter((i3) => i3.id !== id2); - dispatch14.call("change"); - return _photos; - }; - drawPhotos.openPhoto = click; - drawPhotos.fitZoom = function(force) { - const coords = _photos.map((image) => image.loc).filter((l2) => isArray_default(l2) && isNumber_default(l2[0]) && isNumber_default(l2[1])); - if (coords.length === 0) + async parseExifBlock() { + if (this.exif) return; - const extent = coords.map((l2) => geoExtent(l2, l2)).reduce((a2, b2) => a2.extend(b2)); - const map2 = context.map(); - var viewport = map2.trimmedExtent().polygon(); - if (force !== false || !geoPolygonIntersectsPolygon(viewport, coords, true)) { - map2.centerZoom(extent.center(), Math.min(18, map2.trimmedExtentZoom(extent))); - } - }; - function showLayer() { - layer.style("display", "block"); - layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { - dispatch14.call("change"); - }); + if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.exifOffset) + return; + this.file.tiff && await this.file.ensureChunk(this.exifOffset, S(this.options)); + let e3 = this.parseBlock(this.exifOffset, "exif"); + return this.interopOffset || (this.interopOffset = e3.get(40965)), this.makerNote = e3.get(37500), this.userComment = e3.get(37510), this.options.sanitize && (e3.delete(40965), e3.delete(37500), e3.delete(37510)), this.unpack(e3, 41728), this.unpack(e3, 41729), e3; } - function hideLayer() { - layer.transition().duration(250).style("opacity", 0).on("end", () => { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); - }); + unpack(e3, t2) { + let i3 = e3.get(t2); + i3 && 1 === i3.length && e3.set(t2, i3[0]); } - drawPhotos.enabled = function(val) { - if (!arguments.length) - return _enabled2; - _enabled2 = val; - if (_enabled2) { - showLayer(); - } else { - hideLayer(); - } - dispatch14.call("change"); - return this; - }; - drawPhotos.hasData = function() { - return isArray_default(_photos) && _photos.length > 0; - }; - init2(); - return drawPhotos; - } - - // modules/svg/improveOSM.js - var _layerEnabled2 = false; - var _qaService2; - function svgImproveOSM(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); - const minZoom4 = 12; - let touchLayer = select_default2(null); - let drawLayer = select_default2(null); - let layerVisible = false; - function markerPath(selection2, klass) { - selection2.attr("class", klass).attr("transform", "translate(-10, -28)").attr("points", "16,3 4,3 1,6 1,17 4,20 7,20 10,27 13,20 16,20 19,17.033 19,6"); + async parseGpsBlock() { + if (this.gps) + return; + if (this.ifd0 || await this.parseIfd0Block(), void 0 === this.gpsOffset) + return; + let e3 = this.parseBlock(this.gpsOffset, "gps"); + return e3 && e3.has(2) && e3.has(4) && (e3.set("latitude", de(...e3.get(2), e3.get(1))), e3.set("longitude", de(...e3.get(4), e3.get(3)))), e3; } - function getService() { - if (services.improveOSM && !_qaService2) { - _qaService2 = services.improveOSM; - _qaService2.on("loaded", throttledRedraw); - } else if (!services.improveOSM && _qaService2) { - _qaService2 = null; - } - return _qaService2; + async parseInteropBlock() { + if (!this.interop && (this.ifd0 || await this.parseIfd0Block(), void 0 !== this.interopOffset || this.exif || await this.parseExifBlock(), void 0 !== this.interopOffset)) + return this.parseBlock(this.interopOffset, "interop"); } - function editOn() { - if (!layerVisible) { - layerVisible = true; - drawLayer.style("display", "block"); - } + async parseThumbnailBlock(e3 = false) { + if (!this.ifd1 && !this.ifd1Parsed && (!this.options.mergeOutput || e3)) + return this.findIfd1Offset(), this.ifd1Offset > 0 && (this.parseBlock(this.ifd1Offset, "ifd1"), this.ifd1Parsed = true), this.ifd1; } - function editOff() { - if (layerVisible) { - layerVisible = false; - drawLayer.style("display", "none"); - drawLayer.selectAll(".qaItem.improveOSM").remove(); - touchLayer.selectAll(".qaItem.improveOSM").remove(); - } + async extractThumbnail() { + if (this.headerParsed || this.parseHeader(), this.ifd1Parsed || await this.parseThumbnailBlock(true), void 0 === this.ifd1) + return; + let e3 = this.ifd1.get(513), t2 = this.ifd1.get(514); + return this.chunk.getUint8Array(e3, t2); } - function layerOn() { - editOn(); - drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", () => dispatch14.call("change")); + get image() { + return this.ifd0; } - function layerOff() { - throttledRedraw.cancel(); - drawLayer.interrupt(); - touchLayer.selectAll(".qaItem.improveOSM").remove(); - drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", () => { - editOff(); - dispatch14.call("change"); - }); + get thumbnail() { + return this.ifd1; } - function updateMarkers() { - if (!layerVisible || !_layerEnabled2) - return; - const service = getService(); - const selectedID = context.selectedErrorID(); - const data = service ? service.getItems(projection2) : []; - const getTransform = svgPointTransform(projection2); - const markers = drawLayer.selectAll(".qaItem.improveOSM").data(data, (d2) => d2.id); - markers.exit().remove(); - const markersEnter = markers.enter().append("g").attr("class", (d2) => "qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.itemType)); - markersEnter.append("polygon").call(markerPath, "shadow"); - markersEnter.append("ellipse").attr("cx", 0).attr("cy", 0).attr("rx", 4.5).attr("ry", 2).attr("class", "stroke"); - markersEnter.append("polygon").attr("fill", "currentColor").call(markerPath, "qaItem-fill"); - markersEnter.append("use").attr("class", "icon-annotation").attr("transform", "translate(-6, -22)").attr("width", "12px").attr("height", "12px").attr("xlink:href", (d2) => d2.icon ? "#" + d2.icon : ""); - markers.merge(markersEnter).sort(sortY).classed("selected", (d2) => d2.id === selectedID).attr("transform", getTransform); - if (touchLayer.empty()) - return; - const fillClass = context.getDebug("target") ? "pink " : "nocolor "; - const targets = touchLayer.selectAll(".qaItem.improveOSM").data(data, (d2) => d2.id); - targets.exit().remove(); - targets.enter().append("rect").attr("width", "20px").attr("height", "30px").attr("x", "-10px").attr("y", "-28px").merge(targets).sort(sortY).attr("class", (d2) => "qaItem ".concat(d2.service, " target ").concat(fillClass, " itemId-").concat(d2.id)).attr("transform", getTransform); - function sortY(a2, b2) { - return a2.id === selectedID ? 1 : b2.id === selectedID ? -1 : b2.loc[1] - a2.loc[1]; - } + createOutput() { + let e3, t2, i3, n3 = {}; + for (t2 of H) + if (e3 = this[t2], !p(e3)) + if (i3 = this.canTranslate ? this.translateBlock(e3, t2) : Object.fromEntries(e3), this.options.mergeOutput) { + if ("ifd1" === t2) + continue; + Object.assign(n3, i3); + } else + n3[t2] = i3; + return this.makerNote && (n3.makerNote = this.makerNote), this.userComment && (n3.userComment = this.userComment), n3; } - function drawImproveOSM(selection2) { - const service = getService(); - const surface = context.surface(); - if (surface && !surface.empty()) { - touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); - } - drawLayer = selection2.selectAll(".layer-improveOSM").data(service ? [0] : []); - drawLayer.exit().remove(); - drawLayer = drawLayer.enter().append("g").attr("class", "layer-improveOSM").style("display", _layerEnabled2 ? "block" : "none").merge(drawLayer); - if (_layerEnabled2) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - service.loadIssues(projection2); - updateMarkers(); - } else { - editOff(); - } + assignToOutput(e3, t2) { + if (this.globalOptions.mergeOutput) + Object.assign(e3, t2); + else + for (let [i3, n3] of Object.entries(t2)) + this.assignObjectToOutput(e3, i3, n3); + } + }; + function de(e3, t2, i3, n3) { + var s2 = e3 + t2 / 60 + i3 / 3600; + return "S" !== n3 && "W" !== n3 || (s2 *= -1), s2; + } + c(fe, "type", "tiff"), c(fe, "headerLength", 10), T.set("tiff", fe); + var pe = Object.freeze({ __proto__: null, default: ne, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q, parse: ie }); + var ge = { ifd0: false, ifd1: false, exif: false, gps: false, interop: false, sanitize: false, reviveValues: true, translateKeys: false, translateValues: false, mergeOutput: false }; + var me = Object.assign({}, ge, { firstChunkSize: 4e4, gps: [1, 2, 3, 4] }); + async function Se(e3) { + let t2 = new te(me); + await t2.read(e3); + let i3 = await t2.parse(); + if (i3 && i3.gps) { + let { latitude: e4, longitude: t3 } = i3.gps; + return { latitude: e4, longitude: t3 }; + } + } + var Ce = Object.assign({}, ge, { tiff: false, ifd1: true, mergeOutput: false }); + async function ye(e3) { + let t2 = new te(Ce); + await t2.read(e3); + let i3 = await t2.extractThumbnail(); + return i3 && a ? s.from(i3) : i3; + } + async function be(e3) { + let t2 = await this.thumbnail(e3); + if (void 0 !== t2) { + let e4 = new Blob([t2]); + return URL.createObjectURL(e4); + } + } + var Ie = Object.assign({}, ge, { firstChunkSize: 4e4, ifd0: [274] }); + async function Pe(e3) { + let t2 = new te(Ie); + await t2.read(e3); + let i3 = await t2.parse(); + if (i3 && i3.ifd0) + return i3.ifd0[274]; + } + var ke = Object.freeze({ 1: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 0, rad: 0 }, 2: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 0, rad: 0 }, 3: { dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 4: { dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180 }, 5: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 90, rad: 90 * Math.PI / 180 }, 6: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 90, rad: 90 * Math.PI / 180 }, 7: { dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 270, rad: 270 * Math.PI / 180 }, 8: { dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 270, rad: 270 * Math.PI / 180 } }); + var we = true; + var Te = true; + if ("object" == typeof navigator) { + let e3 = navigator.userAgent; + if (e3.includes("iPad") || e3.includes("iPhone")) { + let t2 = e3.match(/OS (\d+)_(\d+)/); + if (t2) { + let [, e4, i3] = t2, n3 = Number(e4) + 0.1 * Number(i3); + we = n3 < 13.4, Te = false; } + } else if (e3.includes("OS X 10")) { + let [, t2] = e3.match(/OS X 10[_.](\d+)/); + we = Te = Number(t2) < 15; } - drawImproveOSM.enabled = function(val) { - if (!arguments.length) - return _layerEnabled2; - _layerEnabled2 = val; - if (_layerEnabled2) { - layerOn(); + if (e3.includes("Chrome/")) { + let [, t2] = e3.match(/Chrome\/(\d+)/); + we = Te = Number(t2) < 81; + } else if (e3.includes("Firefox/")) { + let [, t2] = e3.match(/Firefox\/(\d+)/); + we = Te = Number(t2) < 77; + } + } + async function Ae(e3) { + let t2 = await Pe(e3); + return Object.assign({ canvas: we, css: Te }, ke[t2]); + } + var De = class extends I { + constructor(...e3) { + super(...e3), c(this, "ranges", new Oe()), 0 !== this.byteLength && this.ranges.add(0, this.byteLength); + } + _tryExtend(e3, t2, i3) { + if (0 === e3 && 0 === this.byteLength && i3) { + let e4 = new DataView(i3.buffer || i3, i3.byteOffset, i3.byteLength); + this._swapDataView(e4); } else { - layerOff(); - if (context.selectedErrorID()) { - context.enter(modeBrowse(context)); + let i4 = e3 + t2; + if (i4 > this.byteLength) { + let { dataView: e4 } = this._extend(i4); + this._swapDataView(e4); } } - dispatch14.call("change"); - return this; - }; - drawImproveOSM.supported = () => !!getService(); - return drawImproveOSM; - } - - // modules/svg/osmose.js - var _layerEnabled3 = false; - var _qaService3; - function svgOsmose(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); - const minZoom4 = 12; - let touchLayer = select_default2(null); - let drawLayer = select_default2(null); - let layerVisible = false; - function markerPath(selection2, klass) { - selection2.attr("class", klass).attr("transform", "translate(-10, -28)").attr("points", "16,3 4,3 1,6 1,17 4,20 7,20 10,27 13,20 16,20 19,17.033 19,6"); } - function getService() { - if (services.osmose && !_qaService3) { - _qaService3 = services.osmose; - _qaService3.on("loaded", throttledRedraw); - } else if (!services.osmose && _qaService3) { - _qaService3 = null; - } - return _qaService3; + _extend(e3) { + let t2; + t2 = a ? s.allocUnsafe(e3) : new Uint8Array(e3); + let i3 = new DataView(t2.buffer, t2.byteOffset, t2.byteLength); + return t2.set(new Uint8Array(this.buffer, this.byteOffset, this.byteLength), 0), { uintView: t2, dataView: i3 }; } - function editOn() { - if (!layerVisible) { - layerVisible = true; - drawLayer.style("display", "block"); - } + subarray(e3, t2, i3 = false) { + return t2 = t2 || this._lengthToEnd(e3), i3 && this._tryExtend(e3, t2), this.ranges.add(e3, t2), super.subarray(e3, t2); } - function editOff() { - if (layerVisible) { - layerVisible = false; - drawLayer.style("display", "none"); - drawLayer.selectAll(".qaItem.osmose").remove(); - touchLayer.selectAll(".qaItem.osmose").remove(); - } + set(e3, t2, i3 = false) { + i3 && this._tryExtend(t2, e3.byteLength, e3); + let n3 = super.set(e3, t2); + return this.ranges.add(t2, n3.byteLength), n3; } - function layerOn() { - editOn(); - drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", () => dispatch14.call("change")); + async ensureChunk(e3, t2) { + this.chunked && (this.ranges.available(e3, t2) || await this.readChunk(e3, t2)); } - function layerOff() { - throttledRedraw.cancel(); - drawLayer.interrupt(); - touchLayer.selectAll(".qaItem.osmose").remove(); - drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", () => { - editOff(); - dispatch14.call("change"); - }); + available(e3, t2) { + return this.ranges.available(e3, t2); } - function updateMarkers() { - if (!layerVisible || !_layerEnabled3) - return; - const service = getService(); - const selectedID = context.selectedErrorID(); - const data = service ? service.getItems(projection2) : []; - const getTransform = svgPointTransform(projection2); - const markers = drawLayer.selectAll(".qaItem.osmose").data(data, (d2) => d2.id); - markers.exit().remove(); - const markersEnter = markers.enter().append("g").attr("class", (d2) => "qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.itemType)); - markersEnter.append("polygon").call(markerPath, "shadow"); - markersEnter.append("ellipse").attr("cx", 0).attr("cy", 0).attr("rx", 4.5).attr("ry", 2).attr("class", "stroke"); - markersEnter.append("polygon").attr("fill", (d2) => service.getColor(d2.item)).call(markerPath, "qaItem-fill"); - markersEnter.append("use").attr("class", "icon-annotation").attr("transform", "translate(-6, -22)").attr("width", "12px").attr("height", "12px").attr("xlink:href", (d2) => d2.icon ? "#" + d2.icon : ""); - markers.merge(markersEnter).sort(sortY).classed("selected", (d2) => d2.id === selectedID).attr("transform", getTransform); - if (touchLayer.empty()) - return; - const fillClass = context.getDebug("target") ? "pink" : "nocolor"; - const targets = touchLayer.selectAll(".qaItem.osmose").data(data, (d2) => d2.id); - targets.exit().remove(); - targets.enter().append("rect").attr("width", "20px").attr("height", "30px").attr("x", "-10px").attr("y", "-28px").merge(targets).sort(sortY).attr("class", (d2) => "qaItem ".concat(d2.service, " target ").concat(fillClass, " itemId-").concat(d2.id)).attr("transform", getTransform); - function sortY(a2, b2) { - return a2.id === selectedID ? 1 : b2.id === selectedID ? -1 : b2.loc[1] - a2.loc[1]; - } + }; + var Oe = class { + constructor() { + c(this, "list", []); } - function drawOsmose(selection2) { - const service = getService(); - const surface = context.surface(); - if (surface && !surface.empty()) { - touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); - } - drawLayer = selection2.selectAll(".layer-osmose").data(service ? [0] : []); - drawLayer.exit().remove(); - drawLayer = drawLayer.enter().append("g").attr("class", "layer-osmose").style("display", _layerEnabled3 ? "block" : "none").merge(drawLayer); - if (_layerEnabled3) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - service.loadIssues(projection2); - updateMarkers(); - } else { - editOff(); - } - } + get length() { + return this.list.length; } - drawOsmose.enabled = function(val) { - if (!arguments.length) - return _layerEnabled3; - _layerEnabled3 = val; - if (_layerEnabled3) { - getService().loadStrings().then(layerOn).catch((err) => { - console.log(err); - }); - } else { - layerOff(); - if (context.selectedErrorID()) { - context.enter(modeBrowse(context)); - } - } - dispatch14.call("change"); - return this; - }; - drawOsmose.supported = () => !!getService(); - return drawOsmose; + add(e3, t2, i3 = 0) { + let n3 = e3 + t2, s2 = this.list.filter((t3) => xe(e3, t3.offset, n3) || xe(e3, t3.end, n3)); + if (s2.length > 0) { + e3 = Math.min(e3, ...s2.map((e4) => e4.offset)), n3 = Math.max(n3, ...s2.map((e4) => e4.end)), t2 = n3 - e3; + let i4 = s2.shift(); + i4.offset = e3, i4.length = t2, i4.end = n3, this.list = this.list.filter((e4) => !s2.includes(e4)); + } else + this.list.push({ offset: e3, length: t2, end: n3 }); + } + available(e3, t2) { + let i3 = e3 + t2; + return this.list.some((t3) => t3.offset <= e3 && i3 <= t3.end); + } + }; + function xe(e3, t2, i3) { + return e3 <= t2 && t2 <= i3; } - - // modules/svg/streetside.js - function svgStreetside(projection2, context, dispatch14) { - var throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - var minZoom4 = 14; - var minMarkerZoom = 16; - var minViewfieldZoom2 = 18; - var layer = select_default2(null); - var _viewerYaw = 0; - var _selectedSequence = null; - var _streetside; - function init2() { - if (svgStreetside.initialized) - return; - svgStreetside.enabled = false; - svgStreetside.initialized = true; + var ve = class extends De { + constructor(e3, t2) { + super(0), c(this, "chunksRead", 0), this.input = e3, this.options = t2; } - function getService() { - if (services.streetside && !_streetside) { - _streetside = services.streetside; - _streetside.event.on("viewerChanged.svgStreetside", viewerChanged).on("loadedImages.svgStreetside", throttledRedraw); - } else if (!services.streetside && _streetside) { - _streetside = null; - } - return _streetside; + async readWhole() { + this.chunked = false, await this.readChunk(this.nextChunkOffset); } - function showLayer() { - var service = getService(); - if (!service) - return; - editOn(); - layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { - dispatch14.call("change"); - }); + async readChunked() { + this.chunked = true, await this.readChunk(0, this.options.firstChunkSize); } - function hideLayer() { - throttledRedraw.cancel(); - layer.transition().duration(250).style("opacity", 0).on("end", editOff); + async readNextChunk(e3 = this.nextChunkOffset) { + if (this.fullyRead) + return this.chunksRead++, false; + let t2 = this.options.chunkSize, i3 = await this.readChunk(e3, t2); + return !!i3 && i3.byteLength === t2; } - function editOn() { - layer.style("display", "block"); + async readChunk(e3, t2) { + if (this.chunksRead++, 0 !== (t2 = this.safeWrapAddress(e3, t2))) + return this._readChunk(e3, t2); } - function editOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); + safeWrapAddress(e3, t2) { + return void 0 !== this.size && e3 + t2 > this.size ? Math.max(0, this.size - e3) : t2; } - function click(d3_event, d2) { - var service = getService(); - if (!service) - return; - if (d2.sequenceKey !== _selectedSequence) { - _viewerYaw = 0; - } - _selectedSequence = d2.sequenceKey; - service.ensureViewerLoaded(context).then(function() { - service.selectImage(context, d2.key).yaw(_viewerYaw).showViewer(context); - }); - context.map().centerEase(d2.loc); + get nextChunkOffset() { + if (0 !== this.ranges.list.length) + return this.ranges.list[0].length; } - function mouseover(d3_event, d2) { - var service = getService(); - if (service) - service.setStyles(context, d2); + get canReadNextChunk() { + return this.chunksRead < this.options.chunkLimit; } - function mouseout() { - var service = getService(); - if (service) - service.setStyles(context, null); + get fullyRead() { + return void 0 !== this.size && this.nextChunkOffset === this.size; } - function transform2(d2) { - var t2 = svgPointTransform(projection2)(d2); - var rot = d2.ca + _viewerYaw; - if (rot) { - t2 += " rotate(" + Math.floor(rot) + ",0,0)"; + read() { + return this.options.chunked ? this.readChunked() : this.readWhole(); + } + close() { + } + }; + A.set("blob", class extends ve { + async readWhole() { + this.chunked = false; + let e3 = await R(this.input); + this._swapArrayBuffer(e3); + } + readChunked() { + return this.chunked = true, this.size = this.input.size, super.readChunked(); + } + async _readChunk(e3, t2) { + let i3 = t2 ? e3 + t2 : void 0, n3 = this.input.slice(e3, i3), s2 = await R(n3); + return this.set(s2, e3, true); + } + }); + var Me = Object.freeze({ __proto__: null, default: pe, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q, parse: ie, gpsOnlyOptions: me, gps: Se, thumbnailOnlyOptions: Ce, thumbnail: ye, thumbnailUrl: be, orientationOnlyOptions: Ie, orientation: Pe, rotations: ke, get rotateCanvas() { + return we; + }, get rotateCss() { + return Te; + }, rotation: Ae }); + A.set("url", class extends ve { + async readWhole() { + this.chunked = false; + let e3 = await M(this.input); + e3 instanceof ArrayBuffer ? this._swapArrayBuffer(e3) : e3 instanceof Uint8Array && this._swapBuffer(e3); + } + async _readChunk(e3, t2) { + let i3 = t2 ? e3 + t2 - 1 : void 0, n3 = this.options.httpHeaders || {}; + (e3 || i3) && (n3.range = "bytes=".concat([e3, i3].join("-"))); + let s2 = await h(this.input, { headers: n3 }), r2 = await s2.arrayBuffer(), a2 = r2.byteLength; + if (416 !== s2.status) + return a2 !== t2 && (this.size = e3 + a2), this.set(r2, e3, true); + } + }); + I.prototype.getUint64 = function(e3) { + let t2 = this.getUint32(e3), i3 = this.getUint32(e3 + 4); + return t2 < 1048575 ? t2 << 32 | i3 : void 0 !== typeof r ? (console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."), r(t2) << r(32) | r(i3)) : void g2("Trying to read 64b value but JS can only handle 53b numbers."); + }; + var Re = class extends se { + parseBoxes(e3 = 0) { + let t2 = []; + for (; e3 < this.file.byteLength - 4; ) { + let i3 = this.parseBoxHead(e3); + if (t2.push(i3), 0 === i3.length) + break; + e3 += i3.length; } return t2; } - function viewerChanged() { - var service = getService(); - if (!service) + parseSubBoxes(e3) { + e3.boxes = this.parseBoxes(e3.start); + } + findBox(e3, t2) { + return void 0 === e3.boxes && this.parseSubBoxes(e3), e3.boxes.find((e4) => e4.kind === t2); + } + parseBoxHead(e3) { + let t2 = this.file.getUint32(e3), i3 = this.file.getString(e3 + 4, 4), n3 = e3 + 8; + return 1 === t2 && (t2 = this.file.getUint64(e3 + 8), n3 += 8), { offset: e3, length: t2, kind: i3, start: n3 }; + } + parseBoxFullHead(e3) { + if (void 0 !== e3.version) return; - var viewer = service.viewer(); - if (!viewer) + let t2 = this.file.getUint32(e3.start); + e3.version = t2 >> 24, e3.start += 4; + } + }; + var Le = class extends Re { + static canHandle(e3, t2) { + if (0 !== t2) + return false; + let i3 = e3.getUint16(2); + if (i3 > 50) + return false; + let n3 = 16, s2 = []; + for (; n3 < i3; ) + s2.push(e3.getString(n3, 4)), n3 += 4; + return s2.includes(this.type); + } + async parse() { + let e3 = this.file.getUint32(0), t2 = this.parseBoxHead(e3); + for (; "meta" !== t2.kind; ) + e3 += t2.length, await this.file.ensureChunk(e3, 16), t2 = this.parseBoxHead(e3); + await this.file.ensureChunk(t2.offset, t2.length), this.parseBoxFullHead(t2), this.parseSubBoxes(t2), this.options.icc.enabled && await this.findIcc(t2), this.options.tiff.enabled && await this.findExif(t2); + } + async registerSegment(e3, t2, i3) { + await this.file.ensureChunk(t2, i3); + let n3 = this.file.subarray(t2, i3); + this.createParser(e3, n3); + } + async findIcc(e3) { + let t2 = this.findBox(e3, "iprp"); + if (void 0 === t2) return; - _viewerYaw = viewer.getYaw(); - if (context.map().isTransformed()) + let i3 = this.findBox(t2, "ipco"); + if (void 0 === i3) return; - layer.selectAll(".viewfield-group.currentView").attr("transform", transform2); + let n3 = this.findBox(i3, "colr"); + void 0 !== n3 && await this.registerSegment("icc", n3.offset + 12, n3.length); } - function filterBubbles(bubbles) { - var fromDate = context.photos().fromDate(); - var toDate = context.photos().toDate(); - var usernames = context.photos().usernames(); - if (fromDate) { - var fromTimestamp = new Date(fromDate).getTime(); - bubbles = bubbles.filter(function(bubble) { - return new Date(bubble.captured_at).getTime() >= fromTimestamp; - }); - } - if (toDate) { - var toTimestamp = new Date(toDate).getTime(); - bubbles = bubbles.filter(function(bubble) { - return new Date(bubble.captured_at).getTime() <= toTimestamp; - }); - } - if (usernames) { - bubbles = bubbles.filter(function(bubble) { - return usernames.indexOf(bubble.captured_by) !== -1; - }); - } - return bubbles; + async findExif(e3) { + let t2 = this.findBox(e3, "iinf"); + if (void 0 === t2) + return; + let i3 = this.findBox(e3, "iloc"); + if (void 0 === i3) + return; + let n3 = this.findExifLocIdInIinf(t2), s2 = this.findExtentInIloc(i3, n3); + if (void 0 === s2) + return; + let [r2, a2] = s2; + await this.file.ensureChunk(r2, a2); + let o2 = 4 + this.file.getUint32(r2); + r2 += o2, a2 -= o2, await this.registerSegment("tiff", r2, a2); } - function filterSequences(sequences) { - var fromDate = context.photos().fromDate(); - var toDate = context.photos().toDate(); - var usernames = context.photos().usernames(); - if (fromDate) { - var fromTimestamp = new Date(fromDate).getTime(); - sequences = sequences.filter(function(sequences2) { - return new Date(sequences2.properties.captured_at).getTime() >= fromTimestamp; - }); - } - if (toDate) { - var toTimestamp = new Date(toDate).getTime(); - sequences = sequences.filter(function(sequences2) { - return new Date(sequences2.properties.captured_at).getTime() <= toTimestamp; - }); - } - if (usernames) { - sequences = sequences.filter(function(sequences2) { - return usernames.indexOf(sequences2.properties.captured_by) !== -1; - }); + findExifLocIdInIinf(e3) { + this.parseBoxFullHead(e3); + let t2, i3, n3, s2, r2 = e3.start, a2 = this.file.getUint16(r2); + for (r2 += 2; a2--; ) { + if (t2 = this.parseBoxHead(r2), this.parseBoxFullHead(t2), i3 = t2.start, t2.version >= 2 && (n3 = 3 === t2.version ? 4 : 2, s2 = this.file.getString(i3 + n3 + 2, 4), "Exif" === s2)) + return this.file.getUintBytes(i3, n3); + r2 += t2.length; } - return sequences; } - function update() { - var viewer = context.container().select(".photoviewer"); - var selected = viewer.empty() ? void 0 : viewer.datum(); - var z2 = ~~context.map().zoom(); - var showMarkers = z2 >= minMarkerZoom; - var showViewfields = z2 >= minViewfieldZoom2; - var service = getService(); - var sequences = []; - var bubbles = []; - if (context.photos().showsPanoramic()) { - sequences = service ? service.sequences(projection2) : []; - bubbles = service && showMarkers ? service.bubbles(projection2) : []; - sequences = filterSequences(sequences); - bubbles = filterBubbles(bubbles); - } - var traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { - return d2.properties.key; - }); - traces.exit().remove(); - traces = traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); - var groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(bubbles, function(d2) { - return d2.key + (d2.sequenceKey ? "v1" : "v0"); - }); - groups.exit().remove(); - var groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); - groupsEnter.append("g").attr("class", "viewfield-scale"); - var markers = groups.merge(groupsEnter).sort(function(a2, b2) { - return a2 === selected ? 1 : b2 === selected ? -1 : b2.loc[1] - a2.loc[1]; - }).attr("transform", transform2).select(".viewfield-scale"); - markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - var viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); - viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); - function viewfieldPath() { - var d2 = this.parentNode.__data__; - if (d2.pano) { - return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; - } else { - return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; - } - } + get8bits(e3) { + let t2 = this.file.getUint8(e3); + return [t2 >> 4, 15 & t2]; } - function drawImages(selection2) { - var enabled = svgStreetside.enabled; - var service = getService(); - layer = selection2.selectAll(".layer-streetside-images").data(service ? [0] : []); - layer.exit().remove(); - var layerEnter = layer.enter().append("g").attr("class", "layer-streetside-images").style("display", enabled ? "block" : "none"); - layerEnter.append("g").attr("class", "sequences"); - layerEnter.append("g").attr("class", "markers"); - layer = layerEnter.merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadBubbles(projection2); - } else { - editOff(); - } + findExtentInIloc(e3, t2) { + this.parseBoxFullHead(e3); + let i3 = e3.start, [n3, s2] = this.get8bits(i3++), [r2, a2] = this.get8bits(i3++), o2 = 2 === e3.version ? 4 : 2, l2 = 1 === e3.version || 2 === e3.version ? 2 : 0, h2 = a2 + n3 + s2, u2 = 2 === e3.version ? 4 : 2, c2 = this.file.getUintBytes(i3, u2); + for (i3 += u2; c2--; ) { + let e4 = this.file.getUintBytes(i3, o2); + i3 += o2 + l2 + 2 + r2; + let u3 = this.file.getUint16(i3); + if (i3 += 2, e4 === t2) + return u3 > 1 && console.warn("ILOC box has more than one extent but we're only processing one\nPlease create an issue at https://github.com/MikeKovarik/exifr with this file"), [this.file.getUintBytes(i3 + a2, n3), this.file.getUintBytes(i3 + a2 + n3, s2)]; + i3 += u3 * h2; } } - drawImages.enabled = function(_2) { - if (!arguments.length) - return svgStreetside.enabled; - svgStreetside.enabled = _2; - if (svgStreetside.enabled) { - showLayer(); - context.photos().on("change.streetside", update); - } else { - hideLayer(); - context.photos().on("change.streetside", null); - } - dispatch14.call("change"); - return this; - }; - drawImages.supported = function() { - return !!getService(); - }; - drawImages.rendered = function(zoom) { - return zoom >= minZoom4; - }; - init2(); - return drawImages; + }; + var Ue = class extends Le { + }; + c(Ue, "type", "heic"); + var Fe = class extends Le { + }; + c(Fe, "type", "avif"), w.set("heic", Ue), w.set("avif", Fe), U(E, ["ifd0", "ifd1"], [[256, "ImageWidth"], [257, "ImageHeight"], [258, "BitsPerSample"], [259, "Compression"], [262, "PhotometricInterpretation"], [270, "ImageDescription"], [271, "Make"], [272, "Model"], [273, "StripOffsets"], [274, "Orientation"], [277, "SamplesPerPixel"], [278, "RowsPerStrip"], [279, "StripByteCounts"], [282, "XResolution"], [283, "YResolution"], [284, "PlanarConfiguration"], [296, "ResolutionUnit"], [301, "TransferFunction"], [305, "Software"], [306, "ModifyDate"], [315, "Artist"], [316, "HostComputer"], [317, "Predictor"], [318, "WhitePoint"], [319, "PrimaryChromaticities"], [513, "ThumbnailOffset"], [514, "ThumbnailLength"], [529, "YCbCrCoefficients"], [530, "YCbCrSubSampling"], [531, "YCbCrPositioning"], [532, "ReferenceBlackWhite"], [700, "ApplicationNotes"], [33432, "Copyright"], [33723, "IPTC"], [34665, "ExifIFD"], [34675, "ICC"], [34853, "GpsIFD"], [330, "SubIFD"], [40965, "InteropIFD"], [40091, "XPTitle"], [40092, "XPComment"], [40093, "XPAuthor"], [40094, "XPKeywords"], [40095, "XPSubject"]]), U(E, "exif", [[33434, "ExposureTime"], [33437, "FNumber"], [34850, "ExposureProgram"], [34852, "SpectralSensitivity"], [34855, "ISO"], [34858, "TimeZoneOffset"], [34859, "SelfTimerMode"], [34864, "SensitivityType"], [34865, "StandardOutputSensitivity"], [34866, "RecommendedExposureIndex"], [34867, "ISOSpeed"], [34868, "ISOSpeedLatitudeyyy"], [34869, "ISOSpeedLatitudezzz"], [36864, "ExifVersion"], [36867, "DateTimeOriginal"], [36868, "CreateDate"], [36873, "GooglePlusUploadCode"], [36880, "OffsetTime"], [36881, "OffsetTimeOriginal"], [36882, "OffsetTimeDigitized"], [37121, "ComponentsConfiguration"], [37122, "CompressedBitsPerPixel"], [37377, "ShutterSpeedValue"], [37378, "ApertureValue"], [37379, "BrightnessValue"], [37380, "ExposureCompensation"], [37381, "MaxApertureValue"], [37382, "SubjectDistance"], [37383, "MeteringMode"], [37384, "LightSource"], [37385, "Flash"], [37386, "FocalLength"], [37393, "ImageNumber"], [37394, "SecurityClassification"], [37395, "ImageHistory"], [37396, "SubjectArea"], [37500, "MakerNote"], [37510, "UserComment"], [37520, "SubSecTime"], [37521, "SubSecTimeOriginal"], [37522, "SubSecTimeDigitized"], [37888, "AmbientTemperature"], [37889, "Humidity"], [37890, "Pressure"], [37891, "WaterDepth"], [37892, "Acceleration"], [37893, "CameraElevationAngle"], [40960, "FlashpixVersion"], [40961, "ColorSpace"], [40962, "ExifImageWidth"], [40963, "ExifImageHeight"], [40964, "RelatedSoundFile"], [41483, "FlashEnergy"], [41486, "FocalPlaneXResolution"], [41487, "FocalPlaneYResolution"], [41488, "FocalPlaneResolutionUnit"], [41492, "SubjectLocation"], [41493, "ExposureIndex"], [41495, "SensingMethod"], [41728, "FileSource"], [41729, "SceneType"], [41730, "CFAPattern"], [41985, "CustomRendered"], [41986, "ExposureMode"], [41987, "WhiteBalance"], [41988, "DigitalZoomRatio"], [41989, "FocalLengthIn35mmFormat"], [41990, "SceneCaptureType"], [41991, "GainControl"], [41992, "Contrast"], [41993, "Saturation"], [41994, "Sharpness"], [41996, "SubjectDistanceRange"], [42016, "ImageUniqueID"], [42032, "OwnerName"], [42033, "SerialNumber"], [42034, "LensInfo"], [42035, "LensMake"], [42036, "LensModel"], [42037, "LensSerialNumber"], [42080, "CompositeImage"], [42081, "CompositeImageCount"], [42082, "CompositeImageExposureTimes"], [42240, "Gamma"], [59932, "Padding"], [59933, "OffsetSchema"], [65e3, "OwnerName"], [65001, "SerialNumber"], [65002, "Lens"], [65100, "RawFile"], [65101, "Converter"], [65102, "WhiteBalance"], [65105, "Exposure"], [65106, "Shadows"], [65107, "Brightness"], [65108, "Contrast"], [65109, "Saturation"], [65110, "Sharpness"], [65111, "Smoothness"], [65112, "MoireFilter"], [40965, "InteropIFD"]]), U(E, "gps", [[0, "GPSVersionID"], [1, "GPSLatitudeRef"], [2, "GPSLatitude"], [3, "GPSLongitudeRef"], [4, "GPSLongitude"], [5, "GPSAltitudeRef"], [6, "GPSAltitude"], [7, "GPSTimeStamp"], [8, "GPSSatellites"], [9, "GPSStatus"], [10, "GPSMeasureMode"], [11, "GPSDOP"], [12, "GPSSpeedRef"], [13, "GPSSpeed"], [14, "GPSTrackRef"], [15, "GPSTrack"], [16, "GPSImgDirectionRef"], [17, "GPSImgDirection"], [18, "GPSMapDatum"], [19, "GPSDestLatitudeRef"], [20, "GPSDestLatitude"], [21, "GPSDestLongitudeRef"], [22, "GPSDestLongitude"], [23, "GPSDestBearingRef"], [24, "GPSDestBearing"], [25, "GPSDestDistanceRef"], [26, "GPSDestDistance"], [27, "GPSProcessingMethod"], [28, "GPSAreaInformation"], [29, "GPSDateStamp"], [30, "GPSDifferential"], [31, "GPSHPositioningError"]]), U(B, ["ifd0", "ifd1"], [[274, { 1: "Horizontal (normal)", 2: "Mirror horizontal", 3: "Rotate 180", 4: "Mirror vertical", 5: "Mirror horizontal and rotate 270 CW", 6: "Rotate 90 CW", 7: "Mirror horizontal and rotate 90 CW", 8: "Rotate 270 CW" }], [296, { 1: "None", 2: "inches", 3: "cm" }]]); + var Ee = U(B, "exif", [[34850, { 0: "Not defined", 1: "Manual", 2: "Normal program", 3: "Aperture priority", 4: "Shutter priority", 5: "Creative program", 6: "Action program", 7: "Portrait mode", 8: "Landscape mode" }], [37121, { 0: "-", 1: "Y", 2: "Cb", 3: "Cr", 4: "R", 5: "G", 6: "B" }], [37383, { 0: "Unknown", 1: "Average", 2: "CenterWeightedAverage", 3: "Spot", 4: "MultiSpot", 5: "Pattern", 6: "Partial", 255: "Other" }], [37384, { 0: "Unknown", 1: "Daylight", 2: "Fluorescent", 3: "Tungsten (incandescent light)", 4: "Flash", 9: "Fine weather", 10: "Cloudy weather", 11: "Shade", 12: "Daylight fluorescent (D 5700 - 7100K)", 13: "Day white fluorescent (N 4600 - 5400K)", 14: "Cool white fluorescent (W 3900 - 4500K)", 15: "White fluorescent (WW 3200 - 3700K)", 17: "Standard light A", 18: "Standard light B", 19: "Standard light C", 20: "D55", 21: "D65", 22: "D75", 23: "D50", 24: "ISO studio tungsten", 255: "Other" }], [37385, { 0: "Flash did not fire", 1: "Flash fired", 5: "Strobe return light not detected", 7: "Strobe return light detected", 9: "Flash fired, compulsory flash mode", 13: "Flash fired, compulsory flash mode, return light not detected", 15: "Flash fired, compulsory flash mode, return light detected", 16: "Flash did not fire, compulsory flash mode", 24: "Flash did not fire, auto mode", 25: "Flash fired, auto mode", 29: "Flash fired, auto mode, return light not detected", 31: "Flash fired, auto mode, return light detected", 32: "No flash function", 65: "Flash fired, red-eye reduction mode", 69: "Flash fired, red-eye reduction mode, return light not detected", 71: "Flash fired, red-eye reduction mode, return light detected", 73: "Flash fired, compulsory flash mode, red-eye reduction mode", 77: "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected", 79: "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected", 89: "Flash fired, auto mode, red-eye reduction mode", 93: "Flash fired, auto mode, return light not detected, red-eye reduction mode", 95: "Flash fired, auto mode, return light detected, red-eye reduction mode" }], [41495, { 1: "Not defined", 2: "One-chip color area sensor", 3: "Two-chip color area sensor", 4: "Three-chip color area sensor", 5: "Color sequential area sensor", 7: "Trilinear sensor", 8: "Color sequential linear sensor" }], [41728, { 1: "Film Scanner", 2: "Reflection Print Scanner", 3: "Digital Camera" }], [41729, { 1: "Directly photographed" }], [41985, { 0: "Normal", 1: "Custom", 2: "HDR (no original saved)", 3: "HDR (original saved)", 4: "Original (for HDR)", 6: "Panorama", 7: "Portrait HDR", 8: "Portrait" }], [41986, { 0: "Auto", 1: "Manual", 2: "Auto bracket" }], [41987, { 0: "Auto", 1: "Manual" }], [41990, { 0: "Standard", 1: "Landscape", 2: "Portrait", 3: "Night", 4: "Other" }], [41991, { 0: "None", 1: "Low gain up", 2: "High gain up", 3: "Low gain down", 4: "High gain down" }], [41996, { 0: "Unknown", 1: "Macro", 2: "Close", 3: "Distant" }], [42080, { 0: "Unknown", 1: "Not a Composite Image", 2: "General Composite Image", 3: "Composite Image Captured While Shooting" }]]); + var Be = { 1: "No absolute unit of measurement", 2: "Inch", 3: "Centimeter" }; + Ee.set(37392, Be), Ee.set(41488, Be); + var Ne = { 0: "Normal", 1: "Low", 2: "High" }; + function Ge(e3) { + return "object" == typeof e3 && void 0 !== e3.length ? e3[0] : e3; } - - // modules/svg/vegbilder.js - function svgVegbilder(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); - const minZoom4 = 14; - const minMarkerZoom = 16; - const minViewfieldZoom2 = 18; - let layer = select_default2(null); - let _viewerYaw = 0; - let _vegbilder; - function init2() { - if (svgVegbilder.initialized) - return; - svgVegbilder.enabled = false; - svgVegbilder.initialized = true; - } - function getService() { - if (services.vegbilder && !_vegbilder) { - _vegbilder = services.vegbilder; - _vegbilder.event.on("viewerChanged.svgVegbilder", viewerChanged).on("loadedImages.svgVegbilder", throttledRedraw); - } else if (!services.vegbilder && _vegbilder) { - _vegbilder = null; - } - return _vegbilder; - } - function showLayer() { - const service = getService(); - if (!service) - return; - editOn(); - layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", () => dispatch14.call("change")); + function Ve(e3) { + let t2 = Array.from(e3).slice(1); + return t2[1] > 15 && (t2 = t2.map((e4) => String.fromCharCode(e4))), "0" !== t2[2] && 0 !== t2[2] || t2.pop(), t2.join("."); + } + function ze(e3) { + if ("string" == typeof e3) { + var [t2, i3, n3, s2, r2, a2] = e3.trim().split(/[-: ]/g).map(Number), o2 = new Date(t2, i3 - 1, n3); + return Number.isNaN(s2) || Number.isNaN(r2) || Number.isNaN(a2) || (o2.setHours(s2), o2.setMinutes(r2), o2.setSeconds(a2)), Number.isNaN(+o2) ? e3 : o2; } - function hideLayer() { - throttledRedraw.cancel(); - layer.transition().duration(250).style("opacity", 0).on("end", editOff); + } + function He(e3) { + if ("string" == typeof e3) + return e3; + let t2 = []; + if (0 === e3[1] && 0 === e3[e3.length - 1]) + for (let i3 = 0; i3 < e3.length; i3 += 2) + t2.push(je(e3[i3 + 1], e3[i3])); + else + for (let i3 = 0; i3 < e3.length; i3 += 2) + t2.push(je(e3[i3], e3[i3 + 1])); + return m(String.fromCodePoint(...t2)); + } + function je(e3, t2) { + return e3 << 8 | t2; + } + Ee.set(41992, Ne), Ee.set(41993, Ne), Ee.set(41994, Ne), U(N, ["ifd0", "ifd1"], [[50827, function(e3) { + return "string" != typeof e3 ? b(e3) : e3; + }], [306, ze], [40091, He], [40092, He], [40093, He], [40094, He], [40095, He]]), U(N, "exif", [[40960, Ve], [36864, Ve], [36867, ze], [36868, ze], [40962, Ge], [40963, Ge]]), U(N, "gps", [[0, (e3) => Array.from(e3).join(".")], [7, (e3) => Array.from(e3).join(":")]]); + var We = class extends re2 { + static canHandle(e3, t2) { + return 225 === e3.getUint8(t2 + 1) && 1752462448 === e3.getUint32(t2 + 4) && "http://ns.adobe.com/" === e3.getString(t2 + 4, "http://ns.adobe.com/".length); } - function editOn() { - layer.style("display", "block"); + static headerLength(e3, t2) { + return "http://ns.adobe.com/xmp/extension/" === e3.getString(t2 + 4, "http://ns.adobe.com/xmp/extension/".length) ? 79 : 4 + "http://ns.adobe.com/xap/1.0/".length + 1; } - function editOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); + static findPosition(e3, t2) { + let i3 = super.findPosition(e3, t2); + return i3.multiSegment = i3.extended = 79 === i3.headerLength, i3.multiSegment ? (i3.chunkCount = e3.getUint8(t2 + 72), i3.chunkNumber = e3.getUint8(t2 + 76), 0 !== e3.getUint8(t2 + 77) && i3.chunkNumber++) : (i3.chunkCount = 1 / 0, i3.chunkNumber = -1), i3; } - function click(d3_event, d2) { - const service = getService(); - if (!service) - return; - service.ensureViewerLoaded(context).then(() => { - service.selectImage(context, d2.key).showViewer(context); - }); - context.map().centerEase(d2.loc); + static handleMultiSegments(e3) { + return e3.map((e4) => e4.chunk.getString()).join(""); } - function mouseover(d3_event, d2) { - const service = getService(); - if (service) - service.setStyles(context, d2); + normalizeInput(e3) { + return "string" == typeof e3 ? e3 : I.from(e3).getString(); } - function mouseout() { - const service = getService(); - if (service) - service.setStyles(context, null); + parse(e3 = this.chunk) { + if (!this.localOptions.parse) + return e3; + e3 = function(e4) { + let t3 = {}, i4 = {}; + for (let e6 of Ze) + t3[e6] = [], i4[e6] = 0; + return e4.replace(et, (e6, n4, s2) => { + if ("<" === n4) { + let n5 = ++i4[s2]; + return t3[s2].push(n5), "".concat(e6, "#").concat(n5); + } + return "".concat(e6, "#").concat(t3[s2].pop()); + }); + }(e3); + let t2 = Xe.findAll(e3, "rdf", "Description"); + 0 === t2.length && t2.push(new Xe("rdf", "Description", void 0, e3)); + let i3, n3 = {}; + for (let e4 of t2) + for (let t3 of e4.properties) + i3 = Je(t3.ns, n3), _e(t3, i3); + return function(e4) { + let t3; + for (let i4 in e4) + t3 = e4[i4] = f(e4[i4]), void 0 === t3 && delete e4[i4]; + return f(e4); + }(n3); } - function transform2(d2, selected) { - let t2 = svgPointTransform(projection2)(d2); - let rot = d2.ca; - if (d2 === selected) { - rot += _viewerYaw; - } - if (rot) { - t2 += " rotate(" + Math.floor(rot) + ",0,0)"; - } - return t2; + assignToOutput(e3, t2) { + if (this.localOptions.parse) + for (let [i3, n3] of Object.entries(t2)) + switch (i3) { + case "tiff": + this.assignObjectToOutput(e3, "ifd0", n3); + break; + case "exif": + this.assignObjectToOutput(e3, "exif", n3); + break; + case "xmlns": + break; + default: + this.assignObjectToOutput(e3, i3, n3); + } + else + e3.xmp = t2; } - function viewerChanged() { - const service = getService(); - if (!service) - return; - const frame2 = service.photoFrame(); - _viewerYaw = frame2.getYaw(); - if (context.map().isTransformed()) - return; - layer.selectAll(".viewfield-group.currentView").attr("transform", (d2) => transform2(d2, d2)); + }; + c(We, "type", "xmp"), c(We, "multiSegment", true), T.set("xmp", We); + var Ke = class _Ke { + static findAll(e3) { + return qe(e3, /([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(_Ke.unpackMatch); } - function filterImages(images) { - const photoContext = context.photos(); - const fromDateString = photoContext.fromDate(); - const toDateString = photoContext.toDate(); - const showsFlat = photoContext.showsFlat(); - const showsPano = photoContext.showsPanoramic(); - if (fromDateString) { - const fromDate = new Date(fromDateString); - images = images.filter((image) => image.captured_at.getTime() >= fromDate.getTime()); - } - if (toDateString) { - const toDate = new Date(toDateString); - images = images.filter((image) => image.captured_at.getTime() <= toDate.getTime()); - } - if (!showsPano) { - images = images.filter((image) => !image.is_sphere); - } - if (!showsFlat) { - images = images.filter((image) => image.is_sphere); - } - return images; + static unpackMatch(e3) { + let t2 = e3[1], i3 = e3[2], n3 = e3[3].slice(1, -1); + return n3 = Qe(n3), new _Ke(t2, i3, n3); } - function filterSequences(sequences) { - const photoContext = context.photos(); - const fromDateString = photoContext.fromDate(); - const toDateString = photoContext.toDate(); - const showsFlat = photoContext.showsFlat(); - const showsPano = photoContext.showsPanoramic(); - if (fromDateString) { - const fromDate = new Date(fromDateString); - sequences = sequences.filter(({ images }) => images[0].captured_at.getTime() >= fromDate.getTime()); - } - if (toDateString) { - const toDate = new Date(toDateString); - sequences = sequences.filter(({ images }) => images[images.length - 1].captured_at.getTime() <= toDate.getTime()); - } - if (!showsPano) { - sequences = sequences.filter(({ images }) => !images[0].is_sphere); - } - if (!showsFlat) { - sequences = sequences.filter(({ images }) => images[0].is_sphere); - } - return sequences; + constructor(e3, t2, i3) { + this.ns = e3, this.name = t2, this.value = i3; } - function update() { - const viewer = context.container().select(".photoviewer"); - const selected = viewer.empty() ? void 0 : viewer.datum(); - const z2 = ~~context.map().zoom(); - const showMarkers = z2 >= minMarkerZoom; - const showViewfields = z2 >= minViewfieldZoom2; - const service = getService(); - let sequences = []; - let images = []; - if (service) { - service.loadImages(context); - sequences = service.sequences(projection2); - images = showMarkers ? service.images(projection2) : []; - images = filterImages(images); - sequences = filterSequences(sequences); - } - let traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, (d2) => d2.key); - traces.exit().remove(); - traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); - const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, (d2) => d2.key); - groups.exit().remove(); - const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); - groupsEnter.append("g").attr("class", "viewfield-scale"); - const markers = groups.merge(groupsEnter).sort((a2, b2) => { - return a2 === selected ? 1 : b2 === selected ? -1 : b2.loc[1] - a2.loc[1]; - }).attr("transform", (d2) => transform2(d2, selected)).select(".viewfield-scale"); - markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); - viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); - function viewfieldPath() { - const d2 = this.parentNode.__data__; - if (d2.is_sphere) { - return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; - } else { - return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; - } - } + serialize() { + return this.value; } - function drawImages(selection2) { - const enabled = svgVegbilder.enabled; - const service = getService(); - layer = selection2.selectAll(".layer-vegbilder").data(service ? [0] : []); - layer.exit().remove(); - const layerEnter = layer.enter().append("g").attr("class", "layer-vegbilder").style("display", enabled ? "block" : "none"); - layerEnter.append("g").attr("class", "sequences"); - layerEnter.append("g").attr("class", "markers"); - layer = layerEnter.merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadImages(context); - } else { - editOff(); - } - } + }; + var Xe = class _Xe { + static findAll(e3, t2, i3) { + if (void 0 !== t2 || void 0 !== i3) { + t2 = t2 || "[\\w\\d-]+", i3 = i3 || "[\\w\\d-]+"; + var n3 = new RegExp("<(".concat(t2, "):(").concat(i3, ")(#\\d+)?((\\s+?[\\w\\d-:]+=(\"[^\"]*\"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)"), "gm"); + } else + n3 = /<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm; + return qe(e3, n3).map(_Xe.unpackMatch); } - drawImages.enabled = function(_2) { - if (!arguments.length) - return svgVegbilder.enabled; - svgVegbilder.enabled = _2; - if (svgVegbilder.enabled) { - showLayer(); - context.photos().on("change.vegbilder", update); - } else { - hideLayer(); - context.photos().on("change.vegbilder", null); - } - dispatch14.call("change"); - return this; - }; - drawImages.supported = function() { - return !!getService(); - }; - drawImages.rendered = function(zoom) { - return zoom >= minZoom4; - }; - drawImages.validHere = function(extent, zoom) { - return zoom >= minZoom4 - 2 && getService().validHere(extent); - }; - init2(); - return drawImages; - } - - // modules/svg/mapillary_images.js - function svgMapillaryImages(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - const minZoom4 = 12; - const minMarkerZoom = 16; - const minViewfieldZoom2 = 18; - let layer = select_default2(null); - let _mapillary; - function init2() { - if (svgMapillaryImages.initialized) - return; - svgMapillaryImages.enabled = false; - svgMapillaryImages.initialized = true; + static unpackMatch(e3) { + let t2 = e3[1], i3 = e3[2], n3 = e3[4], s2 = e3[8]; + return new _Xe(t2, i3, n3, s2); } - function getService() { - if (services.mapillary && !_mapillary) { - _mapillary = services.mapillary; - _mapillary.event.on("loadedImages", throttledRedraw); - } else if (!services.mapillary && _mapillary) { - _mapillary = null; - } - return _mapillary; + constructor(e3, t2, i3, n3) { + this.ns = e3, this.name = t2, this.attrString = i3, this.innerXml = n3, this.attrs = Ke.findAll(i3), this.children = _Xe.findAll(n3), this.value = 0 === this.children.length ? Qe(n3) : void 0, this.properties = [...this.attrs, ...this.children]; } - function showLayer() { - const service = getService(); - if (!service) - return; - editOn(); - layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { - dispatch14.call("change"); - }); + get isPrimitive() { + return void 0 !== this.value && 0 === this.attrs.length && 0 === this.children.length; } - function hideLayer() { - throttledRedraw.cancel(); - layer.transition().duration(250).style("opacity", 0).on("end", editOff); + get isListContainer() { + return 1 === this.children.length && this.children[0].isList; } - function editOn() { - layer.style("display", "block"); + get isList() { + let { ns: e3, name: t2 } = this; + return "rdf" === e3 && ("Seq" === t2 || "Bag" === t2 || "Alt" === t2); } - function editOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); + get isListItem() { + return "rdf" === this.ns && "li" === this.name; } - function click(d3_event, image) { - const service = getService(); - if (!service) + serialize() { + if (0 === this.properties.length && void 0 === this.value) return; - service.ensureViewerLoaded(context).then(function() { - service.selectImage(context, image.id).showViewer(context); - }); - context.map().centerEase(image.loc); + if (this.isPrimitive) + return this.value; + if (this.isListContainer) + return this.children[0].serialize(); + if (this.isList) + return $e(this.children.map(Ye)); + if (this.isListItem && 1 === this.children.length && 0 === this.attrs.length) + return this.children[0].serialize(); + let e3 = {}; + for (let t2 of this.properties) + _e(t2, e3); + return void 0 !== this.value && (e3.value = this.value), f(e3); } - function mouseover(d3_event, image) { - const service = getService(); - if (service) - service.setStyles(context, image); + }; + function _e(e3, t2) { + let i3 = e3.serialize(); + void 0 !== i3 && (t2[e3.name] = i3); + } + var Ye = (e3) => e3.serialize(); + var $e = (e3) => 1 === e3.length ? e3[0] : e3; + var Je = (e3, t2) => t2[e3] ? t2[e3] : t2[e3] = {}; + function qe(e3, t2) { + let i3, n3 = []; + if (!e3) + return n3; + for (; null !== (i3 = t2.exec(e3)); ) + n3.push(i3); + return n3; + } + function Qe(e3) { + if (function(e4) { + return null == e4 || "null" === e4 || "undefined" === e4 || "" === e4 || "" === e4.trim(); + }(e3)) + return; + let t2 = Number(e3); + if (!Number.isNaN(t2)) + return t2; + let i3 = e3.toLowerCase(); + return "true" === i3 || "false" !== i3 && e3.trim(); + } + var Ze = ["rdf:li", "rdf:Seq", "rdf:Bag", "rdf:Alt", "rdf:Description"]; + var et = new RegExp("(<|\\/)(".concat(Ze.join("|"), ")"), "g"); + var tt = Object.freeze({ __proto__: null, default: Me, Exifr: te, fileParsers: w, segmentParsers: T, fileReaders: A, tagKeys: E, tagValues: B, tagRevivers: N, createDictionary: U, extendDictionary: F, fetchUrlAsArrayBuffer: M, readBlobAsArrayBuffer: R, chunkedProps: G, otherSegments: V, segments: z, tiffBlocks: H, segmentsAndBlocks: j, tiffExtractables: W, inheritables: K, allFormatters: X, Options: q, parse: ie, gpsOnlyOptions: me, gps: Se, thumbnailOnlyOptions: Ce, thumbnail: ye, thumbnailUrl: be, orientationOnlyOptions: Ie, orientation: Pe, rotations: ke, get rotateCanvas() { + return we; + }, get rotateCss() { + return Te; + }, rotation: Ae }); + var at = l("fs", (e3) => e3.promises); + A.set("fs", class extends ve { + async readWhole() { + this.chunked = false, this.fs = await at; + let e3 = await this.fs.readFile(this.input); + this._swapBuffer(e3); } - function mouseout() { - const service = getService(); - if (service) - service.setStyles(context, null); + async readChunked() { + this.chunked = true, this.fs = await at, await this.open(), await this.readChunk(0, this.options.firstChunkSize); } - function transform2(d2) { - let t2 = svgPointTransform(projection2)(d2); - if (d2.ca) { - t2 += " rotate(" + Math.floor(d2.ca) + ",0,0)"; - } - return t2; + async open() { + void 0 === this.fh && (this.fh = await this.fs.open(this.input, "r"), this.size = (await this.fh.stat(this.input)).size); } - function filterImages(images) { - const showsPano = context.photos().showsPanoramic(); - const showsFlat = context.photos().showsFlat(); - const fromDate = context.photos().fromDate(); - const toDate = context.photos().toDate(); - if (!showsPano || !showsFlat) { - images = images.filter(function(image) { - if (image.is_pano) - return showsPano; - return showsFlat; - }); - } - if (fromDate) { - images = images.filter(function(image) { - return new Date(image.captured_at).getTime() >= new Date(fromDate).getTime(); - }); - } - if (toDate) { - images = images.filter(function(image) { - return new Date(image.captured_at).getTime() <= new Date(toDate).getTime(); - }); - } - return images; + async _readChunk(e3, t2) { + void 0 === this.fh && await this.open(), e3 + t2 > this.size && (t2 = this.size - e3); + var i3 = this.subarray(e3, t2, true); + return await this.fh.read(i3.dataView, 0, t2, e3), i3; } - function filterSequences(sequences) { - const showsPano = context.photos().showsPanoramic(); - const showsFlat = context.photos().showsFlat(); - const fromDate = context.photos().fromDate(); - const toDate = context.photos().toDate(); - if (!showsPano || !showsFlat) { - sequences = sequences.filter(function(sequence) { - if (sequence.properties.hasOwnProperty("is_pano")) { - if (sequence.properties.is_pano) - return showsPano; - return showsFlat; - } - return false; - }); + async close() { + if (this.fh) { + let e3 = this.fh; + this.fh = void 0, await e3.close(); } - if (fromDate) { - sequences = sequences.filter(function(sequence) { - return new Date(sequence.properties.captured_at).getTime() >= new Date(fromDate).getTime().toString(); - }); + } + }); + A.set("base64", class extends ve { + constructor(...e3) { + super(...e3), this.input = this.input.replace(/^data:([^;]+);base64,/gim, ""), this.size = this.input.length / 4 * 3, this.input.endsWith("==") ? this.size -= 2 : this.input.endsWith("=") && (this.size -= 1); + } + async _readChunk(e3, t2) { + let i3, n3, r2 = this.input; + void 0 === e3 ? (e3 = 0, i3 = 0, n3 = 0) : (i3 = 4 * Math.floor(e3 / 3), n3 = e3 - i3 / 4 * 3), void 0 === t2 && (t2 = this.size); + let o2 = e3 + t2, l2 = i3 + 4 * Math.ceil(o2 / 3); + r2 = r2.slice(i3, l2); + let h2 = Math.min(t2, this.size - e3); + if (a) { + let t3 = s.from(r2, "base64").slice(n3, n3 + h2); + return this.set(t3, e3, true); } - if (toDate) { - sequences = sequences.filter(function(sequence) { - return new Date(sequence.properties.captured_at).getTime() <= new Date(toDate).getTime().toString(); - }); + { + let t3 = this.subarray(e3, h2, true), i4 = atob(r2), s2 = t3.toUint8(); + for (let e4 = 0; e4 < h2; e4++) + s2[e4] = i4.charCodeAt(n3 + e4); + return t3; } - return sequences; } - function update() { - const z2 = ~~context.map().zoom(); - const showMarkers = z2 >= minMarkerZoom; - const showViewfields = z2 >= minViewfieldZoom2; - const service = getService(); - let sequences = service ? service.sequences(projection2) : []; - let images = service && showMarkers ? service.images(projection2) : []; - images = filterImages(images); - sequences = filterSequences(sequences, service); - service.filterViewer(context); - let traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { - return d2.properties.id; - }); - traces.exit().remove(); - traces = traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); - const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, function(d2) { - return d2.id; - }); - groups.exit().remove(); - const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); - groupsEnter.append("g").attr("class", "viewfield-scale"); - const markers = groups.merge(groupsEnter).sort(function(a2, b2) { - return b2.loc[1] - a2.loc[1]; - }).attr("transform", transform2).select(".viewfield-scale"); - markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); - viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").classed("pano", function() { - return this.parentNode.__data__.is_pano; - }).attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); - function viewfieldPath() { - if (this.parentNode.__data__.is_pano) { - return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; - } else { - return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; - } - } + }); + var ot = class extends se { + static canHandle(e3, t2) { + return 18761 === t2 || 19789 === t2; } - function drawImages(selection2) { - const enabled = svgMapillaryImages.enabled; - const service = getService(); - layer = selection2.selectAll(".layer-mapillary").data(service ? [0] : []); - layer.exit().remove(); - const layerEnter = layer.enter().append("g").attr("class", "layer-mapillary").style("display", enabled ? "block" : "none"); - layerEnter.append("g").attr("class", "sequences"); - layerEnter.append("g").attr("class", "markers"); - layer = layerEnter.merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadImages(projection2); - } else { - editOff(); - } + extendOptions(e3) { + let { ifd0: t2, xmp: i3, iptc: n3, icc: s2 } = e3; + i3.enabled && t2.deps.add(700), n3.enabled && t2.deps.add(33723), s2.enabled && t2.deps.add(34675), t2.finalizeFilters(); + } + async parse() { + let { tiff: e3, xmp: t2, iptc: i3, icc: n3 } = this.options; + if (e3.enabled || t2.enabled || i3.enabled || n3.enabled) { + let e4 = Math.max(S(this.options), this.options.chunkSize); + await this.file.ensureChunk(0, e4), this.createParser("tiff", this.file), this.parsers.tiff.parseHeader(), await this.parsers.tiff.parseIfd0Block(), this.adaptTiffPropAsSegment("xmp"), this.adaptTiffPropAsSegment("iptc"), this.adaptTiffPropAsSegment("icc"); } } - drawImages.enabled = function(_2) { - if (!arguments.length) - return svgMapillaryImages.enabled; - svgMapillaryImages.enabled = _2; - if (svgMapillaryImages.enabled) { - showLayer(); - context.photos().on("change.mapillary_images", update); - } else { - hideLayer(); - context.photos().on("change.mapillary_images", null); + adaptTiffPropAsSegment(e3) { + if (this.parsers.tiff[e3]) { + let t2 = this.parsers.tiff[e3]; + this.injectSegment(e3, t2); } - dispatch14.call("change"); - return this; - }; - drawImages.supported = function() { - return !!getService(); - }; - drawImages.rendered = function(zoom) { - return zoom >= minZoom4; - }; - init2(); - return drawImages; - } - - // modules/svg/mapillary_position.js - function svgMapillaryPosition(projection2, context) { - const throttledRedraw = throttle_default(function() { - update(); - }, 1e3); - const minZoom4 = 12; - const minViewfieldZoom2 = 18; - let layer = select_default2(null); - let _mapillary; - let viewerCompassAngle; - function init2() { - if (svgMapillaryPosition.initialized) - return; - svgMapillaryPosition.initialized = true; } - function getService() { - if (services.mapillary && !_mapillary) { - _mapillary = services.mapillary; - _mapillary.event.on("imageChanged", throttledRedraw); - _mapillary.event.on("bearingChanged", function(e3) { - viewerCompassAngle = e3.bearing; - if (context.map().isTransformed()) - return; - layer.selectAll(".viewfield-group.currentView").filter(function(d2) { - return d2.is_pano; - }).attr("transform", transform2); - }); - } else if (!services.mapillary && _mapillary) { - _mapillary = null; + }; + c(ot, "type", "tiff"), w.set("tiff", ot); + var lt = l("zlib"); + var ht = ["ihdr", "iccp", "text", "itxt", "exif"]; + var ut = class extends se { + constructor(...e3) { + super(...e3), c(this, "catchError", (e4) => this.errors.push(e4)), c(this, "metaChunks", []), c(this, "unknownChunks", []); + } + static canHandle(e3, t2) { + return 35152 === t2 && 2303741511 === e3.getUint32(0) && 218765834 === e3.getUint32(4); + } + async parse() { + let { file: e3 } = this; + await this.findPngChunksInRange("\x89PNG\r\n\n".length, e3.byteLength), await this.readSegments(this.metaChunks), this.findIhdr(), this.parseTextChunks(), await this.findExif().catch(this.catchError), await this.findXmp().catch(this.catchError), await this.findIcc().catch(this.catchError); + } + async findPngChunksInRange(e3, t2) { + let { file: i3 } = this; + for (; e3 < t2; ) { + let t3 = i3.getUint32(e3), n3 = i3.getUint32(e3 + 4), s2 = i3.getString(e3 + 4, 4).toLowerCase(), r2 = t3 + 4 + 4 + 4, a2 = { type: s2, offset: e3, length: r2, start: e3 + 4 + 4, size: t3, marker: n3 }; + ht.includes(s2) ? this.metaChunks.push(a2) : this.unknownChunks.push(a2), e3 += r2; } - return _mapillary; } - function editOn() { - layer.style("display", "block"); + parseTextChunks() { + let e3 = this.metaChunks.filter((e4) => "text" === e4.type); + for (let t2 of e3) { + let [e4, i3] = this.file.getString(t2.start, t2.size).split("\0"); + this.injectKeyValToIhdr(e4, i3); + } } - function editOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); + injectKeyValToIhdr(e3, t2) { + let i3 = this.parsers.ihdr; + i3 && i3.raw.set(e3, t2); } - function transform2(d2) { - let t2 = svgPointTransform(projection2)(d2); - if (d2.is_pano && viewerCompassAngle !== null && isFinite(viewerCompassAngle)) { - t2 += " rotate(" + Math.floor(viewerCompassAngle) + ",0,0)"; - } else if (d2.ca) { - t2 += " rotate(" + Math.floor(d2.ca) + ",0,0)"; - } - return t2; + findIhdr() { + let e3 = this.metaChunks.find((e4) => "ihdr" === e4.type); + e3 && false !== this.options.ihdr.enabled && this.createParser("ihdr", e3.chunk); } - function update() { - const z2 = ~~context.map().zoom(); - const showViewfields = z2 >= minViewfieldZoom2; - const service = getService(); - const image = service && service.getActiveImage(); - const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(image ? [image] : [], function(d2) { - return d2.id; - }); - groups.exit().remove(); - const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group currentView highlighted"); - groupsEnter.append("g").attr("class", "viewfield-scale"); - const markers = groups.merge(groupsEnter).attr("transform", transform2).select(".viewfield-scale"); - markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); - viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"); + async findExif() { + let e3 = this.metaChunks.find((e4) => "exif" === e4.type); + e3 && this.injectSegment("tiff", e3.chunk); } - function drawImages(selection2) { - const service = getService(); - layer = selection2.selectAll(".layer-mapillary-position").data(service ? [0] : []); - layer.exit().remove(); - const layerEnter = layer.enter().append("g").attr("class", "layer-mapillary-position"); - layerEnter.append("g").attr("class", "markers"); - layer = layerEnter.merge(layer); - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - } else { - editOff(); + async findXmp() { + let e3 = this.metaChunks.filter((e4) => "itxt" === e4.type); + for (let t2 of e3) { + "XML:com.adobe.xmp" === t2.chunk.getString(0, "XML:com.adobe.xmp".length) && this.injectSegment("xmp", t2.chunk); } } - drawImages.enabled = function() { - update(); - return this; - }; - drawImages.supported = function() { - return !!getService(); - }; - drawImages.rendered = function(zoom) { - return zoom >= minZoom4; - }; - init2(); - return drawImages; - } - - // modules/svg/mapillary_signs.js - function svgMapillarySigns(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - const minZoom4 = 12; - let layer = select_default2(null); - let _mapillary; - function init2() { - if (svgMapillarySigns.initialized) + async findIcc() { + let e3 = this.metaChunks.find((e4) => "iccp" === e4.type); + if (!e3) return; - svgMapillarySigns.enabled = false; - svgMapillarySigns.initialized = true; - } - function getService() { - if (services.mapillary && !_mapillary) { - _mapillary = services.mapillary; - _mapillary.event.on("loadedSigns", throttledRedraw); - } else if (!services.mapillary && _mapillary) { - _mapillary = null; + let { chunk: t2 } = e3, i3 = t2.getUint8Array(0, 81), s2 = 0; + for (; s2 < 80 && 0 !== i3[s2]; ) + s2++; + let r2 = s2 + 2, a2 = t2.getString(0, s2); + if (this.injectKeyValToIhdr("ProfileName", a2), n2) { + let e4 = await lt, i4 = t2.getUint8Array(r2); + i4 = e4.inflateSync(i4), this.injectSegment("icc", i4); } - return _mapillary; } - function showLayer() { - const service = getService(); - if (!service) - return; - service.loadSignResources(context); - editOn(); + }; + c(ut, "type", "png"), w.set("png", ut), U(E, "interop", [[1, "InteropIndex"], [2, "InteropVersion"], [4096, "RelatedImageFileFormat"], [4097, "RelatedImageWidth"], [4098, "RelatedImageHeight"]]), F(E, "ifd0", [[11, "ProcessingSoftware"], [254, "SubfileType"], [255, "OldSubfileType"], [263, "Thresholding"], [264, "CellWidth"], [265, "CellLength"], [266, "FillOrder"], [269, "DocumentName"], [280, "MinSampleValue"], [281, "MaxSampleValue"], [285, "PageName"], [286, "XPosition"], [287, "YPosition"], [290, "GrayResponseUnit"], [297, "PageNumber"], [321, "HalftoneHints"], [322, "TileWidth"], [323, "TileLength"], [332, "InkSet"], [337, "TargetPrinter"], [18246, "Rating"], [18249, "RatingPercent"], [33550, "PixelScale"], [34264, "ModelTransform"], [34377, "PhotoshopSettings"], [50706, "DNGVersion"], [50707, "DNGBackwardVersion"], [50708, "UniqueCameraModel"], [50709, "LocalizedCameraModel"], [50736, "DNGLensInfo"], [50739, "ShadowScale"], [50740, "DNGPrivateData"], [33920, "IntergraphMatrix"], [33922, "ModelTiePoint"], [34118, "SEMInfo"], [34735, "GeoTiffDirectory"], [34736, "GeoTiffDoubleParams"], [34737, "GeoTiffAsciiParams"], [50341, "PrintIM"], [50721, "ColorMatrix1"], [50722, "ColorMatrix2"], [50723, "CameraCalibration1"], [50724, "CameraCalibration2"], [50725, "ReductionMatrix1"], [50726, "ReductionMatrix2"], [50727, "AnalogBalance"], [50728, "AsShotNeutral"], [50729, "AsShotWhiteXY"], [50730, "BaselineExposure"], [50731, "BaselineNoise"], [50732, "BaselineSharpness"], [50734, "LinearResponseLimit"], [50735, "CameraSerialNumber"], [50741, "MakerNoteSafety"], [50778, "CalibrationIlluminant1"], [50779, "CalibrationIlluminant2"], [50781, "RawDataUniqueID"], [50827, "OriginalRawFileName"], [50828, "OriginalRawFileData"], [50831, "AsShotICCProfile"], [50832, "AsShotPreProfileMatrix"], [50833, "CurrentICCProfile"], [50834, "CurrentPreProfileMatrix"], [50879, "ColorimetricReference"], [50885, "SRawType"], [50898, "PanasonicTitle"], [50899, "PanasonicTitle2"], [50931, "CameraCalibrationSig"], [50932, "ProfileCalibrationSig"], [50933, "ProfileIFD"], [50934, "AsShotProfileName"], [50936, "ProfileName"], [50937, "ProfileHueSatMapDims"], [50938, "ProfileHueSatMapData1"], [50939, "ProfileHueSatMapData2"], [50940, "ProfileToneCurve"], [50941, "ProfileEmbedPolicy"], [50942, "ProfileCopyright"], [50964, "ForwardMatrix1"], [50965, "ForwardMatrix2"], [50966, "PreviewApplicationName"], [50967, "PreviewApplicationVersion"], [50968, "PreviewSettingsName"], [50969, "PreviewSettingsDigest"], [50970, "PreviewColorSpace"], [50971, "PreviewDateTime"], [50972, "RawImageDigest"], [50973, "OriginalRawFileDigest"], [50981, "ProfileLookTableDims"], [50982, "ProfileLookTableData"], [51043, "TimeCodes"], [51044, "FrameRate"], [51058, "TStop"], [51081, "ReelName"], [51089, "OriginalDefaultFinalSize"], [51090, "OriginalBestQualitySize"], [51091, "OriginalDefaultCropSize"], [51105, "CameraLabel"], [51107, "ProfileHueSatMapEncoding"], [51108, "ProfileLookTableEncoding"], [51109, "BaselineExposureOffset"], [51110, "DefaultBlackRender"], [51111, "NewRawImageDigest"], [51112, "RawToPreviewGain"]]); + var ct = [[273, "StripOffsets"], [279, "StripByteCounts"], [288, "FreeOffsets"], [289, "FreeByteCounts"], [291, "GrayResponseCurve"], [292, "T4Options"], [293, "T6Options"], [300, "ColorResponseUnit"], [320, "ColorMap"], [324, "TileOffsets"], [325, "TileByteCounts"], [326, "BadFaxLines"], [327, "CleanFaxData"], [328, "ConsecutiveBadFaxLines"], [330, "SubIFD"], [333, "InkNames"], [334, "NumberofInks"], [336, "DotRange"], [338, "ExtraSamples"], [339, "SampleFormat"], [340, "SMinSampleValue"], [341, "SMaxSampleValue"], [342, "TransferRange"], [343, "ClipPath"], [344, "XClipPathUnits"], [345, "YClipPathUnits"], [346, "Indexed"], [347, "JPEGTables"], [351, "OPIProxy"], [400, "GlobalParametersIFD"], [401, "ProfileType"], [402, "FaxProfile"], [403, "CodingMethods"], [404, "VersionYear"], [405, "ModeNumber"], [433, "Decode"], [434, "DefaultImageColor"], [435, "T82Options"], [437, "JPEGTables"], [512, "JPEGProc"], [515, "JPEGRestartInterval"], [517, "JPEGLosslessPredictors"], [518, "JPEGPointTransforms"], [519, "JPEGQTables"], [520, "JPEGDCTables"], [521, "JPEGACTables"], [559, "StripRowCounts"], [999, "USPTOMiscellaneous"], [18247, "XP_DIP_XML"], [18248, "StitchInfo"], [28672, "SonyRawFileType"], [28688, "SonyToneCurve"], [28721, "VignettingCorrection"], [28722, "VignettingCorrParams"], [28724, "ChromaticAberrationCorrection"], [28725, "ChromaticAberrationCorrParams"], [28726, "DistortionCorrection"], [28727, "DistortionCorrParams"], [29895, "SonyCropTopLeft"], [29896, "SonyCropSize"], [32781, "ImageID"], [32931, "WangTag1"], [32932, "WangAnnotation"], [32933, "WangTag3"], [32934, "WangTag4"], [32953, "ImageReferencePoints"], [32954, "RegionXformTackPoint"], [32955, "WarpQuadrilateral"], [32956, "AffineTransformMat"], [32995, "Matteing"], [32996, "DataType"], [32997, "ImageDepth"], [32998, "TileDepth"], [33300, "ImageFullWidth"], [33301, "ImageFullHeight"], [33302, "TextureFormat"], [33303, "WrapModes"], [33304, "FovCot"], [33305, "MatrixWorldToScreen"], [33306, "MatrixWorldToCamera"], [33405, "Model2"], [33421, "CFARepeatPatternDim"], [33422, "CFAPattern2"], [33423, "BatteryLevel"], [33424, "KodakIFD"], [33445, "MDFileTag"], [33446, "MDScalePixel"], [33447, "MDColorTable"], [33448, "MDLabName"], [33449, "MDSampleInfo"], [33450, "MDPrepDate"], [33451, "MDPrepTime"], [33452, "MDFileUnits"], [33589, "AdventScale"], [33590, "AdventRevision"], [33628, "UIC1Tag"], [33629, "UIC2Tag"], [33630, "UIC3Tag"], [33631, "UIC4Tag"], [33918, "IntergraphPacketData"], [33919, "IntergraphFlagRegisters"], [33921, "INGRReserved"], [34016, "Site"], [34017, "ColorSequence"], [34018, "IT8Header"], [34019, "RasterPadding"], [34020, "BitsPerRunLength"], [34021, "BitsPerExtendedRunLength"], [34022, "ColorTable"], [34023, "ImageColorIndicator"], [34024, "BackgroundColorIndicator"], [34025, "ImageColorValue"], [34026, "BackgroundColorValue"], [34027, "PixelIntensityRange"], [34028, "TransparencyIndicator"], [34029, "ColorCharacterization"], [34030, "HCUsage"], [34031, "TrapIndicator"], [34032, "CMYKEquivalent"], [34152, "AFCP_IPTC"], [34232, "PixelMagicJBIGOptions"], [34263, "JPLCartoIFD"], [34306, "WB_GRGBLevels"], [34310, "LeafData"], [34687, "TIFF_FXExtensions"], [34688, "MultiProfiles"], [34689, "SharedData"], [34690, "T88Options"], [34732, "ImageLayer"], [34750, "JBIGOptions"], [34856, "Opto-ElectricConvFactor"], [34857, "Interlace"], [34908, "FaxRecvParams"], [34909, "FaxSubAddress"], [34910, "FaxRecvTime"], [34929, "FedexEDR"], [34954, "LeafSubIFD"], [37387, "FlashEnergy"], [37388, "SpatialFrequencyResponse"], [37389, "Noise"], [37390, "FocalPlaneXResolution"], [37391, "FocalPlaneYResolution"], [37392, "FocalPlaneResolutionUnit"], [37397, "ExposureIndex"], [37398, "TIFF-EPStandardID"], [37399, "SensingMethod"], [37434, "CIP3DataFile"], [37435, "CIP3Sheet"], [37436, "CIP3Side"], [37439, "StoNits"], [37679, "MSDocumentText"], [37680, "MSPropertySetStorage"], [37681, "MSDocumentTextPosition"], [37724, "ImageSourceData"], [40965, "InteropIFD"], [40976, "SamsungRawPointersOffset"], [40977, "SamsungRawPointersLength"], [41217, "SamsungRawByteOrder"], [41218, "SamsungRawUnknown"], [41484, "SpatialFrequencyResponse"], [41485, "Noise"], [41489, "ImageNumber"], [41490, "SecurityClassification"], [41491, "ImageHistory"], [41494, "TIFF-EPStandardID"], [41995, "DeviceSettingDescription"], [42112, "GDALMetadata"], [42113, "GDALNoData"], [44992, "ExpandSoftware"], [44993, "ExpandLens"], [44994, "ExpandFilm"], [44995, "ExpandFilterLens"], [44996, "ExpandScanner"], [44997, "ExpandFlashLamp"], [46275, "HasselbladRawImage"], [48129, "PixelFormat"], [48130, "Transformation"], [48131, "Uncompressed"], [48132, "ImageType"], [48256, "ImageWidth"], [48257, "ImageHeight"], [48258, "WidthResolution"], [48259, "HeightResolution"], [48320, "ImageOffset"], [48321, "ImageByteCount"], [48322, "AlphaOffset"], [48323, "AlphaByteCount"], [48324, "ImageDataDiscard"], [48325, "AlphaDataDiscard"], [50215, "OceScanjobDesc"], [50216, "OceApplicationSelector"], [50217, "OceIDNumber"], [50218, "OceImageLogic"], [50255, "Annotations"], [50459, "HasselbladExif"], [50547, "OriginalFileName"], [50560, "USPTOOriginalContentType"], [50656, "CR2CFAPattern"], [50710, "CFAPlaneColor"], [50711, "CFALayout"], [50712, "LinearizationTable"], [50713, "BlackLevelRepeatDim"], [50714, "BlackLevel"], [50715, "BlackLevelDeltaH"], [50716, "BlackLevelDeltaV"], [50717, "WhiteLevel"], [50718, "DefaultScale"], [50719, "DefaultCropOrigin"], [50720, "DefaultCropSize"], [50733, "BayerGreenSplit"], [50737, "ChromaBlurRadius"], [50738, "AntiAliasStrength"], [50752, "RawImageSegmentation"], [50780, "BestQualityScale"], [50784, "AliasLayerMetadata"], [50829, "ActiveArea"], [50830, "MaskedAreas"], [50935, "NoiseReductionApplied"], [50974, "SubTileBlockSize"], [50975, "RowInterleaveFactor"], [51008, "OpcodeList1"], [51009, "OpcodeList2"], [51022, "OpcodeList3"], [51041, "NoiseProfile"], [51114, "CacheVersion"], [51125, "DefaultUserCrop"], [51157, "NikonNEFInfo"], [65024, "KdcIFD"]]; + F(E, "ifd0", ct), F(E, "exif", ct), U(B, "gps", [[23, { M: "Magnetic North", T: "True North" }], [25, { K: "Kilometers", M: "Miles", N: "Nautical Miles" }]]); + var ft = class extends re2 { + static canHandle(e3, t2) { + return 224 === e3.getUint8(t2 + 1) && 1246120262 === e3.getUint32(t2 + 4) && 0 === e3.getUint8(t2 + 8); } - function hideLayer() { - throttledRedraw.cancel(); - editOff(); + parse() { + return this.parseTags(), this.translate(), this.output; } - function editOn() { - layer.style("display", "block"); + parseTags() { + this.raw = /* @__PURE__ */ new Map([[0, this.chunk.getUint16(0)], [2, this.chunk.getUint8(2)], [3, this.chunk.getUint16(3)], [5, this.chunk.getUint16(5)], [7, this.chunk.getUint8(7)], [8, this.chunk.getUint8(8)]]); } - function editOff() { - layer.selectAll(".icon-sign").remove(); - layer.style("display", "none"); + }; + c(ft, "type", "jfif"), c(ft, "headerLength", 9), T.set("jfif", ft), U(E, "jfif", [[0, "JFIFVersion"], [2, "ResolutionUnit"], [3, "XResolution"], [5, "YResolution"], [7, "ThumbnailWidth"], [8, "ThumbnailHeight"]]); + var dt = class extends re2 { + parse() { + return this.parseTags(), this.translate(), this.output; } - function click(d3_event, d2) { - const service = getService(); - if (!service) - return; - context.map().centerEase(d2.loc); - const selectedImageId = service.getActiveImage() && service.getActiveImage().id; - service.getDetections(d2.id).then((detections) => { - if (detections.length) { - const imageId = detections[0].image.id; - if (imageId === selectedImageId) { - service.highlightDetection(detections[0]).selectImage(context, imageId); - } else { - service.ensureViewerLoaded(context).then(function() { - service.highlightDetection(detections[0]).selectImage(context, imageId).showViewer(context); - }); - } - } - }); + parseTags() { + this.raw = new Map([[0, this.chunk.getUint32(0)], [4, this.chunk.getUint32(4)], [8, this.chunk.getUint8(8)], [9, this.chunk.getUint8(9)], [10, this.chunk.getUint8(10)], [11, this.chunk.getUint8(11)], [12, this.chunk.getUint8(12)], ...Array.from(this.raw)]); } - function filterData(detectedFeatures) { - var fromDate = context.photos().fromDate(); - var toDate = context.photos().toDate(); - if (fromDate) { - var fromTimestamp = new Date(fromDate).getTime(); - detectedFeatures = detectedFeatures.filter(function(feature3) { - return new Date(feature3.last_seen_at).getTime() >= fromTimestamp; - }); - } - if (toDate) { - var toTimestamp = new Date(toDate).getTime(); - detectedFeatures = detectedFeatures.filter(function(feature3) { - return new Date(feature3.first_seen_at).getTime() <= toTimestamp; - }); - } - return detectedFeatures; + }; + c(dt, "type", "ihdr"), T.set("ihdr", dt), U(E, "ihdr", [[0, "ImageWidth"], [4, "ImageHeight"], [8, "BitDepth"], [9, "ColorType"], [10, "Compression"], [11, "Filter"], [12, "Interlace"]]), U(B, "ihdr", [[9, { 0: "Grayscale", 2: "RGB", 3: "Palette", 4: "Grayscale with Alpha", 6: "RGB with Alpha", DEFAULT: "Unknown" }], [10, { 0: "Deflate/Inflate", DEFAULT: "Unknown" }], [11, { 0: "Adaptive", DEFAULT: "Unknown" }], [12, { 0: "Noninterlaced", 1: "Adam7 Interlace", DEFAULT: "Unknown" }]]); + var pt = class extends re2 { + static canHandle(e3, t2) { + return 226 === e3.getUint8(t2 + 1) && 1229144927 === e3.getUint32(t2 + 4); } - function update() { - const service = getService(); - let data = service ? service.signs(projection2) : []; - data = filterData(data); - const transform2 = svgPointTransform(projection2); - const signs = layer.selectAll(".icon-sign").data(data, function(d2) { - return d2.id; - }); - signs.exit().remove(); - const enter = signs.enter().append("g").attr("class", "icon-sign icon-detected").on("click", click); - enter.append("use").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px").attr("xlink:href", function(d2) { - return "#" + d2.value; - }); - enter.append("rect").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px"); - signs.merge(enter).attr("transform", transform2); + static findPosition(e3, t2) { + let i3 = super.findPosition(e3, t2); + return i3.chunkNumber = e3.getUint8(t2 + 16), i3.chunkCount = e3.getUint8(t2 + 17), i3.multiSegment = i3.chunkCount > 1, i3; } - function drawSigns(selection2) { - const enabled = svgMapillarySigns.enabled; - const service = getService(); - layer = selection2.selectAll(".layer-mapillary-signs").data(service ? [0] : []); - layer.exit().remove(); - layer = layer.enter().append("g").attr("class", "layer-mapillary-signs layer-mapillary-detections").style("display", enabled ? "block" : "none").merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadSigns(projection2); - service.showSignDetections(true); - } else { - editOff(); - } - } else if (service) { - service.showSignDetections(false); + static handleMultiSegments(e3) { + return function(e4) { + let t2 = function(e6) { + let t3 = e6[0].constructor, i3 = 0; + for (let t4 of e6) + i3 += t4.length; + let n3 = new t3(i3), s2 = 0; + for (let t4 of e6) + n3.set(t4, s2), s2 += t4.length; + return n3; + }(e4.map((e6) => e6.chunk.toUint8())); + return new I(t2); + }(e3); + } + parse() { + return this.raw = /* @__PURE__ */ new Map(), this.parseHeader(), this.parseTags(), this.translate(), this.output; + } + parseHeader() { + let { raw: e3 } = this; + this.chunk.byteLength < 84 && g2("ICC header is too short"); + for (let [t2, i3] of Object.entries(gt)) { + t2 = parseInt(t2, 10); + let n3 = i3(this.chunk, t2); + "\0\0\0\0" !== n3 && e3.set(t2, n3); } } - drawSigns.enabled = function(_2) { - if (!arguments.length) - return svgMapillarySigns.enabled; - svgMapillarySigns.enabled = _2; - if (svgMapillarySigns.enabled) { - showLayer(); - context.photos().on("change.mapillary_signs", update); - } else { - hideLayer(); - context.photos().on("change.mapillary_signs", null); + parseTags() { + let e3, t2, i3, n3, s2, { raw: r2 } = this, a2 = this.chunk.getUint32(128), o2 = 132, l2 = this.chunk.byteLength; + for (; a2--; ) { + if (e3 = this.chunk.getString(o2, 4), t2 = this.chunk.getUint32(o2 + 4), i3 = this.chunk.getUint32(o2 + 8), n3 = this.chunk.getString(t2, 4), t2 + i3 > l2) + return void console.warn("reached the end of the first ICC chunk. Enable options.tiff.multiSegment to read all ICC segments."); + s2 = this.parseTag(n3, t2, i3), void 0 !== s2 && "\0\0\0\0" !== s2 && r2.set(e3, s2), o2 += 12; } - dispatch14.call("change"); - return this; - }; - drawSigns.supported = function() { - return !!getService(); - }; - drawSigns.rendered = function(zoom) { - return zoom >= minZoom4; - }; - init2(); - return drawSigns; - } - - // modules/svg/mapillary_map_features.js - function svgMapillaryMapFeatures(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - const minZoom4 = 12; - let layer = select_default2(null); - let _mapillary; - function init2() { - if (svgMapillaryMapFeatures.initialized) - return; - svgMapillaryMapFeatures.enabled = false; - svgMapillaryMapFeatures.initialized = true; } - function getService() { - if (services.mapillary && !_mapillary) { - _mapillary = services.mapillary; - _mapillary.event.on("loadedMapFeatures", throttledRedraw); - } else if (!services.mapillary && _mapillary) { - _mapillary = null; + parseTag(e3, t2, i3) { + switch (e3) { + case "desc": + return this.parseDesc(t2); + case "mluc": + return this.parseMluc(t2); + case "text": + return this.parseText(t2, i3); + case "sig ": + return this.parseSig(t2); } - return _mapillary; + if (!(t2 + i3 > this.chunk.byteLength)) + return this.chunk.getUint8Array(t2, i3); } - function showLayer() { - const service = getService(); - if (!service) - return; - service.loadObjectResources(context); - editOn(); + parseDesc(e3) { + let t2 = this.chunk.getUint32(e3 + 8) - 1; + return m(this.chunk.getString(e3 + 12, t2)); } - function hideLayer() { - throttledRedraw.cancel(); - editOff(); + parseText(e3, t2) { + return m(this.chunk.getString(e3 + 8, t2 - 8)); } - function editOn() { - layer.style("display", "block"); + parseSig(e3) { + return m(this.chunk.getString(e3 + 8, 4)); } - function editOff() { - layer.selectAll(".icon-map-feature").remove(); - layer.style("display", "none"); + parseMluc(e3) { + let { chunk: t2 } = this, i3 = t2.getUint32(e3 + 8), n3 = t2.getUint32(e3 + 12), s2 = e3 + 16, r2 = []; + for (let a2 = 0; a2 < i3; a2++) { + let i4 = t2.getString(s2 + 0, 2), a3 = t2.getString(s2 + 2, 2), o2 = t2.getUint32(s2 + 4), l2 = t2.getUint32(s2 + 8) + e3, h2 = m(t2.getUnicodeString(l2, o2)); + r2.push({ lang: i4, country: a3, text: h2 }), s2 += n3; + } + return 1 === i3 ? r2[0].text : r2; } - function click(d3_event, d2) { - const service = getService(); - if (!service) - return; - context.map().centerEase(d2.loc); - const selectedImageId = service.getActiveImage() && service.getActiveImage().id; - service.getDetections(d2.id).then((detections) => { - if (detections.length) { - const imageId = detections[0].image.id; - if (imageId === selectedImageId) { - service.highlightDetection(detections[0]).selectImage(context, imageId); - } else { - service.ensureViewerLoaded(context).then(function() { - service.highlightDetection(detections[0]).selectImage(context, imageId).showViewer(context); - }); - } - } - }); + translateValue(e3, t2) { + return "string" == typeof e3 ? t2[e3] || t2[e3.toLowerCase()] || e3 : t2[e3] || e3; } - function filterData(detectedFeatures) { - const fromDate = context.photos().fromDate(); - const toDate = context.photos().toDate(); - if (fromDate) { - detectedFeatures = detectedFeatures.filter(function(feature3) { - return new Date(feature3.last_seen_at).getTime() >= new Date(fromDate).getTime(); - }); - } - if (toDate) { - detectedFeatures = detectedFeatures.filter(function(feature3) { - return new Date(feature3.first_seen_at).getTime() <= new Date(toDate).getTime(); - }); - } - return detectedFeatures; + }; + c(pt, "type", "icc"), c(pt, "multiSegment", true), c(pt, "headerLength", 18); + var gt = { 4: mt, 8: function(e3, t2) { + return [e3.getUint8(t2), e3.getUint8(t2 + 1) >> 4, e3.getUint8(t2 + 1) % 16].map((e4) => e4.toString(10)).join("."); + }, 12: mt, 16: mt, 20: mt, 24: function(e3, t2) { + const i3 = e3.getUint16(t2), n3 = e3.getUint16(t2 + 2) - 1, s2 = e3.getUint16(t2 + 4), r2 = e3.getUint16(t2 + 6), a2 = e3.getUint16(t2 + 8), o2 = e3.getUint16(t2 + 10); + return new Date(Date.UTC(i3, n3, s2, r2, a2, o2)); + }, 36: mt, 40: mt, 48: mt, 52: mt, 64: (e3, t2) => e3.getUint32(t2), 80: mt }; + function mt(e3, t2) { + return m(e3.getString(t2, 4)); + } + T.set("icc", pt), U(E, "icc", [[4, "ProfileCMMType"], [8, "ProfileVersion"], [12, "ProfileClass"], [16, "ColorSpaceData"], [20, "ProfileConnectionSpace"], [24, "ProfileDateTime"], [36, "ProfileFileSignature"], [40, "PrimaryPlatform"], [44, "CMMFlags"], [48, "DeviceManufacturer"], [52, "DeviceModel"], [56, "DeviceAttributes"], [64, "RenderingIntent"], [68, "ConnectionSpaceIlluminant"], [80, "ProfileCreator"], [84, "ProfileID"], ["Header", "ProfileHeader"], ["MS00", "WCSProfiles"], ["bTRC", "BlueTRC"], ["bXYZ", "BlueMatrixColumn"], ["bfd", "UCRBG"], ["bkpt", "MediaBlackPoint"], ["calt", "CalibrationDateTime"], ["chad", "ChromaticAdaptation"], ["chrm", "Chromaticity"], ["ciis", "ColorimetricIntentImageState"], ["clot", "ColorantTableOut"], ["clro", "ColorantOrder"], ["clrt", "ColorantTable"], ["cprt", "ProfileCopyright"], ["crdi", "CRDInfo"], ["desc", "ProfileDescription"], ["devs", "DeviceSettings"], ["dmdd", "DeviceModelDesc"], ["dmnd", "DeviceMfgDesc"], ["dscm", "ProfileDescriptionML"], ["fpce", "FocalPlaneColorimetryEstimates"], ["gTRC", "GreenTRC"], ["gXYZ", "GreenMatrixColumn"], ["gamt", "Gamut"], ["kTRC", "GrayTRC"], ["lumi", "Luminance"], ["meas", "Measurement"], ["meta", "Metadata"], ["mmod", "MakeAndModel"], ["ncl2", "NamedColor2"], ["ncol", "NamedColor"], ["ndin", "NativeDisplayInfo"], ["pre0", "Preview0"], ["pre1", "Preview1"], ["pre2", "Preview2"], ["ps2i", "PS2RenderingIntent"], ["ps2s", "PostScript2CSA"], ["psd0", "PostScript2CRD0"], ["psd1", "PostScript2CRD1"], ["psd2", "PostScript2CRD2"], ["psd3", "PostScript2CRD3"], ["pseq", "ProfileSequenceDesc"], ["psid", "ProfileSequenceIdentifier"], ["psvm", "PS2CRDVMSize"], ["rTRC", "RedTRC"], ["rXYZ", "RedMatrixColumn"], ["resp", "OutputResponse"], ["rhoc", "ReflectionHardcopyOrigColorimetry"], ["rig0", "PerceptualRenderingIntentGamut"], ["rig2", "SaturationRenderingIntentGamut"], ["rpoc", "ReflectionPrintOutputColorimetry"], ["sape", "SceneAppearanceEstimates"], ["scoe", "SceneColorimetryEstimates"], ["scrd", "ScreeningDesc"], ["scrn", "Screening"], ["targ", "CharTarget"], ["tech", "Technology"], ["vcgt", "VideoCardGamma"], ["view", "ViewingConditions"], ["vued", "ViewingCondDesc"], ["wtpt", "MediaWhitePoint"]]); + var St = { "4d2p": "Erdt Systems", AAMA: "Aamazing Technologies", ACER: "Acer", ACLT: "Acolyte Color Research", ACTI: "Actix Sytems", ADAR: "Adara Technology", ADBE: "Adobe", ADI: "ADI Systems", AGFA: "Agfa Graphics", ALMD: "Alps Electric", ALPS: "Alps Electric", ALWN: "Alwan Color Expertise", AMTI: "Amiable Technologies", AOC: "AOC International", APAG: "Apago", APPL: "Apple Computer", AST: "AST", "AT&T": "AT&T", BAEL: "BARBIERI electronic", BRCO: "Barco NV", BRKP: "Breakpoint", BROT: "Brother", BULL: "Bull", BUS: "Bus Computer Systems", "C-IT": "C-Itoh", CAMR: "Intel", CANO: "Canon", CARR: "Carroll Touch", CASI: "Casio", CBUS: "Colorbus PL", CEL: "Crossfield", CELx: "Crossfield", CGS: "CGS Publishing Technologies International", CHM: "Rochester Robotics", CIGL: "Colour Imaging Group, London", CITI: "Citizen", CL00: "Candela", CLIQ: "Color IQ", CMCO: "Chromaco", CMiX: "CHROMiX", COLO: "Colorgraphic Communications", COMP: "Compaq", COMp: "Compeq/Focus Technology", CONR: "Conrac Display Products", CORD: "Cordata Technologies", CPQ: "Compaq", CPRO: "ColorPro", CRN: "Cornerstone", CTX: "CTX International", CVIS: "ColorVision", CWC: "Fujitsu Laboratories", DARI: "Darius Technology", DATA: "Dataproducts", DCP: "Dry Creek Photo", DCRC: "Digital Contents Resource Center, Chung-Ang University", DELL: "Dell Computer", DIC: "Dainippon Ink and Chemicals", DICO: "Diconix", DIGI: "Digital", "DL&C": "Digital Light & Color", DPLG: "Doppelganger", DS: "Dainippon Screen", DSOL: "DOOSOL", DUPN: "DuPont", EPSO: "Epson", ESKO: "Esko-Graphics", ETRI: "Electronics and Telecommunications Research Institute", EVER: "Everex Systems", EXAC: "ExactCODE", Eizo: "Eizo", FALC: "Falco Data Products", FF: "Fuji Photo Film", FFEI: "FujiFilm Electronic Imaging", FNRD: "Fnord Software", FORA: "Fora", FORE: "Forefront Technology", FP: "Fujitsu", FPA: "WayTech Development", FUJI: "Fujitsu", FX: "Fuji Xerox", GCC: "GCC Technologies", GGSL: "Global Graphics Software", GMB: "Gretagmacbeth", GMG: "GMG", GOLD: "GoldStar Technology", GOOG: "Google", GPRT: "Giantprint", GTMB: "Gretagmacbeth", GVC: "WayTech Development", GW2K: "Sony", HCI: "HCI", HDM: "Heidelberger Druckmaschinen", HERM: "Hermes", HITA: "Hitachi America", HP: "Hewlett-Packard", HTC: "Hitachi", HiTi: "HiTi Digital", IBM: "IBM", IDNT: "Scitex", IEC: "Hewlett-Packard", IIYA: "Iiyama North America", IKEG: "Ikegami Electronics", IMAG: "Image Systems", IMI: "Ingram Micro", INTC: "Intel", INTL: "N/A (INTL)", INTR: "Intra Electronics", IOCO: "Iocomm International Technology", IPS: "InfoPrint Solutions Company", IRIS: "Scitex", ISL: "Ichikawa Soft Laboratory", ITNL: "N/A (ITNL)", IVM: "IVM", IWAT: "Iwatsu Electric", Idnt: "Scitex", Inca: "Inca Digital Printers", Iris: "Scitex", JPEG: "Joint Photographic Experts Group", JSFT: "Jetsoft Development", JVC: "JVC Information Products", KART: "Scitex", KFC: "KFC Computek Components", KLH: "KLH Computers", KMHD: "Konica Minolta", KNCA: "Konica", KODA: "Kodak", KYOC: "Kyocera", Kart: "Scitex", LCAG: "Leica", LCCD: "Leeds Colour", LDAK: "Left Dakota", LEAD: "Leading Technology", LEXM: "Lexmark International", LINK: "Link Computer", LINO: "Linotronic", LITE: "Lite-On", Leaf: "Leaf", Lino: "Linotronic", MAGC: "Mag Computronic", MAGI: "MAG Innovision", MANN: "Mannesmann", MICN: "Micron Technology", MICR: "Microtek", MICV: "Microvitec", MINO: "Minolta", MITS: "Mitsubishi Electronics America", MITs: "Mitsuba", MNLT: "Minolta", MODG: "Modgraph", MONI: "Monitronix", MONS: "Monaco Systems", MORS: "Morse Technology", MOTI: "Motive Systems", MSFT: "Microsoft", MUTO: "MUTOH INDUSTRIES", Mits: "Mitsubishi Electric", NANA: "NANAO", NEC: "NEC", NEXP: "NexPress Solutions", NISS: "Nissei Sangyo America", NKON: "Nikon", NONE: "none", OCE: "Oce Technologies", OCEC: "OceColor", OKI: "Oki", OKID: "Okidata", OKIP: "Okidata", OLIV: "Olivetti", OLYM: "Olympus", ONYX: "Onyx Graphics", OPTI: "Optiquest", PACK: "Packard Bell", PANA: "Matsushita Electric Industrial", PANT: "Pantone", PBN: "Packard Bell", PFU: "PFU", PHIL: "Philips Consumer Electronics", PNTX: "HOYA", POne: "Phase One A/S", PREM: "Premier Computer Innovations", PRIN: "Princeton Graphic Systems", PRIP: "Princeton Publishing Labs", QLUX: "Hong Kong", QMS: "QMS", QPCD: "QPcard AB", QUAD: "QuadLaser", QUME: "Qume", RADI: "Radius", RDDx: "Integrated Color Solutions", RDG: "Roland DG", REDM: "REDMS Group", RELI: "Relisys", RGMS: "Rolf Gierling Multitools", RICO: "Ricoh", RNLD: "Edmund Ronald", ROYA: "Royal", RPC: "Ricoh Printing Systems", RTL: "Royal Information Electronics", SAMP: "Sampo", SAMS: "Samsung", SANT: "Jaime Santana Pomares", SCIT: "Scitex", SCRN: "Dainippon Screen", SDP: "Scitex", SEC: "Samsung", SEIK: "Seiko Instruments", SEIk: "Seikosha", SGUY: "ScanGuy.com", SHAR: "Sharp Laboratories", SICC: "International Color Consortium", SONY: "Sony", SPCL: "SpectraCal", STAR: "Star", STC: "Sampo Technology", Scit: "Scitex", Sdp: "Scitex", Sony: "Sony", TALO: "Talon Technology", TAND: "Tandy", TATU: "Tatung", TAXA: "TAXAN America", TDS: "Tokyo Denshi Sekei", TECO: "TECO Information Systems", TEGR: "Tegra", TEKT: "Tektronix", TI: "Texas Instruments", TMKR: "TypeMaker", TOSB: "Toshiba", TOSH: "Toshiba", TOTK: "TOTOKU ELECTRIC", TRIU: "Triumph", TSBT: "Toshiba", TTX: "TTX Computer Products", TVM: "TVM Professional Monitor", TW: "TW Casper", ULSX: "Ulead Systems", UNIS: "Unisys", UTZF: "Utz Fehlau & Sohn", VARI: "Varityper", VIEW: "Viewsonic", VISL: "Visual communication", VIVO: "Vivo Mobile Communication", WANG: "Wang", WLBR: "Wilbur Imaging", WTG2: "Ware To Go", WYSE: "WYSE Technology", XERX: "Xerox", XRIT: "X-Rite", ZRAN: "Zoran", Zebr: "Zebra Technologies", appl: "Apple Computer", bICC: "basICColor", berg: "bergdesign", ceyd: "Integrated Color Solutions", clsp: "MacDermid ColorSpan", ds: "Dainippon Screen", dupn: "DuPont", ffei: "FujiFilm Electronic Imaging", flux: "FluxData", iris: "Scitex", kart: "Scitex", lcms: "Little CMS", lino: "Linotronic", none: "none", ob4d: "Erdt Systems", obic: "Medigraph", quby: "Qubyx Sarl", scit: "Scitex", scrn: "Dainippon Screen", sdp: "Scitex", siwi: "SIWI GRAFIKA", yxym: "YxyMaster" }; + var Ct = { scnr: "Scanner", mntr: "Monitor", prtr: "Printer", link: "Device Link", abst: "Abstract", spac: "Color Space Conversion Profile", nmcl: "Named Color", cenc: "ColorEncodingSpace profile", mid: "MultiplexIdentification profile", mlnk: "MultiplexLink profile", mvis: "MultiplexVisualization profile", nkpf: "Nikon Input Device Profile (NON-STANDARD!)" }; + U(B, "icc", [[4, St], [12, Ct], [40, Object.assign({}, St, Ct)], [48, St], [80, St], [64, { 0: "Perceptual", 1: "Relative Colorimetric", 2: "Saturation", 3: "Absolute Colorimetric" }], ["tech", { amd: "Active Matrix Display", crt: "Cathode Ray Tube Display", kpcd: "Photo CD", pmd: "Passive Matrix Display", dcam: "Digital Camera", dcpj: "Digital Cinema Projector", dmpc: "Digital Motion Picture Camera", dsub: "Dye Sublimation Printer", epho: "Electrophotographic Printer", esta: "Electrostatic Printer", flex: "Flexography", fprn: "Film Writer", fscn: "Film Scanner", grav: "Gravure", ijet: "Ink Jet Printer", imgs: "Photo Image Setter", mpfr: "Motion Picture Film Recorder", mpfs: "Motion Picture Film Scanner", offs: "Offset Lithography", pjtv: "Projection Television", rpho: "Photographic Paper Printer", rscn: "Reflective Scanner", silk: "Silkscreen", twax: "Thermal Wax Printer", vidc: "Video Camera", vidm: "Video Monitor" }]]); + var yt = class extends re2 { + static canHandle(e3, t2, i3) { + return 237 === e3.getUint8(t2 + 1) && "Photoshop" === e3.getString(t2 + 4, 9) && void 0 !== this.containsIptc8bim(e3, t2, i3); } - function update() { - const service = getService(); - let data = service ? service.mapFeatures(projection2) : []; - data = filterData(data); - const transform2 = svgPointTransform(projection2); - const mapFeatures = layer.selectAll(".icon-map-feature").data(data, function(d2) { - return d2.id; - }); - mapFeatures.exit().remove(); - const enter = mapFeatures.enter().append("g").attr("class", "icon-map-feature icon-detected").on("click", click); - enter.append("title").text(function(d2) { - var id2 = d2.value.replace(/--/g, ".").replace(/-/g, "_"); - return _t("mapillary_map_features." + id2); - }); - enter.append("use").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px").attr("xlink:href", function(d2) { - if (d2.value === "object--billboard") { - return "#object--sign--advertisement"; - } - return "#" + d2.value; - }); - enter.append("rect").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px"); - mapFeatures.merge(enter).attr("transform", transform2); + static headerLength(e3, t2, i3) { + let n3, s2 = this.containsIptc8bim(e3, t2, i3); + if (void 0 !== s2) + return n3 = e3.getUint8(t2 + s2 + 7), n3 % 2 != 0 && (n3 += 1), 0 === n3 && (n3 = 4), s2 + 8 + n3; } - function drawMapFeatures(selection2) { - const enabled = svgMapillaryMapFeatures.enabled; - const service = getService(); - layer = selection2.selectAll(".layer-mapillary-map-features").data(service ? [0] : []); - layer.exit().remove(); - layer = layer.enter().append("g").attr("class", "layer-mapillary-map-features layer-mapillary-detections").style("display", enabled ? "block" : "none").merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadMapFeatures(projection2); - service.showFeatureDetections(true); - } else { - editOff(); - } - } else if (service) { - service.showFeatureDetections(false); - } + static containsIptc8bim(e3, t2, i3) { + for (let n3 = 0; n3 < i3; n3++) + if (this.isIptcSegmentHead(e3, t2 + n3)) + return n3; } - drawMapFeatures.enabled = function(_2) { - if (!arguments.length) - return svgMapillaryMapFeatures.enabled; - svgMapillaryMapFeatures.enabled = _2; - if (svgMapillaryMapFeatures.enabled) { - showLayer(); - context.photos().on("change.mapillary_map_features", update); - } else { - hideLayer(); - context.photos().on("change.mapillary_map_features", null); + static isIptcSegmentHead(e3, t2) { + return 56 === e3.getUint8(t2) && 943868237 === e3.getUint32(t2) && 1028 === e3.getUint16(t2 + 4); + } + parse() { + let { raw: e3 } = this, t2 = this.chunk.byteLength - 1, i3 = false; + for (let n3 = 0; n3 < t2; n3++) + if (28 === this.chunk.getUint8(n3) && 2 === this.chunk.getUint8(n3 + 1)) { + i3 = true; + let t3 = this.chunk.getUint16(n3 + 3), s2 = this.chunk.getUint8(n3 + 2), r2 = this.chunk.getLatin1String(n3 + 5, t3); + e3.set(s2, this.pluralizeValue(e3.get(s2), r2)), n3 += 4 + t3; + } else if (i3) + break; + return this.translate(), this.output; + } + pluralizeValue(e3, t2) { + return void 0 !== e3 ? e3 instanceof Array ? (e3.push(t2), e3) : [e3, t2] : t2; + } + }; + c(yt, "type", "iptc"), c(yt, "translateValues", false), c(yt, "reviveValues", false), T.set("iptc", yt), U(E, "iptc", [[0, "ApplicationRecordVersion"], [3, "ObjectTypeReference"], [4, "ObjectAttributeReference"], [5, "ObjectName"], [7, "EditStatus"], [8, "EditorialUpdate"], [10, "Urgency"], [12, "SubjectReference"], [15, "Category"], [20, "SupplementalCategories"], [22, "FixtureIdentifier"], [25, "Keywords"], [26, "ContentLocationCode"], [27, "ContentLocationName"], [30, "ReleaseDate"], [35, "ReleaseTime"], [37, "ExpirationDate"], [38, "ExpirationTime"], [40, "SpecialInstructions"], [42, "ActionAdvised"], [45, "ReferenceService"], [47, "ReferenceDate"], [50, "ReferenceNumber"], [55, "DateCreated"], [60, "TimeCreated"], [62, "DigitalCreationDate"], [63, "DigitalCreationTime"], [65, "OriginatingProgram"], [70, "ProgramVersion"], [75, "ObjectCycle"], [80, "Byline"], [85, "BylineTitle"], [90, "City"], [92, "Sublocation"], [95, "State"], [100, "CountryCode"], [101, "Country"], [103, "OriginalTransmissionReference"], [105, "Headline"], [110, "Credit"], [115, "Source"], [116, "CopyrightNotice"], [118, "Contact"], [120, "Caption"], [121, "LocalCaption"], [122, "Writer"], [125, "RasterizedCaption"], [130, "ImageType"], [131, "ImageOrientation"], [135, "LanguageIdentifier"], [150, "AudioType"], [151, "AudioSamplingRate"], [152, "AudioSamplingResolution"], [153, "AudioDuration"], [154, "AudioOutcue"], [184, "JobID"], [185, "MasterDocumentID"], [186, "ShortDocumentID"], [187, "UniqueDocumentID"], [188, "OwnerID"], [200, "ObjectPreviewFileFormat"], [201, "ObjectPreviewFileVersion"], [202, "ObjectPreviewData"], [221, "Prefs"], [225, "ClassifyState"], [228, "SimilarityIndex"], [230, "DocumentNotes"], [231, "DocumentHistory"], [232, "ExifCameraInfo"], [255, "CatalogSets"]]), U(B, "iptc", [[10, { 0: "0 (reserved)", 1: "1 (most urgent)", 2: "2", 3: "3", 4: "4", 5: "5 (normal urgency)", 6: "6", 7: "7", 8: "8 (least urgent)", 9: "9 (user-defined priority)" }], [75, { a: "Morning", b: "Both Morning and Evening", p: "Evening" }], [131, { L: "Landscape", P: "Portrait", S: "Square" }]]); + var full_esm_default = tt; + + // modules/services/plane_photo.js + var dispatch6 = dispatch_default("viewerChanged"); + var _photo; + var _wrapper; + var imgZoom; + var _widthOverflow; + function zoomPan(d3_event) { + let t2 = d3_event.transform; + _photo.call(utilSetTransform, t2.x, t2.y, t2.k); + } + function zoomBeahvior() { + const { width: wrapperWidth, height: wrapperHeight } = _wrapper.node().getBoundingClientRect(); + const { naturalHeight, naturalWidth } = _photo.node(); + const intrinsicRatio = naturalWidth / naturalHeight; + _widthOverflow = wrapperHeight * intrinsicRatio - wrapperWidth; + return zoom_default2().extent([[0, 0], [wrapperWidth, wrapperHeight]]).translateExtent([[0, 0], [wrapperWidth + _widthOverflow, wrapperHeight]]).scaleExtent([1, 15]).on("zoom", zoomPan); + } + function loadImage(selection2, path) { + return new Promise((resolve) => { + selection2.attr("src", path); + selection2.on("load", () => { + resolve(selection2); + }); + }); + } + var plane_photo_default = { + init: async function(context, selection2) { + this.event = utilRebind(this, dispatch6, "on"); + _wrapper = selection2.append("div").attr("class", "photo-frame plane-frame").classed("hide", true); + _photo = _wrapper.append("img").attr("class", "plane-photo"); + context.ui().photoviewer.on("resize.plane", () => { + imgZoom = zoomBeahvior(); + _wrapper.call(imgZoom); + }); + await Promise.resolve(); + return this; + }, + showPhotoFrame: function(context) { + const isHidden = context.selectAll(".photo-frame.plane-frame.hide").size(); + if (isHidden) { + context.selectAll(".photo-frame:not(.plane-frame)").classed("hide", true); + context.selectAll(".photo-frame.plane-frame").classed("hide", false); } - dispatch14.call("change"); return this; - }; - drawMapFeatures.supported = function() { - return !!getService(); - }; - drawMapFeatures.rendered = function(zoom) { - return zoom >= minZoom4; - }; - init2(); - return drawMapFeatures; - } + }, + hidePhotoFrame: function(context) { + context.select("photo-frame.plane-frame").classed("hide", false); + return this; + }, + selectPhoto: function(data, keepOrientation) { + dispatch6.call("viewerChanged"); + loadImage(_photo, ""); + loadImage(_photo, data.image_path).then(() => { + if (!keepOrientation) { + imgZoom = zoomBeahvior(); + _wrapper.call(imgZoom); + _wrapper.call(imgZoom.transform, identity2.translate(-_widthOverflow / 2, 0)); + } + }); + return this; + }, + getYaw: function() { + return 0; + } + }; - // modules/svg/kartaview_images.js - function svgKartaviewImages(projection2, context, dispatch14) { - var throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - var minZoom4 = 12; - var minMarkerZoom = 16; - var minViewfieldZoom2 = 18; - var layer = select_default2(null); - var _kartaview; + // modules/svg/local_photos.js + var _initialized2 = false; + var _enabled2 = false; + var minViewfieldZoom = 16; + function svgLocalPhotos(projection2, context, dispatch14) { + const detected = utilDetect(); + let layer = select_default2(null); + let _fileList; + let _photos = []; + let _idAutoinc = 0; + let _photoFrame; function init2() { - if (svgKartaviewImages.initialized) + if (_initialized2) return; - svgKartaviewImages.enabled = false; - svgKartaviewImages.initialized = true; - } - function getService() { - if (services.kartaview && !_kartaview) { - _kartaview = services.kartaview; - _kartaview.event.on("loadedImages", throttledRedraw); - } else if (!services.kartaview && _kartaview) { - _kartaview = null; + _enabled2 = true; + function over(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + d3_event.dataTransfer.dropEffect = "copy"; } - return _kartaview; + context.container().attr("dropzone", "copy").on("drop.svgLocalPhotos", function(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + if (!detected.filedrop) + return; + drawPhotos.fileList(d3_event.dataTransfer.files, (loaded) => { + if (loaded.length > 0) { + drawPhotos.fitZoom(false); + } + }); + }).on("dragenter.svgLocalPhotos", over).on("dragexit.svgLocalPhotos", over).on("dragover.svgLocalPhotos", over); + _initialized2 = true; } - function showLayer() { - var service = getService(); - if (!service) - return; - editOn(); - layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { - dispatch14.call("change"); + function ensureViewerLoaded(context2) { + if (_photoFrame) { + return Promise.resolve(_photoFrame); + } + const viewer = context2.container().select(".photoviewer").selectAll(".local-photos-wrapper").data([0]); + const viewerEnter = viewer.enter().append("div").attr("class", "photo-wrapper local-photos-wrapper").classed("hide", true); + viewerEnter.append("div").attr("class", "photo-attribution photo-attribution-dual fillD"); + return plane_photo_default.init(context2, viewerEnter).then((planePhotoFrame) => { + _photoFrame = planePhotoFrame; }); } - function hideLayer() { - throttledRedraw.cancel(); - layer.transition().duration(250).style("opacity", 0).on("end", editOff); - } - function editOn() { - layer.style("display", "block"); - } - function editOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); - } - function click(d3_event, d2) { - var service = getService(); - if (!service) - return; - service.ensureViewerLoaded(context).then(function() { - service.selectImage(context, d2.key).showViewer(context); + function click(d3_event, image, zoomTo) { + ensureViewerLoaded(context).then(() => { + const viewer = context.container().select(".photoviewer").datum(image).classed("hide", false); + const viewerWrap = viewer.select(".local-photos-wrapper").classed("hide", false); + const attribution = viewerWrap.selectAll(".photo-attribution").text(""); + if (image.date) { + attribution.append("span").text(image.date.toLocaleString()); + } + if (image.name) { + attribution.append("span").classed("filename", true).text(image.name); + } + _photoFrame.selectPhoto({ image_path: "" }); + image.getSrc().then((src) => { + _photoFrame.selectPhoto({ image_path: src }).showPhotoFrame(viewerWrap); + setStyles(); + }); }); - context.map().centerEase(d2.loc); - } - function mouseover(d3_event, d2) { - var service = getService(); - if (service) - service.setStyles(context, d2); - } - function mouseout() { - var service = getService(); - if (service) - service.setStyles(context, null); - } - function transform2(d2) { - var t2 = svgPointTransform(projection2)(d2); - if (d2.ca) { - t2 += " rotate(" + Math.floor(d2.ca) + ",0,0)"; + if (zoomTo) { + context.map().centerEase(image.loc); } - return t2; } - function filterImages(images) { - var fromDate = context.photos().fromDate(); - var toDate = context.photos().toDate(); - var usernames = context.photos().usernames(); - if (fromDate) { - var fromTimestamp = new Date(fromDate).getTime(); - images = images.filter(function(item) { - return new Date(item.captured_at).getTime() >= fromTimestamp; - }); - } - if (toDate) { - var toTimestamp = new Date(toDate).getTime(); - images = images.filter(function(item) { - return new Date(item.captured_at).getTime() <= toTimestamp; - }); - } - if (usernames) { - images = images.filter(function(item) { - return usernames.indexOf(item.captured_by) !== -1; - }); - } - return images; + function transform2(d2) { + var svgpoint = projection2(d2.loc); + return "translate(" + svgpoint[0] + "," + svgpoint[1] + ")"; } - function filterSequences(sequences) { - var fromDate = context.photos().fromDate(); - var toDate = context.photos().toDate(); - var usernames = context.photos().usernames(); - if (fromDate) { - var fromTimestamp = new Date(fromDate).getTime(); - sequences = sequences.filter(function(image) { - return new Date(image.properties.captured_at).getTime() >= fromTimestamp; - }); - } - if (toDate) { - var toTimestamp = new Date(toDate).getTime(); - sequences = sequences.filter(function(image) { - return new Date(image.properties.captured_at).getTime() <= toTimestamp; - }); - } - if (usernames) { - sequences = sequences.filter(function(image) { - return usernames.indexOf(image.properties.captured_by) !== -1; - }); - } - return sequences; + function setStyles(hovered) { + const viewer = context.container().select(".photoviewer"); + const selected = viewer.empty() ? void 0 : viewer.datum(); + context.container().selectAll(".layer-local-photos .viewfield-group").classed("hovered", (d2) => d2.id === (hovered == null ? void 0 : hovered.id)).classed("highlighted", (d2) => d2.id === (hovered == null ? void 0 : hovered.id) || d2.id === (selected == null ? void 0 : selected.id)).classed("currentView", (d2) => d2.id === (selected == null ? void 0 : selected.id)); } - function update() { - var viewer = context.container().select(".photoviewer"); - var selected = viewer.empty() ? void 0 : viewer.datum(); - var z2 = ~~context.map().zoom(); - var showMarkers = z2 >= minMarkerZoom; - var showViewfields = z2 >= minViewfieldZoom2; - var service = getService(); - var sequences = []; - var images = []; - if (context.photos().showsFlat()) { - sequences = service ? service.sequences(projection2) : []; - images = service && showMarkers ? service.images(projection2) : []; - sequences = filterSequences(sequences); - images = filterImages(images); - } - var traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { - return d2.properties.key; - }); - traces.exit().remove(); - traces = traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); - var groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, function(d2) { - return d2.key; + function display_markers(imageList) { + imageList = imageList.filter((image) => isArray_default(image.loc) && isNumber_default(image.loc[0]) && isNumber_default(image.loc[1])); + const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(imageList, function(d2) { + return d2.id; }); groups.exit().remove(); - var groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); + const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", (d3_event, d2) => setStyles(d2)).on("mouseleave", () => setStyles(null)).on("click", click); groupsEnter.append("g").attr("class", "viewfield-scale"); - var markers = groups.merge(groupsEnter).sort(function(a2, b2) { - return a2 === selected ? 1 : b2 === selected ? -1 : b2.loc[1] - a2.loc[1]; - }).attr("transform", transform2).select(".viewfield-scale"); + const markers = groups.merge(groupsEnter).attr("transform", transform2).select(".viewfield-scale"); markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - var viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + const showViewfields = context.map().zoom() >= minViewfieldZoom; + const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", function() { + var _a2; + const d2 = this.parentNode.__data__; + return "rotate(".concat(Math.round((_a2 = d2.direction) != null ? _a2 : 0), ",0,0),scale(1.5,1.5),translate(-8,-13)"); + }).attr("d", "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z").style("visibility", function() { + const d2 = this.parentNode.__data__; + return isNumber_default(d2.direction) ? "visible" : "hidden"; + }); } - function drawImages(selection2) { - var enabled = svgKartaviewImages.enabled, service = getService(); - layer = selection2.selectAll(".layer-kartaview").data(service ? [0] : []); + function drawPhotos(selection2) { + layer = selection2.selectAll(".layer-local-photos").data(_photos ? [0] : []); layer.exit().remove(); - var layerEnter = layer.enter().append("g").attr("class", "layer-kartaview").style("display", enabled ? "block" : "none"); - layerEnter.append("g").attr("class", "sequences"); + const layerEnter = layer.enter().append("g").attr("class", "layer-local-photos"); layerEnter.append("g").attr("class", "markers"); layer = layerEnter.merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadImages(projection2); - } else { - editOff(); - } + if (_photos) { + display_markers(_photos); } } - drawImages.enabled = function(_2) { - if (!arguments.length) - return svgKartaviewImages.enabled; - svgKartaviewImages.enabled = _2; - if (svgKartaviewImages.enabled) { - showLayer(); - context.photos().on("change.kartaview_images", update); - } else { - hideLayer(); - context.photos().on("change.kartaview_images", null); + function readFileAsDataURL(file) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = (error) => reject(error); + reader.readAsDataURL(file); + }); + } + async function readmultifiles(files, callback) { + const loaded = []; + for (const file of files) { + try { + const exifData = await full_esm_default.parse(file); + const photo = { + id: _idAutoinc++, + name: file.name, + getSrc: () => readFileAsDataURL(file), + file, + loc: [exifData.longitude, exifData.latitude], + direction: exifData.GPSImgDirection, + date: exifData.CreateDate || exifData.DateTimeOriginal || exifData.ModifyDate + }; + loaded.push(photo); + const sameName = _photos.filter((i3) => i3.name === photo.name); + if (sameName.length === 0) { + _photos.push(photo); + } else { + const thisContent = await photo.getSrc(); + const sameNameContent = await Promise.allSettled(sameName.map((i3) => i3.getSrc())); + if (!sameNameContent.some((i3) => i3.value === thisContent)) { + _photos.push(photo); + } + } + } catch (err) { + } } + if (typeof callback === "function") + callback(loaded); dispatch14.call("change"); + } + drawPhotos.setFiles = function(fileList, callback) { + readmultifiles(Array.from(fileList), callback); return this; }; - drawImages.supported = function() { - return !!getService(); + drawPhotos.fileList = function(fileList, callback) { + if (!arguments.length) + return _fileList; + _fileList = fileList; + if (!fileList || !fileList.length) + return this; + drawPhotos.setFiles(_fileList, callback); + return this; }; - drawImages.rendered = function(zoom) { - return zoom >= minZoom4; + drawPhotos.getPhotos = function() { + return _photos; }; - init2(); - return drawImages; - } - - // modules/svg/mapilio_images.js - function svgMapilioImages(projection2, context, dispatch14) { - const throttledRedraw = throttle_default(function() { + drawPhotos.removePhoto = function(id2) { + _photos = _photos.filter((i3) => i3.id !== id2); dispatch14.call("change"); - }, 1e3); - const minZoom4 = 12; - let layer = select_default2(null); - let _mapilio; - const viewFieldZoomLevel = 18; - function init2() { - if (svgMapilioImages.initialized) + return _photos; + }; + drawPhotos.openPhoto = click; + drawPhotos.fitZoom = function(force) { + const coords = _photos.map((image) => image.loc).filter((l2) => isArray_default(l2) && isNumber_default(l2[0]) && isNumber_default(l2[1])); + if (coords.length === 0) return; - svgMapilioImages.enabled = false; - svgMapilioImages.initialized = true; - } - function getService() { - if (services.mapilio && !_mapilio) { - _mapilio = services.mapilio; - _mapilio.event.on("loadedImages", throttledRedraw); - } else if (!services.mapilio && _mapilio) { - _mapilio = null; + const extent = coords.map((l2) => geoExtent(l2, l2)).reduce((a2, b2) => a2.extend(b2)); + const map2 = context.map(); + var viewport = map2.trimmedExtent().polygon(); + if (force !== false || !geoPolygonIntersectsPolygon(viewport, coords, true)) { + map2.centerZoom(extent.center(), Math.min(18, map2.trimmedExtentZoom(extent))); } - return _mapilio; - } + }; function showLayer() { - const service = getService(); - if (!service) - return; - editOn(); + layer.style("display", "block"); layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { dispatch14.call("change"); }); } function hideLayer() { - throttledRedraw.cancel(); - layer.transition().duration(250).style("opacity", 0).on("end", editOff); - } - function transform2(d2) { - let t2 = svgPointTransform(projection2)(d2); - if (d2.heading) { - t2 += " rotate(" + Math.floor(d2.heading) + ",0,0)"; - } - return t2; - } - function editOn() { - layer.style("display", "block"); - } - function editOff() { - layer.selectAll(".viewfield-group").remove(); - layer.style("display", "none"); - } - function click(d3_event, image) { - const service = getService(); - if (!service) - return; - service.ensureViewerLoaded(context, image.id).then(function() { - service.selectImage(context, image.id).showViewer(context); - }); - context.map().centerEase(image.loc); - } - function mouseover(d3_event, image) { - const service = getService(); - if (service) - service.setStyles(context, image); - } - function mouseout() { - const service = getService(); - if (service) - service.setStyles(context, null); - } - function update() { - const z2 = ~~context.map().zoom(); - const showViewfields = z2 >= viewFieldZoomLevel; - const service = getService(); - let sequences = service ? service.sequences(projection2) : []; - let images = service ? service.images(projection2) : []; - let traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { - return d2.properties.id; - }); - traces.exit().remove(); - traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); - const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, function(d2) { - return d2.id; + layer.transition().duration(250).style("opacity", 0).on("end", () => { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); }); - groups.exit().remove(); - const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); - groupsEnter.append("g").attr("class", "viewfield-scale"); - const markers = groups.merge(groupsEnter).sort(function(a2, b2) { - return b2.loc[1] - a2.loc[1]; - }).attr("transform", transform2).select(".viewfield-scale"); - markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); - const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); - viewfields.exit().remove(); - viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); - function viewfieldPath() { - if (this.parentNode.__data__.isPano) { - return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; - } else { - return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; - } - } - } - function drawImages(selection2) { - const enabled = svgMapilioImages.enabled; - const service = getService(); - layer = selection2.selectAll(".layer-mapilio").data(service ? [0] : []); - layer.exit().remove(); - const layerEnter = layer.enter().append("g").attr("class", "layer-mapilio").style("display", enabled ? "block" : "none"); - layerEnter.append("g").attr("class", "sequences"); - layerEnter.append("g").attr("class", "markers"); - layer = layerEnter.merge(layer); - if (enabled) { - if (service && ~~context.map().zoom() >= minZoom4) { - editOn(); - update(); - service.loadImages(projection2); - service.loadLines(projection2); - } else { - editOff(); - } - } } - drawImages.enabled = function(_2) { + drawPhotos.enabled = function(val) { if (!arguments.length) - return svgMapilioImages.enabled; - svgMapilioImages.enabled = _2; - if (svgMapilioImages.enabled) { + return _enabled2; + _enabled2 = val; + if (_enabled2) { showLayer(); - context.photos().on("change.mapilio_images", null); } else { hideLayer(); - context.photos().on("change.mapilio_images", null); } dispatch14.call("change"); return this; }; - drawImages.supported = function() { - return !!getService(); - }; - drawImages.rendered = function(zoom) { - return zoom >= minZoom4; + drawPhotos.hasData = function() { + return isArray_default(_photos) && _photos.length > 0; }; init2(); - return drawImages; + return drawPhotos; } - // modules/svg/osm.js - function svgOsm(projection2, context, dispatch14) { - var enabled = true; - function drawOsm(selection2) { - selection2.selectAll(".layer-osm").data(["covered", "areas", "lines", "points", "labels"]).enter().append("g").attr("class", function(d2) { - return "layer-osm " + d2; - }); - selection2.selectAll(".layer-osm.points").selectAll(".points-group").data(["points", "midpoints", "vertices", "turns"]).enter().append("g").attr("class", function(d2) { - return "points-group " + d2; - }); + // modules/svg/improveOSM.js + var _layerEnabled2 = false; + var _qaService2; + function svgImproveOSM(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); + const minZoom4 = 12; + let touchLayer = select_default2(null); + let drawLayer = select_default2(null); + let layerVisible = false; + function markerPath(selection2, klass) { + selection2.attr("class", klass).attr("transform", "translate(-10, -28)").attr("points", "16,3 4,3 1,6 1,17 4,20 7,20 10,27 13,20 16,20 19,17.033 19,6"); } - function showLayer() { - var layer = context.surface().selectAll(".data-layer.osm"); - layer.interrupt(); - layer.classed("disabled", false).style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", function() { - dispatch14.call("change"); - }); + function getService() { + if (services.improveOSM && !_qaService2) { + _qaService2 = services.improveOSM; + _qaService2.on("loaded", throttledRedraw); + } else if (!services.improveOSM && _qaService2) { + _qaService2 = null; + } + return _qaService2; } - function hideLayer() { - var layer = context.surface().selectAll(".data-layer.osm"); - layer.interrupt(); - layer.transition().duration(250).style("opacity", 0).on("end interrupt", function() { - layer.classed("disabled", true); + function editOn() { + if (!layerVisible) { + layerVisible = true; + drawLayer.style("display", "block"); + } + } + function editOff() { + if (layerVisible) { + layerVisible = false; + drawLayer.style("display", "none"); + drawLayer.selectAll(".qaItem.improveOSM").remove(); + touchLayer.selectAll(".qaItem.improveOSM").remove(); + } + } + function layerOn() { + editOn(); + drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", () => dispatch14.call("change")); + } + function layerOff() { + throttledRedraw.cancel(); + drawLayer.interrupt(); + touchLayer.selectAll(".qaItem.improveOSM").remove(); + drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", () => { + editOff(); dispatch14.call("change"); }); } - drawOsm.enabled = function(val) { + function updateMarkers() { + if (!layerVisible || !_layerEnabled2) + return; + const service = getService(); + const selectedID = context.selectedErrorID(); + const data = service ? service.getItems(projection2) : []; + const getTransform = svgPointTransform(projection2); + const markers = drawLayer.selectAll(".qaItem.improveOSM").data(data, (d2) => d2.id); + markers.exit().remove(); + const markersEnter = markers.enter().append("g").attr("class", (d2) => "qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.itemType)); + markersEnter.append("polygon").call(markerPath, "shadow"); + markersEnter.append("ellipse").attr("cx", 0).attr("cy", 0).attr("rx", 4.5).attr("ry", 2).attr("class", "stroke"); + markersEnter.append("polygon").attr("fill", "currentColor").call(markerPath, "qaItem-fill"); + markersEnter.append("use").attr("class", "icon-annotation").attr("transform", "translate(-6, -22)").attr("width", "12px").attr("height", "12px").attr("xlink:href", (d2) => d2.icon ? "#" + d2.icon : ""); + markers.merge(markersEnter).sort(sortY).classed("selected", (d2) => d2.id === selectedID).attr("transform", getTransform); + if (touchLayer.empty()) + return; + const fillClass = context.getDebug("target") ? "pink " : "nocolor "; + const targets = touchLayer.selectAll(".qaItem.improveOSM").data(data, (d2) => d2.id); + targets.exit().remove(); + targets.enter().append("rect").attr("width", "20px").attr("height", "30px").attr("x", "-10px").attr("y", "-28px").merge(targets).sort(sortY).attr("class", (d2) => "qaItem ".concat(d2.service, " target ").concat(fillClass, " itemId-").concat(d2.id)).attr("transform", getTransform); + function sortY(a2, b2) { + return a2.id === selectedID ? 1 : b2.id === selectedID ? -1 : b2.loc[1] - a2.loc[1]; + } + } + function drawImproveOSM(selection2) { + const service = getService(); + const surface = context.surface(); + if (surface && !surface.empty()) { + touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); + } + drawLayer = selection2.selectAll(".layer-improveOSM").data(service ? [0] : []); + drawLayer.exit().remove(); + drawLayer = drawLayer.enter().append("g").attr("class", "layer-improveOSM").style("display", _layerEnabled2 ? "block" : "none").merge(drawLayer); + if (_layerEnabled2) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + service.loadIssues(projection2); + updateMarkers(); + } else { + editOff(); + } + } + } + drawImproveOSM.enabled = function(val) { if (!arguments.length) - return enabled; - enabled = val; - if (enabled) { - showLayer(); + return _layerEnabled2; + _layerEnabled2 = val; + if (_layerEnabled2) { + layerOn(); } else { - hideLayer(); + layerOff(); + if (context.selectedErrorID()) { + context.enter(modeBrowse(context)); + } } dispatch14.call("change"); return this; }; - return drawOsm; + drawImproveOSM.supported = () => !!getService(); + return drawImproveOSM; } - // modules/svg/notes.js - var _notesEnabled = false; - var _osmService; - function svgNotes(projection2, context, dispatch14) { - if (!dispatch14) { - dispatch14 = dispatch_default("change"); - } - var throttledRedraw = throttle_default(function() { - dispatch14.call("change"); - }, 1e3); - var minZoom4 = 12; - var touchLayer = select_default2(null); - var drawLayer = select_default2(null); - var _notesVisible = false; + // modules/svg/osmose.js + var _layerEnabled3 = false; + var _qaService3; + function svgOsmose(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); + const minZoom4 = 12; + let touchLayer = select_default2(null); + let drawLayer = select_default2(null); + let layerVisible = false; function markerPath(selection2, klass) { - selection2.attr("class", klass).attr("transform", "translate(-8, -22)").attr("d", "m17.5,0l-15,0c-1.37,0 -2.5,1.12 -2.5,2.5l0,11.25c0,1.37 1.12,2.5 2.5,2.5l3.75,0l0,3.28c0,0.38 0.43,0.6 0.75,0.37l4.87,-3.65l5.62,0c1.37,0 2.5,-1.12 2.5,-2.5l0,-11.25c0,-1.37 -1.12,-2.5 -2.5,-2.5z"); + selection2.attr("class", klass).attr("transform", "translate(-10, -28)").attr("points", "16,3 4,3 1,6 1,17 4,20 7,20 10,27 13,20 16,20 19,17.033 19,6"); } function getService() { - if (services.osm && !_osmService) { - _osmService = services.osm; - _osmService.on("loadedNotes", throttledRedraw); - } else if (!services.osm && _osmService) { - _osmService = null; + if (services.osmose && !_qaService3) { + _qaService3 = services.osmose; + _qaService3.on("loaded", throttledRedraw); + } else if (!services.osmose && _qaService3) { + _qaService3 = null; } - return _osmService; + return _qaService3; } function editOn() { - if (!_notesVisible) { - _notesVisible = true; + if (!layerVisible) { + layerVisible = true; drawLayer.style("display", "block"); } } function editOff() { - if (_notesVisible) { - _notesVisible = false; + if (layerVisible) { + layerVisible = false; drawLayer.style("display", "none"); - drawLayer.selectAll(".note").remove(); - touchLayer.selectAll(".note").remove(); + drawLayer.selectAll(".qaItem.osmose").remove(); + touchLayer.selectAll(".qaItem.osmose").remove(); } } function layerOn() { editOn(); - drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", function() { - dispatch14.call("change"); - }); + drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", () => dispatch14.call("change")); } function layerOff() { throttledRedraw.cancel(); drawLayer.interrupt(); - touchLayer.selectAll(".note").remove(); - drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", function() { + touchLayer.selectAll(".qaItem.osmose").remove(); + drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", () => { editOff(); dispatch14.call("change"); }); } function updateMarkers() { - if (!_notesVisible || !_notesEnabled) + if (!layerVisible || !_layerEnabled3) return; - var service = getService(); - var selectedID = context.selectedNoteID(); - var data = service ? service.notes(projection2) : []; - var getTransform = svgPointTransform(projection2); - var notes = drawLayer.selectAll(".note").data(data, function(d2) { - return d2.status + d2.id; - }); - notes.exit().remove(); - var notesEnter = notes.enter().append("g").attr("class", function(d2) { - return "note note-" + d2.id + " " + d2.status; - }).classed("new", function(d2) { - return d2.id < 0; - }); - notesEnter.append("ellipse").attr("cx", 0.5).attr("cy", 1).attr("rx", 6.5).attr("ry", 3).attr("class", "stroke"); - notesEnter.append("path").call(markerPath, "shadow"); - notesEnter.append("use").attr("class", "note-fill").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").attr("xlink:href", "#iD-icon-note"); - notesEnter.selectAll(".icon-annotation").data(function(d2) { - return [d2]; - }).enter().append("use").attr("class", "icon-annotation").attr("width", "10px").attr("height", "10px").attr("x", "-3px").attr("y", "-19px").attr("xlink:href", function(d2) { - if (d2.id < 0) - return "#iD-icon-plus"; - if (d2.status === "open") - return "#iD-icon-close"; - return "#iD-icon-apply"; - }); - notes.merge(notesEnter).sort(sortY).classed("selected", function(d2) { - var mode = context.mode(); - var isMoving = mode && mode.id === "drag-note"; - return !isMoving && d2.id === selectedID; - }).attr("transform", getTransform); + const service = getService(); + const selectedID = context.selectedErrorID(); + const data = service ? service.getItems(projection2) : []; + const getTransform = svgPointTransform(projection2); + const markers = drawLayer.selectAll(".qaItem.osmose").data(data, (d2) => d2.id); + markers.exit().remove(); + const markersEnter = markers.enter().append("g").attr("class", (d2) => "qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.itemType)); + markersEnter.append("polygon").call(markerPath, "shadow"); + markersEnter.append("ellipse").attr("cx", 0).attr("cy", 0).attr("rx", 4.5).attr("ry", 2).attr("class", "stroke"); + markersEnter.append("polygon").attr("fill", (d2) => service.getColor(d2.item)).call(markerPath, "qaItem-fill"); + markersEnter.append("use").attr("class", "icon-annotation").attr("transform", "translate(-6, -22)").attr("width", "12px").attr("height", "12px").attr("xlink:href", (d2) => d2.icon ? "#" + d2.icon : ""); + markers.merge(markersEnter).sort(sortY).classed("selected", (d2) => d2.id === selectedID).attr("transform", getTransform); if (touchLayer.empty()) return; - var fillClass = context.getDebug("target") ? "pink " : "nocolor "; - var targets = touchLayer.selectAll(".note").data(data, function(d2) { - return d2.id; - }); + const fillClass = context.getDebug("target") ? "pink" : "nocolor"; + const targets = touchLayer.selectAll(".qaItem.osmose").data(data, (d2) => d2.id); targets.exit().remove(); - targets.enter().append("rect").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").merge(targets).sort(sortY).attr("class", function(d2) { - var newClass = d2.id < 0 ? "new" : ""; - return "note target note-" + d2.id + " " + fillClass + newClass; - }).attr("transform", getTransform); + targets.enter().append("rect").attr("width", "20px").attr("height", "30px").attr("x", "-10px").attr("y", "-28px").merge(targets).sort(sortY).attr("class", (d2) => "qaItem ".concat(d2.service, " target ").concat(fillClass, " itemId-").concat(d2.id)).attr("transform", getTransform); function sortY(a2, b2) { - if (a2.id === selectedID) - return 1; - if (b2.id === selectedID) - return -1; - return b2.loc[1] - a2.loc[1]; + return a2.id === selectedID ? 1 : b2.id === selectedID ? -1 : b2.loc[1] - a2.loc[1]; } } - function drawNotes(selection2) { - var service = getService(); - var surface = context.surface(); + function drawOsmose(selection2) { + const service = getService(); + const surface = context.surface(); if (surface && !surface.empty()) { touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); } - drawLayer = selection2.selectAll(".layer-notes").data(service ? [0] : []); + drawLayer = selection2.selectAll(".layer-osmose").data(service ? [0] : []); drawLayer.exit().remove(); - drawLayer = drawLayer.enter().append("g").attr("class", "layer-notes").style("display", _notesEnabled ? "block" : "none").merge(drawLayer); - if (_notesEnabled) { + drawLayer = drawLayer.enter().append("g").attr("class", "layer-osmose").style("display", _layerEnabled3 ? "block" : "none").merge(drawLayer); + if (_layerEnabled3) { if (service && ~~context.map().zoom() >= minZoom4) { editOn(); - service.loadNotes(projection2); + service.loadIssues(projection2); updateMarkers(); } else { editOff(); } } } - drawNotes.enabled = function(val) { + drawOsmose.enabled = function(val) { if (!arguments.length) - return _notesEnabled; - _notesEnabled = val; - if (_notesEnabled) { - layerOn(); + return _layerEnabled3; + _layerEnabled3 = val; + if (_layerEnabled3) { + getService().loadStrings().then(layerOn).catch((err) => { + console.log(err); + }); } else { layerOff(); - if (context.selectedNoteID()) { + if (context.selectedErrorID()) { context.enter(modeBrowse(context)); } } dispatch14.call("change"); return this; }; - return drawNotes; + drawOsmose.supported = () => !!getService(); + return drawOsmose; } - // modules/svg/touch.js - function svgTouch() { - function drawTouch(selection2) { - selection2.selectAll(".layer-touch").data(["areas", "lines", "points", "turns", "markers"]).enter().append("g").attr("class", function(d2) { - return "layer-touch " + d2; + // modules/svg/streetside.js + function svgStreetside(projection2, context, dispatch14) { + var throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + var minZoom4 = 14; + var minMarkerZoom = 16; + var minViewfieldZoom2 = 18; + var layer = select_default2(null); + var _viewerYaw = 0; + var _selectedSequence = null; + var _streetside; + function init2() { + if (svgStreetside.initialized) + return; + svgStreetside.enabled = false; + svgStreetside.initialized = true; + } + function getService() { + if (services.streetside && !_streetside) { + _streetside = services.streetside; + _streetside.event.on("viewerChanged.svgStreetside", viewerChanged).on("loadedImages.svgStreetside", throttledRedraw); + } else if (!services.streetside && _streetside) { + _streetside = null; + } + return _streetside; + } + function showLayer() { + var service = getService(); + if (!service) + return; + editOn(); + layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { + dispatch14.call("change"); }); } - return drawTouch; - } - - // modules/util/dimensions.js - function refresh(selection2, node) { - var cr = node.getBoundingClientRect(); - var prop = [cr.width, cr.height]; - selection2.property("__dimensions__", prop); - return prop; - } - function utilGetDimensions(selection2, force) { - if (!selection2 || selection2.empty()) { - return [0, 0]; + function hideLayer() { + throttledRedraw.cancel(); + layer.transition().duration(250).style("opacity", 0).on("end", editOff); } - var node = selection2.node(), cached = selection2.property("__dimensions__"); - return !cached || force ? refresh(selection2, node) : cached; - } - function utilSetDimensions(selection2, dimensions) { - if (!selection2 || selection2.empty()) { - return selection2; + function editOn() { + layer.style("display", "block"); } - var node = selection2.node(); - if (dimensions === null) { - refresh(selection2, node); - return selection2; + function editOff() { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); } - return selection2.property("__dimensions__", [dimensions[0], dimensions[1]]).attr("width", dimensions[0]).attr("height", dimensions[1]); - } - - // modules/svg/layers.js - function svgLayers(projection2, context) { - var dispatch14 = dispatch_default("change"); - var svg2 = select_default2(null); - var _layers = [ - { id: "osm", layer: svgOsm(projection2, context, dispatch14) }, - { id: "notes", layer: svgNotes(projection2, context, dispatch14) }, - { id: "data", layer: svgData(projection2, context, dispatch14) }, - { id: "keepRight", layer: svgKeepRight(projection2, context, dispatch14) }, - { id: "improveOSM", layer: svgImproveOSM(projection2, context, dispatch14) }, - { id: "osmose", layer: svgOsmose(projection2, context, dispatch14) }, - { id: "streetside", layer: svgStreetside(projection2, context, dispatch14) }, - { id: "mapillary", layer: svgMapillaryImages(projection2, context, dispatch14) }, - { id: "mapillary-position", layer: svgMapillaryPosition(projection2, context, dispatch14) }, - { id: "mapillary-map-features", layer: svgMapillaryMapFeatures(projection2, context, dispatch14) }, - { id: "mapillary-signs", layer: svgMapillarySigns(projection2, context, dispatch14) }, - { id: "kartaview", layer: svgKartaviewImages(projection2, context, dispatch14) }, - { id: "mapilio", layer: svgMapilioImages(projection2, context, dispatch14) }, - { id: "vegbilder", layer: svgVegbilder(projection2, context, dispatch14) }, - { id: "local-photos", layer: svgLocalPhotos(projection2, context, dispatch14) }, - { id: "debug", layer: svgDebug(projection2, context, dispatch14) }, - { id: "geolocate", layer: svgGeolocate(projection2, context, dispatch14) }, - { id: "touch", layer: svgTouch(projection2, context, dispatch14) } - ]; - function drawLayers(selection2) { - svg2 = selection2.selectAll(".surface").data([0]); - svg2 = svg2.enter().append("svg").attr("class", "surface").merge(svg2); - var defs = svg2.selectAll(".surface-defs").data([0]); - defs.enter().append("defs").attr("class", "surface-defs"); - var groups = svg2.selectAll(".data-layer").data(_layers); - groups.exit().remove(); - groups.enter().append("g").attr("class", function(d2) { - return "data-layer " + d2.id; - }).merge(groups).each(function(d2) { - select_default2(this).call(d2.layer); + function click(d3_event, d2) { + var service = getService(); + if (!service) + return; + if (d2.sequenceKey !== _selectedSequence) { + _viewerYaw = 0; + } + _selectedSequence = d2.sequenceKey; + service.ensureViewerLoaded(context).then(function() { + service.selectImage(context, d2.key).yaw(_viewerYaw).showViewer(context); }); + context.map().centerEase(d2.loc); } - drawLayers.all = function() { - return _layers; - }; - drawLayers.layer = function(id2) { - var obj = _layers.find(function(o2) { - return o2.id === id2; - }); - return obj && obj.layer; - }; - drawLayers.only = function(what) { - var arr = [].concat(what); - var all = _layers.map(function(layer) { - return layer.id; - }); - return drawLayers.remove(utilArrayDifference(all, arr)); - }; - drawLayers.remove = function(what) { - var arr = [].concat(what); - arr.forEach(function(id2) { - _layers = _layers.filter(function(o2) { - return o2.id !== id2; - }); - }); - dispatch14.call("change"); - return this; - }; - drawLayers.add = function(what) { - var arr = [].concat(what); - arr.forEach(function(obj) { - if ("id" in obj && "layer" in obj) { - _layers.push(obj); - } - }); - dispatch14.call("change"); - return this; - }; - drawLayers.dimensions = function(val) { - if (!arguments.length) - return utilGetDimensions(svg2); - utilSetDimensions(svg2, val); - return this; - }; - return utilRebind(drawLayers, dispatch14, "on"); - } - - // modules/svg/lines.js - var import_fast_deep_equal6 = __toESM(require_fast_deep_equal()); - function svgLines(projection2, context) { - var detected = utilDetect(); - var highway_stack = { - motorway: 0, - motorway_link: 1, - trunk: 2, - trunk_link: 3, - primary: 4, - primary_link: 5, - secondary: 6, - tertiary: 7, - unclassified: 8, - residential: 9, - service: 10, - footway: 11 - }; - function drawTargets(selection2, graph, entities, filter2) { - var targetClass = context.getDebug("target") ? "pink " : "nocolor "; - var nopeClass = context.getDebug("target") ? "red " : "nocolor "; - var getPath = svgPath(projection2).geojson; - var activeID = context.activeID(); - var base = context.history().base(); - var data = { targets: [], nopes: [] }; - entities.forEach(function(way) { - var features = svgSegmentWay(way, graph, activeID); - data.targets.push.apply(data.targets, features.passive); - data.nopes.push.apply(data.nopes, features.active); - }); - var targetData = data.targets.filter(getPath); - var targets = selection2.selectAll(".line.target-allowed").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(targetData, function key(d2) { - return d2.id; - }); - targets.exit().remove(); - var segmentWasEdited = function(d2) { - var wayID = d2.properties.entity.id; - if (!base.entities[wayID] || !(0, import_fast_deep_equal6.default)(graph.entities[wayID].nodes, base.entities[wayID].nodes)) { - return false; - } - return d2.properties.nodes.some(function(n3) { - return !base.entities[n3.id] || !(0, import_fast_deep_equal6.default)(graph.entities[n3.id].loc, base.entities[n3.id].loc); - }); - }; - targets.enter().append("path").merge(targets).attr("d", getPath).attr("class", function(d2) { - return "way line target target-allowed " + targetClass + d2.id; - }).classed("segment-edited", segmentWasEdited); - var nopeData = data.nopes.filter(getPath); - var nopes = selection2.selectAll(".line.target-nope").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(nopeData, function key(d2) { - return d2.id; - }); - nopes.exit().remove(); - nopes.enter().append("path").merge(nopes).attr("d", getPath).attr("class", function(d2) { - return "way line target target-nope " + nopeClass + d2.id; - }).classed("segment-edited", segmentWasEdited); + function mouseover(d3_event, d2) { + var service = getService(); + if (service) + service.setStyles(context, d2); } - function drawLines(selection2, graph, entities, filter2) { - var base = context.history().base(); - function waystack(a2, b2) { - var selected = context.selectedIDs(); - var scoreA = selected.indexOf(a2.id) !== -1 ? 20 : 0; - var scoreB = selected.indexOf(b2.id) !== -1 ? 20 : 0; - if (a2.tags.highway) { - scoreA -= highway_stack[a2.tags.highway]; - } - if (b2.tags.highway) { - scoreB -= highway_stack[b2.tags.highway]; - } - return scoreA - scoreB; - } - function drawLineGroup(selection3, klass, isSelected) { - var mode = context.mode(); - var isDrawing = mode && /^draw/.test(mode.id); - var selectedClass = !isDrawing && isSelected ? "selected " : ""; - var lines = selection3.selectAll("path").filter(filter2).data(getPathData(isSelected), osmEntity.key); - lines.exit().remove(); - lines.enter().append("path").attr("class", function(d2) { - var prefix = "way line"; - if (!d2.hasInterestingTags()) { - var parentRelations = graph.parentRelations(d2); - var parentMultipolygons = parentRelations.filter(function(relation) { - return relation.isMultipolygon(); - }); - if (parentMultipolygons.length > 0 && // and only multipolygon relations - parentRelations.length === parentMultipolygons.length) { - prefix = "relation area"; - } - } - var oldMPClass = oldMultiPolygonOuters[d2.id] ? "old-multipolygon " : ""; - return prefix + " " + klass + " " + selectedClass + oldMPClass + d2.id; - }).classed("added", function(d2) { - return !base.entities[d2.id]; - }).classed("geometry-edited", function(d2) { - return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal6.default)(graph.entities[d2.id].nodes, base.entities[d2.id].nodes); - }).classed("retagged", function(d2) { - return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal6.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); - }).call(svgTagClasses()).merge(lines).sort(waystack).attr("d", getPath).call(svgTagClasses().tags(svgRelationMemberTags(graph))); - return selection3; + function mouseout() { + var service = getService(); + if (service) + service.setStyles(context, null); + } + function transform2(d2) { + var t2 = svgPointTransform(projection2)(d2); + var rot = d2.ca + _viewerYaw; + if (rot) { + t2 += " rotate(" + Math.floor(rot) + ",0,0)"; } - function getPathData(isSelected) { - return function() { - var layer = this.parentNode.__data__; - var data = pathdata[layer] || []; - return data.filter(function(d2) { - if (isSelected) { - return context.selectedIDs().indexOf(d2.id) !== -1; - } else { - return context.selectedIDs().indexOf(d2.id) === -1; - } - }); - }; + return t2; + } + function viewerChanged() { + var service = getService(); + if (!service) + return; + var viewer = service.viewer(); + if (!viewer) + return; + _viewerYaw = viewer.getYaw(); + if (context.map().isTransformed()) + return; + layer.selectAll(".viewfield-group.currentView").attr("transform", transform2); + } + function filterBubbles(bubbles) { + var fromDate = context.photos().fromDate(); + var toDate = context.photos().toDate(); + var usernames = context.photos().usernames(); + if (fromDate) { + var fromTimestamp = new Date(fromDate).getTime(); + bubbles = bubbles.filter(function(bubble) { + return new Date(bubble.captured_at).getTime() >= fromTimestamp; + }); } - function addMarkers(layergroup, pathclass, groupclass, groupdata, marker) { - var markergroup = layergroup.selectAll("g." + groupclass).data([pathclass]); - markergroup = markergroup.enter().append("g").attr("class", groupclass).merge(markergroup); - var markers = markergroup.selectAll("path").filter(filter2).data( - function data() { - return groupdata[this.parentNode.__data__] || []; - }, - function key(d2) { - return [d2.id, d2.index]; - } - ); - markers.exit().remove(); - markers = markers.enter().append("path").attr("class", pathclass).merge(markers).attr("marker-mid", marker).attr("d", function(d2) { - return d2.d; + if (toDate) { + var toTimestamp = new Date(toDate).getTime(); + bubbles = bubbles.filter(function(bubble) { + return new Date(bubble.captured_at).getTime() <= toTimestamp; }); - if (detected.ie) { - markers.each(function() { - this.parentNode.insertBefore(this, this); - }); - } } - var getPath = svgPath(projection2, graph); - var ways = []; - var onewaydata = {}; - var sideddata = {}; - var oldMultiPolygonOuters = {}; - for (var i3 = 0; i3 < entities.length; i3++) { - var entity = entities[i3]; - var outer = osmOldMultipolygonOuterMember(entity, graph); - if (outer) { - ways.push(entity.mergeTags(outer.tags)); - oldMultiPolygonOuters[outer.id] = true; - } else if (entity.geometry(graph) === "line" || entity.geometry(graph) === "area" && entity.sidednessIdentifier && entity.sidednessIdentifier() === "coastline") { - ways.push(entity); - } + if (usernames) { + bubbles = bubbles.filter(function(bubble) { + return usernames.indexOf(bubble.captured_by) !== -1; + }); } - ways = ways.filter(getPath); - var pathdata = utilArrayGroupBy(ways, function(way) { - return way.layer(); - }); - Object.keys(pathdata).forEach(function(k2) { - var v2 = pathdata[k2]; - var onewayArr = v2.filter(function(d2) { - return d2.isOneWay(); + return bubbles; + } + function filterSequences(sequences) { + var fromDate = context.photos().fromDate(); + var toDate = context.photos().toDate(); + var usernames = context.photos().usernames(); + if (fromDate) { + var fromTimestamp = new Date(fromDate).getTime(); + sequences = sequences.filter(function(sequences2) { + return new Date(sequences2.properties.captured_at).getTime() >= fromTimestamp; }); - var onewaySegments = svgMarkerSegments( - projection2, - graph, - 35, - function shouldReverse(entity2) { - return entity2.tags.oneway === "-1"; - }, - function bothDirections(entity2) { - return entity2.tags.oneway === "reversible" || entity2.tags.oneway === "alternating"; - } - ); - onewaydata[k2] = utilArrayFlatten(onewayArr.map(onewaySegments)); - var sidedArr = v2.filter(function(d2) { - return d2.isSided(); + } + if (toDate) { + var toTimestamp = new Date(toDate).getTime(); + sequences = sequences.filter(function(sequences2) { + return new Date(sequences2.properties.captured_at).getTime() <= toTimestamp; }); - var sidedSegments = svgMarkerSegments( - projection2, - graph, - 30, - function shouldReverse() { - return false; - }, - function bothDirections() { - return false; - } - ); - sideddata[k2] = utilArrayFlatten(sidedArr.map(sidedSegments)); - }); - var covered = selection2.selectAll(".layer-osm.covered"); - var uncovered = selection2.selectAll(".layer-osm.lines"); - var touchLayer = selection2.selectAll(".layer-touch.lines"); - [covered, uncovered].forEach(function(selection3) { - var range3 = selection3 === covered ? range(-10, 0) : range(0, 11); - var layergroup = selection3.selectAll("g.layergroup").data(range3); - layergroup = layergroup.enter().append("g").attr("class", function(d2) { - return "layergroup layer" + String(d2); - }).merge(layergroup); - layergroup.selectAll("g.linegroup").data(["shadow", "casing", "stroke", "shadow-highlighted", "casing-highlighted", "stroke-highlighted"]).enter().append("g").attr("class", function(d2) { - return "linegroup line-" + d2; + } + if (usernames) { + sequences = sequences.filter(function(sequences2) { + return usernames.indexOf(sequences2.properties.captured_by) !== -1; }); - layergroup.selectAll("g.line-shadow").call(drawLineGroup, "shadow", false); - layergroup.selectAll("g.line-casing").call(drawLineGroup, "casing", false); - layergroup.selectAll("g.line-stroke").call(drawLineGroup, "stroke", false); - layergroup.selectAll("g.line-shadow-highlighted").call(drawLineGroup, "shadow", true); - layergroup.selectAll("g.line-casing-highlighted").call(drawLineGroup, "casing", true); - layergroup.selectAll("g.line-stroke-highlighted").call(drawLineGroup, "stroke", true); - addMarkers(layergroup, "oneway", "onewaygroup", onewaydata, "url(#ideditor-oneway-marker)"); - addMarkers( - layergroup, - "sided", - "sidedgroup", - sideddata, - function marker(d2) { - var category = graph.entity(d2.id).sidednessIdentifier(); - return "url(#ideditor-sided-marker-" + category + ")"; - } - ); - }); - touchLayer.call(drawTargets, graph, ways, filter2); + } + return sequences; } - return drawLines; - } - - // modules/svg/midpoints.js - function svgMidpoints(projection2, context) { - var targetRadius = 8; - function drawTargets(selection2, graph, entities, filter2) { - var fillClass = context.getDebug("target") ? "pink " : "nocolor "; - var getTransform = svgPointTransform(projection2).geojson; - var data = entities.map(function(midpoint) { - return { - type: "Feature", - id: midpoint.id, - properties: { - target: true, - entity: midpoint - }, - geometry: { - type: "Point", - coordinates: midpoint.loc - } - }; + function update() { + var viewer = context.container().select(".photoviewer"); + var selected = viewer.empty() ? void 0 : viewer.datum(); + var z2 = ~~context.map().zoom(); + var showMarkers = z2 >= minMarkerZoom; + var showViewfields = z2 >= minViewfieldZoom2; + var service = getService(); + var sequences = []; + var bubbles = []; + if (context.photos().showsPanoramic()) { + sequences = service ? service.sequences(projection2) : []; + bubbles = service && showMarkers ? service.bubbles(projection2) : []; + sequences = filterSequences(sequences); + bubbles = filterBubbles(bubbles); + } + var traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { + return d2.properties.key; }); - var targets = selection2.selectAll(".midpoint.target").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(data, function key(d2) { - return d2.id; + traces.exit().remove(); + traces = traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); + var groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(bubbles, function(d2) { + return d2.key + (d2.sequenceKey ? "v1" : "v0"); }); - targets.exit().remove(); - targets.enter().append("circle").attr("r", targetRadius).merge(targets).attr("class", function(d2) { - return "node midpoint target " + fillClass + d2.id; - }).attr("transform", getTransform); - } - function drawMidpoints(selection2, graph, entities, filter2, extent) { - var drawLayer = selection2.selectAll(".layer-osm.points .points-group.midpoints"); - var touchLayer = selection2.selectAll(".layer-touch.points"); - var mode = context.mode(); - if (mode && mode.id !== "select" || !context.map().withinEditableZoom()) { - drawLayer.selectAll(".midpoint").remove(); - touchLayer.selectAll(".midpoint.target").remove(); - return; - } - var poly = extent.polygon(); - var midpoints = {}; - for (var i3 = 0; i3 < entities.length; i3++) { - var entity = entities[i3]; - if (entity.type !== "way") - continue; - if (!filter2(entity)) - continue; - if (context.selectedIDs().indexOf(entity.id) < 0) - continue; - var nodes = graph.childNodes(entity); - for (var j3 = 0; j3 < nodes.length - 1; j3++) { - var a2 = nodes[j3]; - var b2 = nodes[j3 + 1]; - var id2 = [a2.id, b2.id].sort().join("-"); - if (midpoints[id2]) { - midpoints[id2].parents.push(entity); - } else if (geoVecLength(projection2(a2.loc), projection2(b2.loc)) > 40) { - var point2 = geoVecInterp(a2.loc, b2.loc, 0.5); - var loc = null; - if (extent.intersects(point2)) { - loc = point2; - } else { - for (var k2 = 0; k2 < 4; k2++) { - point2 = geoLineIntersection([a2.loc, b2.loc], [poly[k2], poly[k2 + 1]]); - if (point2 && geoVecLength(projection2(a2.loc), projection2(point2)) > 20 && geoVecLength(projection2(b2.loc), projection2(point2)) > 20) { - loc = point2; - break; - } - } - } - if (loc) { - midpoints[id2] = { - type: "midpoint", - id: id2, - loc, - edge: [a2.id, b2.id], - parents: [entity] - }; - } - } + groups.exit().remove(); + var groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); + groupsEnter.append("g").attr("class", "viewfield-scale"); + var markers = groups.merge(groupsEnter).sort(function(a2, b2) { + return a2 === selected ? 1 : b2 === selected ? -1 : b2.loc[1] - a2.loc[1]; + }).attr("transform", transform2).select(".viewfield-scale"); + markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); + var viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + viewfields.exit().remove(); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); + function viewfieldPath() { + var d2 = this.parentNode.__data__; + if (d2.pano) { + return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; + } else { + return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; } } - function midpointFilter(d2) { - if (midpoints[d2.id]) - return true; - for (var i4 = 0; i4 < d2.parents.length; i4++) { - if (filter2(d2.parents[i4])) { - return true; - } + } + function drawImages(selection2) { + var enabled = svgStreetside.enabled; + var service = getService(); + layer = selection2.selectAll(".layer-streetside-images").data(service ? [0] : []); + layer.exit().remove(); + var layerEnter = layer.enter().append("g").attr("class", "layer-streetside-images").style("display", enabled ? "block" : "none"); + layerEnter.append("g").attr("class", "sequences"); + layerEnter.append("g").attr("class", "markers"); + layer = layerEnter.merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadBubbles(projection2); + } else { + editOff(); } - return false; } - var groups = drawLayer.selectAll(".midpoint").filter(midpointFilter).data(Object.values(midpoints), function(d2) { - return d2.id; - }); - groups.exit().remove(); - var enter = groups.enter().insert("g", ":first-child").attr("class", "midpoint"); - enter.append("polygon").attr("points", "-6,8 10,0 -6,-8").attr("class", "shadow"); - enter.append("polygon").attr("points", "-3,4 5,0 -3,-4").attr("class", "fill"); - groups = groups.merge(enter).attr("transform", function(d2) { - var translate = svgPointTransform(projection2); - var a3 = graph.entity(d2.edge[0]); - var b3 = graph.entity(d2.edge[1]); - var angle2 = geoAngle(a3, b3, projection2) * (180 / Math.PI); - return translate(d2) + " rotate(" + angle2 + ")"; - }).call(svgTagClasses().tags( - function(d2) { - return d2.parents[0].tags; - } - )); - groups.select("polygon.shadow"); - groups.select("polygon.fill"); - touchLayer.call(drawTargets, graph, Object.values(midpoints), midpointFilter); } - return drawMidpoints; + drawImages.enabled = function(_2) { + if (!arguments.length) + return svgStreetside.enabled; + svgStreetside.enabled = _2; + if (svgStreetside.enabled) { + showLayer(); + context.photos().on("change.streetside", update); + } else { + hideLayer(); + context.photos().on("change.streetside", null); + } + dispatch14.call("change"); + return this; + }; + drawImages.supported = function() { + return !!getService(); + }; + drawImages.rendered = function(zoom) { + return zoom >= minZoom4; + }; + init2(); + return drawImages; } - // modules/svg/points.js - var import_fast_deep_equal7 = __toESM(require_fast_deep_equal()); - function svgPoints(projection2, context) { - function markerPath(selection2, klass) { - selection2.attr("class", klass).attr("transform", "translate(-8, -23)").attr("d", "M 17,8 C 17,13 11,21 8.5,23.5 C 6,21 0,13 0,8 C 0,4 4,-0.5 8.5,-0.5 C 13,-0.5 17,4 17,8 z"); + // modules/svg/vegbilder.js + function svgVegbilder(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(() => dispatch14.call("change"), 1e3); + const minZoom4 = 14; + const minMarkerZoom = 16; + const minViewfieldZoom2 = 18; + let layer = select_default2(null); + let _viewerYaw = 0; + let _vegbilder; + function init2() { + if (svgVegbilder.initialized) + return; + svgVegbilder.enabled = false; + svgVegbilder.initialized = true; } - function sortY(a2, b2) { - return b2.loc[1] - a2.loc[1]; + function getService() { + if (services.vegbilder && !_vegbilder) { + _vegbilder = services.vegbilder; + _vegbilder.event.on("viewerChanged.svgVegbilder", viewerChanged).on("loadedImages.svgVegbilder", throttledRedraw); + } else if (!services.vegbilder && _vegbilder) { + _vegbilder = null; + } + return _vegbilder; } - function fastEntityKey(d2) { - var mode = context.mode(); - var isMoving = mode && /^(add|draw|drag|move|rotate)/.test(mode.id); - return isMoving ? d2.id : osmEntity.key(d2); + function showLayer() { + const service = getService(); + if (!service) + return; + editOn(); + layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", () => dispatch14.call("change")); } - function drawTargets(selection2, graph, entities, filter2) { - var fillClass = context.getDebug("target") ? "pink " : "nocolor "; - var getTransform = svgPointTransform(projection2).geojson; - var activeID = context.activeID(); - var data = []; - entities.forEach(function(node) { - if (activeID === node.id) - return; - data.push({ - type: "Feature", - id: node.id, - properties: { - target: true, - entity: node - }, - geometry: node.asGeoJSON() - }); - }); - var targets = selection2.selectAll(".point.target").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(data, function key(d2) { - return d2.id; + function hideLayer() { + throttledRedraw.cancel(); + layer.transition().duration(250).style("opacity", 0).on("end", editOff); + } + function editOn() { + layer.style("display", "block"); + } + function editOff() { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); + } + function click(d3_event, d2) { + const service = getService(); + if (!service) + return; + service.ensureViewerLoaded(context).then(() => { + service.selectImage(context, d2.key).showViewer(context); }); - targets.exit().remove(); - targets.enter().append("rect").attr("x", -10).attr("y", -26).attr("width", 20).attr("height", 30).merge(targets).attr("class", function(d2) { - return "node point target " + fillClass + d2.id; - }).attr("transform", getTransform); + context.map().centerEase(d2.loc); + } + function mouseover(d3_event, d2) { + const service = getService(); + if (service) + service.setStyles(context, d2); + } + function mouseout() { + const service = getService(); + if (service) + service.setStyles(context, null); + } + function transform2(d2, selected) { + let t2 = svgPointTransform(projection2)(d2); + let rot = d2.ca; + if (d2 === selected) { + rot += _viewerYaw; + } + if (rot) { + t2 += " rotate(" + Math.floor(rot) + ",0,0)"; + } + return t2; + } + function viewerChanged() { + const service = getService(); + if (!service) + return; + const frame2 = service.photoFrame(); + _viewerYaw = frame2.getYaw(); + if (context.map().isTransformed()) + return; + layer.selectAll(".viewfield-group.currentView").attr("transform", (d2) => transform2(d2, d2)); + } + function filterImages(images) { + const photoContext = context.photos(); + const fromDateString = photoContext.fromDate(); + const toDateString = photoContext.toDate(); + const showsFlat = photoContext.showsFlat(); + const showsPano = photoContext.showsPanoramic(); + if (fromDateString) { + const fromDate = new Date(fromDateString); + images = images.filter((image) => image.captured_at.getTime() >= fromDate.getTime()); + } + if (toDateString) { + const toDate = new Date(toDateString); + images = images.filter((image) => image.captured_at.getTime() <= toDate.getTime()); + } + if (!showsPano) { + images = images.filter((image) => !image.is_sphere); + } + if (!showsFlat) { + images = images.filter((image) => image.is_sphere); + } + return images; + } + function filterSequences(sequences) { + const photoContext = context.photos(); + const fromDateString = photoContext.fromDate(); + const toDateString = photoContext.toDate(); + const showsFlat = photoContext.showsFlat(); + const showsPano = photoContext.showsPanoramic(); + if (fromDateString) { + const fromDate = new Date(fromDateString); + sequences = sequences.filter(({ images }) => images[0].captured_at.getTime() >= fromDate.getTime()); + } + if (toDateString) { + const toDate = new Date(toDateString); + sequences = sequences.filter(({ images }) => images[images.length - 1].captured_at.getTime() <= toDate.getTime()); + } + if (!showsPano) { + sequences = sequences.filter(({ images }) => !images[0].is_sphere); + } + if (!showsFlat) { + sequences = sequences.filter(({ images }) => images[0].is_sphere); + } + return sequences; + } + function update() { + const viewer = context.container().select(".photoviewer"); + const selected = viewer.empty() ? void 0 : viewer.datum(); + const z2 = ~~context.map().zoom(); + const showMarkers = z2 >= minMarkerZoom; + const showViewfields = z2 >= minViewfieldZoom2; + const service = getService(); + let sequences = []; + let images = []; + if (service) { + service.loadImages(context); + sequences = service.sequences(projection2); + images = showMarkers ? service.images(projection2) : []; + images = filterImages(images); + sequences = filterSequences(sequences); + } + let traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, (d2) => d2.key); + traces.exit().remove(); + traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); + const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, (d2) => d2.key); + groups.exit().remove(); + const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); + groupsEnter.append("g").attr("class", "viewfield-scale"); + const markers = groups.merge(groupsEnter).sort((a2, b2) => { + return a2 === selected ? 1 : b2 === selected ? -1 : b2.loc[1] - a2.loc[1]; + }).attr("transform", (d2) => transform2(d2, selected)).select(".viewfield-scale"); + markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); + const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + viewfields.exit().remove(); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); + function viewfieldPath() { + const d2 = this.parentNode.__data__; + if (d2.is_sphere) { + return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; + } else { + return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; + } + } } - function drawPoints(selection2, graph, entities, filter2) { - var wireframe = context.surface().classed("fill-wireframe"); - var zoom = geoScaleToZoom(projection2.scale()); - var base = context.history().base(); - function renderAsPoint(entity) { - return entity.geometry(graph) === "point" && !(zoom >= 18 && entity.directions(graph, projection2).length); + function drawImages(selection2) { + const enabled = svgVegbilder.enabled; + const service = getService(); + layer = selection2.selectAll(".layer-vegbilder").data(service ? [0] : []); + layer.exit().remove(); + const layerEnter = layer.enter().append("g").attr("class", "layer-vegbilder").style("display", enabled ? "block" : "none"); + layerEnter.append("g").attr("class", "sequences"); + layerEnter.append("g").attr("class", "markers"); + layer = layerEnter.merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadImages(context); + } else { + editOff(); + } } - var points = wireframe ? [] : entities.filter(renderAsPoint); - points.sort(sortY); - var drawLayer = selection2.selectAll(".layer-osm.points .points-group.points"); - var touchLayer = selection2.selectAll(".layer-touch.points"); - var groups = drawLayer.selectAll("g.point").filter(filter2).data(points, fastEntityKey); - groups.exit().remove(); - var enter = groups.enter().append("g").attr("class", function(d2) { - return "node point " + d2.id; - }).order(); - enter.append("path").call(markerPath, "shadow"); - enter.append("ellipse").attr("cx", 0.5).attr("cy", 1).attr("rx", 6.5).attr("ry", 3).attr("class", "stroke"); - enter.append("path").call(markerPath, "stroke"); - enter.append("use").attr("transform", "translate(-5.5, -20)").attr("class", "icon").attr("width", "12px").attr("height", "12px"); - groups = groups.merge(enter).attr("transform", svgPointTransform(projection2)).classed("added", function(d2) { - return !base.entities[d2.id]; - }).classed("moved", function(d2) { - return base.entities[d2.id] && !(0, import_fast_deep_equal7.default)(graph.entities[d2.id].loc, base.entities[d2.id].loc); - }).classed("retagged", function(d2) { - return base.entities[d2.id] && !(0, import_fast_deep_equal7.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); - }).call(svgTagClasses()); - groups.select(".shadow"); - groups.select(".stroke"); - groups.select(".icon").attr("xlink:href", function(entity) { - var preset = _mainPresetIndex.match(entity, graph); - var picon = preset && preset.icon; - return picon ? "#" + picon : ""; - }); - touchLayer.call(drawTargets, graph, points, filter2); } - return drawPoints; + drawImages.enabled = function(_2) { + if (!arguments.length) + return svgVegbilder.enabled; + svgVegbilder.enabled = _2; + if (svgVegbilder.enabled) { + showLayer(); + context.photos().on("change.vegbilder", update); + } else { + hideLayer(); + context.photos().on("change.vegbilder", null); + } + dispatch14.call("change"); + return this; + }; + drawImages.supported = function() { + return !!getService(); + }; + drawImages.rendered = function(zoom) { + return zoom >= minZoom4; + }; + drawImages.validHere = function(extent, zoom) { + return zoom >= minZoom4 - 2 && getService().validHere(extent); + }; + init2(); + return drawImages; } - // modules/svg/turns.js - function svgTurns(projection2, context) { - function icon2(turn) { - var u2 = turn.u ? "-u" : ""; - if (turn.no) - return "#iD-turn-no" + u2; - if (turn.only) - return "#iD-turn-only" + u2; - return "#iD-turn-yes" + u2; + // modules/svg/mapillary_images.js + function svgMapillaryImages(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + const minZoom4 = 12; + const minMarkerZoom = 16; + const minViewfieldZoom2 = 18; + let layer = select_default2(null); + let _mapillary; + function init2() { + if (svgMapillaryImages.initialized) + return; + svgMapillaryImages.enabled = false; + svgMapillaryImages.initialized = true; } - function drawTurns(selection2, graph, turns) { - function turnTransform(d2) { - var pxRadius = 50; - var toWay = graph.entity(d2.to.way); - var toPoints = graph.childNodes(toWay).map(function(n3) { - return n3.loc; - }).map(projection2); - var toLength = geoPathLength(toPoints); - var mid = toLength / 2; - var toNode = graph.entity(d2.to.node); - var toVertex = graph.entity(d2.to.vertex); - var a2 = geoAngle(toVertex, toNode, projection2); - var o2 = projection2(toVertex.loc); - var r2 = d2.u ? 0 : !toWay.__via ? pxRadius : Math.min(mid, pxRadius); - return "translate(" + (r2 * Math.cos(a2) + o2[0]) + "," + (r2 * Math.sin(a2) + o2[1]) + ") rotate(" + a2 * 180 / Math.PI + ")"; + function getService() { + if (services.mapillary && !_mapillary) { + _mapillary = services.mapillary; + _mapillary.event.on("loadedImages", throttledRedraw); + } else if (!services.mapillary && _mapillary) { + _mapillary = null; } - var drawLayer = selection2.selectAll(".layer-osm.points .points-group.turns"); - var touchLayer = selection2.selectAll(".layer-touch.turns"); - var groups = drawLayer.selectAll("g.turn").data(turns, function(d2) { - return d2.key; - }); - groups.exit().remove(); - var groupsEnter = groups.enter().append("g").attr("class", function(d2) { - return "turn " + d2.key; - }); - var turnsEnter = groupsEnter.filter(function(d2) { - return !d2.u; - }); - turnsEnter.append("rect").attr("transform", "translate(-22, -12)").attr("width", "44").attr("height", "24"); - turnsEnter.append("use").attr("transform", "translate(-22, -12)").attr("width", "44").attr("height", "24"); - var uEnter = groupsEnter.filter(function(d2) { - return d2.u; - }); - uEnter.append("circle").attr("r", "16"); - uEnter.append("use").attr("transform", "translate(-16, -16)").attr("width", "32").attr("height", "32"); - groups = groups.merge(groupsEnter).attr("opacity", function(d2) { - return d2.direct === false ? "0.7" : null; - }).attr("transform", turnTransform); - groups.select("use").attr("xlink:href", icon2); - groups.select("rect"); - groups.select("circle"); - var fillClass = context.getDebug("target") ? "pink " : "nocolor "; - groups = touchLayer.selectAll("g.turn").data(turns, function(d2) { - return d2.key; - }); - groups.exit().remove(); - groupsEnter = groups.enter().append("g").attr("class", function(d2) { - return "turn " + d2.key; - }); - turnsEnter = groupsEnter.filter(function(d2) { - return !d2.u; + return _mapillary; + } + function showLayer() { + const service = getService(); + if (!service) + return; + editOn(); + layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { + dispatch14.call("change"); }); - turnsEnter.append("rect").attr("class", "target " + fillClass).attr("transform", "translate(-22, -12)").attr("width", "44").attr("height", "24"); - uEnter = groupsEnter.filter(function(d2) { - return d2.u; + } + function hideLayer() { + throttledRedraw.cancel(); + layer.transition().duration(250).style("opacity", 0).on("end", editOff); + } + function editOn() { + layer.style("display", "block"); + } + function editOff() { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); + } + function click(d3_event, image) { + const service = getService(); + if (!service) + return; + service.ensureViewerLoaded(context).then(function() { + service.selectImage(context, image.id).showViewer(context); }); - uEnter.append("circle").attr("class", "target " + fillClass).attr("r", "16"); - groups = groups.merge(groupsEnter).attr("transform", turnTransform); - groups.select("rect"); - groups.select("circle"); - return this; + context.map().centerEase(image.loc); } - return drawTurns; - } - - // modules/svg/vertices.js - var import_fast_deep_equal8 = __toESM(require_fast_deep_equal()); - function svgVertices(projection2, context) { - var radiuses = { - // z16-, z17, z18+, w/icon - shadow: [6, 7.5, 7.5, 12], - stroke: [2.5, 3.5, 3.5, 8], - fill: [1, 1.5, 1.5, 1.5] - }; - var _currHoverTarget; - var _currPersistent = {}; - var _currHover = {}; - var _prevHover = {}; - var _currSelected = {}; - var _prevSelected = {}; - var _radii = {}; - function sortY(a2, b2) { - return b2.loc[1] - a2.loc[1]; + function mouseover(d3_event, image) { + const service = getService(); + if (service) + service.setStyles(context, image); } - function fastEntityKey(d2) { - var mode = context.mode(); - var isMoving = mode && /^(add|draw|drag|move|rotate)/.test(mode.id); - return isMoving ? d2.id : osmEntity.key(d2); + function mouseout() { + const service = getService(); + if (service) + service.setStyles(context, null); } - function draw(selection2, graph, vertices, sets2, filter2) { - sets2 = sets2 || { selected: {}, important: {}, hovered: {} }; - var icons = {}; - var directions = {}; - var wireframe = context.surface().classed("fill-wireframe"); - var zoom = geoScaleToZoom(projection2.scale()); - var z2 = zoom < 17 ? 0 : zoom < 18 ? 1 : 2; - var activeID = context.activeID(); - var base = context.history().base(); - function getIcon(d2) { - var entity = graph.entity(d2.id); - if (entity.id in icons) - return icons[entity.id]; - icons[entity.id] = entity.hasInterestingTags() && _mainPresetIndex.match(entity, graph).icon; - return icons[entity.id]; + function transform2(d2) { + let t2 = svgPointTransform(projection2)(d2); + if (d2.ca) { + t2 += " rotate(" + Math.floor(d2.ca) + ",0,0)"; } - function getDirections(entity) { - if (entity.id in directions) - return directions[entity.id]; - var angles = entity.directions(graph, projection2); - directions[entity.id] = angles.length ? angles : false; - return angles; + return t2; + } + function filterImages(images) { + const showsPano = context.photos().showsPanoramic(); + const showsFlat = context.photos().showsFlat(); + const fromDate = context.photos().fromDate(); + const toDate = context.photos().toDate(); + if (!showsPano || !showsFlat) { + images = images.filter(function(image) { + if (image.is_pano) + return showsPano; + return showsFlat; + }); } - function updateAttributes(selection3) { - ["shadow", "stroke", "fill"].forEach(function(klass) { - var rads = radiuses[klass]; - selection3.selectAll("." + klass).each(function(entity) { - var i3 = z2 && getIcon(entity); - var r2 = rads[i3 ? 3 : z2]; - if (entity.id !== activeID && entity.isEndpoint(graph) && !entity.isConnected(graph)) { - r2 += 1.5; - } - if (klass === "shadow") { - _radii[entity.id] = r2; - } - select_default2(this).attr("r", r2).attr("visibility", i3 && klass === "fill" ? "hidden" : null); - }); + if (fromDate) { + images = images.filter(function(image) { + return new Date(image.captured_at).getTime() >= new Date(fromDate).getTime(); }); } - vertices.sort(sortY); - var groups = selection2.selectAll("g.vertex").filter(filter2).data(vertices, fastEntityKey); - groups.exit().remove(); - var enter = groups.enter().append("g").attr("class", function(d2) { - return "node vertex " + d2.id; - }).order(); - enter.append("circle").attr("class", "shadow"); - enter.append("circle").attr("class", "stroke"); - enter.filter(function(d2) { - return d2.hasInterestingTags(); - }).append("circle").attr("class", "fill"); - groups = groups.merge(enter).attr("transform", svgPointTransform(projection2)).classed("sibling", function(d2) { - return d2.id in sets2.selected; - }).classed("shared", function(d2) { - return graph.isShared(d2); - }).classed("endpoint", function(d2) { - return d2.isEndpoint(graph); - }).classed("added", function(d2) { - return !base.entities[d2.id]; - }).classed("moved", function(d2) { - return base.entities[d2.id] && !(0, import_fast_deep_equal8.default)(graph.entities[d2.id].loc, base.entities[d2.id].loc); - }).classed("retagged", function(d2) { - return base.entities[d2.id] && !(0, import_fast_deep_equal8.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); - }).call(updateAttributes); - var iconUse = groups.selectAll(".icon").data(function data(d2) { - return zoom >= 17 && getIcon(d2) ? [d2] : []; - }, fastEntityKey); - iconUse.exit().remove(); - iconUse.enter().append("use").attr("class", "icon").attr("width", "12px").attr("height", "12px").attr("transform", "translate(-6, -6)").attr("xlink:href", function(d2) { - var picon = getIcon(d2); - return picon ? "#" + picon : ""; - }); - var dgroups = groups.selectAll(".viewfieldgroup").data(function data(d2) { - return zoom >= 18 && getDirections(d2) ? [d2] : []; - }, fastEntityKey); - dgroups.exit().remove(); - dgroups = dgroups.enter().insert("g", ".shadow").attr("class", "viewfieldgroup").merge(dgroups); - var viewfields = dgroups.selectAll(".viewfield").data(getDirections, function key(d2) { - return osmEntity.key(d2); - }); - viewfields.exit().remove(); - viewfields.enter().append("path").attr("class", "viewfield").attr("d", "M0,0H0").merge(viewfields).attr("marker-start", "url(#ideditor-viewfield-marker" + (wireframe ? "-wireframe" : "") + ")").attr("transform", function(d2) { - return "rotate(" + d2 + ")"; - }); - } - function drawTargets(selection2, graph, entities, filter2) { - var targetClass = context.getDebug("target") ? "pink " : "nocolor "; - var nopeClass = context.getDebug("target") ? "red " : "nocolor "; - var getTransform = svgPointTransform(projection2).geojson; - var activeID = context.activeID(); - var data = { targets: [], nopes: [] }; - entities.forEach(function(node) { - if (activeID === node.id) - return; - var vertexType = svgPassiveVertex(node, graph, activeID); - if (vertexType !== 0) { - data.targets.push({ - type: "Feature", - id: node.id, - properties: { - target: true, - entity: node - }, - geometry: node.asGeoJSON() - }); - } else { - data.nopes.push({ - type: "Feature", - id: node.id + "-nope", - properties: { - nope: true, - target: true, - entity: node - }, - geometry: node.asGeoJSON() - }); - } - }); - var targets = selection2.selectAll(".vertex.target-allowed").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(data.targets, function key(d2) { - return d2.id; - }); - targets.exit().remove(); - targets.enter().append("circle").attr("r", function(d2) { - return _radii[d2.id] || radiuses.shadow[3]; - }).merge(targets).attr("class", function(d2) { - return "node vertex target target-allowed " + targetClass + d2.id; - }).attr("transform", getTransform); - var nopes = selection2.selectAll(".vertex.target-nope").filter(function(d2) { - return filter2(d2.properties.entity); - }).data(data.nopes, function key(d2) { - return d2.id; - }); - nopes.exit().remove(); - nopes.enter().append("circle").attr("r", function(d2) { - return _radii[d2.properties.entity.id] || radiuses.shadow[3]; - }).merge(nopes).attr("class", function(d2) { - return "node vertex target target-nope " + nopeClass + d2.id; - }).attr("transform", getTransform); - } - function renderAsVertex(entity, graph, wireframe, zoom) { - var geometry = entity.geometry(graph); - return geometry === "vertex" || geometry === "point" && (wireframe || zoom >= 18 && entity.directions(graph, projection2).length); - } - function isEditedNode(node, base, head) { - var baseNode = base.entities[node.id]; - var headNode = head.entities[node.id]; - return !headNode || !baseNode || !(0, import_fast_deep_equal8.default)(headNode.tags, baseNode.tags) || !(0, import_fast_deep_equal8.default)(headNode.loc, baseNode.loc); + if (toDate) { + images = images.filter(function(image) { + return new Date(image.captured_at).getTime() <= new Date(toDate).getTime(); + }); + } + return images; } - function getSiblingAndChildVertices(ids, graph, wireframe, zoom) { - var results = {}; - var seenIds = {}; - function addChildVertices(entity) { - if (seenIds[entity.id]) - return; - seenIds[entity.id] = true; - var geometry = entity.geometry(graph); - if (!context.features().isHiddenFeature(entity, graph, geometry)) { - var i3; - if (entity.type === "way") { - for (i3 = 0; i3 < entity.nodes.length; i3++) { - var child = graph.hasEntity(entity.nodes[i3]); - if (child) { - addChildVertices(child); - } - } - } else if (entity.type === "relation") { - for (i3 = 0; i3 < entity.members.length; i3++) { - var member = graph.hasEntity(entity.members[i3].id); - if (member) { - addChildVertices(member); - } - } - } else if (renderAsVertex(entity, graph, wireframe, zoom)) { - results[entity.id] = entity; + function filterSequences(sequences) { + const showsPano = context.photos().showsPanoramic(); + const showsFlat = context.photos().showsFlat(); + const fromDate = context.photos().fromDate(); + const toDate = context.photos().toDate(); + if (!showsPano || !showsFlat) { + sequences = sequences.filter(function(sequence) { + if (sequence.properties.hasOwnProperty("is_pano")) { + if (sequence.properties.is_pano) + return showsPano; + return showsFlat; } - } + return false; + }); } - ids.forEach(function(id2) { - var entity = graph.hasEntity(id2); - if (!entity) - return; - if (entity.type === "node") { - if (renderAsVertex(entity, graph, wireframe, zoom)) { - results[entity.id] = entity; - graph.parentWays(entity).forEach(function(entity2) { - addChildVertices(entity2); - }); - } - } else { - addChildVertices(entity); - } - }); - return results; - } - function drawVertices(selection2, graph, entities, filter2, extent, fullRedraw) { - var wireframe = context.surface().classed("fill-wireframe"); - var visualDiff = context.surface().classed("highlight-edited"); - var zoom = geoScaleToZoom(projection2.scale()); - var mode = context.mode(); - var isMoving = mode && /^(add|draw|drag|move|rotate)/.test(mode.id); - var base = context.history().base(); - var drawLayer = selection2.selectAll(".layer-osm.points .points-group.vertices"); - var touchLayer = selection2.selectAll(".layer-touch.points"); - if (fullRedraw) { - _currPersistent = {}; - _radii = {}; + if (fromDate) { + sequences = sequences.filter(function(sequence) { + return new Date(sequence.properties.captured_at).getTime() >= new Date(fromDate).getTime().toString(); + }); } - for (var i3 = 0; i3 < entities.length; i3++) { - var entity = entities[i3]; - var geometry = entity.geometry(graph); - var keep = false; - if (geometry === "point" && renderAsVertex(entity, graph, wireframe, zoom)) { - _currPersistent[entity.id] = entity; - keep = true; - } else if (geometry === "vertex" && (entity.hasInterestingTags() || entity.isEndpoint(graph) || entity.isConnected(graph) || visualDiff && isEditedNode(entity, base, graph))) { - _currPersistent[entity.id] = entity; - keep = true; - } - if (!keep && !fullRedraw) { - delete _currPersistent[entity.id]; + if (toDate) { + sequences = sequences.filter(function(sequence) { + return new Date(sequence.properties.captured_at).getTime() <= new Date(toDate).getTime().toString(); + }); + } + return sequences; + } + function update() { + const z2 = ~~context.map().zoom(); + const showMarkers = z2 >= minMarkerZoom; + const showViewfields = z2 >= minViewfieldZoom2; + const service = getService(); + let sequences = service ? service.sequences(projection2) : []; + let images = service && showMarkers ? service.images(projection2) : []; + images = filterImages(images); + sequences = filterSequences(sequences, service); + service.filterViewer(context); + let traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { + return d2.properties.id; + }); + traces.exit().remove(); + traces = traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); + const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, function(d2) { + return d2.id; + }); + groups.exit().remove(); + const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); + groupsEnter.append("g").attr("class", "viewfield-scale"); + const markers = groups.merge(groupsEnter).sort(function(a2, b2) { + return b2.loc[1] - a2.loc[1]; + }).attr("transform", transform2).select(".viewfield-scale"); + markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); + const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + viewfields.exit().remove(); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").classed("pano", function() { + return this.parentNode.__data__.is_pano; + }).attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); + function viewfieldPath() { + if (this.parentNode.__data__.is_pano) { + return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; + } else { + return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; } } - var sets2 = { - persistent: _currPersistent, - // persistent = important vertices (render always) - selected: _currSelected, - // selected + siblings of selected (render always) - hovered: _currHover - // hovered + siblings of hovered (render only in draw modes) - }; - var all = Object.assign({}, isMoving ? _currHover : {}, _currSelected, _currPersistent); - var filterRendered = function(d2) { - return d2.id in _currPersistent || d2.id in _currSelected || d2.id in _currHover || filter2(d2); - }; - drawLayer.call(draw, graph, currentVisible(all), sets2, filterRendered); - var filterTouch = function(d2) { - return isMoving ? true : filterRendered(d2); - }; - touchLayer.call(drawTargets, graph, currentVisible(all), filterTouch); - function currentVisible(which) { - return Object.keys(which).map(graph.hasEntity, graph).filter(function(entity2) { - return entity2 && entity2.intersects(extent, graph); - }); + } + function drawImages(selection2) { + const enabled = svgMapillaryImages.enabled; + const service = getService(); + layer = selection2.selectAll(".layer-mapillary").data(service ? [0] : []); + layer.exit().remove(); + const layerEnter = layer.enter().append("g").attr("class", "layer-mapillary").style("display", enabled ? "block" : "none"); + layerEnter.append("g").attr("class", "sequences"); + layerEnter.append("g").attr("class", "markers"); + layer = layerEnter.merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadImages(projection2); + } else { + editOff(); + } } } - drawVertices.drawSelected = function(selection2, graph, extent) { - var wireframe = context.surface().classed("fill-wireframe"); - var zoom = geoScaleToZoom(projection2.scale()); - _prevSelected = _currSelected || {}; - if (context.map().isInWideSelection()) { - _currSelected = {}; - context.selectedIDs().forEach(function(id2) { - var entity = graph.hasEntity(id2); - if (!entity) - return; - if (entity.type === "node") { - if (renderAsVertex(entity, graph, wireframe, zoom)) { - _currSelected[entity.id] = entity; - } - } - }); + drawImages.enabled = function(_2) { + if (!arguments.length) + return svgMapillaryImages.enabled; + svgMapillaryImages.enabled = _2; + if (svgMapillaryImages.enabled) { + showLayer(); + context.photos().on("change.mapillary_images", update); } else { - _currSelected = getSiblingAndChildVertices(context.selectedIDs(), graph, wireframe, zoom); + hideLayer(); + context.photos().on("change.mapillary_images", null); } - var filter2 = function(d2) { - return d2.id in _prevSelected; - }; - drawVertices(selection2, graph, Object.values(_prevSelected), filter2, extent, false); + dispatch14.call("change"); + return this; }; - drawVertices.drawHover = function(selection2, graph, target, extent) { - if (target === _currHoverTarget) - return; - var wireframe = context.surface().classed("fill-wireframe"); - var zoom = geoScaleToZoom(projection2.scale()); - _prevHover = _currHover || {}; - _currHoverTarget = target; - var entity = target && target.properties && target.properties.entity; - if (entity) { - _currHover = getSiblingAndChildVertices([entity.id], graph, wireframe, zoom); - } else { - _currHover = {}; - } - var filter2 = function(d2) { - return d2.id in _prevHover; - }; - drawVertices(selection2, graph, Object.values(_prevHover), filter2, extent, false); + drawImages.supported = function() { + return !!getService(); }; - return drawVertices; + drawImages.rendered = function(zoom) { + return zoom >= minZoom4; + }; + init2(); + return drawImages; } - // modules/util/bind_once.js - function utilBindOnce(target, type2, listener, capture) { - var typeOnce = type2 + ".once"; - function one2() { - target.on(typeOnce, null); - listener.apply(this, arguments); + // modules/svg/mapillary_position.js + function svgMapillaryPosition(projection2, context) { + const throttledRedraw = throttle_default(function() { + update(); + }, 1e3); + const minZoom4 = 12; + const minViewfieldZoom2 = 18; + let layer = select_default2(null); + let _mapillary; + let viewerCompassAngle; + function init2() { + if (svgMapillaryPosition.initialized) + return; + svgMapillaryPosition.initialized = true; } - target.on(typeOnce, one2, capture); - return this; - } - - // modules/util/zoom_pan.js - function defaultFilter3(d3_event) { - return !d3_event.ctrlKey && !d3_event.button; - } - function defaultExtent2() { - var e3 = this; - if (e3 instanceof SVGElement) { - e3 = e3.ownerSVGElement || e3; - if (e3.hasAttribute("viewBox")) { - e3 = e3.viewBox.baseVal; - return [[e3.x, e3.y], [e3.x + e3.width, e3.y + e3.height]]; + function getService() { + if (services.mapillary && !_mapillary) { + _mapillary = services.mapillary; + _mapillary.event.on("imageChanged", throttledRedraw); + _mapillary.event.on("bearingChanged", function(e3) { + viewerCompassAngle = e3.bearing; + if (context.map().isTransformed()) + return; + layer.selectAll(".viewfield-group.currentView").filter(function(d2) { + return d2.is_pano; + }).attr("transform", transform2); + }); + } else if (!services.mapillary && _mapillary) { + _mapillary = null; } - return [[0, 0], [e3.width.baseVal.value, e3.height.baseVal.value]]; + return _mapillary; } - return [[0, 0], [e3.clientWidth, e3.clientHeight]]; - } - function defaultWheelDelta2(d3_event) { - return -d3_event.deltaY * (d3_event.deltaMode === 1 ? 0.05 : d3_event.deltaMode ? 1 : 2e-3); - } - function defaultConstrain2(transform2, extent, translateExtent) { - var dx0 = transform2.invertX(extent[0][0]) - translateExtent[0][0], dx1 = transform2.invertX(extent[1][0]) - translateExtent[1][0], dy0 = transform2.invertY(extent[0][1]) - translateExtent[0][1], dy1 = transform2.invertY(extent[1][1]) - translateExtent[1][1]; - return transform2.translate( - dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1), - dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1) - ); - } - function utilZoomPan() { - var filter2 = defaultFilter3, extent = defaultExtent2, constrain = defaultConstrain2, wheelDelta = defaultWheelDelta2, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], interpolate = zoom_default, dispatch14 = dispatch_default("start", "zoom", "end"), _wheelDelay = 150, _transform = identity2, _activeGesture; - function zoom(selection2) { - selection2.on("pointerdown.zoom", pointerdown).on("wheel.zoom", wheeled).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)"); - select_default2(window).on("pointermove.zoompan", pointermove).on("pointerup.zoompan pointercancel.zoompan", pointerup); + function editOn() { + layer.style("display", "block"); } - zoom.transform = function(collection, transform2, point2) { - var selection2 = collection.selection ? collection.selection() : collection; - if (collection !== selection2) { - schedule(collection, transform2, point2); + function editOff() { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); + } + function transform2(d2) { + let t2 = svgPointTransform(projection2)(d2); + if (d2.is_pano && viewerCompassAngle !== null && isFinite(viewerCompassAngle)) { + t2 += " rotate(" + Math.floor(viewerCompassAngle) + ",0,0)"; + } else if (d2.ca) { + t2 += " rotate(" + Math.floor(d2.ca) + ",0,0)"; + } + return t2; + } + function update() { + const z2 = ~~context.map().zoom(); + const showViewfields = z2 >= minViewfieldZoom2; + const service = getService(); + const image = service && service.getActiveImage(); + const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(image ? [image] : [], function(d2) { + return d2.id; + }); + groups.exit().remove(); + const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group currentView highlighted"); + groupsEnter.append("g").attr("class", "viewfield-scale"); + const markers = groups.merge(groupsEnter).attr("transform", transform2).select(".viewfield-scale"); + markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); + const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + viewfields.exit().remove(); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"); + } + function drawImages(selection2) { + const service = getService(); + layer = selection2.selectAll(".layer-mapillary-position").data(service ? [0] : []); + layer.exit().remove(); + const layerEnter = layer.enter().append("g").attr("class", "layer-mapillary-position"); + layerEnter.append("g").attr("class", "markers"); + layer = layerEnter.merge(layer); + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); } else { - selection2.interrupt().each(function() { - gesture(this, arguments).start(null).zoom(null, null, typeof transform2 === "function" ? transform2.apply(this, arguments) : transform2).end(null); - }); + editOff(); } + } + drawImages.enabled = function() { + update(); + return this; }; - zoom.scaleBy = function(selection2, k2, p2) { - zoom.scaleTo(selection2, function() { - var k0 = _transform.k, k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2; - return k0 * k1; - }, p2); - }; - zoom.scaleTo = function(selection2, k2, p2) { - zoom.transform(selection2, function() { - var e3 = extent.apply(this, arguments), t0 = _transform, p02 = !p2 ? centroid(e3) : typeof p2 === "function" ? p2.apply(this, arguments) : p2, p1 = t0.invert(p02), k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2; - return constrain(translate(scale(t0, k1), p02, p1), e3, translateExtent); - }, p2); - }; - zoom.translateBy = function(selection2, x2, y2) { - zoom.transform(selection2, function() { - return constrain(_transform.translate( - typeof x2 === "function" ? x2.apply(this, arguments) : x2, - typeof y2 === "function" ? y2.apply(this, arguments) : y2 - ), extent.apply(this, arguments), translateExtent); - }); + drawImages.supported = function() { + return !!getService(); }; - zoom.translateTo = function(selection2, x2, y2, p2) { - zoom.transform(selection2, function() { - var e3 = extent.apply(this, arguments), t2 = _transform, p02 = !p2 ? centroid(e3) : typeof p2 === "function" ? p2.apply(this, arguments) : p2; - return constrain(identity2.translate(p02[0], p02[1]).scale(t2.k).translate( - typeof x2 === "function" ? -x2.apply(this, arguments) : -x2, - typeof y2 === "function" ? -y2.apply(this, arguments) : -y2 - ), e3, translateExtent); - }, p2); + drawImages.rendered = function(zoom) { + return zoom >= minZoom4; }; - function scale(transform2, k2) { - k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k2)); - return k2 === transform2.k ? transform2 : new Transform(k2, transform2.x, transform2.y); + init2(); + return drawImages; + } + + // modules/svg/mapillary_signs.js + function svgMapillarySigns(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + const minZoom4 = 12; + let layer = select_default2(null); + let _mapillary; + function init2() { + if (svgMapillarySigns.initialized) + return; + svgMapillarySigns.enabled = false; + svgMapillarySigns.initialized = true; } - function translate(transform2, p02, p1) { - var x2 = p02[0] - p1[0] * transform2.k, y2 = p02[1] - p1[1] * transform2.k; - return x2 === transform2.x && y2 === transform2.y ? transform2 : new Transform(transform2.k, x2, y2); + function getService() { + if (services.mapillary && !_mapillary) { + _mapillary = services.mapillary; + _mapillary.event.on("loadedSigns", throttledRedraw); + } else if (!services.mapillary && _mapillary) { + _mapillary = null; + } + return _mapillary; } - function centroid(extent2) { - return [(+extent2[0][0] + +extent2[1][0]) / 2, (+extent2[0][1] + +extent2[1][1]) / 2]; + function showLayer() { + const service = getService(); + if (!service) + return; + service.loadSignResources(context); + editOn(); } - function schedule(transition2, transform2, point2) { - transition2.on("start.zoom", function() { - gesture(this, arguments).start(null); - }).on("interrupt.zoom end.zoom", function() { - gesture(this, arguments).end(null); - }).tween("zoom", function() { - var that = this, args = arguments, g3 = gesture(that, args), e3 = extent.apply(that, args), p2 = !point2 ? centroid(e3) : typeof point2 === "function" ? point2.apply(that, args) : point2, w2 = Math.max(e3[1][0] - e3[0][0], e3[1][1] - e3[0][1]), a2 = _transform, b2 = typeof transform2 === "function" ? transform2.apply(that, args) : transform2, i3 = interpolate(a2.invert(p2).concat(w2 / a2.k), b2.invert(p2).concat(w2 / b2.k)); - return function(t2) { - if (t2 === 1) { - t2 = b2; - } else { - var l2 = i3(t2); - var k2 = w2 / l2[2]; - t2 = new Transform(k2, p2[0] - l2[0] * k2, p2[1] - l2[1] * k2); - } - g3.zoom(null, null, t2); - }; - }); + function hideLayer() { + throttledRedraw.cancel(); + editOff(); } - function gesture(that, args, clean2) { - return !clean2 && _activeGesture || new Gesture(that, args); + function editOn() { + layer.style("display", "block"); } - function Gesture(that, args) { - this.that = that; - this.args = args; - this.active = 0; - this.extent = extent.apply(that, args); + function editOff() { + layer.selectAll(".icon-sign").remove(); + layer.style("display", "none"); } - Gesture.prototype = { - start: function(d3_event) { - if (++this.active === 1) { - _activeGesture = this; - dispatch14.call("start", this, d3_event); - } - return this; - }, - zoom: function(d3_event, key, transform2) { - if (this.mouse && key !== "mouse") - this.mouse[1] = transform2.invert(this.mouse[0]); - if (this.pointer0 && key !== "touch") - this.pointer0[1] = transform2.invert(this.pointer0[0]); - if (this.pointer1 && key !== "touch") - this.pointer1[1] = transform2.invert(this.pointer1[0]); - _transform = transform2; - dispatch14.call("zoom", this, d3_event, key, transform2); - return this; - }, - end: function(d3_event) { - if (--this.active === 0) { - _activeGesture = null; - dispatch14.call("end", this, d3_event); - } - return this; - } - }; - function wheeled(d3_event) { - if (!filter2.apply(this, arguments)) + function click(d3_event, d2) { + const service = getService(); + if (!service) return; - var g3 = gesture(this, arguments), t2 = _transform, k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t2.k * Math.pow(2, wheelDelta.apply(this, arguments)))), p2 = utilFastMouse(this)(d3_event); - if (g3.wheel) { - if (g3.mouse[0][0] !== p2[0] || g3.mouse[0][1] !== p2[1]) { - g3.mouse[1] = t2.invert(g3.mouse[0] = p2); + context.map().centerEase(d2.loc); + const selectedImageId = service.getActiveImage() && service.getActiveImage().id; + service.getDetections(d2.id).then((detections) => { + if (detections.length) { + const imageId = detections[0].image.id; + if (imageId === selectedImageId) { + service.highlightDetection(detections[0]).selectImage(context, imageId); + } else { + service.ensureViewerLoaded(context).then(function() { + service.highlightDetection(detections[0]).selectImage(context, imageId).showViewer(context); + }); + } } - clearTimeout(g3.wheel); - } else { - g3.mouse = [p2, t2.invert(p2)]; - interrupt_default(this); - g3.start(d3_event); - } - d3_event.preventDefault(); - d3_event.stopImmediatePropagation(); - g3.wheel = setTimeout(wheelidled, _wheelDelay); - g3.zoom(d3_event, "mouse", constrain(translate(scale(t2, k2), g3.mouse[0], g3.mouse[1]), g3.extent, translateExtent)); - function wheelidled() { - g3.wheel = null; - g3.end(d3_event); - } + }); } - var _downPointerIDs = /* @__PURE__ */ new Set(); - var _pointerLocGetter; - function pointerdown(d3_event) { - _downPointerIDs.add(d3_event.pointerId); - if (!filter2.apply(this, arguments)) - return; - var g3 = gesture(this, arguments, _downPointerIDs.size === 1); - var started; - d3_event.stopImmediatePropagation(); - _pointerLocGetter = utilFastMouse(this); - var loc = _pointerLocGetter(d3_event); - var p2 = [loc, _transform.invert(loc), d3_event.pointerId]; - if (!g3.pointer0) { - g3.pointer0 = p2; - started = true; - } else if (!g3.pointer1 && g3.pointer0[2] !== p2[2]) { - g3.pointer1 = p2; + function filterData(detectedFeatures) { + var fromDate = context.photos().fromDate(); + var toDate = context.photos().toDate(); + if (fromDate) { + var fromTimestamp = new Date(fromDate).getTime(); + detectedFeatures = detectedFeatures.filter(function(feature3) { + return new Date(feature3.last_seen_at).getTime() >= fromTimestamp; + }); } - if (started) { - interrupt_default(this); - g3.start(d3_event); + if (toDate) { + var toTimestamp = new Date(toDate).getTime(); + detectedFeatures = detectedFeatures.filter(function(feature3) { + return new Date(feature3.first_seen_at).getTime() <= toTimestamp; + }); } + return detectedFeatures; } - function pointermove(d3_event) { - if (!_downPointerIDs.has(d3_event.pointerId)) - return; - if (!_activeGesture || !_pointerLocGetter) - return; - var g3 = gesture(this, arguments); - var isPointer0 = g3.pointer0 && g3.pointer0[2] === d3_event.pointerId; - var isPointer1 = !isPointer0 && g3.pointer1 && g3.pointer1[2] === d3_event.pointerId; - if ((isPointer0 || isPointer1) && "buttons" in d3_event && !d3_event.buttons) { - if (g3.pointer0) - _downPointerIDs.delete(g3.pointer0[2]); - if (g3.pointer1) - _downPointerIDs.delete(g3.pointer1[2]); - g3.end(d3_event); - return; - } - d3_event.preventDefault(); - d3_event.stopImmediatePropagation(); - var loc = _pointerLocGetter(d3_event); - var t2, p2, l2; - if (isPointer0) - g3.pointer0[0] = loc; - else if (isPointer1) - g3.pointer1[0] = loc; - t2 = _transform; - if (g3.pointer1) { - var p02 = g3.pointer0[0], l0 = g3.pointer0[1], p1 = g3.pointer1[0], l1 = g3.pointer1[1], dp = (dp = p1[0] - p02[0]) * dp + (dp = p1[1] - p02[1]) * dp, dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl; - t2 = scale(t2, Math.sqrt(dp / dl)); - p2 = [(p02[0] + p1[0]) / 2, (p02[1] + p1[1]) / 2]; - l2 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2]; - } else if (g3.pointer0) { - p2 = g3.pointer0[0]; - l2 = g3.pointer0[1]; - } else { - return; - } - g3.zoom(d3_event, "touch", constrain(translate(t2, p2, l2), g3.extent, translateExtent)); + function update() { + const service = getService(); + let data = service ? service.signs(projection2) : []; + data = filterData(data); + const transform2 = svgPointTransform(projection2); + const signs = layer.selectAll(".icon-sign").data(data, function(d2) { + return d2.id; + }); + signs.exit().remove(); + const enter = signs.enter().append("g").attr("class", "icon-sign icon-detected").on("click", click); + enter.append("use").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px").attr("xlink:href", function(d2) { + return "#" + d2.value; + }); + enter.append("rect").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px"); + signs.merge(enter).attr("transform", transform2); } - function pointerup(d3_event) { - if (!_downPointerIDs.has(d3_event.pointerId)) - return; - _downPointerIDs.delete(d3_event.pointerId); - if (!_activeGesture) - return; - var g3 = gesture(this, arguments); - d3_event.stopImmediatePropagation(); - if (g3.pointer0 && g3.pointer0[2] === d3_event.pointerId) - delete g3.pointer0; - else if (g3.pointer1 && g3.pointer1[2] === d3_event.pointerId) - delete g3.pointer1; - if (g3.pointer1 && !g3.pointer0) { - g3.pointer0 = g3.pointer1; - delete g3.pointer1; + function drawSigns(selection2) { + const enabled = svgMapillarySigns.enabled; + const service = getService(); + layer = selection2.selectAll(".layer-mapillary-signs").data(service ? [0] : []); + layer.exit().remove(); + layer = layer.enter().append("g").attr("class", "layer-mapillary-signs layer-mapillary-detections").style("display", enabled ? "block" : "none").merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadSigns(projection2); + service.showSignDetections(true); + } else { + editOff(); + } + } else if (service) { + service.showSignDetections(false); } - if (g3.pointer0) { - g3.pointer0[1] = _transform.invert(g3.pointer0[0]); + } + drawSigns.enabled = function(_2) { + if (!arguments.length) + return svgMapillarySigns.enabled; + svgMapillarySigns.enabled = _2; + if (svgMapillarySigns.enabled) { + showLayer(); + context.photos().on("change.mapillary_signs", update); } else { - g3.end(d3_event); + hideLayer(); + context.photos().on("change.mapillary_signs", null); } - } - zoom.wheelDelta = function(_2) { - return arguments.length ? (wheelDelta = utilFunctor(+_2), zoom) : wheelDelta; - }; - zoom.filter = function(_2) { - return arguments.length ? (filter2 = utilFunctor(!!_2), zoom) : filter2; - }; - zoom.extent = function(_2) { - return arguments.length ? (extent = utilFunctor([[+_2[0][0], +_2[0][1]], [+_2[1][0], +_2[1][1]]]), zoom) : extent; - }; - zoom.scaleExtent = function(_2) { - return arguments.length ? (scaleExtent[0] = +_2[0], scaleExtent[1] = +_2[1], zoom) : [scaleExtent[0], scaleExtent[1]]; - }; - zoom.translateExtent = function(_2) { - return arguments.length ? (translateExtent[0][0] = +_2[0][0], translateExtent[1][0] = +_2[1][0], translateExtent[0][1] = +_2[0][1], translateExtent[1][1] = +_2[1][1], zoom) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]]; - }; - zoom.constrain = function(_2) { - return arguments.length ? (constrain = _2, zoom) : constrain; + dispatch14.call("change"); + return this; }; - zoom.interpolate = function(_2) { - return arguments.length ? (interpolate = _2, zoom) : interpolate; + drawSigns.supported = function() { + return !!getService(); }; - zoom._transform = function(_2) { - return arguments.length ? (_transform = _2, zoom) : _transform; + drawSigns.rendered = function(zoom) { + return zoom >= minZoom4; }; - return utilRebind(zoom, dispatch14, "on"); + init2(); + return drawSigns; } - // modules/util/double_up.js - function utilDoubleUp() { - var dispatch14 = dispatch_default("doubleUp"); - var _maxTimespan = 500; - var _maxDistance = 20; - var _pointer; - function pointerIsValidFor(loc) { - return (/* @__PURE__ */ new Date()).getTime() - _pointer.startTime <= _maxTimespan && // all pointer events must occur within a small distance of the first pointerdown - geoVecLength(_pointer.startLoc, loc) <= _maxDistance; - } - function pointerdown(d3_event) { - if (d3_event.ctrlKey || d3_event.button === 2) + // modules/svg/mapillary_map_features.js + function svgMapillaryMapFeatures(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + const minZoom4 = 12; + let layer = select_default2(null); + let _mapillary; + function init2() { + if (svgMapillaryMapFeatures.initialized) return; - var loc = [d3_event.clientX, d3_event.clientY]; - if (_pointer && !pointerIsValidFor(loc)) { - _pointer = void 0; - } - if (!_pointer) { - _pointer = { - startLoc: loc, - startTime: (/* @__PURE__ */ new Date()).getTime(), - upCount: 0, - pointerId: d3_event.pointerId - }; - } else { - _pointer.pointerId = d3_event.pointerId; + svgMapillaryMapFeatures.enabled = false; + svgMapillaryMapFeatures.initialized = true; + } + function getService() { + if (services.mapillary && !_mapillary) { + _mapillary = services.mapillary; + _mapillary.event.on("loadedMapFeatures", throttledRedraw); + } else if (!services.mapillary && _mapillary) { + _mapillary = null; } + return _mapillary; } - function pointerup(d3_event) { - if (d3_event.ctrlKey || d3_event.button === 2) + function showLayer() { + const service = getService(); + if (!service) return; - if (!_pointer || _pointer.pointerId !== d3_event.pointerId) + service.loadObjectResources(context); + editOn(); + } + function hideLayer() { + throttledRedraw.cancel(); + editOff(); + } + function editOn() { + layer.style("display", "block"); + } + function editOff() { + layer.selectAll(".icon-map-feature").remove(); + layer.style("display", "none"); + } + function click(d3_event, d2) { + const service = getService(); + if (!service) return; - _pointer.upCount += 1; - if (_pointer.upCount === 2) { - var loc = [d3_event.clientX, d3_event.clientY]; - if (pointerIsValidFor(loc)) { - var locInThis = utilFastMouse(this)(d3_event); - dispatch14.call("doubleUp", this, d3_event, locInThis); + context.map().centerEase(d2.loc); + const selectedImageId = service.getActiveImage() && service.getActiveImage().id; + service.getDetections(d2.id).then((detections) => { + if (detections.length) { + const imageId = detections[0].image.id; + if (imageId === selectedImageId) { + service.highlightDetection(detections[0]).selectImage(context, imageId); + } else { + service.ensureViewerLoaded(context).then(function() { + service.highlightDetection(detections[0]).selectImage(context, imageId).showViewer(context); + }); + } } - _pointer = void 0; - } + }); } - function doubleUp(selection2) { - if ("PointerEvent" in window) { - selection2.on("pointerdown.doubleUp", pointerdown).on("pointerup.doubleUp", pointerup); - } else { - selection2.on("dblclick.doubleUp", function(d3_event) { - dispatch14.call("doubleUp", this, d3_event, utilFastMouse(this)(d3_event)); + function filterData(detectedFeatures) { + const fromDate = context.photos().fromDate(); + const toDate = context.photos().toDate(); + if (fromDate) { + detectedFeatures = detectedFeatures.filter(function(feature3) { + return new Date(feature3.last_seen_at).getTime() >= new Date(fromDate).getTime(); + }); + } + if (toDate) { + detectedFeatures = detectedFeatures.filter(function(feature3) { + return new Date(feature3.first_seen_at).getTime() <= new Date(toDate).getTime(); }); } + return detectedFeatures; } - doubleUp.off = function(selection2) { - selection2.on("pointerdown.doubleUp", null).on("pointerup.doubleUp", null).on("dblclick.doubleUp", null); + function update() { + const service = getService(); + let data = service ? service.mapFeatures(projection2) : []; + data = filterData(data); + const transform2 = svgPointTransform(projection2); + const mapFeatures = layer.selectAll(".icon-map-feature").data(data, function(d2) { + return d2.id; + }); + mapFeatures.exit().remove(); + const enter = mapFeatures.enter().append("g").attr("class", "icon-map-feature icon-detected").on("click", click); + enter.append("title").text(function(d2) { + var id2 = d2.value.replace(/--/g, ".").replace(/-/g, "_"); + return _t("mapillary_map_features." + id2); + }); + enter.append("use").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px").attr("xlink:href", function(d2) { + if (d2.value === "object--billboard") { + return "#object--sign--advertisement"; + } + return "#" + d2.value; + }); + enter.append("rect").attr("width", "24px").attr("height", "24px").attr("x", "-12px").attr("y", "-12px"); + mapFeatures.merge(enter).attr("transform", transform2); + } + function drawMapFeatures(selection2) { + const enabled = svgMapillaryMapFeatures.enabled; + const service = getService(); + layer = selection2.selectAll(".layer-mapillary-map-features").data(service ? [0] : []); + layer.exit().remove(); + layer = layer.enter().append("g").attr("class", "layer-mapillary-map-features layer-mapillary-detections").style("display", enabled ? "block" : "none").merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadMapFeatures(projection2); + service.showFeatureDetections(true); + } else { + editOff(); + } + } else if (service) { + service.showFeatureDetections(false); + } + } + drawMapFeatures.enabled = function(_2) { + if (!arguments.length) + return svgMapillaryMapFeatures.enabled; + svgMapillaryMapFeatures.enabled = _2; + if (svgMapillaryMapFeatures.enabled) { + showLayer(); + context.photos().on("change.mapillary_map_features", update); + } else { + hideLayer(); + context.photos().on("change.mapillary_map_features", null); + } + dispatch14.call("change"); + return this; }; - return utilRebind(doubleUp, dispatch14, "on"); + drawMapFeatures.supported = function() { + return !!getService(); + }; + drawMapFeatures.rendered = function(zoom) { + return zoom >= minZoom4; + }; + init2(); + return drawMapFeatures; } - // modules/renderer/map.js - var TILESIZE = 256; - var minZoom2 = 2; - var maxZoom = 24; - var kMin = geoZoomToScale(minZoom2, TILESIZE); - var kMax = geoZoomToScale(maxZoom, TILESIZE); - function clamp(num, min3, max3) { - return Math.max(min3, Math.min(num, max3)); - } - function rendererMap(context) { - var dispatch14 = dispatch_default( - "move", - "drawn", - "crossEditableZoom", - "hitMinZoom", - "changeHighlighting", - "changeAreaFill" - ); - var projection2 = context.projection; - var curtainProjection = context.curtainProjection; - var drawLayers; - var drawPoints; - var drawVertices; - var drawLines; - var drawAreas; - var drawMidpoints; - var drawLabels; - var _selection = select_default2(null); - var supersurface = select_default2(null); - var wrapper = select_default2(null); - var surface = select_default2(null); - var _dimensions = [1, 1]; - var _dblClickZoomEnabled = true; - var _redrawEnabled = true; - var _gestureTransformStart; - var _transformStart = projection2.transform(); - var _transformLast; - var _isTransformed = false; - var _minzoom = 0; - var _getMouseCoords; - var _lastPointerEvent; - var _lastWithinEditableZoom; - var _pointerDown = false; - var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; - var _zoomerPannerFunction = "PointerEvent" in window ? utilZoomPan : zoom_default2; - var _zoomerPanner = _zoomerPannerFunction().scaleExtent([kMin, kMax]).interpolate(value_default).filter(zoomEventFilter).on("zoom.map", zoomPan2).on("start.map", function(d3_event) { - _pointerDown = d3_event && (d3_event.type === "pointerdown" || d3_event.sourceEvent && d3_event.sourceEvent.type === "pointerdown"); - }).on("end.map", function() { - _pointerDown = false; - }); - var _doubleUpHandler = utilDoubleUp(); - var scheduleRedraw = throttle_default(redraw, 750); - function cancelPendingRedraw() { - scheduleRedraw.cancel(); + // modules/svg/kartaview_images.js + function svgKartaviewImages(projection2, context, dispatch14) { + var throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + var minZoom4 = 12; + var minMarkerZoom = 16; + var minViewfieldZoom2 = 18; + var layer = select_default2(null); + var _kartaview; + function init2() { + if (svgKartaviewImages.initialized) + return; + svgKartaviewImages.enabled = false; + svgKartaviewImages.initialized = true; } - function map2(selection2) { - _selection = selection2; - context.on("change.map", immediateRedraw); - var osm = context.connection(); - if (osm) { - osm.on("change.map", immediateRedraw); - } - function didUndoOrRedo(targetTransform) { - var mode = context.mode().id; - if (mode !== "browse" && mode !== "select") - return; - if (targetTransform) { - map2.transformEase(targetTransform); - } + function getService() { + if (services.kartaview && !_kartaview) { + _kartaview = services.kartaview; + _kartaview.event.on("loadedImages", throttledRedraw); + } else if (!services.kartaview && _kartaview) { + _kartaview = null; } - context.history().on("merge.map", function() { - scheduleRedraw(); - }).on("change.map", immediateRedraw).on("undone.map", function(stack, fromStack) { - didUndoOrRedo(fromStack.transform); - }).on("redone.map", function(stack) { - didUndoOrRedo(stack.transform); - }); - context.background().on("change.map", immediateRedraw); - context.features().on("redraw.map", immediateRedraw); - drawLayers.on("change.map", function() { - context.background().updateImagery(); - immediateRedraw(); + return _kartaview; + } + function showLayer() { + var service = getService(); + if (!service) + return; + editOn(); + layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { + dispatch14.call("change"); }); - selection2.on("wheel.map mousewheel.map", function(d3_event) { - d3_event.preventDefault(); - }).call(_zoomerPanner).call(_zoomerPanner.transform, projection2.transform()).on("dblclick.zoom", null); - map2.supersurface = supersurface = selection2.append("div").attr("class", "supersurface").call(utilSetTransform, 0, 0); - wrapper = supersurface.append("div").attr("class", "layer layer-data"); - map2.surface = surface = wrapper.call(drawLayers).selectAll(".surface"); - surface.call(drawLabels.observe).call(_doubleUpHandler).on(_pointerPrefix + "down.zoom", function(d3_event) { - _lastPointerEvent = d3_event; - if (d3_event.button === 2) { - d3_event.stopPropagation(); - } - }, true).on(_pointerPrefix + "up.zoom", function(d3_event) { - _lastPointerEvent = d3_event; - if (resetTransform()) { - immediateRedraw(); - } - }).on(_pointerPrefix + "move.map", function(d3_event) { - _lastPointerEvent = d3_event; - }).on(_pointerPrefix + "over.vertices", function(d3_event) { - if (map2.editableDataEnabled() && !_isTransformed) { - var hover = d3_event.target.__data__; - surface.call(drawVertices.drawHover, context.graph(), hover, map2.extent()); - dispatch14.call("drawn", this, { full: false }); - } - }).on(_pointerPrefix + "out.vertices", function(d3_event) { - if (map2.editableDataEnabled() && !_isTransformed) { - var hover = d3_event.relatedTarget && d3_event.relatedTarget.__data__; - surface.call(drawVertices.drawHover, context.graph(), hover, map2.extent()); - dispatch14.call("drawn", this, { full: false }); - } + } + function hideLayer() { + throttledRedraw.cancel(); + layer.transition().duration(250).style("opacity", 0).on("end", editOff); + } + function editOn() { + layer.style("display", "block"); + } + function editOff() { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); + } + function click(d3_event, d2) { + var service = getService(); + if (!service) + return; + service.ensureViewerLoaded(context).then(function() { + service.selectImage(context, d2.key).showViewer(context); }); - var detected = utilDetect(); - if ("GestureEvent" in window && // Listening for gesture events on iOS 13.4+ breaks double-tapping, - // but we only need to do this on desktop Safari anyway. – #7694 - !detected.isMobileWebKit) { - surface.on("gesturestart.surface", function(d3_event) { - d3_event.preventDefault(); - _gestureTransformStart = projection2.transform(); - }).on("gesturechange.surface", gestureChange); + context.map().centerEase(d2.loc); + } + function mouseover(d3_event, d2) { + var service = getService(); + if (service) + service.setStyles(context, d2); + } + function mouseout() { + var service = getService(); + if (service) + service.setStyles(context, null); + } + function transform2(d2) { + var t2 = svgPointTransform(projection2)(d2); + if (d2.ca) { + t2 += " rotate(" + Math.floor(d2.ca) + ",0,0)"; } - updateAreaFill(); - _doubleUpHandler.on("doubleUp.map", function(d3_event, p02) { - if (!_dblClickZoomEnabled) - return; - if (typeof d3_event.target.__data__ === "object" && // or area fills - !select_default2(d3_event.target).classed("fill")) - return; - var zoomOut2 = d3_event.shiftKey; - var t2 = projection2.transform(); - var p1 = t2.invert(p02); - t2 = t2.scale(zoomOut2 ? 0.5 : 2); - t2.x = p02[0] - p1[0] * t2.k; - t2.y = p02[1] - p1[1] * t2.k; - map2.transformEase(t2); - }); - context.on("enter.map", function() { - if (!map2.editableDataEnabled( - true - /* skip zoom check */ - )) - return; - if (_isTransformed) - return; - var graph = context.graph(); - var selectedAndParents = {}; - context.selectedIDs().forEach(function(id2) { - var entity = graph.hasEntity(id2); - if (entity) { - selectedAndParents[entity.id] = entity; - if (entity.type === "node") { - graph.parentWays(entity).forEach(function(parent) { - selectedAndParents[parent.id] = parent; - }); - } - } + return t2; + } + function filterImages(images) { + var fromDate = context.photos().fromDate(); + var toDate = context.photos().toDate(); + var usernames = context.photos().usernames(); + if (fromDate) { + var fromTimestamp = new Date(fromDate).getTime(); + images = images.filter(function(item) { + return new Date(item.captured_at).getTime() >= fromTimestamp; }); - var data = Object.values(selectedAndParents); - var filter2 = function(d2) { - return d2.id in selectedAndParents; - }; - data = context.features().filter(data, graph); - surface.call(drawVertices.drawSelected, graph, map2.extent()).call(drawLines, graph, data, filter2).call(drawAreas, graph, data, filter2).call(drawMidpoints, graph, data, filter2, map2.trimmedExtent()); - dispatch14.call("drawn", this, { full: false }); - scheduleRedraw(); - }); - map2.dimensions(utilGetDimensions(selection2)); + } + if (toDate) { + var toTimestamp = new Date(toDate).getTime(); + images = images.filter(function(item) { + return new Date(item.captured_at).getTime() <= toTimestamp; + }); + } + if (usernames) { + images = images.filter(function(item) { + return usernames.indexOf(item.captured_by) !== -1; + }); + } + return images; } - function zoomEventFilter(d3_event) { - if (d3_event.type === "mousedown") { - var hasOrphan = false; - var listeners = window.__on; - for (var i3 = 0; i3 < listeners.length; i3++) { - var listener = listeners[i3]; - if (listener.name === "zoom" && listener.type === "mouseup") { - hasOrphan = true; - break; - } - } - if (hasOrphan) { - var event = window.CustomEvent; - if (event) { - event = new event("mouseup"); - } else { - event = window.document.createEvent("Event"); - event.initEvent("mouseup", false, false); - } - event.view = window; - window.dispatchEvent(event); - } + function filterSequences(sequences) { + var fromDate = context.photos().fromDate(); + var toDate = context.photos().toDate(); + var usernames = context.photos().usernames(); + if (fromDate) { + var fromTimestamp = new Date(fromDate).getTime(); + sequences = sequences.filter(function(image) { + return new Date(image.properties.captured_at).getTime() >= fromTimestamp; + }); + } + if (toDate) { + var toTimestamp = new Date(toDate).getTime(); + sequences = sequences.filter(function(image) { + return new Date(image.properties.captured_at).getTime() <= toTimestamp; + }); } - return d3_event.button !== 2; + if (usernames) { + sequences = sequences.filter(function(image) { + return usernames.indexOf(image.properties.captured_by) !== -1; + }); + } + return sequences; } - function pxCenter() { - return [_dimensions[0] / 2, _dimensions[1] / 2]; + function update() { + var viewer = context.container().select(".photoviewer"); + var selected = viewer.empty() ? void 0 : viewer.datum(); + var z2 = ~~context.map().zoom(); + var showMarkers = z2 >= minMarkerZoom; + var showViewfields = z2 >= minViewfieldZoom2; + var service = getService(); + var sequences = []; + var images = []; + if (context.photos().showsFlat()) { + sequences = service ? service.sequences(projection2) : []; + images = service && showMarkers ? service.images(projection2) : []; + sequences = filterSequences(sequences); + images = filterImages(images); + } + var traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { + return d2.properties.key; + }); + traces.exit().remove(); + traces = traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); + var groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, function(d2) { + return d2.key; + }); + groups.exit().remove(); + var groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); + groupsEnter.append("g").attr("class", "viewfield-scale"); + var markers = groups.merge(groupsEnter).sort(function(a2, b2) { + return a2 === selected ? 1 : b2 === selected ? -1 : b2.loc[1] - a2.loc[1]; + }).attr("transform", transform2).select(".viewfield-scale"); + markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); + var viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + viewfields.exit().remove(); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"); } - function drawEditable(difference, extent) { - var mode = context.mode(); - var graph = context.graph(); - var features = context.features(); - var all = context.history().intersects(map2.extent()); - var fullRedraw = false; - var data; - var set3; - var filter2; - var applyFeatureLayerFilters = true; - if (map2.isInWideSelection()) { - data = []; - utilEntityAndDeepMemberIDs(mode.selectedIDs(), context.graph()).forEach(function(id2) { - var entity = context.hasEntity(id2); - if (entity) - data.push(entity); - }); - fullRedraw = true; - filter2 = utilFunctor(true); - applyFeatureLayerFilters = false; - } else if (difference) { - var complete = difference.complete(map2.extent()); - data = Object.values(complete).filter(Boolean); - set3 = new Set(Object.keys(complete)); - filter2 = function(d2) { - return set3.has(d2.id); - }; - features.clear(data); - } else { - if (features.gatherStats(all, graph, _dimensions)) { - extent = void 0; - } - if (extent) { - data = context.history().intersects(map2.extent().intersection(extent)); - set3 = new Set(data.map(function(entity) { - return entity.id; - })); - filter2 = function(d2) { - return set3.has(d2.id); - }; + function drawImages(selection2) { + var enabled = svgKartaviewImages.enabled, service = getService(); + layer = selection2.selectAll(".layer-kartaview").data(service ? [0] : []); + layer.exit().remove(); + var layerEnter = layer.enter().append("g").attr("class", "layer-kartaview").style("display", enabled ? "block" : "none"); + layerEnter.append("g").attr("class", "sequences"); + layerEnter.append("g").attr("class", "markers"); + layer = layerEnter.merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadImages(projection2); } else { - data = all; - fullRedraw = true; - filter2 = utilFunctor(true); + editOff(); } } - if (applyFeatureLayerFilters) { - data = features.filter(data, graph); + } + drawImages.enabled = function(_2) { + if (!arguments.length) + return svgKartaviewImages.enabled; + svgKartaviewImages.enabled = _2; + if (svgKartaviewImages.enabled) { + showLayer(); + context.photos().on("change.kartaview_images", update); } else { - context.features().resetStats(); - } - if (mode && mode.id === "select") { - surface.call(drawVertices.drawSelected, graph, map2.extent()); + hideLayer(); + context.photos().on("change.kartaview_images", null); } - surface.call(drawVertices, graph, data, filter2, map2.extent(), fullRedraw).call(drawLines, graph, data, filter2).call(drawAreas, graph, data, filter2).call(drawMidpoints, graph, data, filter2, map2.trimmedExtent()).call(drawLabels, graph, data, filter2, _dimensions, fullRedraw).call(drawPoints, graph, data, filter2); - dispatch14.call("drawn", this, { full: true }); - } - map2.init = function() { - drawLayers = svgLayers(projection2, context); - drawPoints = svgPoints(projection2, context); - drawVertices = svgVertices(projection2, context); - drawLines = svgLines(projection2, context); - drawAreas = svgAreas(projection2, context); - drawMidpoints = svgMidpoints(projection2, context); - drawLabels = svgLabels(projection2, context); + dispatch14.call("change"); + return this; }; - function editOff() { - context.features().resetStats(); - surface.selectAll(".layer-osm *").remove(); - surface.selectAll(".layer-touch:not(.markers) *").remove(); - var allowed = { - "browse": true, - "save": true, - "select-note": true, - "select-data": true, - "select-error": true - }; - var mode = context.mode(); - if (mode && !allowed[mode.id]) { - context.enter(modeBrowse(context)); - } - dispatch14.call("drawn", this, { full: true }); - } - function gestureChange(d3_event) { - var e3 = d3_event; - e3.preventDefault(); - var props = { - deltaMode: 0, - // dummy values to ignore in zoomPan - deltaY: 1, - // dummy values to ignore in zoomPan - clientX: e3.clientX, - clientY: e3.clientY, - screenX: e3.screenX, - screenY: e3.screenY, - x: e3.x, - y: e3.y - }; - var e22 = new WheelEvent("wheel", props); - e22._scale = e3.scale; - e22._rotation = e3.rotation; - _selection.node().dispatchEvent(e22); + drawImages.supported = function() { + return !!getService(); + }; + drawImages.rendered = function(zoom) { + return zoom >= minZoom4; + }; + init2(); + return drawImages; + } + + // modules/svg/mapilio_images.js + function svgMapilioImages(projection2, context, dispatch14) { + const throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + const minZoom4 = 12; + let layer = select_default2(null); + let _mapilio; + const viewFieldZoomLevel = 18; + function init2() { + if (svgMapilioImages.initialized) + return; + svgMapilioImages.enabled = false; + svgMapilioImages.initialized = true; } - function zoomPan2(event, key, transform2) { - var source = event && event.sourceEvent || event; - var eventTransform = transform2 || event && event.transform; - var x2 = eventTransform.x; - var y2 = eventTransform.y; - var k2 = eventTransform.k; - if (source && source.type === "wheel") { - if (_pointerDown) - return; - var detected = utilDetect(); - var dX = source.deltaX; - var dY = source.deltaY; - var x22 = x2; - var y22 = y2; - var k22 = k2; - var t0, p02, p1; - if (source.deltaMode === 1) { - var lines = Math.abs(source.deltaY); - var sign2 = source.deltaY > 0 ? 1 : -1; - dY = sign2 * clamp( - Math.exp((lines - 1) * 0.75) * 4.000244140625, - 4.000244140625, - // min - 350.000244140625 - // max - ); - if (detected.os !== "mac") { - dY *= 5; - } - t0 = _isTransformed ? _transformLast : _transformStart; - p02 = _getMouseCoords(source); - p1 = t0.invert(p02); - k22 = t0.k * Math.pow(2, -dY / 500); - k22 = clamp(k22, kMin, kMax); - x22 = p02[0] - p1[0] * k22; - y22 = p02[1] - p1[1] * k22; - } else if (source._scale) { - t0 = _gestureTransformStart; - p02 = _getMouseCoords(source); - p1 = t0.invert(p02); - k22 = t0.k * source._scale; - k22 = clamp(k22, kMin, kMax); - x22 = p02[0] - p1[0] * k22; - y22 = p02[1] - p1[1] * k22; - } else if (source.ctrlKey && !isInteger(dY)) { - dY *= 6; - t0 = _isTransformed ? _transformLast : _transformStart; - p02 = _getMouseCoords(source); - p1 = t0.invert(p02); - k22 = t0.k * Math.pow(2, -dY / 500); - k22 = clamp(k22, kMin, kMax); - x22 = p02[0] - p1[0] * k22; - y22 = p02[1] - p1[1] * k22; - } else if ((source.altKey || source.shiftKey) && isInteger(dY)) { - t0 = _isTransformed ? _transformLast : _transformStart; - p02 = _getMouseCoords(source); - p1 = t0.invert(p02); - k22 = t0.k * Math.pow(2, -dY / 500); - k22 = clamp(k22, kMin, kMax); - x22 = p02[0] - p1[0] * k22; - y22 = p02[1] - p1[1] * k22; - } else if (detected.os === "mac" && detected.browser !== "Firefox" && !source.ctrlKey && isInteger(dX) && isInteger(dY)) { - p1 = projection2.translate(); - x22 = p1[0] - dX; - y22 = p1[1] - dY; - k22 = projection2.scale(); - k22 = clamp(k22, kMin, kMax); - } - if (x22 !== x2 || y22 !== y2 || k22 !== k2) { - x2 = x22; - y2 = y22; - k2 = k22; - eventTransform = identity2.translate(x22, y22).scale(k22); - if (_zoomerPanner._transform) { - _zoomerPanner._transform(eventTransform); - } else { - _selection.node().__zoom = eventTransform; - } - } + function getService() { + if (services.mapilio && !_mapilio) { + _mapilio = services.mapilio; + _mapilio.event.on("loadedImages", throttledRedraw); + } else if (!services.mapilio && _mapilio) { + _mapilio = null; } - if (_transformStart.x === x2 && _transformStart.y === y2 && _transformStart.k === k2) { + return _mapilio; + } + function showLayer() { + const service = getService(); + if (!service) return; + editOn(); + layer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end", function() { + dispatch14.call("change"); + }); + } + function hideLayer() { + throttledRedraw.cancel(); + layer.transition().duration(250).style("opacity", 0).on("end", editOff); + } + function transform2(d2) { + let t2 = svgPointTransform(projection2)(d2); + if (d2.heading) { + t2 += " rotate(" + Math.floor(d2.heading) + ",0,0)"; } - if (geoScaleToZoom(k2, TILESIZE) < _minzoom) { - surface.interrupt(); - dispatch14.call("hitMinZoom", this, map2); - setCenterZoom(map2.center(), context.minEditableZoom(), 0, true); - scheduleRedraw(); - dispatch14.call("move", this, map2); + return t2; + } + function editOn() { + layer.style("display", "block"); + } + function editOff() { + layer.selectAll(".viewfield-group").remove(); + layer.style("display", "none"); + } + function click(d3_event, image) { + const service = getService(); + if (!service) return; - } - projection2.transform(eventTransform); - var withinEditableZoom = map2.withinEditableZoom(); - if (_lastWithinEditableZoom !== withinEditableZoom) { - if (_lastWithinEditableZoom !== void 0) { - dispatch14.call("crossEditableZoom", this, withinEditableZoom); + service.ensureViewerLoaded(context, image.id).then(function() { + service.selectImage(context, image.id).showViewer(context); + }); + context.map().centerEase(image.loc); + } + function mouseover(d3_event, image) { + const service = getService(); + if (service) + service.setStyles(context, image); + } + function mouseout() { + const service = getService(); + if (service) + service.setStyles(context, null); + } + function update() { + const z2 = ~~context.map().zoom(); + const showViewfields = z2 >= viewFieldZoomLevel; + const service = getService(); + let sequences = service ? service.sequences(projection2) : []; + let images = service ? service.images(projection2) : []; + let traces = layer.selectAll(".sequences").selectAll(".sequence").data(sequences, function(d2) { + return d2.properties.id; + }); + traces.exit().remove(); + traces.enter().append("path").attr("class", "sequence").merge(traces).attr("d", svgPath(projection2).geojson); + const groups = layer.selectAll(".markers").selectAll(".viewfield-group").data(images, function(d2) { + return d2.id; + }); + groups.exit().remove(); + const groupsEnter = groups.enter().append("g").attr("class", "viewfield-group").on("mouseenter", mouseover).on("mouseleave", mouseout).on("click", click); + groupsEnter.append("g").attr("class", "viewfield-scale"); + const markers = groups.merge(groupsEnter).sort(function(a2, b2) { + return b2.loc[1] - a2.loc[1]; + }).attr("transform", transform2).select(".viewfield-scale"); + markers.selectAll("circle").data([0]).enter().append("circle").attr("dx", "0").attr("dy", "0").attr("r", "6"); + const viewfields = markers.selectAll(".viewfield").data(showViewfields ? [0] : []); + viewfields.exit().remove(); + viewfields.enter().insert("path", "circle").attr("class", "viewfield").attr("transform", "scale(1.5,1.5),translate(-8, -13)").attr("d", viewfieldPath); + function viewfieldPath() { + if (this.parentNode.__data__.isPano) { + return "M 8,13 m -10,0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0"; + } else { + return "M 6,9 C 8,8.4 8,8.4 10,9 L 16,-2 C 12,-5 4,-5 0,-2 z"; } - _lastWithinEditableZoom = withinEditableZoom; - } - var scale = k2 / _transformStart.k; - var tX = (x2 / scale - _transformStart.x) * scale; - var tY = (y2 / scale - _transformStart.y) * scale; - if (context.inIntro()) { - curtainProjection.transform({ - x: x2 - tX, - y: y2 - tY, - k: k2 - }); } - if (source) { - _lastPointerEvent = event; + } + function drawImages(selection2) { + const enabled = svgMapilioImages.enabled; + const service = getService(); + layer = selection2.selectAll(".layer-mapilio").data(service ? [0] : []); + layer.exit().remove(); + const layerEnter = layer.enter().append("g").attr("class", "layer-mapilio").style("display", enabled ? "block" : "none"); + layerEnter.append("g").attr("class", "sequences"); + layerEnter.append("g").attr("class", "markers"); + layer = layerEnter.merge(layer); + if (enabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + update(); + service.loadImages(projection2); + service.loadLines(projection2); + } else { + editOff(); + } } - _isTransformed = true; - _transformLast = eventTransform; - utilSetTransform(supersurface, tX, tY, scale); - scheduleRedraw(); - dispatch14.call("move", this, map2); - function isInteger(val) { - return typeof val === "number" && isFinite(val) && Math.floor(val) === val; + } + drawImages.enabled = function(_2) { + if (!arguments.length) + return svgMapilioImages.enabled; + svgMapilioImages.enabled = _2; + if (svgMapilioImages.enabled) { + showLayer(); + context.photos().on("change.mapilio_images", null); + } else { + hideLayer(); + context.photos().on("change.mapilio_images", null); } + dispatch14.call("change"); + return this; + }; + drawImages.supported = function() { + return !!getService(); + }; + drawImages.rendered = function(zoom) { + return zoom >= minZoom4; + }; + init2(); + return drawImages; + } + + // modules/svg/osm.js + function svgOsm(projection2, context, dispatch14) { + var enabled = true; + function drawOsm(selection2) { + selection2.selectAll(".layer-osm").data(["covered", "areas", "lines", "points", "labels"]).enter().append("g").attr("class", function(d2) { + return "layer-osm " + d2; + }); + selection2.selectAll(".layer-osm.points").selectAll(".points-group").data(["points", "midpoints", "vertices", "turns"]).enter().append("g").attr("class", function(d2) { + return "points-group " + d2; + }); } - function resetTransform() { - if (!_isTransformed) - return false; - utilSetTransform(supersurface, 0, 0); - _isTransformed = false; - if (context.inIntro()) { - curtainProjection.transform(projection2.transform()); + function showLayer() { + var layer = context.surface().selectAll(".data-layer.osm"); + layer.interrupt(); + layer.classed("disabled", false).style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", function() { + dispatch14.call("change"); + }); + } + function hideLayer() { + var layer = context.surface().selectAll(".data-layer.osm"); + layer.interrupt(); + layer.transition().duration(250).style("opacity", 0).on("end interrupt", function() { + layer.classed("disabled", true); + dispatch14.call("change"); + }); + } + drawOsm.enabled = function(val) { + if (!arguments.length) + return enabled; + enabled = val; + if (enabled) { + showLayer(); + } else { + hideLayer(); } - return true; + dispatch14.call("change"); + return this; + }; + return drawOsm; + } + + // modules/svg/notes.js + var _notesEnabled = false; + var _osmService; + function svgNotes(projection2, context, dispatch14) { + if (!dispatch14) { + dispatch14 = dispatch_default("change"); } - function redraw(difference, extent) { - if (surface.empty() || !_redrawEnabled) - return; - if (resetTransform()) { - difference = extent = void 0; + var throttledRedraw = throttle_default(function() { + dispatch14.call("change"); + }, 1e3); + var minZoom4 = 12; + var touchLayer = select_default2(null); + var drawLayer = select_default2(null); + var _notesVisible = false; + function markerPath(selection2, klass) { + selection2.attr("class", klass).attr("transform", "translate(-8, -22)").attr("d", "m17.5,0l-15,0c-1.37,0 -2.5,1.12 -2.5,2.5l0,11.25c0,1.37 1.12,2.5 2.5,2.5l3.75,0l0,3.28c0,0.38 0.43,0.6 0.75,0.37l4.87,-3.65l5.62,0c1.37,0 2.5,-1.12 2.5,-2.5l0,-11.25c0,-1.37 -1.12,-2.5 -2.5,-2.5z"); + } + function getService() { + if (services.osm && !_osmService) { + _osmService = services.osm; + _osmService.on("loadedNotes", throttledRedraw); + } else if (!services.osm && _osmService) { + _osmService = null; } - var zoom = map2.zoom(); - var z2 = String(~~zoom); - if (surface.attr("data-zoom") !== z2) { - surface.attr("data-zoom", z2); + return _osmService; + } + function editOn() { + if (!_notesVisible) { + _notesVisible = true; + drawLayer.style("display", "block"); } - var lat = map2.center()[1]; - var lowzoom = linear3().domain([-60, 0, 60]).range([17, 18.5, 17]).clamp(true); - surface.classed("low-zoom", zoom <= lowzoom(lat)); - if (!difference) { - supersurface.call(context.background()); - wrapper.call(drawLayers); + } + function editOff() { + if (_notesVisible) { + _notesVisible = false; + drawLayer.style("display", "none"); + drawLayer.selectAll(".note").remove(); + touchLayer.selectAll(".note").remove(); } - if (map2.editableDataEnabled() || map2.isInWideSelection()) { - context.loadTiles(projection2); - drawEditable(difference, extent); - } else { + } + function layerOn() { + editOn(); + drawLayer.style("opacity", 0).transition().duration(250).style("opacity", 1).on("end interrupt", function() { + dispatch14.call("change"); + }); + } + function layerOff() { + throttledRedraw.cancel(); + drawLayer.interrupt(); + touchLayer.selectAll(".note").remove(); + drawLayer.transition().duration(250).style("opacity", 0).on("end interrupt", function() { editOff(); + dispatch14.call("change"); + }); + } + function updateMarkers() { + if (!_notesVisible || !_notesEnabled) + return; + var service = getService(); + var selectedID = context.selectedNoteID(); + var data = service ? service.notes(projection2) : []; + var getTransform = svgPointTransform(projection2); + var notes = drawLayer.selectAll(".note").data(data, function(d2) { + return d2.status + d2.id; + }); + notes.exit().remove(); + var notesEnter = notes.enter().append("g").attr("class", function(d2) { + return "note note-" + d2.id + " " + d2.status; + }).classed("new", function(d2) { + return d2.id < 0; + }); + notesEnter.append("ellipse").attr("cx", 0.5).attr("cy", 1).attr("rx", 6.5).attr("ry", 3).attr("class", "stroke"); + notesEnter.append("path").call(markerPath, "shadow"); + notesEnter.append("use").attr("class", "note-fill").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").attr("xlink:href", "#iD-icon-note"); + notesEnter.selectAll(".icon-annotation").data(function(d2) { + return [d2]; + }).enter().append("use").attr("class", "icon-annotation").attr("width", "10px").attr("height", "10px").attr("x", "-3px").attr("y", "-19px").attr("xlink:href", function(d2) { + if (d2.id < 0) + return "#iD-icon-plus"; + if (d2.status === "open") + return "#iD-icon-close"; + return "#iD-icon-apply"; + }); + notes.merge(notesEnter).sort(sortY).classed("selected", function(d2) { + var mode = context.mode(); + var isMoving = mode && mode.id === "drag-note"; + return !isMoving && d2.id === selectedID; + }).attr("transform", getTransform); + if (touchLayer.empty()) + return; + var fillClass = context.getDebug("target") ? "pink " : "nocolor "; + var targets = touchLayer.selectAll(".note").data(data, function(d2) { + return d2.id; + }); + targets.exit().remove(); + targets.enter().append("rect").attr("width", "20px").attr("height", "20px").attr("x", "-8px").attr("y", "-22px").merge(targets).sort(sortY).attr("class", function(d2) { + var newClass = d2.id < 0 ? "new" : ""; + return "note target note-" + d2.id + " " + fillClass + newClass; + }).attr("transform", getTransform); + function sortY(a2, b2) { + if (a2.id === selectedID) + return 1; + if (b2.id === selectedID) + return -1; + return b2.loc[1] - a2.loc[1]; } - _transformStart = projection2.transform(); - return map2; } - var immediateRedraw = function(difference, extent) { - if (!difference && !extent) - cancelPendingRedraw(); - redraw(difference, extent); - }; - map2.lastPointerEvent = function() { - return _lastPointerEvent; - }; - map2.mouse = function(d3_event) { - var event = d3_event || _lastPointerEvent; - if (event) { - var s2; - while (s2 = event.sourceEvent) { - event = s2; + function drawNotes(selection2) { + var service = getService(); + var surface = context.surface(); + if (surface && !surface.empty()) { + touchLayer = surface.selectAll(".data-layer.touch .layer-touch.markers"); + } + drawLayer = selection2.selectAll(".layer-notes").data(service ? [0] : []); + drawLayer.exit().remove(); + drawLayer = drawLayer.enter().append("g").attr("class", "layer-notes").style("display", _notesEnabled ? "block" : "none").merge(drawLayer); + if (_notesEnabled) { + if (service && ~~context.map().zoom() >= minZoom4) { + editOn(); + service.loadNotes(projection2); + updateMarkers(); + } else { + editOff(); } - return _getMouseCoords(event); } - return null; - }; - map2.mouseCoordinates = function() { - var coord2 = map2.mouse() || pxCenter(); - return projection2.invert(coord2); - }; - map2.dblclickZoomEnable = function(val) { - if (!arguments.length) - return _dblClickZoomEnabled; - _dblClickZoomEnabled = val; - return map2; - }; - map2.redrawEnable = function(val) { + } + drawNotes.enabled = function(val) { if (!arguments.length) - return _redrawEnabled; - _redrawEnabled = val; - return map2; - }; - map2.isTransformed = function() { - return _isTransformed; - }; - function setTransform(t2, duration, force) { - var t3 = projection2.transform(); - if (!force && t2.k === t3.k && t2.x === t3.x && t2.y === t3.y) - return false; - if (duration) { - _selection.transition().duration(duration).on("start", function() { - map2.startEase(); - }).call(_zoomerPanner.transform, identity2.translate(t2.x, t2.y).scale(t2.k)); + return _notesEnabled; + _notesEnabled = val; + if (_notesEnabled) { + layerOn(); } else { - projection2.transform(t2); - _transformStart = t2; - _selection.call(_zoomerPanner.transform, _transformStart); + layerOff(); + if (context.selectedNoteID()) { + context.enter(modeBrowse(context)); + } } - return true; + dispatch14.call("change"); + return this; + }; + return drawNotes; + } + + // modules/svg/touch.js + function svgTouch() { + function drawTouch(selection2) { + selection2.selectAll(".layer-touch").data(["areas", "lines", "points", "turns", "markers"]).enter().append("g").attr("class", function(d2) { + return "layer-touch " + d2; + }); } - function setCenterZoom(loc2, z2, duration, force) { - var c2 = map2.center(); - var z3 = map2.zoom(); - if (loc2[0] === c2[0] && loc2[1] === c2[1] && z2 === z3 && !force) - return false; - var proj = geoRawMercator().transform(projection2.transform()); - var k2 = clamp(geoZoomToScale(z2, TILESIZE), kMin, kMax); - proj.scale(k2); - var t2 = proj.translate(); - var point2 = proj(loc2); - var center = pxCenter(); - t2[0] += center[0] - point2[0]; - t2[1] += center[1] - point2[1]; - return setTransform(identity2.translate(t2[0], t2[1]).scale(k2), duration, force); + return drawTouch; + } + + // modules/util/dimensions.js + function refresh(selection2, node) { + var cr = node.getBoundingClientRect(); + var prop = [cr.width, cr.height]; + selection2.property("__dimensions__", prop); + return prop; + } + function utilGetDimensions(selection2, force) { + if (!selection2 || selection2.empty()) { + return [0, 0]; } - map2.pan = function(delta, duration) { - var t2 = projection2.translate(); - var k2 = projection2.scale(); - t2[0] += delta[0]; - t2[1] += delta[1]; - if (duration) { - _selection.transition().duration(duration).on("start", function() { - map2.startEase(); - }).call(_zoomerPanner.transform, identity2.translate(t2[0], t2[1]).scale(k2)); - } else { - projection2.translate(t2); - _transformStart = projection2.transform(); - _selection.call(_zoomerPanner.transform, _transformStart); - dispatch14.call("move", this, map2); - immediateRedraw(); - } - return map2; - }; - map2.dimensions = function(val) { - if (!arguments.length) - return _dimensions; - _dimensions = val; - drawLayers.dimensions(_dimensions); - context.background().dimensions(_dimensions); - projection2.clipExtent([[0, 0], _dimensions]); - _getMouseCoords = utilFastMouse(supersurface.node()); - scheduleRedraw(); - return map2; - }; - function zoomIn(delta) { - setCenterZoom(map2.center(), ~~map2.zoom() + delta, 250, true); + var node = selection2.node(), cached = selection2.property("__dimensions__"); + return !cached || force ? refresh(selection2, node) : cached; + } + function utilSetDimensions(selection2, dimensions) { + if (!selection2 || selection2.empty()) { + return selection2; } - function zoomOut(delta) { - setCenterZoom(map2.center(), ~~map2.zoom() - delta, 250, true); + var node = selection2.node(); + if (dimensions === null) { + refresh(selection2, node); + return selection2; } - map2.zoomIn = function() { - zoomIn(1); - }; - map2.zoomInFurther = function() { - zoomIn(4); - }; - map2.canZoomIn = function() { - return map2.zoom() < maxZoom; + return selection2.property("__dimensions__", [dimensions[0], dimensions[1]]).attr("width", dimensions[0]).attr("height", dimensions[1]); + } + + // modules/svg/layers.js + function svgLayers(projection2, context) { + var dispatch14 = dispatch_default("change"); + var svg2 = select_default2(null); + var _layers = [ + { id: "osm", layer: svgOsm(projection2, context, dispatch14) }, + { id: "notes", layer: svgNotes(projection2, context, dispatch14) }, + { id: "data", layer: svgData(projection2, context, dispatch14) }, + { id: "keepRight", layer: svgKeepRight(projection2, context, dispatch14) }, + { id: "improveOSM", layer: svgImproveOSM(projection2, context, dispatch14) }, + { id: "osmose", layer: svgOsmose(projection2, context, dispatch14) }, + { id: "streetside", layer: svgStreetside(projection2, context, dispatch14) }, + { id: "mapillary", layer: svgMapillaryImages(projection2, context, dispatch14) }, + { id: "mapillary-position", layer: svgMapillaryPosition(projection2, context, dispatch14) }, + { id: "mapillary-map-features", layer: svgMapillaryMapFeatures(projection2, context, dispatch14) }, + { id: "mapillary-signs", layer: svgMapillarySigns(projection2, context, dispatch14) }, + { id: "kartaview", layer: svgKartaviewImages(projection2, context, dispatch14) }, + { id: "mapilio", layer: svgMapilioImages(projection2, context, dispatch14) }, + { id: "vegbilder", layer: svgVegbilder(projection2, context, dispatch14) }, + { id: "local-photos", layer: svgLocalPhotos(projection2, context, dispatch14) }, + { id: "debug", layer: svgDebug(projection2, context, dispatch14) }, + { id: "geolocate", layer: svgGeolocate(projection2, context, dispatch14) }, + { id: "touch", layer: svgTouch(projection2, context, dispatch14) } + ]; + function drawLayers(selection2) { + svg2 = selection2.selectAll(".surface").data([0]); + svg2 = svg2.enter().append("svg").attr("class", "surface").merge(svg2); + var defs = svg2.selectAll(".surface-defs").data([0]); + defs.enter().append("defs").attr("class", "surface-defs"); + var groups = svg2.selectAll(".data-layer").data(_layers); + groups.exit().remove(); + groups.enter().append("g").attr("class", function(d2) { + return "data-layer " + d2.id; + }).merge(groups).each(function(d2) { + select_default2(this).call(d2.layer); + }); + } + drawLayers.all = function() { + return _layers; }; - map2.zoomOut = function() { - zoomOut(1); + drawLayers.layer = function(id2) { + var obj = _layers.find(function(o2) { + return o2.id === id2; + }); + return obj && obj.layer; }; - map2.zoomOutFurther = function() { - zoomOut(4); + drawLayers.only = function(what) { + var arr = [].concat(what); + var all = _layers.map(function(layer) { + return layer.id; + }); + return drawLayers.remove(utilArrayDifference(all, arr)); }; - map2.canZoomOut = function() { - return map2.zoom() > minZoom2; + drawLayers.remove = function(what) { + var arr = [].concat(what); + arr.forEach(function(id2) { + _layers = _layers.filter(function(o2) { + return o2.id !== id2; + }); + }); + dispatch14.call("change"); + return this; }; - map2.center = function(loc2) { - if (!arguments.length) { - return projection2.invert(pxCenter()); - } - if (setCenterZoom(loc2, map2.zoom())) { - dispatch14.call("move", this, map2); - } - scheduleRedraw(); - return map2; + drawLayers.add = function(what) { + var arr = [].concat(what); + arr.forEach(function(obj) { + if ("id" in obj && "layer" in obj) { + _layers.push(obj); + } + }); + dispatch14.call("change"); + return this; }; - map2.unobscuredCenterZoomEase = function(loc, zoom) { - var offset = map2.unobscuredOffsetPx(); - var proj = geoRawMercator().transform(projection2.transform()); - proj.scale(geoZoomToScale(zoom, TILESIZE)); - var locPx = proj(loc); - var offsetLocPx = [locPx[0] + offset[0], locPx[1] + offset[1]]; - var offsetLoc = proj.invert(offsetLocPx); - map2.centerZoomEase(offsetLoc, zoom); + drawLayers.dimensions = function(val) { + if (!arguments.length) + return utilGetDimensions(svg2); + utilSetDimensions(svg2, val); + return this; }; - map2.unobscuredOffsetPx = function() { - var openPane = context.container().select(".map-panes .map-pane.shown"); - if (!openPane.empty()) { - return [openPane.node().offsetWidth / 2, 0]; - } - return [0, 0]; + return utilRebind(drawLayers, dispatch14, "on"); + } + + // modules/svg/lines.js + var import_fast_deep_equal6 = __toESM(require_fast_deep_equal()); + function svgLines(projection2, context) { + var detected = utilDetect(); + var highway_stack = { + motorway: 0, + motorway_link: 1, + trunk: 2, + trunk_link: 3, + primary: 4, + primary_link: 5, + secondary: 6, + tertiary: 7, + unclassified: 8, + residential: 9, + service: 10, + busway: 11, + footway: 12 }; - map2.zoom = function(z2) { - if (!arguments.length) { - return Math.max(geoScaleToZoom(projection2.scale(), TILESIZE), 0); - } - if (z2 < _minzoom) { - surface.interrupt(); - dispatch14.call("hitMinZoom", this, map2); - z2 = context.minEditableZoom(); + function drawTargets(selection2, graph, entities, filter2) { + var targetClass = context.getDebug("target") ? "pink " : "nocolor "; + var nopeClass = context.getDebug("target") ? "red " : "nocolor "; + var getPath = svgPath(projection2).geojson; + var activeID = context.activeID(); + var base = context.history().base(); + var data = { targets: [], nopes: [] }; + entities.forEach(function(way) { + var features = svgSegmentWay(way, graph, activeID); + data.targets.push.apply(data.targets, features.passive); + data.nopes.push.apply(data.nopes, features.active); + }); + var targetData = data.targets.filter(getPath); + var targets = selection2.selectAll(".line.target-allowed").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(targetData, function key(d2) { + return d2.id; + }); + targets.exit().remove(); + var segmentWasEdited = function(d2) { + var wayID = d2.properties.entity.id; + if (!base.entities[wayID] || !(0, import_fast_deep_equal6.default)(graph.entities[wayID].nodes, base.entities[wayID].nodes)) { + return false; + } + return d2.properties.nodes.some(function(n3) { + return !base.entities[n3.id] || !(0, import_fast_deep_equal6.default)(graph.entities[n3.id].loc, base.entities[n3.id].loc); + }); + }; + targets.enter().append("path").merge(targets).attr("d", getPath).attr("class", function(d2) { + return "way line target target-allowed " + targetClass + d2.id; + }).classed("segment-edited", segmentWasEdited); + var nopeData = data.nopes.filter(getPath); + var nopes = selection2.selectAll(".line.target-nope").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(nopeData, function key(d2) { + return d2.id; + }); + nopes.exit().remove(); + nopes.enter().append("path").merge(nopes).attr("d", getPath).attr("class", function(d2) { + return "way line target target-nope " + nopeClass + d2.id; + }).classed("segment-edited", segmentWasEdited); + } + function drawLines(selection2, graph, entities, filter2) { + var base = context.history().base(); + function waystack(a2, b2) { + var selected = context.selectedIDs(); + var scoreA = selected.indexOf(a2.id) !== -1 ? 20 : 0; + var scoreB = selected.indexOf(b2.id) !== -1 ? 20 : 0; + if (a2.tags.highway) { + scoreA -= highway_stack[a2.tags.highway]; + } + if (b2.tags.highway) { + scoreB -= highway_stack[b2.tags.highway]; + } + return scoreA - scoreB; } - if (setCenterZoom(map2.center(), z2)) { - dispatch14.call("move", this, map2); + function drawLineGroup(selection3, klass, isSelected) { + var mode = context.mode(); + var isDrawing = mode && /^draw/.test(mode.id); + var selectedClass = !isDrawing && isSelected ? "selected " : ""; + var lines = selection3.selectAll("path").filter(filter2).data(getPathData(isSelected), osmEntity.key); + lines.exit().remove(); + lines.enter().append("path").attr("class", function(d2) { + var prefix = "way line"; + if (!d2.hasInterestingTags()) { + var parentRelations = graph.parentRelations(d2); + var parentMultipolygons = parentRelations.filter(function(relation) { + return relation.isMultipolygon(); + }); + if (parentMultipolygons.length > 0 && // and only multipolygon relations + parentRelations.length === parentMultipolygons.length) { + prefix = "relation area"; + } + } + var oldMPClass = oldMultiPolygonOuters[d2.id] ? "old-multipolygon " : ""; + return prefix + " " + klass + " " + selectedClass + oldMPClass + d2.id; + }).classed("added", function(d2) { + return !base.entities[d2.id]; + }).classed("geometry-edited", function(d2) { + return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal6.default)(graph.entities[d2.id].nodes, base.entities[d2.id].nodes); + }).classed("retagged", function(d2) { + return graph.entities[d2.id] && base.entities[d2.id] && !(0, import_fast_deep_equal6.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); + }).call(svgTagClasses()).merge(lines).sort(waystack).attr("d", getPath).call(svgTagClasses().tags(svgRelationMemberTags(graph))); + return selection3; } - scheduleRedraw(); - return map2; - }; - map2.centerZoom = function(loc2, z2) { - if (setCenterZoom(loc2, z2)) { - dispatch14.call("move", this, map2); + function getPathData(isSelected) { + return function() { + var layer = this.parentNode.__data__; + var data = pathdata[layer] || []; + return data.filter(function(d2) { + if (isSelected) { + return context.selectedIDs().indexOf(d2.id) !== -1; + } else { + return context.selectedIDs().indexOf(d2.id) === -1; + } + }); + }; } - scheduleRedraw(); - return map2; - }; - map2.zoomTo = function(entity) { - var extent = entity.extent(context.graph()); - if (!isFinite(extent.area())) - return map2; - var z2 = clamp(map2.trimmedExtentZoom(extent), 0, 20); - return map2.centerZoom(extent.center(), z2); - }; - map2.centerEase = function(loc2, duration) { - duration = duration || 250; - setCenterZoom(loc2, map2.zoom(), duration); - return map2; - }; - map2.zoomEase = function(z2, duration) { - duration = duration || 250; - setCenterZoom(map2.center(), z2, duration, false); - return map2; - }; - map2.centerZoomEase = function(loc2, z2, duration) { - duration = duration || 250; - setCenterZoom(loc2, z2, duration, false); - return map2; - }; - map2.transformEase = function(t2, duration) { - duration = duration || 250; - setTransform( - t2, - duration, - false - /* don't force */ - ); - return map2; - }; - map2.zoomToEase = function(obj, duration) { - var extent; - if (Array.isArray(obj)) { - obj.forEach(function(entity) { - var entityExtent = entity.extent(context.graph()); - if (!extent) { - extent = entityExtent; - } else { - extent = extent.extend(entityExtent); + function addMarkers(layergroup, pathclass, groupclass, groupdata, marker) { + var markergroup = layergroup.selectAll("g." + groupclass).data([pathclass]); + markergroup = markergroup.enter().append("g").attr("class", groupclass).merge(markergroup); + var markers = markergroup.selectAll("path").filter(filter2).data( + function data() { + return groupdata[this.parentNode.__data__] || []; + }, + function key(d2) { + return [d2.id, d2.index]; } + ); + markers.exit().remove(); + markers = markers.enter().append("path").attr("class", pathclass).merge(markers).attr("marker-mid", marker).attr("d", function(d2) { + return d2.d; }); - } else { - extent = obj.extent(context.graph()); + if (detected.ie) { + markers.each(function() { + this.parentNode.insertBefore(this, this); + }); + } } - if (!isFinite(extent.area())) - return map2; - var z2 = clamp(map2.trimmedExtentZoom(extent), 0, 20); - return map2.centerZoomEase(extent.center(), z2, duration); - }; - map2.startEase = function() { - utilBindOnce(surface, _pointerPrefix + "down.ease", function() { - map2.cancelEase(); + var getPath = svgPath(projection2, graph); + var ways = []; + var onewaydata = {}; + var sideddata = {}; + var oldMultiPolygonOuters = {}; + for (var i3 = 0; i3 < entities.length; i3++) { + var entity = entities[i3]; + var outer = osmOldMultipolygonOuterMember(entity, graph); + if (outer) { + ways.push(entity.mergeTags(outer.tags)); + oldMultiPolygonOuters[outer.id] = true; + } else if (entity.geometry(graph) === "line" || entity.geometry(graph) === "area" && entity.sidednessIdentifier && entity.sidednessIdentifier() === "coastline") { + ways.push(entity); + } + } + ways = ways.filter(getPath); + var pathdata = utilArrayGroupBy(ways, function(way) { + return way.layer(); }); - return map2; - }; - map2.cancelEase = function() { - _selection.interrupt(); - return map2; - }; - map2.extent = function(val) { - if (!arguments.length) { - return new geoExtent( - projection2.invert([0, _dimensions[1]]), - projection2.invert([_dimensions[0], 0]) + Object.keys(pathdata).forEach(function(k2) { + var v2 = pathdata[k2]; + var onewayArr = v2.filter(function(d2) { + return d2.isOneWay(); + }); + var onewaySegments = svgMarkerSegments( + projection2, + graph, + 35, + function shouldReverse(entity2) { + return entity2.tags.oneway === "-1"; + }, + function bothDirections(entity2) { + return entity2.tags.oneway === "reversible" || entity2.tags.oneway === "alternating"; + } ); - } else { - var extent = geoExtent(val); - map2.centerZoom(extent.center(), map2.extentZoom(extent)); - } - }; - map2.trimmedExtent = function(val) { - if (!arguments.length) { - var headerY = 71; - var footerY = 30; - var pad2 = 10; - return new geoExtent( - projection2.invert([pad2, _dimensions[1] - footerY - pad2]), - projection2.invert([_dimensions[0] - pad2, headerY + pad2]) + onewaydata[k2] = utilArrayFlatten(onewayArr.map(onewaySegments)); + var sidedArr = v2.filter(function(d2) { + return d2.isSided(); + }); + var sidedSegments = svgMarkerSegments( + projection2, + graph, + 30, + function shouldReverse() { + return false; + }, + function bothDirections() { + return false; + } + ); + sideddata[k2] = utilArrayFlatten(sidedArr.map(sidedSegments)); + }); + var covered = selection2.selectAll(".layer-osm.covered"); + var uncovered = selection2.selectAll(".layer-osm.lines"); + var touchLayer = selection2.selectAll(".layer-touch.lines"); + [covered, uncovered].forEach(function(selection3) { + var range3 = selection3 === covered ? range(-10, 0) : range(0, 11); + var layergroup = selection3.selectAll("g.layergroup").data(range3); + layergroup = layergroup.enter().append("g").attr("class", function(d2) { + return "layergroup layer" + String(d2); + }).merge(layergroup); + layergroup.selectAll("g.linegroup").data(["shadow", "casing", "stroke", "shadow-highlighted", "casing-highlighted", "stroke-highlighted"]).enter().append("g").attr("class", function(d2) { + return "linegroup line-" + d2; + }); + layergroup.selectAll("g.line-shadow").call(drawLineGroup, "shadow", false); + layergroup.selectAll("g.line-casing").call(drawLineGroup, "casing", false); + layergroup.selectAll("g.line-stroke").call(drawLineGroup, "stroke", false); + layergroup.selectAll("g.line-shadow-highlighted").call(drawLineGroup, "shadow", true); + layergroup.selectAll("g.line-casing-highlighted").call(drawLineGroup, "casing", true); + layergroup.selectAll("g.line-stroke-highlighted").call(drawLineGroup, "stroke", true); + addMarkers(layergroup, "oneway", "onewaygroup", onewaydata, "url(#ideditor-oneway-marker)"); + addMarkers( + layergroup, + "sided", + "sidedgroup", + sideddata, + function marker(d2) { + var category = graph.entity(d2.id).sidednessIdentifier(); + return "url(#ideditor-sided-marker-" + category + ")"; + } ); - } else { - var extent = geoExtent(val); - map2.centerZoom(extent.center(), map2.trimmedExtentZoom(extent)); - } - }; - function calcExtentZoom(extent, dim) { - var tl = projection2([extent[0][0], extent[1][1]]); - var br = projection2([extent[1][0], extent[0][1]]); - var hFactor = (br[0] - tl[0]) / dim[0]; - var vFactor = (br[1] - tl[1]) / dim[1]; - var hZoomDiff = Math.log(Math.abs(hFactor)) / Math.LN2; - var vZoomDiff = Math.log(Math.abs(vFactor)) / Math.LN2; - var newZoom = map2.zoom() - Math.max(hZoomDiff, vZoomDiff); - return newZoom; - } - map2.extentZoom = function(val) { - return calcExtentZoom(geoExtent(val), _dimensions); - }; - map2.trimmedExtentZoom = function(val) { - var trimY = 120; - var trimX = 40; - var trimmed = [_dimensions[0] - trimX, _dimensions[1] - trimY]; - return calcExtentZoom(geoExtent(val), trimmed); - }; - map2.withinEditableZoom = function() { - return map2.zoom() >= context.minEditableZoom(); - }; - map2.isInWideSelection = function() { - return !map2.withinEditableZoom() && context.selectedIDs().length; - }; - map2.editableDataEnabled = function(skipZoomCheck) { - var layer = context.layers().layer("osm"); - if (!layer || !layer.enabled()) - return false; - return skipZoomCheck || map2.withinEditableZoom(); - }; - map2.notesEditable = function() { - var layer = context.layers().layer("notes"); - if (!layer || !layer.enabled()) - return false; - return map2.withinEditableZoom(); - }; - map2.minzoom = function(val) { - if (!arguments.length) - return _minzoom; - _minzoom = val; - return map2; - }; - map2.toggleHighlightEdited = function() { - surface.classed("highlight-edited", !surface.classed("highlight-edited")); - map2.pan([0, 0]); - dispatch14.call("changeHighlighting", this); - }; - map2.areaFillOptions = ["wireframe", "partial", "full"]; - map2.activeAreaFill = function(val) { - if (!arguments.length) - return corePreferences("area-fill") || "partial"; - corePreferences("area-fill", val); - if (val !== "wireframe") { - corePreferences("area-fill-toggle", val); - } - updateAreaFill(); - map2.pan([0, 0]); - dispatch14.call("changeAreaFill", this); - return map2; - }; - map2.toggleWireframe = function() { - var activeFill = map2.activeAreaFill(); - if (activeFill === "wireframe") { - activeFill = corePreferences("area-fill-toggle") || "partial"; - } else { - activeFill = "wireframe"; - } - map2.activeAreaFill(activeFill); - }; - function updateAreaFill() { - var activeFill = map2.activeAreaFill(); - map2.areaFillOptions.forEach(function(opt) { - surface.classed("fill-" + opt, Boolean(opt === activeFill)); }); + touchLayer.call(drawTargets, graph, ways, filter2); } - map2.layers = () => drawLayers; - map2.doubleUpHandler = function() { - return _doubleUpHandler; - }; - return utilRebind(map2, dispatch14, "on"); + return drawLines; } - // modules/renderer/photos.js - function rendererPhotos(context) { - var dispatch14 = dispatch_default("change"); - var _layerIDs = ["streetside", "mapillary", "mapillary-map-features", "mapillary-signs", "kartaview", "mapilio", "vegbilder"]; - var _allPhotoTypes = ["flat", "panoramic"]; - var _shownPhotoTypes = _allPhotoTypes.slice(); - var _dateFilters = ["fromDate", "toDate"]; - var _fromDate; - var _toDate; - var _usernames; - function photos() { - } - function updateStorage() { - if (window.mocha) - return; - var hash = utilStringQs(window.location.hash); - var enabled = context.layers().all().filter(function(d2) { - return _layerIDs.indexOf(d2.id) !== -1 && d2.layer && d2.layer.supported() && d2.layer.enabled(); - }).map(function(d2) { + // modules/svg/midpoints.js + function svgMidpoints(projection2, context) { + var targetRadius = 8; + function drawTargets(selection2, graph, entities, filter2) { + var fillClass = context.getDebug("target") ? "pink " : "nocolor "; + var getTransform = svgPointTransform(projection2).geojson; + var data = entities.map(function(midpoint) { + return { + type: "Feature", + id: midpoint.id, + properties: { + target: true, + entity: midpoint + }, + geometry: { + type: "Point", + coordinates: midpoint.loc + } + }; + }); + var targets = selection2.selectAll(".midpoint.target").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(data, function key(d2) { return d2.id; }); - if (enabled.length) { - hash.photo_overlay = enabled.join(","); - } else { - delete hash.photo_overlay; - } - window.location.replace("#" + utilQsString(hash, true)); + targets.exit().remove(); + targets.enter().append("circle").attr("r", targetRadius).merge(targets).attr("class", function(d2) { + return "node midpoint target " + fillClass + d2.id; + }).attr("transform", getTransform); } - photos.overlayLayerIDs = function() { - return _layerIDs; - }; - photos.allPhotoTypes = function() { - return _allPhotoTypes; - }; - photos.dateFilters = function() { - return _dateFilters; - }; - photos.dateFilterValue = function(val) { - return val === _dateFilters[0] ? _fromDate : _toDate; - }; - photos.setDateFilter = function(type2, val, updateUrl) { - var date = val && new Date(val); - if (date && !isNaN(date)) { - val = date.toISOString().slice(0, 10); - } else { - val = null; - } - if (type2 === _dateFilters[0]) { - _fromDate = val; - if (_fromDate && _toDate && new Date(_toDate) < new Date(_fromDate)) { - _toDate = _fromDate; - } + function drawMidpoints(selection2, graph, entities, filter2, extent) { + var drawLayer = selection2.selectAll(".layer-osm.points .points-group.midpoints"); + var touchLayer = selection2.selectAll(".layer-touch.points"); + var mode = context.mode(); + if (mode && mode.id !== "select" || !context.map().withinEditableZoom()) { + drawLayer.selectAll(".midpoint").remove(); + touchLayer.selectAll(".midpoint.target").remove(); + return; } - if (type2 === _dateFilters[1]) { - _toDate = val; - if (_fromDate && _toDate && new Date(_toDate) < new Date(_fromDate)) { - _fromDate = _toDate; + var poly = extent.polygon(); + var midpoints = {}; + for (var i3 = 0; i3 < entities.length; i3++) { + var entity = entities[i3]; + if (entity.type !== "way") + continue; + if (!filter2(entity)) + continue; + if (context.selectedIDs().indexOf(entity.id) < 0) + continue; + var nodes = graph.childNodes(entity); + for (var j2 = 0; j2 < nodes.length - 1; j2++) { + var a2 = nodes[j2]; + var b2 = nodes[j2 + 1]; + var id2 = [a2.id, b2.id].sort().join("-"); + if (midpoints[id2]) { + midpoints[id2].parents.push(entity); + } else if (geoVecLength(projection2(a2.loc), projection2(b2.loc)) > 40) { + var point2 = geoVecInterp(a2.loc, b2.loc, 0.5); + var loc = null; + if (extent.intersects(point2)) { + loc = point2; + } else { + for (var k2 = 0; k2 < 4; k2++) { + point2 = geoLineIntersection([a2.loc, b2.loc], [poly[k2], poly[k2 + 1]]); + if (point2 && geoVecLength(projection2(a2.loc), projection2(point2)) > 20 && geoVecLength(projection2(b2.loc), projection2(point2)) > 20) { + loc = point2; + break; + } + } + } + if (loc) { + midpoints[id2] = { + type: "midpoint", + id: id2, + loc, + edge: [a2.id, b2.id], + parents: [entity] + }; + } + } } } - dispatch14.call("change", this); - if (updateUrl) { - var rangeString; - if (_fromDate || _toDate) { - rangeString = (_fromDate || "") + "_" + (_toDate || ""); + function midpointFilter(d2) { + if (midpoints[d2.id]) + return true; + for (var i4 = 0; i4 < d2.parents.length; i4++) { + if (filter2(d2.parents[i4])) { + return true; + } } - setUrlFilterValue("photo_dates", rangeString); + return false; } - }; - photos.setUsernameFilter = function(val, updateUrl) { - if (val && typeof val === "string") - val = val.replace(/;/g, ",").split(","); - if (val) { - val = val.map((d2) => d2.trim()).filter(Boolean); - if (!val.length) { - val = null; + var groups = drawLayer.selectAll(".midpoint").filter(midpointFilter).data(Object.values(midpoints), function(d2) { + return d2.id; + }); + groups.exit().remove(); + var enter = groups.enter().insert("g", ":first-child").attr("class", "midpoint"); + enter.append("polygon").attr("points", "-6,8 10,0 -6,-8").attr("class", "shadow"); + enter.append("polygon").attr("points", "-3,4 5,0 -3,-4").attr("class", "fill"); + groups = groups.merge(enter).attr("transform", function(d2) { + var translate = svgPointTransform(projection2); + var a3 = graph.entity(d2.edge[0]); + var b3 = graph.entity(d2.edge[1]); + var angle2 = geoAngle(a3, b3, projection2) * (180 / Math.PI); + return translate(d2) + " rotate(" + angle2 + ")"; + }).call(svgTagClasses().tags( + function(d2) { + return d2.parents[0].tags; } + )); + groups.select("polygon.shadow"); + groups.select("polygon.fill"); + touchLayer.call(drawTargets, graph, Object.values(midpoints), midpointFilter); + } + return drawMidpoints; + } + + // modules/svg/points.js + var import_fast_deep_equal7 = __toESM(require_fast_deep_equal()); + function svgPoints(projection2, context) { + function markerPath(selection2, klass) { + selection2.attr("class", klass).attr("transform", "translate(-8, -23)").attr("d", "M 17,8 C 17,13 11,21 8.5,23.5 C 6,21 0,13 0,8 C 0,4 4,-0.5 8.5,-0.5 C 13,-0.5 17,4 17,8 z"); + } + function sortY(a2, b2) { + return b2.loc[1] - a2.loc[1]; + } + function fastEntityKey(d2) { + var mode = context.mode(); + var isMoving = mode && /^(add|draw|drag|move|rotate)/.test(mode.id); + return isMoving ? d2.id : osmEntity.key(d2); + } + function drawTargets(selection2, graph, entities, filter2) { + var fillClass = context.getDebug("target") ? "pink " : "nocolor "; + var getTransform = svgPointTransform(projection2).geojson; + var activeID = context.activeID(); + var data = []; + entities.forEach(function(node) { + if (activeID === node.id) + return; + data.push({ + type: "Feature", + id: node.id, + properties: { + target: true, + entity: node + }, + geometry: node.asGeoJSON() + }); + }); + var targets = selection2.selectAll(".point.target").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(data, function key(d2) { + return d2.id; + }); + targets.exit().remove(); + targets.enter().append("rect").attr("x", -10).attr("y", -26).attr("width", 20).attr("height", 30).merge(targets).attr("class", function(d2) { + return "node point target " + fillClass + d2.id; + }).attr("transform", getTransform); + } + function drawPoints(selection2, graph, entities, filter2) { + var wireframe = context.surface().classed("fill-wireframe"); + var zoom = geoScaleToZoom(projection2.scale()); + var base = context.history().base(); + function renderAsPoint(entity) { + return entity.geometry(graph) === "point" && !(zoom >= 18 && entity.directions(graph, projection2).length); } - _usernames = val; - dispatch14.call("change", this); - if (updateUrl) { - var hashString; - if (_usernames) { - hashString = _usernames.join(","); - } - setUrlFilterValue("photo_username", hashString); + var points = wireframe ? [] : entities.filter(renderAsPoint); + points.sort(sortY); + var drawLayer = selection2.selectAll(".layer-osm.points .points-group.points"); + var touchLayer = selection2.selectAll(".layer-touch.points"); + var groups = drawLayer.selectAll("g.point").filter(filter2).data(points, fastEntityKey); + groups.exit().remove(); + var enter = groups.enter().append("g").attr("class", function(d2) { + return "node point " + d2.id; + }).order(); + enter.append("path").call(markerPath, "shadow"); + enter.append("ellipse").attr("cx", 0.5).attr("cy", 1).attr("rx", 6.5).attr("ry", 3).attr("class", "stroke"); + enter.append("path").call(markerPath, "stroke"); + enter.append("use").attr("transform", "translate(-5.5, -20)").attr("class", "icon").attr("width", "12px").attr("height", "12px"); + groups = groups.merge(enter).attr("transform", svgPointTransform(projection2)).classed("added", function(d2) { + return !base.entities[d2.id]; + }).classed("moved", function(d2) { + return base.entities[d2.id] && !(0, import_fast_deep_equal7.default)(graph.entities[d2.id].loc, base.entities[d2.id].loc); + }).classed("retagged", function(d2) { + return base.entities[d2.id] && !(0, import_fast_deep_equal7.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); + }).call(svgTagClasses()); + groups.select(".shadow"); + groups.select(".stroke"); + groups.select(".icon").attr("xlink:href", function(entity) { + var preset = _mainPresetIndex.match(entity, graph); + var picon = preset && preset.icon; + return picon ? "#" + picon : ""; + }); + touchLayer.call(drawTargets, graph, points, filter2); + } + return drawPoints; + } + + // modules/svg/turns.js + function svgTurns(projection2, context) { + function icon2(turn) { + var u2 = turn.u ? "-u" : ""; + if (turn.no) + return "#iD-turn-no" + u2; + if (turn.only) + return "#iD-turn-only" + u2; + return "#iD-turn-yes" + u2; + } + function drawTurns(selection2, graph, turns) { + function turnTransform(d2) { + var pxRadius = 50; + var toWay = graph.entity(d2.to.way); + var toPoints = graph.childNodes(toWay).map(function(n3) { + return n3.loc; + }).map(projection2); + var toLength = geoPathLength(toPoints); + var mid = toLength / 2; + var toNode = graph.entity(d2.to.node); + var toVertex = graph.entity(d2.to.vertex); + var a2 = geoAngle(toVertex, toNode, projection2); + var o2 = projection2(toVertex.loc); + var r2 = d2.u ? 0 : !toWay.__via ? pxRadius : Math.min(mid, pxRadius); + return "translate(" + (r2 * Math.cos(a2) + o2[0]) + "," + (r2 * Math.sin(a2) + o2[1]) + ") rotate(" + a2 * 180 / Math.PI + ")"; } + var drawLayer = selection2.selectAll(".layer-osm.points .points-group.turns"); + var touchLayer = selection2.selectAll(".layer-touch.turns"); + var groups = drawLayer.selectAll("g.turn").data(turns, function(d2) { + return d2.key; + }); + groups.exit().remove(); + var groupsEnter = groups.enter().append("g").attr("class", function(d2) { + return "turn " + d2.key; + }); + var turnsEnter = groupsEnter.filter(function(d2) { + return !d2.u; + }); + turnsEnter.append("rect").attr("transform", "translate(-22, -12)").attr("width", "44").attr("height", "24"); + turnsEnter.append("use").attr("transform", "translate(-22, -12)").attr("width", "44").attr("height", "24"); + var uEnter = groupsEnter.filter(function(d2) { + return d2.u; + }); + uEnter.append("circle").attr("r", "16"); + uEnter.append("use").attr("transform", "translate(-16, -16)").attr("width", "32").attr("height", "32"); + groups = groups.merge(groupsEnter).attr("opacity", function(d2) { + return d2.direct === false ? "0.7" : null; + }).attr("transform", turnTransform); + groups.select("use").attr("xlink:href", icon2); + groups.select("rect"); + groups.select("circle"); + var fillClass = context.getDebug("target") ? "pink " : "nocolor "; + groups = touchLayer.selectAll("g.turn").data(turns, function(d2) { + return d2.key; + }); + groups.exit().remove(); + groupsEnter = groups.enter().append("g").attr("class", function(d2) { + return "turn " + d2.key; + }); + turnsEnter = groupsEnter.filter(function(d2) { + return !d2.u; + }); + turnsEnter.append("rect").attr("class", "target " + fillClass).attr("transform", "translate(-22, -12)").attr("width", "44").attr("height", "24"); + uEnter = groupsEnter.filter(function(d2) { + return d2.u; + }); + uEnter.append("circle").attr("class", "target " + fillClass).attr("r", "16"); + groups = groups.merge(groupsEnter).attr("transform", turnTransform); + groups.select("rect"); + groups.select("circle"); + return this; + } + return drawTurns; + } + + // modules/svg/vertices.js + var import_fast_deep_equal8 = __toESM(require_fast_deep_equal()); + function svgVertices(projection2, context) { + var radiuses = { + // z16-, z17, z18+, w/icon + shadow: [6, 7.5, 7.5, 12], + stroke: [2.5, 3.5, 3.5, 8], + fill: [1, 1.5, 1.5, 1.5] }; - function setUrlFilterValue(property, val) { - if (!window.mocha) { - var hash = utilStringQs(window.location.hash); - if (val) { - if (hash[property] === val) - return; - hash[property] = val; - } else { - if (!(property in hash)) - return; - delete hash[property]; - } - window.location.replace("#" + utilQsString(hash, true)); - } + var _currHoverTarget; + var _currPersistent = {}; + var _currHover = {}; + var _prevHover = {}; + var _currSelected = {}; + var _prevSelected = {}; + var _radii = {}; + function sortY(a2, b2) { + return b2.loc[1] - a2.loc[1]; } - function showsLayer(id2) { - var layer = context.layers().layer(id2); - return layer && layer.supported() && layer.enabled(); + function fastEntityKey(d2) { + var mode = context.mode(); + var isMoving = mode && /^(add|draw|drag|move|rotate)/.test(mode.id); + return isMoving ? d2.id : osmEntity.key(d2); } - photos.shouldFilterByDate = function() { - return showsLayer("mapillary") || showsLayer("kartaview") || showsLayer("streetside") || showsLayer("vegbilder"); - }; - photos.shouldFilterByPhotoType = function() { - return showsLayer("mapillary") || showsLayer("streetside") && showsLayer("kartaview") || showsLayer("vegbilder"); - }; - photos.shouldFilterByUsername = function() { - return !showsLayer("mapillary") && showsLayer("kartaview") && !showsLayer("streetside"); - }; - photos.showsPhotoType = function(val) { - if (!photos.shouldFilterByPhotoType()) - return true; - return _shownPhotoTypes.indexOf(val) !== -1; - }; - photos.showsFlat = function() { - return photos.showsPhotoType("flat"); - }; - photos.showsPanoramic = function() { - return photos.showsPhotoType("panoramic"); - }; - photos.fromDate = function() { - return _fromDate; - }; - photos.toDate = function() { - return _toDate; - }; - photos.togglePhotoType = function(val) { - var index = _shownPhotoTypes.indexOf(val); - if (index !== -1) { - _shownPhotoTypes.splice(index, 1); - } else { - _shownPhotoTypes.push(val); - } - dispatch14.call("change", this); - return photos; - }; - photos.usernames = function() { - return _usernames; - }; - photos.init = function() { - var hash = utilStringQs(window.location.hash); - if (hash.photo_dates) { - var parts = /^(.*)[–_](.*)$/g.exec(hash.photo_dates.trim()); - this.setDateFilter("fromDate", parts && parts.length >= 2 && parts[1], false); - this.setDateFilter("toDate", parts && parts.length >= 3 && parts[2], false); + function draw(selection2, graph, vertices, sets2, filter2) { + sets2 = sets2 || { selected: {}, important: {}, hovered: {} }; + var icons = {}; + var directions = {}; + var wireframe = context.surface().classed("fill-wireframe"); + var zoom = geoScaleToZoom(projection2.scale()); + var z2 = zoom < 17 ? 0 : zoom < 18 ? 1 : 2; + var activeID = context.activeID(); + var base = context.history().base(); + function getIcon(d2) { + var entity = graph.entity(d2.id); + if (entity.id in icons) + return icons[entity.id]; + icons[entity.id] = entity.hasInterestingTags() && _mainPresetIndex.match(entity, graph).icon; + return icons[entity.id]; } - if (hash.photo_username) { - this.setUsernameFilter(hash.photo_username, false); + function getDirections(entity) { + if (entity.id in directions) + return directions[entity.id]; + var angles = entity.directions(graph, projection2); + directions[entity.id] = angles.length ? angles : false; + return angles; } - if (hash.photo_overlay) { - var hashOverlayIDs = hash.photo_overlay.replace(/;/g, ",").split(","); - hashOverlayIDs.forEach(function(id2) { - if (id2 === "openstreetcam") - id2 = "kartaview"; - var layer2 = _layerIDs.indexOf(id2) !== -1 && context.layers().layer(id2); - if (layer2 && !layer2.enabled()) - layer2.enabled(true); + function updateAttributes(selection3) { + ["shadow", "stroke", "fill"].forEach(function(klass) { + var rads = radiuses[klass]; + selection3.selectAll("." + klass).each(function(entity) { + var i3 = z2 && getIcon(entity); + var r2 = rads[i3 ? 3 : z2]; + if (entity.id !== activeID && entity.isEndpoint(graph) && !entity.isConnected(graph)) { + r2 += 1.5; + } + if (klass === "shadow") { + _radii[entity.id] = r2; + } + select_default2(this).attr("r", r2).attr("visibility", i3 && klass === "fill" ? "hidden" : null); + }); }); } - if (hash.photo) { - var photoIds = hash.photo.replace(/;/g, ",").split(","); - var photoId = photoIds.length && photoIds[0].trim(); - var results = /(.*)\/(.*)/g.exec(photoId); - if (results && results.length >= 3) { - var serviceId = results[1]; - if (serviceId === "openstreetcam") - serviceId = "kartaview"; - var photoKey = results[2]; - var service = services[serviceId]; - if (service && service.ensureViewerLoaded) { - var layer = _layerIDs.indexOf(serviceId) !== -1 && context.layers().layer(serviceId); - if (layer && !layer.enabled()) - layer.enabled(true); - var baselineTime = Date.now(); - service.on("loadedImages.rendererPhotos", function() { - if (Date.now() - baselineTime > 45e3) { - service.on("loadedImages.rendererPhotos", null); - return; - } - if (!service.cachedImage(photoKey)) - return; - service.on("loadedImages.rendererPhotos", null); - service.ensureViewerLoaded(context).then(function() { - service.selectImage(context, photoKey).showViewer(context); - }); - }); - } - } - } - context.layers().on("change.rendererPhotos", updateStorage); - }; - return utilRebind(photos, dispatch14, "on"); - } - - // modules/ui/account.js - function uiAccount(context) { - const osm = context.connection(); - function updateUserDetails(selection2) { - if (!osm) - return; - if (!osm.authenticated()) { - render(selection2, null); - } else { - osm.userDetails((err, user) => render(selection2, user)); - } + vertices.sort(sortY); + var groups = selection2.selectAll("g.vertex").filter(filter2).data(vertices, fastEntityKey); + groups.exit().remove(); + var enter = groups.enter().append("g").attr("class", function(d2) { + return "node vertex " + d2.id; + }).order(); + enter.append("circle").attr("class", "shadow"); + enter.append("circle").attr("class", "stroke"); + enter.filter(function(d2) { + return d2.hasInterestingTags(); + }).append("circle").attr("class", "fill"); + groups = groups.merge(enter).attr("transform", svgPointTransform(projection2)).classed("sibling", function(d2) { + return d2.id in sets2.selected; + }).classed("shared", function(d2) { + return graph.isShared(d2); + }).classed("endpoint", function(d2) { + return d2.isEndpoint(graph); + }).classed("added", function(d2) { + return !base.entities[d2.id]; + }).classed("moved", function(d2) { + return base.entities[d2.id] && !(0, import_fast_deep_equal8.default)(graph.entities[d2.id].loc, base.entities[d2.id].loc); + }).classed("retagged", function(d2) { + return base.entities[d2.id] && !(0, import_fast_deep_equal8.default)(graph.entities[d2.id].tags, base.entities[d2.id].tags); + }).call(updateAttributes); + var iconUse = groups.selectAll(".icon").data(function data(d2) { + return zoom >= 17 && getIcon(d2) ? [d2] : []; + }, fastEntityKey); + iconUse.exit().remove(); + iconUse.enter().append("use").attr("class", "icon").attr("width", "12px").attr("height", "12px").attr("transform", "translate(-6, -6)").attr("xlink:href", function(d2) { + var picon = getIcon(d2); + return picon ? "#" + picon : ""; + }); + var dgroups = groups.selectAll(".viewfieldgroup").data(function data(d2) { + return zoom >= 18 && getDirections(d2) ? [d2] : []; + }, fastEntityKey); + dgroups.exit().remove(); + dgroups = dgroups.enter().insert("g", ".shadow").attr("class", "viewfieldgroup").merge(dgroups); + var viewfields = dgroups.selectAll(".viewfield").data(getDirections, function key(d2) { + return osmEntity.key(d2); + }); + viewfields.exit().remove(); + viewfields.enter().append("path").attr("class", "viewfield").attr("d", "M0,0H0").merge(viewfields).attr("marker-start", "url(#ideditor-viewfield-marker" + (wireframe ? "-wireframe" : "") + ")").attr("transform", function(d2) { + return "rotate(" + d2 + ")"; + }); } - function render(selection2, user) { - let userInfo = selection2.select(".userInfo"); - let loginLogout = selection2.select(".loginLogout"); - if (user) { - userInfo.html("").classed("hide", false); - let userLink = userInfo.append("a").attr("href", osm.userURL(user.display_name)).attr("target", "_blank"); - if (user.image_url) { - userLink.append("img").attr("class", "icon pre-text user-icon").attr("src", user.image_url); + function drawTargets(selection2, graph, entities, filter2) { + var targetClass = context.getDebug("target") ? "pink " : "nocolor "; + var nopeClass = context.getDebug("target") ? "red " : "nocolor "; + var getTransform = svgPointTransform(projection2).geojson; + var activeID = context.activeID(); + var data = { targets: [], nopes: [] }; + entities.forEach(function(node) { + if (activeID === node.id) + return; + var vertexType = svgPassiveVertex(node, graph, activeID); + if (vertexType !== 0) { + data.targets.push({ + type: "Feature", + id: node.id, + properties: { + target: true, + entity: node + }, + geometry: node.asGeoJSON() + }); } else { - userLink.call(svgIcon("#iD-icon-avatar", "pre-text light")); + data.nopes.push({ + type: "Feature", + id: node.id + "-nope", + properties: { + nope: true, + target: true, + entity: node + }, + geometry: node.asGeoJSON() + }); } - userLink.append("span").attr("class", "label").text(user.display_name); - loginLogout.classed("hide", false).select("a").text(_t("logout")).on("click", (e3) => { - e3.preventDefault(); - osm.logout(); - tryLogout(); - }); - } else { - userInfo.html("").classed("hide", true); - loginLogout.classed("hide", false).select("a").text(_t("login")).on("click", (e3) => { - e3.preventDefault(); - osm.authenticate(); - }); - } + }); + var targets = selection2.selectAll(".vertex.target-allowed").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(data.targets, function key(d2) { + return d2.id; + }); + targets.exit().remove(); + targets.enter().append("circle").attr("r", function(d2) { + return _radii[d2.id] || radiuses.shadow[3]; + }).merge(targets).attr("class", function(d2) { + return "node vertex target target-allowed " + targetClass + d2.id; + }).attr("transform", getTransform); + var nopes = selection2.selectAll(".vertex.target-nope").filter(function(d2) { + return filter2(d2.properties.entity); + }).data(data.nopes, function key(d2) { + return d2.id; + }); + nopes.exit().remove(); + nopes.enter().append("circle").attr("r", function(d2) { + return _radii[d2.properties.entity.id] || radiuses.shadow[3]; + }).merge(nopes).attr("class", function(d2) { + return "node vertex target target-nope " + nopeClass + d2.id; + }).attr("transform", getTransform); } - function tryLogout() { - if (!osm) - return; - const url = osm.getUrlRoot() + "/logout?referer=%2Flogin"; - const w2 = 600; - const h2 = 550; - const settings = [ - ["width", w2], - ["height", h2], - ["left", window.screen.width / 2 - w2 / 2], - ["top", window.screen.height / 2 - h2 / 2] - ].map((x2) => x2.join("=")).join(","); - window.open(url, "_blank", settings); + function renderAsVertex(entity, graph, wireframe, zoom) { + var geometry = entity.geometry(graph); + return geometry === "vertex" || geometry === "point" && (wireframe || zoom >= 18 && entity.directions(graph, projection2).length); } - return function(selection2) { - if (!osm) - return; - selection2.append("li").attr("class", "userInfo").classed("hide", true); - selection2.append("li").attr("class", "loginLogout").classed("hide", true).append("a").attr("href", "#"); - osm.on("change.account", () => updateUserDetails(selection2)); - updateUserDetails(selection2); - }; - } - - // modules/ui/attribution.js - function uiAttribution(context) { - let _selection = select_default2(null); - function render(selection2, data, klass) { - let div = selection2.selectAll(".".concat(klass)).data([0]); - div = div.enter().append("div").attr("class", klass).merge(div); - let attributions = div.selectAll(".attribution").data(data, (d2) => d2.id); - attributions.exit().remove(); - attributions = attributions.enter().append("span").attr("class", "attribution").each((d2, i3, nodes) => { - let attribution = select_default2(nodes[i3]); - if (d2.terms_html) { - attribution.html(d2.terms_html); + function isEditedNode(node, base, head) { + var baseNode = base.entities[node.id]; + var headNode = head.entities[node.id]; + return !headNode || !baseNode || !(0, import_fast_deep_equal8.default)(headNode.tags, baseNode.tags) || !(0, import_fast_deep_equal8.default)(headNode.loc, baseNode.loc); + } + function getSiblingAndChildVertices(ids, graph, wireframe, zoom) { + var results = {}; + var seenIds = {}; + function addChildVertices(entity) { + if (seenIds[entity.id]) return; + seenIds[entity.id] = true; + var geometry = entity.geometry(graph); + if (!context.features().isHiddenFeature(entity, graph, geometry)) { + var i3; + if (entity.type === "way") { + for (i3 = 0; i3 < entity.nodes.length; i3++) { + var child = graph.hasEntity(entity.nodes[i3]); + if (child) { + addChildVertices(child); + } + } + } else if (entity.type === "relation") { + for (i3 = 0; i3 < entity.members.length; i3++) { + var member = graph.hasEntity(entity.members[i3].id); + if (member) { + addChildVertices(member); + } + } + } else if (renderAsVertex(entity, graph, wireframe, zoom)) { + results[entity.id] = entity; + } } - if (d2.terms_url) { - attribution = attribution.append("a").attr("href", d2.terms_url).attr("target", "_blank"); - } - const sourceID = d2.id.replace(/\./g, ""); - const terms_text = _t( - "imagery.".concat(sourceID, ".attribution.text"), - { default: d2.terms_text || d2.id || d2.name() } - ); - if (d2.icon && !d2.overlay) { - attribution.append("img").attr("class", "source-image").attr("src", d2.icon); + } + ids.forEach(function(id2) { + var entity = graph.hasEntity(id2); + if (!entity) + return; + if (entity.type === "node") { + if (renderAsVertex(entity, graph, wireframe, zoom)) { + results[entity.id] = entity; + graph.parentWays(entity).forEach(function(entity2) { + addChildVertices(entity2); + }); + } + } else { + addChildVertices(entity); } - attribution.append("span").attr("class", "attribution-text").text(terms_text); - }).merge(attributions); - let copyright = attributions.selectAll(".copyright-notice").data((d2) => { - let notice = d2.copyrightNotices(context.map().zoom(), context.map().extent()); - return notice ? [notice] : []; - }); - copyright.exit().remove(); - copyright = copyright.enter().append("span").attr("class", "copyright-notice").merge(copyright); - copyright.text(String); - } - function update() { - let baselayer = context.background().baseLayerSource(); - _selection.call(render, baselayer ? [baselayer] : [], "base-layer-attribution"); - const z2 = context.map().zoom(); - let overlays = context.background().overlayLayerSources() || []; - _selection.call(render, overlays.filter((s2) => s2.validZoom(z2)), "overlay-layer-attribution"); - } - return function(selection2) { - _selection = selection2; - context.background().on("change.attribution", update); - context.map().on("move.attribution", throttle_default(update, 400, { leading: false })); - update(); - }; - } - - // modules/ui/contributors.js - function uiContributors(context) { - var osm = context.connection(), debouncedUpdate = debounce_default(function() { - update(); - }, 1e3), limit = 4, hidden = false, wrap2 = select_default2(null); - function update() { - if (!osm) - return; - var users = {}, entities = context.history().intersects(context.map().extent()); - entities.forEach(function(entity) { - if (entity && entity.user) - users[entity.user] = true; }); - var u2 = Object.keys(users), subset = u2.slice(0, u2.length > limit ? limit - 1 : limit); - wrap2.html("").call(svgIcon("#iD-icon-nearby", "pre-text light")); - var userList = select_default2(document.createElement("span")); - userList.selectAll().data(subset).enter().append("a").attr("class", "user-link").attr("href", function(d2) { - return osm.userURL(d2); - }).attr("target", "_blank").text(String); - if (u2.length > limit) { - var count = select_default2(document.createElement("span")); - var othersNum = u2.length - limit + 1; - count.append("a").attr("target", "_blank").attr("href", function() { - return osm.changesetsURL(context.map().center(), context.map().zoom()); - }).text(othersNum); - wrap2.append("span").html(_t.html("contributors.truncated_list", { n: othersNum, users: { html: userList.html() }, count: { html: count.html() } })); - } else { - wrap2.append("span").html(_t.html("contributors.list", { users: { html: userList.html() } })); - } - if (!u2.length) { - hidden = true; - wrap2.transition().style("opacity", 0); - } else if (hidden) { - wrap2.transition().style("opacity", 1); - } + return results; } - return function(selection2) { - if (!osm) - return; - wrap2 = selection2; - update(); - osm.on("loaded.contributors", debouncedUpdate); - context.map().on("move.contributors", debouncedUpdate); - }; - } - - // modules/ui/popover.js - var _popoverID = 0; - function uiPopover(klass) { - var _id = _popoverID++; - var _anchorSelection = select_default2(null); - var popover = function(selection2) { - _anchorSelection = selection2; - selection2.each(setup); - }; - var _animation = utilFunctor(false); - var _placement = utilFunctor("top"); - var _alignment = utilFunctor("center"); - var _scrollContainer = utilFunctor(select_default2(null)); - var _content; - var _displayType = utilFunctor(""); - var _hasArrow = utilFunctor(true); - var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; - popover.displayType = function(val) { - if (arguments.length) { - _displayType = utilFunctor(val); - return popover; - } else { - return _displayType; + function drawVertices(selection2, graph, entities, filter2, extent, fullRedraw) { + var wireframe = context.surface().classed("fill-wireframe"); + var visualDiff = context.surface().classed("highlight-edited"); + var zoom = geoScaleToZoom(projection2.scale()); + var mode = context.mode(); + var isMoving = mode && /^(add|draw|drag|move|rotate)/.test(mode.id); + var base = context.history().base(); + var drawLayer = selection2.selectAll(".layer-osm.points .points-group.vertices"); + var touchLayer = selection2.selectAll(".layer-touch.points"); + if (fullRedraw) { + _currPersistent = {}; + _radii = {}; } - }; - popover.hasArrow = function(val) { - if (arguments.length) { - _hasArrow = utilFunctor(val); - return popover; - } else { - return _hasArrow; + for (var i3 = 0; i3 < entities.length; i3++) { + var entity = entities[i3]; + var geometry = entity.geometry(graph); + var keep = false; + if (geometry === "point" && renderAsVertex(entity, graph, wireframe, zoom)) { + _currPersistent[entity.id] = entity; + keep = true; + } else if (geometry === "vertex" && (entity.hasInterestingTags() || entity.isEndpoint(graph) || entity.isConnected(graph) || visualDiff && isEditedNode(entity, base, graph))) { + _currPersistent[entity.id] = entity; + keep = true; + } + if (!keep && !fullRedraw) { + delete _currPersistent[entity.id]; + } } - }; - popover.placement = function(val) { - if (arguments.length) { - _placement = utilFunctor(val); - return popover; - } else { - return _placement; + var sets2 = { + persistent: _currPersistent, + // persistent = important vertices (render always) + selected: _currSelected, + // selected + siblings of selected (render always) + hovered: _currHover + // hovered + siblings of hovered (render only in draw modes) + }; + var all = Object.assign({}, isMoving ? _currHover : {}, _currSelected, _currPersistent); + var filterRendered = function(d2) { + return d2.id in _currPersistent || d2.id in _currSelected || d2.id in _currHover || filter2(d2); + }; + drawLayer.call(draw, graph, currentVisible(all), sets2, filterRendered); + var filterTouch = function(d2) { + return isMoving ? true : filterRendered(d2); + }; + touchLayer.call(drawTargets, graph, currentVisible(all), filterTouch); + function currentVisible(which) { + return Object.keys(which).map(graph.hasEntity, graph).filter(function(entity2) { + return entity2 && entity2.intersects(extent, graph); + }); } - }; - popover.alignment = function(val) { - if (arguments.length) { - _alignment = utilFunctor(val); - return popover; + } + drawVertices.drawSelected = function(selection2, graph, extent) { + var wireframe = context.surface().classed("fill-wireframe"); + var zoom = geoScaleToZoom(projection2.scale()); + _prevSelected = _currSelected || {}; + if (context.map().isInWideSelection()) { + _currSelected = {}; + context.selectedIDs().forEach(function(id2) { + var entity = graph.hasEntity(id2); + if (!entity) + return; + if (entity.type === "node") { + if (renderAsVertex(entity, graph, wireframe, zoom)) { + _currSelected[entity.id] = entity; + } + } + }); } else { - return _alignment; + _currSelected = getSiblingAndChildVertices(context.selectedIDs(), graph, wireframe, zoom); } + var filter2 = function(d2) { + return d2.id in _prevSelected; + }; + drawVertices(selection2, graph, Object.values(_prevSelected), filter2, extent, false); }; - popover.scrollContainer = function(val) { - if (arguments.length) { - _scrollContainer = utilFunctor(val); - return popover; + drawVertices.drawHover = function(selection2, graph, target, extent) { + if (target === _currHoverTarget) + return; + var wireframe = context.surface().classed("fill-wireframe"); + var zoom = geoScaleToZoom(projection2.scale()); + _prevHover = _currHover || {}; + _currHoverTarget = target; + var entity = target && target.properties && target.properties.entity; + if (entity) { + _currHover = getSiblingAndChildVertices([entity.id], graph, wireframe, zoom); } else { - return _scrollContainer; + _currHover = {}; } + var filter2 = function(d2) { + return d2.id in _prevHover; + }; + drawVertices(selection2, graph, Object.values(_prevHover), filter2, extent, false); }; - popover.content = function(val) { - if (arguments.length) { - _content = val; - return popover; + return drawVertices; + } + + // modules/util/bind_once.js + function utilBindOnce(target, type2, listener, capture) { + var typeOnce = type2 + ".once"; + function one2() { + target.on(typeOnce, null); + listener.apply(this, arguments); + } + target.on(typeOnce, one2, capture); + return this; + } + + // modules/util/zoom_pan.js + function defaultFilter3(d3_event) { + return !d3_event.ctrlKey && !d3_event.button; + } + function defaultExtent2() { + var e3 = this; + if (e3 instanceof SVGElement) { + e3 = e3.ownerSVGElement || e3; + if (e3.hasAttribute("viewBox")) { + e3 = e3.viewBox.baseVal; + return [[e3.x, e3.y], [e3.x + e3.width, e3.y + e3.height]]; + } + return [[0, 0], [e3.width.baseVal.value, e3.height.baseVal.value]]; + } + return [[0, 0], [e3.clientWidth, e3.clientHeight]]; + } + function defaultWheelDelta2(d3_event) { + return -d3_event.deltaY * (d3_event.deltaMode === 1 ? 0.05 : d3_event.deltaMode ? 1 : 2e-3); + } + function defaultConstrain2(transform2, extent, translateExtent) { + var dx0 = transform2.invertX(extent[0][0]) - translateExtent[0][0], dx1 = transform2.invertX(extent[1][0]) - translateExtent[1][0], dy0 = transform2.invertY(extent[0][1]) - translateExtent[0][1], dy1 = transform2.invertY(extent[1][1]) - translateExtent[1][1]; + return transform2.translate( + dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1), + dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1) + ); + } + function utilZoomPan() { + var filter2 = defaultFilter3, extent = defaultExtent2, constrain = defaultConstrain2, wheelDelta = defaultWheelDelta2, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], interpolate = zoom_default, dispatch14 = dispatch_default("start", "zoom", "end"), _wheelDelay = 150, _transform = identity2, _activeGesture; + function zoom(selection2) { + selection2.on("pointerdown.zoom", pointerdown).on("wheel.zoom", wheeled).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)"); + select_default2(window).on("pointermove.zoompan", pointermove).on("pointerup.zoompan pointercancel.zoompan", pointerup); + } + zoom.transform = function(collection, transform2, point2) { + var selection2 = collection.selection ? collection.selection() : collection; + if (collection !== selection2) { + schedule(collection, transform2, point2); } else { - return _content; + selection2.interrupt().each(function() { + gesture(this, arguments).start(null).zoom(null, null, typeof transform2 === "function" ? transform2.apply(this, arguments) : transform2).end(null); + }); } }; - popover.isShown = function() { - var popoverSelection = _anchorSelection.select(".popover-" + _id); - return !popoverSelection.empty() && popoverSelection.classed("in"); - }; - popover.show = function() { - _anchorSelection.each(show); - }; - popover.updateContent = function() { - _anchorSelection.each(updateContent); - }; - popover.hide = function() { - _anchorSelection.each(hide); + zoom.scaleBy = function(selection2, k2, p2) { + zoom.scaleTo(selection2, function() { + var k0 = _transform.k, k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2; + return k0 * k1; + }, p2); }; - popover.toggle = function() { - _anchorSelection.each(toggle); + zoom.scaleTo = function(selection2, k2, p2) { + zoom.transform(selection2, function() { + var e3 = extent.apply(this, arguments), t0 = _transform, p02 = !p2 ? centroid(e3) : typeof p2 === "function" ? p2.apply(this, arguments) : p2, p1 = t0.invert(p02), k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2; + return constrain(translate(scale(t0, k1), p02, p1), e3, translateExtent); + }, p2); }; - popover.destroy = function(selection2, selector) { - selector = selector || ".popover-" + _id; - selection2.on(_pointerPrefix + "enter.popover", null).on(_pointerPrefix + "leave.popover", null).on(_pointerPrefix + "up.popover", null).on(_pointerPrefix + "down.popover", null).on("click.popover", null).attr("title", function() { - return this.getAttribute("data-original-title") || this.getAttribute("title"); - }).attr("data-original-title", null).selectAll(selector).remove(); + zoom.translateBy = function(selection2, x2, y2) { + zoom.transform(selection2, function() { + return constrain(_transform.translate( + typeof x2 === "function" ? x2.apply(this, arguments) : x2, + typeof y2 === "function" ? y2.apply(this, arguments) : y2 + ), extent.apply(this, arguments), translateExtent); + }); }; - popover.destroyAny = function(selection2) { - selection2.call(popover.destroy, ".popover"); + zoom.translateTo = function(selection2, x2, y2, p2) { + zoom.transform(selection2, function() { + var e3 = extent.apply(this, arguments), t2 = _transform, p02 = !p2 ? centroid(e3) : typeof p2 === "function" ? p2.apply(this, arguments) : p2; + return constrain(identity2.translate(p02[0], p02[1]).scale(t2.k).translate( + typeof x2 === "function" ? -x2.apply(this, arguments) : -x2, + typeof y2 === "function" ? -y2.apply(this, arguments) : -y2 + ), e3, translateExtent); + }, p2); }; - function setup() { - var anchor = select_default2(this); - var animate = _animation.apply(this, arguments); - var popoverSelection = anchor.selectAll(".popover-" + _id).data([0]); - var enter = popoverSelection.enter().append("div").attr("class", "popover popover-" + _id + " " + (klass ? klass : "")).classed("arrowed", _hasArrow.apply(this, arguments)); - enter.append("div").attr("class", "popover-arrow"); - enter.append("div").attr("class", "popover-inner"); - popoverSelection = enter.merge(popoverSelection); - if (animate) { - popoverSelection.classed("fade", true); - } - var display = _displayType.apply(this, arguments); - if (display === "hover") { - var _lastNonMouseEnterTime; - anchor.on(_pointerPrefix + "enter.popover", function(d3_event) { - if (d3_event.pointerType) { - if (d3_event.pointerType !== "mouse") { - _lastNonMouseEnterTime = d3_event.timeStamp; - return; - } else if (_lastNonMouseEnterTime && d3_event.timeStamp - _lastNonMouseEnterTime < 1500) { - return; - } - } - if (d3_event.buttons !== 0) - return; - show.apply(this, arguments); - }).on(_pointerPrefix + "leave.popover", function() { - hide.apply(this, arguments); - }).on("focus.popover", function() { - show.apply(this, arguments); - }).on("blur.popover", function() { - hide.apply(this, arguments); - }); - } else if (display === "clickFocus") { - anchor.on(_pointerPrefix + "down.popover", function(d3_event) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - }).on(_pointerPrefix + "up.popover", function(d3_event) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - }).on("click.popover", toggle); - popoverSelection.attr("tabindex", 0).on("blur.popover", function() { - anchor.each(function() { - hide.apply(this, arguments); - }); - }); - } + function scale(transform2, k2) { + k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k2)); + return k2 === transform2.k ? transform2 : new Transform(k2, transform2.x, transform2.y); } - function show() { - var anchor = select_default2(this); - var popoverSelection = anchor.selectAll(".popover-" + _id); - if (popoverSelection.empty()) { - anchor.call(popover.destroy); - anchor.each(setup); - popoverSelection = anchor.selectAll(".popover-" + _id); - } - popoverSelection.classed("in", true); - var displayType = _displayType.apply(this, arguments); - if (displayType === "clickFocus") { - anchor.classed("active", true); - popoverSelection.node().focus(); - } - anchor.each(updateContent); + function translate(transform2, p02, p1) { + var x2 = p02[0] - p1[0] * transform2.k, y2 = p02[1] - p1[1] * transform2.k; + return x2 === transform2.x && y2 === transform2.y ? transform2 : new Transform(transform2.k, x2, y2); } - function updateContent() { - var anchor = select_default2(this); - if (_content) { - anchor.selectAll(".popover-" + _id + " > .popover-inner").call(_content.apply(this, arguments)); - } - updatePosition.apply(this, arguments); - updatePosition.apply(this, arguments); - updatePosition.apply(this, arguments); + function centroid(extent2) { + return [(+extent2[0][0] + +extent2[1][0]) / 2, (+extent2[0][1] + +extent2[1][1]) / 2]; } - function updatePosition() { - var anchor = select_default2(this); - var popoverSelection = anchor.selectAll(".popover-" + _id); - var scrollContainer = _scrollContainer && _scrollContainer.apply(this, arguments); - var scrollNode = scrollContainer && !scrollContainer.empty() && scrollContainer.node(); - var scrollLeft = scrollNode ? scrollNode.scrollLeft : 0; - var scrollTop = scrollNode ? scrollNode.scrollTop : 0; - var placement = _placement.apply(this, arguments); - popoverSelection.classed("left", false).classed("right", false).classed("top", false).classed("bottom", false).classed(placement, true); - var alignment = _alignment.apply(this, arguments); - var alignFactor = 0.5; - if (alignment === "leading") { - alignFactor = 0; - } else if (alignment === "trailing") { - alignFactor = 1; - } - var anchorFrame = getFrame(anchor.node()); - var popoverFrame = getFrame(popoverSelection.node()); - var position; - switch (placement) { - case "top": - position = { - x: anchorFrame.x + (anchorFrame.w - popoverFrame.w) * alignFactor, - y: anchorFrame.y - popoverFrame.h - }; - break; - case "bottom": - position = { - x: anchorFrame.x + (anchorFrame.w - popoverFrame.w) * alignFactor, - y: anchorFrame.y + anchorFrame.h - }; - break; - case "left": - position = { - x: anchorFrame.x - popoverFrame.w, - y: anchorFrame.y + (anchorFrame.h - popoverFrame.h) * alignFactor - }; - break; - case "right": - position = { - x: anchorFrame.x + anchorFrame.w, - y: anchorFrame.y + (anchorFrame.h - popoverFrame.h) * alignFactor - }; - break; - } - if (position) { - if (scrollNode && (placement === "top" || placement === "bottom")) { - var initialPosX = position.x; - if (position.x + popoverFrame.w > scrollNode.offsetWidth - 10) { - position.x = scrollNode.offsetWidth - 10 - popoverFrame.w; - } else if (position.x < 10) { - position.x = 10; + function schedule(transition2, transform2, point2) { + transition2.on("start.zoom", function() { + gesture(this, arguments).start(null); + }).on("interrupt.zoom end.zoom", function() { + gesture(this, arguments).end(null); + }).tween("zoom", function() { + var that = this, args = arguments, g3 = gesture(that, args), e3 = extent.apply(that, args), p2 = !point2 ? centroid(e3) : typeof point2 === "function" ? point2.apply(that, args) : point2, w2 = Math.max(e3[1][0] - e3[0][0], e3[1][1] - e3[0][1]), a2 = _transform, b2 = typeof transform2 === "function" ? transform2.apply(that, args) : transform2, i3 = interpolate(a2.invert(p2).concat(w2 / a2.k), b2.invert(p2).concat(w2 / b2.k)); + return function(t2) { + if (t2 === 1) { + t2 = b2; + } else { + var l2 = i3(t2); + var k2 = w2 / l2[2]; + t2 = new Transform(k2, p2[0] - l2[0] * k2, p2[1] - l2[1] * k2); } - var arrow = anchor.selectAll(".popover-" + _id + " > .popover-arrow"); - var arrowPosX = Math.min(Math.max(popoverFrame.w / 2 - (position.x - initialPosX), 10), popoverFrame.w - 10); - arrow.style("left", ~~arrowPosX + "px"); - } - popoverSelection.style("left", ~~position.x + "px").style("top", ~~position.y + "px"); - } else { - popoverSelection.style("left", null).style("top", null); - } - function getFrame(node) { - var positionStyle = select_default2(node).style("position"); - if (positionStyle === "absolute" || positionStyle === "static") { - return { - x: node.offsetLeft - scrollLeft, - y: node.offsetTop - scrollTop, - w: node.offsetWidth, - h: node.offsetHeight - }; - } else { - return { - x: 0, - y: 0, - w: node.offsetWidth, - h: node.offsetHeight - }; - } - } + g3.zoom(null, null, t2); + }; + }); } - function hide() { - var anchor = select_default2(this); - if (_displayType.apply(this, arguments) === "clickFocus") { - anchor.classed("active", false); - } - anchor.selectAll(".popover-" + _id).classed("in", false); + function gesture(that, args, clean2) { + return !clean2 && _activeGesture || new Gesture(that, args); } - function toggle() { - if (select_default2(this).select(".popover-" + _id).classed("in")) { - hide.apply(this, arguments); - } else { - show.apply(this, arguments); - } + function Gesture(that, args) { + this.that = that; + this.args = args; + this.active = 0; + this.extent = extent.apply(that, args); } - return popover; - } - - // modules/ui/tooltip.js - function uiTooltip(klass) { - var tooltip = uiPopover((klass || "") + " tooltip").displayType("hover"); - var _title = function() { - var title = this.getAttribute("data-original-title"); - if (title) { - return title; - } else { - title = this.getAttribute("title"); - this.removeAttribute("title"); - this.setAttribute("data-original-title", title); + Gesture.prototype = { + start: function(d3_event) { + if (++this.active === 1) { + _activeGesture = this; + dispatch14.call("start", this, d3_event); + } + return this; + }, + zoom: function(d3_event, key, transform2) { + if (this.mouse && key !== "mouse") + this.mouse[1] = transform2.invert(this.mouse[0]); + if (this.pointer0 && key !== "touch") + this.pointer0[1] = transform2.invert(this.pointer0[0]); + if (this.pointer1 && key !== "touch") + this.pointer1[1] = transform2.invert(this.pointer1[0]); + _transform = transform2; + dispatch14.call("zoom", this, d3_event, key, transform2); + return this; + }, + end: function(d3_event) { + if (--this.active === 0) { + _activeGesture = null; + dispatch14.call("end", this, d3_event); + } + return this; } - return title; - }; - var _heading = utilFunctor(null); - var _keys = utilFunctor(null); - tooltip.title = function(val) { - if (!arguments.length) - return _title; - _title = utilFunctor(val); - return tooltip; - }; - tooltip.heading = function(val) { - if (!arguments.length) - return _heading; - _heading = utilFunctor(val); - return tooltip; - }; - tooltip.keys = function(val) { - if (!arguments.length) - return _keys; - _keys = utilFunctor(val); - return tooltip; }; - tooltip.content(function() { - var heading = _heading.apply(this, arguments); - var text2 = _title.apply(this, arguments); - var keys2 = _keys.apply(this, arguments); - var headingCallback = typeof heading === "function" ? heading : (s2) => s2.text(heading); - var textCallback = typeof text2 === "function" ? text2 : (s2) => s2.text(text2); - return function(selection2) { - var headingSelect = selection2.selectAll(".tooltip-heading").data(heading ? [heading] : []); - headingSelect.exit().remove(); - headingSelect.enter().append("div").attr("class", "tooltip-heading").merge(headingSelect).text("").call(headingCallback); - var textSelect = selection2.selectAll(".tooltip-text").data(text2 ? [text2] : []); - textSelect.exit().remove(); - textSelect.enter().append("div").attr("class", "tooltip-text").merge(textSelect).text("").call(textCallback); - var keyhintWrap = selection2.selectAll(".keyhint-wrap").data(keys2 && keys2.length ? [0] : []); - keyhintWrap.exit().remove(); - var keyhintWrapEnter = keyhintWrap.enter().append("div").attr("class", "keyhint-wrap"); - keyhintWrapEnter.append("span").call(_t.append("tooltip_keyhint")); - keyhintWrap = keyhintWrapEnter.merge(keyhintWrap); - keyhintWrap.selectAll("kbd.shortcut").data(keys2 && keys2.length ? keys2 : []).enter().append("kbd").attr("class", "shortcut").text(function(d2) { - return d2; - }); - }; - }); - return tooltip; - } - - // modules/ui/edit_menu.js - function uiEditMenu(context) { - var dispatch14 = dispatch_default("toggled"); - var _menu = select_default2(null); - var _operations = []; - var _anchorLoc = [0, 0]; - var _anchorLocLonLat = [0, 0]; - var _triggerType = ""; - var _vpTopMargin = 85; - var _vpBottomMargin = 45; - var _vpSideMargin = 35; - var _menuTop = false; - var _menuHeight; - var _menuWidth; - var _verticalPadding = 4; - var _tooltipWidth = 210; - var _menuSideMargin = 10; - var _tooltips = []; - var editMenu = function(selection2) { - var isTouchMenu = _triggerType.includes("touch") || _triggerType.includes("pen"); - var ops = _operations.filter(function(op) { - return !isTouchMenu || !op.mouseOnly; - }); - if (!ops.length) + function wheeled(d3_event) { + if (!filter2.apply(this, arguments)) return; - _tooltips = []; - _menuTop = isTouchMenu; - var showLabels = isTouchMenu; - var buttonHeight = showLabels ? 32 : 34; - if (showLabels) { - _menuWidth = 52 + Math.min(120, 6 * Math.max.apply(Math, ops.map(function(op) { - return op.title.length; - }))); + var g3 = gesture(this, arguments), t2 = _transform, k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t2.k * Math.pow(2, wheelDelta.apply(this, arguments)))), p2 = utilFastMouse(this)(d3_event); + if (g3.wheel) { + if (g3.mouse[0][0] !== p2[0] || g3.mouse[0][1] !== p2[1]) { + g3.mouse[1] = t2.invert(g3.mouse[0] = p2); + } + clearTimeout(g3.wheel); } else { - _menuWidth = 44; + g3.mouse = [p2, t2.invert(p2)]; + interrupt_default(this); + g3.start(d3_event); } - _menuHeight = _verticalPadding * 2 + ops.length * buttonHeight; - _menu = selection2.append("div").attr("class", "edit-menu").classed("touch-menu", isTouchMenu).style("padding", _verticalPadding + "px 0"); - var buttons = _menu.selectAll(".edit-menu-item").data(ops); - var buttonsEnter = buttons.enter().append("button").attr("class", function(d2) { - return "edit-menu-item edit-menu-item-" + d2.id; - }).style("height", buttonHeight + "px").on("click", click).on("pointerup", pointerup).on("pointerdown mousedown", function pointerdown(d3_event) { - d3_event.stopPropagation(); - }).on("mouseenter.highlight", function(d3_event, d2) { - if (!d2.relatedEntityIds || select_default2(this).classed("disabled")) - return; - utilHighlightEntities(d2.relatedEntityIds(), true, context); - }).on("mouseleave.highlight", function(d3_event, d2) { - if (!d2.relatedEntityIds) - return; - utilHighlightEntities(d2.relatedEntityIds(), false, context); - }); - buttonsEnter.each(function(d2) { - var tooltip = uiTooltip().heading(() => d2.title).title(d2.tooltip).keys([d2.keys[0]]); - _tooltips.push(tooltip); - select_default2(this).call(tooltip).append("div").attr("class", "icon-wrap").call(svgIcon(d2.icon && d2.icon() || "#iD-operation-" + d2.id, "operation")); - }); - if (showLabels) { - buttonsEnter.append("span").attr("class", "label").each(function(d2) { - select_default2(this).call(d2.title); - }); + d3_event.preventDefault(); + d3_event.stopImmediatePropagation(); + g3.wheel = setTimeout(wheelidled, _wheelDelay); + g3.zoom(d3_event, "mouse", constrain(translate(scale(t2, k2), g3.mouse[0], g3.mouse[1]), g3.extent, translateExtent)); + function wheelidled() { + g3.wheel = null; + g3.end(d3_event); } - buttonsEnter.merge(buttons).classed("disabled", function(d2) { - return d2.disabled(); - }); - updatePosition(); - var initialScale = context.projection.scale(); - context.map().on("move.edit-menu", function() { - if (initialScale !== context.projection.scale()) { - editMenu.close(); - } - }).on("drawn.edit-menu", function(info) { - if (info.full) - updatePosition(); - }); - var lastPointerUpType; - function pointerup(d3_event) { - lastPointerUpType = d3_event.pointerType; + } + var _downPointerIDs = /* @__PURE__ */ new Set(); + var _pointerLocGetter; + function pointerdown(d3_event) { + _downPointerIDs.add(d3_event.pointerId); + if (!filter2.apply(this, arguments)) + return; + var g3 = gesture(this, arguments, _downPointerIDs.size === 1); + var started; + d3_event.stopImmediatePropagation(); + _pointerLocGetter = utilFastMouse(this); + var loc = _pointerLocGetter(d3_event); + var p2 = [loc, _transform.invert(loc), d3_event.pointerId]; + if (!g3.pointer0) { + g3.pointer0 = p2; + started = true; + } else if (!g3.pointer1 && g3.pointer0[2] !== p2[2]) { + g3.pointer1 = p2; } - function click(d3_event, operation) { - d3_event.stopPropagation(); - if (operation.relatedEntityIds) { - utilHighlightEntities(operation.relatedEntityIds(), false, context); - } - if (operation.disabled()) { - if (lastPointerUpType === "touch" || lastPointerUpType === "pen") { - context.ui().flash.duration(4e3).iconName("#iD-operation-" + operation.id).iconClass("operation disabled").label(operation.tooltip())(); - } - } else { - if (lastPointerUpType === "touch" || lastPointerUpType === "pen") { - context.ui().flash.duration(2e3).iconName("#iD-operation-" + operation.id).iconClass("operation").label(operation.annotation() || operation.title)(); - } - operation(); - editMenu.close(); - } - lastPointerUpType = null; + if (started) { + interrupt_default(this); + g3.start(d3_event); } - dispatch14.call("toggled", this, true); - }; - function updatePosition() { - if (!_menu || _menu.empty()) + } + function pointermove(d3_event) { + if (!_downPointerIDs.has(d3_event.pointerId)) return; - var anchorLoc = context.projection(_anchorLocLonLat); - var viewport = context.surfaceRect(); - if (anchorLoc[0] < 0 || anchorLoc[0] > viewport.width || anchorLoc[1] < 0 || anchorLoc[1] > viewport.height) { - editMenu.close(); + if (!_activeGesture || !_pointerLocGetter) + return; + var g3 = gesture(this, arguments); + var isPointer0 = g3.pointer0 && g3.pointer0[2] === d3_event.pointerId; + var isPointer1 = !isPointer0 && g3.pointer1 && g3.pointer1[2] === d3_event.pointerId; + if ((isPointer0 || isPointer1) && "buttons" in d3_event && !d3_event.buttons) { + if (g3.pointer0) + _downPointerIDs.delete(g3.pointer0[2]); + if (g3.pointer1) + _downPointerIDs.delete(g3.pointer1[2]); + g3.end(d3_event); return; } - var menuLeft = displayOnLeft(viewport); - var offset = [0, 0]; - offset[0] = menuLeft ? -1 * (_menuSideMargin + _menuWidth) : _menuSideMargin; - if (_menuTop) { - if (anchorLoc[1] - _menuHeight < _vpTopMargin) { - offset[1] = -anchorLoc[1] + _vpTopMargin; - } else { - offset[1] = -_menuHeight; - } + d3_event.preventDefault(); + d3_event.stopImmediatePropagation(); + var loc = _pointerLocGetter(d3_event); + var t2, p2, l2; + if (isPointer0) + g3.pointer0[0] = loc; + else if (isPointer1) + g3.pointer1[0] = loc; + t2 = _transform; + if (g3.pointer1) { + var p02 = g3.pointer0[0], l0 = g3.pointer0[1], p1 = g3.pointer1[0], l1 = g3.pointer1[1], dp = (dp = p1[0] - p02[0]) * dp + (dp = p1[1] - p02[1]) * dp, dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl; + t2 = scale(t2, Math.sqrt(dp / dl)); + p2 = [(p02[0] + p1[0]) / 2, (p02[1] + p1[1]) / 2]; + l2 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2]; + } else if (g3.pointer0) { + p2 = g3.pointer0[0]; + l2 = g3.pointer0[1]; } else { - if (anchorLoc[1] + _menuHeight > viewport.height - _vpBottomMargin) { - offset[1] = -anchorLoc[1] - _menuHeight + viewport.height - _vpBottomMargin; - } else { - offset[1] = 0; - } + return; } - var origin = geoVecAdd(anchorLoc, offset); - _menu.style("left", origin[0] + "px").style("top", origin[1] + "px"); - var tooltipSide = tooltipPosition(viewport, menuLeft); - _tooltips.forEach(function(tooltip) { - tooltip.placement(tooltipSide); - }); - function displayOnLeft(viewport2) { - if (_mainLocalizer.textDirection() === "ltr") { - if (anchorLoc[0] + _menuSideMargin + _menuWidth > viewport2.width - _vpSideMargin) { - return true; - } - return false; - } else { - if (anchorLoc[0] - _menuSideMargin - _menuWidth < _vpSideMargin) { - return false; - } - return true; - } + g3.zoom(d3_event, "touch", constrain(translate(t2, p2, l2), g3.extent, translateExtent)); + } + function pointerup(d3_event) { + if (!_downPointerIDs.has(d3_event.pointerId)) + return; + _downPointerIDs.delete(d3_event.pointerId); + if (!_activeGesture) + return; + var g3 = gesture(this, arguments); + d3_event.stopImmediatePropagation(); + if (g3.pointer0 && g3.pointer0[2] === d3_event.pointerId) + delete g3.pointer0; + else if (g3.pointer1 && g3.pointer1[2] === d3_event.pointerId) + delete g3.pointer1; + if (g3.pointer1 && !g3.pointer0) { + g3.pointer0 = g3.pointer1; + delete g3.pointer1; } - function tooltipPosition(viewport2, menuLeft2) { - if (_mainLocalizer.textDirection() === "ltr") { - if (menuLeft2) { - return "left"; - } - if (anchorLoc[0] + _menuSideMargin + _menuWidth + _tooltipWidth > viewport2.width - _vpSideMargin) { - return "left"; - } - return "right"; - } else { - if (!menuLeft2) { - return "right"; - } - if (anchorLoc[0] - _menuSideMargin - _menuWidth - _tooltipWidth < _vpSideMargin) { - return "right"; - } - return "left"; - } + if (g3.pointer0) { + g3.pointer0[1] = _transform.invert(g3.pointer0[0]); + } else { + g3.end(d3_event); } } - editMenu.close = function() { - context.map().on("move.edit-menu", null).on("drawn.edit-menu", null); - _menu.remove(); - _tooltips = []; - dispatch14.call("toggled", this, false); + zoom.wheelDelta = function(_2) { + return arguments.length ? (wheelDelta = utilFunctor(+_2), zoom) : wheelDelta; }; - editMenu.anchorLoc = function(val) { - if (!arguments.length) - return _anchorLoc; - _anchorLoc = val; - _anchorLocLonLat = context.projection.invert(_anchorLoc); - return editMenu; + zoom.filter = function(_2) { + return arguments.length ? (filter2 = utilFunctor(!!_2), zoom) : filter2; }; - editMenu.triggerType = function(val) { - if (!arguments.length) - return _triggerType; - _triggerType = val; - return editMenu; + zoom.extent = function(_2) { + return arguments.length ? (extent = utilFunctor([[+_2[0][0], +_2[0][1]], [+_2[1][0], +_2[1][1]]]), zoom) : extent; }; - editMenu.operations = function(val) { - if (!arguments.length) - return _operations; - _operations = val; - return editMenu; + zoom.scaleExtent = function(_2) { + return arguments.length ? (scaleExtent[0] = +_2[0], scaleExtent[1] = +_2[1], zoom) : [scaleExtent[0], scaleExtent[1]]; }; - return utilRebind(editMenu, dispatch14, "on"); + zoom.translateExtent = function(_2) { + return arguments.length ? (translateExtent[0][0] = +_2[0][0], translateExtent[1][0] = +_2[1][0], translateExtent[0][1] = +_2[0][1], translateExtent[1][1] = +_2[1][1], zoom) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]]; + }; + zoom.constrain = function(_2) { + return arguments.length ? (constrain = _2, zoom) : constrain; + }; + zoom.interpolate = function(_2) { + return arguments.length ? (interpolate = _2, zoom) : interpolate; + }; + zoom._transform = function(_2) { + return arguments.length ? (_transform = _2, zoom) : _transform; + }; + return utilRebind(zoom, dispatch14, "on"); } - // modules/ui/feature_info.js - function uiFeatureInfo(context) { - function update(selection2) { - var features = context.features(); - var stats = features.stats(); - var count = 0; - var hiddenList = features.hidden().map(function(k2) { - if (stats[k2]) { - count += stats[k2]; - return _t.append("inspector.title_count", { - title: _t("feature." + k2 + ".description"), - count: stats[k2] - }); - } - return null; - }).filter(Boolean); - selection2.text(""); - if (hiddenList.length) { - var tooltipBehavior = uiTooltip().placement("top").title(function() { - return (selection3) => { - hiddenList.forEach((hiddenFeature) => { - selection3.append("div").call(hiddenFeature); - }); - }; - }); - selection2.append("a").attr("class", "chip").attr("href", "#").call(_t.append("feature_info.hidden_warning", { count })).call(tooltipBehavior).on("click", function(d3_event) { - tooltipBehavior.hide(); - d3_event.preventDefault(); - context.ui().togglePanes(context.container().select(".map-panes .map-data-pane")); - }); + // modules/util/double_up.js + function utilDoubleUp() { + var dispatch14 = dispatch_default("doubleUp"); + var _maxTimespan = 500; + var _maxDistance = 20; + var _pointer; + function pointerIsValidFor(loc) { + return (/* @__PURE__ */ new Date()).getTime() - _pointer.startTime <= _maxTimespan && // all pointer events must occur within a small distance of the first pointerdown + geoVecLength(_pointer.startLoc, loc) <= _maxDistance; + } + function pointerdown(d3_event) { + if (d3_event.ctrlKey || d3_event.button === 2) + return; + var loc = [d3_event.clientX, d3_event.clientY]; + if (_pointer && !pointerIsValidFor(loc)) { + _pointer = void 0; + } + if (!_pointer) { + _pointer = { + startLoc: loc, + startTime: (/* @__PURE__ */ new Date()).getTime(), + upCount: 0, + pointerId: d3_event.pointerId + }; + } else { + _pointer.pointerId = d3_event.pointerId; } - selection2.classed("hide", !hiddenList.length); } - return function(selection2) { - update(selection2); - context.features().on("change.feature_info", function() { - update(selection2); - }); - }; - } - - // modules/ui/flash.js - function uiFlash(context) { - var _flashTimer; - var _duration = 2e3; - var _iconName = "#iD-icon-no"; - var _iconClass = "disabled"; - var _label = (s2) => s2.text(""); - function flash() { - if (_flashTimer) { - _flashTimer.stop(); + function pointerup(d3_event) { + if (d3_event.ctrlKey || d3_event.button === 2) + return; + if (!_pointer || _pointer.pointerId !== d3_event.pointerId) + return; + _pointer.upCount += 1; + if (_pointer.upCount === 2) { + var loc = [d3_event.clientX, d3_event.clientY]; + if (pointerIsValidFor(loc)) { + var locInThis = utilFastMouse(this)(d3_event); + dispatch14.call("doubleUp", this, d3_event, locInThis); + } + _pointer = void 0; } - context.container().select(".main-footer-wrap").classed("footer-hide", true).classed("footer-show", false); - context.container().select(".flash-wrap").classed("footer-hide", false).classed("footer-show", true); - var content = context.container().select(".flash-wrap").selectAll(".flash-content").data([0]); - var contentEnter = content.enter().append("div").attr("class", "flash-content"); - var iconEnter = contentEnter.append("svg").attr("class", "flash-icon icon").append("g").attr("transform", "translate(10,10)"); - iconEnter.append("circle").attr("r", 9); - iconEnter.append("use").attr("transform", "translate(-7,-7)").attr("width", "14").attr("height", "14"); - contentEnter.append("div").attr("class", "flash-text"); - content = content.merge(contentEnter); - content.selectAll(".flash-icon").attr("class", "icon flash-icon " + (_iconClass || "")); - content.selectAll(".flash-icon use").attr("xlink:href", _iconName); - content.selectAll(".flash-text").attr("class", "flash-text").call(_label); - _flashTimer = timeout_default(function() { - _flashTimer = null; - context.container().select(".main-footer-wrap").classed("footer-hide", false).classed("footer-show", true); - context.container().select(".flash-wrap").classed("footer-hide", true).classed("footer-show", false); - }, _duration); - return content; } - flash.duration = function(_2) { - if (!arguments.length) - return _duration; - _duration = _2; - return flash; - }; - flash.label = function(_2) { - if (!arguments.length) - return _label; - if (typeof _2 !== "function") { - _label = (selection2) => selection2.text(_2); + function doubleUp(selection2) { + if ("PointerEvent" in window) { + selection2.on("pointerdown.doubleUp", pointerdown).on("pointerup.doubleUp", pointerup); } else { - _label = (selection2) => selection2.text("").call(_2); + selection2.on("dblclick.doubleUp", function(d3_event) { + dispatch14.call("doubleUp", this, d3_event, utilFastMouse(this)(d3_event)); + }); } - return flash; - }; - flash.iconName = function(_2) { - if (!arguments.length) - return _iconName; - _iconName = _2; - return flash; - }; - flash.iconClass = function(_2) { - if (!arguments.length) - return _iconClass; - _iconClass = _2; - return flash; + } + doubleUp.off = function(selection2) { + selection2.on("pointerdown.doubleUp", null).on("pointerup.doubleUp", null).on("dblclick.doubleUp", null); }; - return flash; + return utilRebind(doubleUp, dispatch14, "on"); } - // modules/ui/full_screen.js - function uiFullScreen(context) { - var element = context.container().node(); - function getFullScreenFn() { - if (element.requestFullscreen) { - return element.requestFullscreen; - } else if (element.msRequestFullscreen) { - return element.msRequestFullscreen; - } else if (element.mozRequestFullScreen) { - return element.mozRequestFullScreen; - } else if (element.webkitRequestFullscreen) { - return element.webkitRequestFullscreen; + // modules/renderer/map.js + var TILESIZE = 256; + var minZoom2 = 2; + var maxZoom = 24; + var kMin = geoZoomToScale(minZoom2, TILESIZE); + var kMax = geoZoomToScale(maxZoom, TILESIZE); + function clamp2(num, min3, max3) { + return Math.max(min3, Math.min(num, max3)); + } + function rendererMap(context) { + var dispatch14 = dispatch_default( + "move", + "drawn", + "crossEditableZoom", + "hitMinZoom", + "changeHighlighting", + "changeAreaFill" + ); + var projection2 = context.projection; + var curtainProjection = context.curtainProjection; + var drawLayers; + var drawPoints; + var drawVertices; + var drawLines; + var drawAreas; + var drawMidpoints; + var drawLabels; + var _selection = select_default2(null); + var supersurface = select_default2(null); + var wrapper = select_default2(null); + var surface = select_default2(null); + var _dimensions = [1, 1]; + var _dblClickZoomEnabled = true; + var _redrawEnabled = true; + var _gestureTransformStart; + var _transformStart = projection2.transform(); + var _transformLast; + var _isTransformed = false; + var _minzoom = 0; + var _getMouseCoords; + var _lastPointerEvent; + var _lastWithinEditableZoom; + var _pointerDown = false; + var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; + var _zoomerPannerFunction = "PointerEvent" in window ? utilZoomPan : zoom_default2; + var _zoomerPanner = _zoomerPannerFunction().scaleExtent([kMin, kMax]).interpolate(value_default).filter(zoomEventFilter).on("zoom.map", zoomPan2).on("start.map", function(d3_event) { + _pointerDown = d3_event && (d3_event.type === "pointerdown" || d3_event.sourceEvent && d3_event.sourceEvent.type === "pointerdown"); + }).on("end.map", function() { + _pointerDown = false; + }); + var _doubleUpHandler = utilDoubleUp(); + var scheduleRedraw = throttle_default(redraw, 750); + function cancelPendingRedraw() { + scheduleRedraw.cancel(); + } + function map2(selection2) { + _selection = selection2; + context.on("change.map", immediateRedraw); + var osm = context.connection(); + if (osm) { + osm.on("change.map", immediateRedraw); + } + function didUndoOrRedo(targetTransform) { + var mode = context.mode().id; + if (mode !== "browse" && mode !== "select") + return; + if (targetTransform) { + map2.transformEase(targetTransform); + } + } + context.history().on("merge.map", function() { + scheduleRedraw(); + }).on("change.map", immediateRedraw).on("undone.map", function(stack, fromStack) { + didUndoOrRedo(fromStack.transform); + }).on("redone.map", function(stack) { + didUndoOrRedo(stack.transform); + }); + context.background().on("change.map", immediateRedraw); + context.features().on("redraw.map", immediateRedraw); + drawLayers.on("change.map", function() { + context.background().updateImagery(); + immediateRedraw(); + }); + selection2.on("wheel.map mousewheel.map", function(d3_event) { + d3_event.preventDefault(); + }).call(_zoomerPanner).call(_zoomerPanner.transform, projection2.transform()).on("dblclick.zoom", null); + map2.supersurface = supersurface = selection2.append("div").attr("class", "supersurface").call(utilSetTransform, 0, 0); + wrapper = supersurface.append("div").attr("class", "layer layer-data"); + map2.surface = surface = wrapper.call(drawLayers).selectAll(".surface"); + surface.call(drawLabels.observe).call(_doubleUpHandler).on(_pointerPrefix + "down.zoom", function(d3_event) { + _lastPointerEvent = d3_event; + if (d3_event.button === 2) { + d3_event.stopPropagation(); + } + }, true).on(_pointerPrefix + "up.zoom", function(d3_event) { + _lastPointerEvent = d3_event; + if (resetTransform()) { + immediateRedraw(); + } + }).on(_pointerPrefix + "move.map", function(d3_event) { + _lastPointerEvent = d3_event; + }).on(_pointerPrefix + "over.vertices", function(d3_event) { + if (map2.editableDataEnabled() && !_isTransformed) { + var hover = d3_event.target.__data__; + surface.call(drawVertices.drawHover, context.graph(), hover, map2.extent()); + dispatch14.call("drawn", this, { full: false }); + } + }).on(_pointerPrefix + "out.vertices", function(d3_event) { + if (map2.editableDataEnabled() && !_isTransformed) { + var hover = d3_event.relatedTarget && d3_event.relatedTarget.__data__; + surface.call(drawVertices.drawHover, context.graph(), hover, map2.extent()); + dispatch14.call("drawn", this, { full: false }); + } + }); + var detected = utilDetect(); + if ("GestureEvent" in window && // Listening for gesture events on iOS 13.4+ breaks double-tapping, + // but we only need to do this on desktop Safari anyway. – #7694 + !detected.isMobileWebKit) { + surface.on("gesturestart.surface", function(d3_event) { + d3_event.preventDefault(); + _gestureTransformStart = projection2.transform(); + }).on("gesturechange.surface", gestureChange); } + updateAreaFill(); + _doubleUpHandler.on("doubleUp.map", function(d3_event, p02) { + if (!_dblClickZoomEnabled) + return; + if (typeof d3_event.target.__data__ === "object" && // or area fills + !select_default2(d3_event.target).classed("fill")) + return; + var zoomOut2 = d3_event.shiftKey; + var t2 = projection2.transform(); + var p1 = t2.invert(p02); + t2 = t2.scale(zoomOut2 ? 0.5 : 2); + t2.x = p02[0] - p1[0] * t2.k; + t2.y = p02[1] - p1[1] * t2.k; + map2.transformEase(t2); + }); + context.on("enter.map", function() { + if (!map2.editableDataEnabled( + true + /* skip zoom check */ + )) + return; + if (_isTransformed) + return; + var graph = context.graph(); + var selectedAndParents = {}; + context.selectedIDs().forEach(function(id2) { + var entity = graph.hasEntity(id2); + if (entity) { + selectedAndParents[entity.id] = entity; + if (entity.type === "node") { + graph.parentWays(entity).forEach(function(parent) { + selectedAndParents[parent.id] = parent; + }); + } + } + }); + var data = Object.values(selectedAndParents); + var filter2 = function(d2) { + return d2.id in selectedAndParents; + }; + data = context.features().filter(data, graph); + surface.call(drawVertices.drawSelected, graph, map2.extent()).call(drawLines, graph, data, filter2).call(drawAreas, graph, data, filter2).call(drawMidpoints, graph, data, filter2, map2.trimmedExtent()); + dispatch14.call("drawn", this, { full: false }); + scheduleRedraw(); + }); + map2.dimensions(utilGetDimensions(selection2)); } - function getExitFullScreenFn() { - if (document.exitFullscreen) { - return document.exitFullscreen; - } else if (document.msExitFullscreen) { - return document.msExitFullscreen; - } else if (document.mozCancelFullScreen) { - return document.mozCancelFullScreen; - } else if (document.webkitExitFullscreen) { - return document.webkitExitFullscreen; + function zoomEventFilter(d3_event) { + if (d3_event.type === "mousedown") { + var hasOrphan = false; + var listeners = window.__on; + for (var i3 = 0; i3 < listeners.length; i3++) { + var listener = listeners[i3]; + if (listener.name === "zoom" && listener.type === "mouseup") { + hasOrphan = true; + break; + } + } + if (hasOrphan) { + var event = window.CustomEvent; + if (event) { + event = new event("mouseup"); + } else { + event = window.document.createEvent("Event"); + event.initEvent("mouseup", false, false); + } + event.view = window; + window.dispatchEvent(event); + } } + return d3_event.button !== 2; } - function isFullScreen() { - return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement; - } - function isSupported() { - return !!getFullScreenFn(); + function pxCenter() { + return [_dimensions[0] / 2, _dimensions[1] / 2]; } - function fullScreen(d3_event) { - d3_event.preventDefault(); - if (!isFullScreen()) { - getFullScreenFn().apply(element); + function drawEditable(difference2, extent) { + var mode = context.mode(); + var graph = context.graph(); + var features = context.features(); + var all = context.history().intersects(map2.extent()); + var fullRedraw = false; + var data; + var set4; + var filter2; + var applyFeatureLayerFilters = true; + if (map2.isInWideSelection()) { + data = []; + utilEntityAndDeepMemberIDs(mode.selectedIDs(), context.graph()).forEach(function(id2) { + var entity = context.hasEntity(id2); + if (entity) + data.push(entity); + }); + fullRedraw = true; + filter2 = utilFunctor(true); + applyFeatureLayerFilters = false; + } else if (difference2) { + var complete = difference2.complete(map2.extent()); + data = Object.values(complete).filter(Boolean); + set4 = new Set(Object.keys(complete)); + filter2 = function(d2) { + return set4.has(d2.id); + }; + features.clear(data); } else { - getExitFullScreenFn().apply(document); + if (features.gatherStats(all, graph, _dimensions)) { + extent = void 0; + } + if (extent) { + data = context.history().intersects(map2.extent().intersection(extent)); + set4 = new Set(data.map(function(entity) { + return entity.id; + })); + filter2 = function(d2) { + return set4.has(d2.id); + }; + } else { + data = all; + fullRedraw = true; + filter2 = utilFunctor(true); + } } - } - return function() { - if (!isSupported()) - return; - var detected = utilDetect(); - var keys2 = detected.os === "mac" ? [uiCmd("\u2303\u2318F"), "f11"] : ["f11"]; - context.keybinding().on(keys2, fullScreen); - }; - } - - // modules/ui/geolocate.js - function uiGeolocate(context) { - var _geolocationOptions = { - // prioritize speed and power usage over precision - enableHighAccuracy: false, - // don't hang indefinitely getting the location - timeout: 6e3 - // 6sec - }; - var _locating = uiLoading(context).message(_t.html("geolocate.locating")).blocking(true); - var _layer = context.layers().layer("geolocate"); - var _position; - var _extent; - var _timeoutID; - var _button = select_default2(null); - function click() { - if (context.inIntro()) - return; - if (!_layer.enabled() && !_locating.isShown()) { - _timeoutID = setTimeout( - error, - 1e4 - /* 10sec */ - ); - context.container().call(_locating); - navigator.geolocation.getCurrentPosition(success, error, _geolocationOptions); + if (applyFeatureLayerFilters) { + data = features.filter(data, graph); } else { - _locating.close(); - _layer.enabled(null, false); - updateButtonState(); + context.features().resetStats(); } - } - function zoomTo() { - context.enter(modeBrowse(context)); - var map2 = context.map(); - _layer.enabled(_position, true); - updateButtonState(); - map2.centerZoomEase(_extent.center(), Math.min(20, map2.extentZoom(_extent))); - } - function success(geolocation) { - _position = geolocation; - var coords = _position.coords; - _extent = geoExtent([coords.longitude, coords.latitude]).padByMeters(coords.accuracy); - zoomTo(); - finish(); - } - function error() { - if (_position) { - zoomTo(); - } else { - context.ui().flash.label(_t.append("geolocate.location_unavailable")).iconName("#iD-icon-geolocate")(); + if (mode && mode.id === "select") { + surface.call(drawVertices.drawSelected, graph, map2.extent()); } - finish(); + surface.call(drawVertices, graph, data, filter2, map2.extent(), fullRedraw).call(drawLines, graph, data, filter2).call(drawAreas, graph, data, filter2).call(drawMidpoints, graph, data, filter2, map2.trimmedExtent()).call(drawLabels, graph, data, filter2, _dimensions, fullRedraw).call(drawPoints, graph, data, filter2); + dispatch14.call("drawn", this, { full: true }); } - function finish() { - _locating.close(); - if (_timeoutID) { - clearTimeout(_timeoutID); + map2.init = function() { + drawLayers = svgLayers(projection2, context); + drawPoints = svgPoints(projection2, context); + drawVertices = svgVertices(projection2, context); + drawLines = svgLines(projection2, context); + drawAreas = svgAreas(projection2, context); + drawMidpoints = svgMidpoints(projection2, context); + drawLabels = svgLabels(projection2, context); + }; + function editOff() { + context.features().resetStats(); + surface.selectAll(".layer-osm *").remove(); + surface.selectAll(".layer-touch:not(.markers) *").remove(); + var allowed = { + "browse": true, + "save": true, + "select-note": true, + "select-data": true, + "select-error": true + }; + var mode = context.mode(); + if (mode && !allowed[mode.id]) { + context.enter(modeBrowse(context)); } - _timeoutID = void 0; + dispatch14.call("drawn", this, { full: true }); } - function updateButtonState() { - _button.classed("active", _layer.enabled()); - _button.attr("aria-pressed", _layer.enabled()); + function gestureChange(d3_event) { + var e3 = d3_event; + e3.preventDefault(); + var props = { + deltaMode: 0, + // dummy values to ignore in zoomPan + deltaY: 1, + // dummy values to ignore in zoomPan + clientX: e3.clientX, + clientY: e3.clientY, + screenX: e3.screenX, + screenY: e3.screenY, + x: e3.x, + y: e3.y + }; + var e22 = new WheelEvent("wheel", props); + e22._scale = e3.scale; + e22._rotation = e3.rotation; + _selection.node().dispatchEvent(e22); } - return function(selection2) { - if (!navigator.geolocation || !navigator.geolocation.getCurrentPosition) - return; - _button = selection2.append("button").on("click", click).attr("aria-pressed", false).call(svgIcon("#iD-icon-geolocate", "light")).call( - uiTooltip().placement(_mainLocalizer.textDirection() === "rtl" ? "right" : "left").title(() => _t.append("geolocate.title")).keys([_t("geolocate.key")]) - ); - context.keybinding().on(_t("geolocate.key"), click); - }; - } - - // modules/ui/panels/background.js - function uiPanelBackground(context) { - var background = context.background(); - var _currSourceName = null; - var _metadata = {}; - var _metadataKeys = [ - "zoom", - "vintage", - "source", - "description", - "resolution", - "accuracy" - ]; - var debouncedRedraw = debounce_default(redraw, 250); - function redraw(selection2) { - var source = background.baseLayerSource(); - if (!source) - return; - var isDG = source.id.match(/^DigitalGlobe/i) !== null; - var sourceLabel = source.label(); - if (_currSourceName !== sourceLabel) { - _currSourceName = sourceLabel; - _metadata = {}; - } - selection2.text(""); - var list = selection2.append("ul").attr("class", "background-info"); - list.append("li").call(_currSourceName); - _metadataKeys.forEach(function(k2) { - if (isDG && k2 === "vintage") + function zoomPan2(event, key, transform2) { + var source = event && event.sourceEvent || event; + var eventTransform = transform2 || event && event.transform; + var x2 = eventTransform.x; + var y2 = eventTransform.y; + var k2 = eventTransform.k; + if (source && source.type === "wheel") { + if (_pointerDown) return; - list.append("li").attr("class", "background-info-list-" + k2).classed("hide", !_metadata[k2]).call(_t.append("info_panels.background." + k2, { suffix: ":" })).append("span").attr("class", "background-info-span-" + k2).text(_metadata[k2]); - }); - debouncedGetMetadata(selection2); - var toggleTiles = context.getDebug("tile") ? "hide_tiles" : "show_tiles"; - selection2.append("a").call(_t.append("info_panels.background." + toggleTiles)).attr("href", "#").attr("class", "button button-toggle-tiles").on("click", function(d3_event) { - d3_event.preventDefault(); - context.setDebug("tile", !context.getDebug("tile")); - selection2.call(redraw); - }); - if (isDG) { - var key = source.id + "-vintage"; - var sourceVintage = context.background().findSource(key); - var showsVintage = context.background().showsLayer(sourceVintage); - var toggleVintage = showsVintage ? "hide_vintage" : "show_vintage"; - selection2.append("a").call(_t.append("info_panels.background." + toggleVintage)).attr("href", "#").attr("class", "button button-toggle-vintage").on("click", function(d3_event) { - d3_event.preventDefault(); - context.background().toggleOverlayLayer(sourceVintage); - selection2.call(redraw); - }); - } - ["DigitalGlobe-Premium", "DigitalGlobe-Standard"].forEach(function(layerId) { - if (source.id !== layerId) { - var key2 = layerId + "-vintage"; - var sourceVintage2 = context.background().findSource(key2); - if (context.background().showsLayer(sourceVintage2)) { - context.background().toggleOverlayLayer(sourceVintage2); + var detected = utilDetect(); + var dX = source.deltaX; + var dY = source.deltaY; + var x22 = x2; + var y22 = y2; + var k22 = k2; + var t0, p02, p1; + if (source.deltaMode === 1) { + var lines = Math.abs(source.deltaY); + var sign2 = source.deltaY > 0 ? 1 : -1; + dY = sign2 * clamp2( + Math.exp((lines - 1) * 0.75) * 4.000244140625, + 4.000244140625, + // min + 350.000244140625 + // max + ); + if (detected.os !== "mac") { + dY *= 5; + } + t0 = _isTransformed ? _transformLast : _transformStart; + p02 = _getMouseCoords(source); + p1 = t0.invert(p02); + k22 = t0.k * Math.pow(2, -dY / 500); + k22 = clamp2(k22, kMin, kMax); + x22 = p02[0] - p1[0] * k22; + y22 = p02[1] - p1[1] * k22; + } else if (source._scale) { + t0 = _gestureTransformStart; + p02 = _getMouseCoords(source); + p1 = t0.invert(p02); + k22 = t0.k * source._scale; + k22 = clamp2(k22, kMin, kMax); + x22 = p02[0] - p1[0] * k22; + y22 = p02[1] - p1[1] * k22; + } else if (source.ctrlKey && !isInteger(dY)) { + dY *= 6; + t0 = _isTransformed ? _transformLast : _transformStart; + p02 = _getMouseCoords(source); + p1 = t0.invert(p02); + k22 = t0.k * Math.pow(2, -dY / 500); + k22 = clamp2(k22, kMin, kMax); + x22 = p02[0] - p1[0] * k22; + y22 = p02[1] - p1[1] * k22; + } else if ((source.altKey || source.shiftKey) && isInteger(dY)) { + t0 = _isTransformed ? _transformLast : _transformStart; + p02 = _getMouseCoords(source); + p1 = t0.invert(p02); + k22 = t0.k * Math.pow(2, -dY / 500); + k22 = clamp2(k22, kMin, kMax); + x22 = p02[0] - p1[0] * k22; + y22 = p02[1] - p1[1] * k22; + } else if (detected.os === "mac" && detected.browser !== "Firefox" && !source.ctrlKey && isInteger(dX) && isInteger(dY)) { + p1 = projection2.translate(); + x22 = p1[0] - dX; + y22 = p1[1] - dY; + k22 = projection2.scale(); + k22 = clamp2(k22, kMin, kMax); + } + if (x22 !== x2 || y22 !== y2 || k22 !== k2) { + x2 = x22; + y2 = y22; + k2 = k22; + eventTransform = identity2.translate(x22, y22).scale(k22); + if (_zoomerPanner._transform) { + _zoomerPanner._transform(eventTransform); + } else { + _selection.node().__zoom = eventTransform; } } - }); - } - var debouncedGetMetadata = debounce_default(getMetadata, 250); - function getMetadata(selection2) { - var tile = context.container().select(".layer-background img.tile-center"); - if (tile.empty()) + } + if (_transformStart.x === x2 && _transformStart.y === y2 && _transformStart.k === k2) { return; - var sourceName = _currSourceName; - var d2 = tile.datum(); - var zoom = d2 && d2.length >= 3 && d2[2] || Math.floor(context.map().zoom()); - var center = context.map().center(); - _metadata.zoom = String(zoom); - selection2.selectAll(".background-info-list-zoom").classed("hide", false).selectAll(".background-info-span-zoom").text(_metadata.zoom); - if (!d2 || !d2.length >= 3) + } + if (geoScaleToZoom(k2, TILESIZE) < _minzoom) { + surface.interrupt(); + dispatch14.call("hitMinZoom", this, map2); + setCenterZoom(map2.center(), context.minEditableZoom(), 0, true); + scheduleRedraw(); + dispatch14.call("move", this, map2); return; - background.baseLayerSource().getMetadata(center, d2, function(err, result) { - if (err || _currSourceName !== sourceName) - return; - var vintage = result.vintage; - _metadata.vintage = vintage && vintage.range || _t("info_panels.background.unknown"); - selection2.selectAll(".background-info-list-vintage").classed("hide", false).selectAll(".background-info-span-vintage").text(_metadata.vintage); - _metadataKeys.forEach(function(k2) { - if (k2 === "zoom" || k2 === "vintage") - return; - var val = result[k2]; - _metadata[k2] = val; - selection2.selectAll(".background-info-list-" + k2).classed("hide", !val).selectAll(".background-info-span-" + k2).text(val); + } + projection2.transform(eventTransform); + var withinEditableZoom = map2.withinEditableZoom(); + if (_lastWithinEditableZoom !== withinEditableZoom) { + if (_lastWithinEditableZoom !== void 0) { + dispatch14.call("crossEditableZoom", this, withinEditableZoom); + } + _lastWithinEditableZoom = withinEditableZoom; + } + var scale = k2 / _transformStart.k; + var tX = (x2 / scale - _transformStart.x) * scale; + var tY = (y2 / scale - _transformStart.y) * scale; + if (context.inIntro()) { + curtainProjection.transform({ + x: x2 - tX, + y: y2 - tY, + k: k2 }); - }); - } - var panel = function(selection2) { - selection2.call(redraw); - context.map().on("drawn.info-background", function() { - selection2.call(debouncedRedraw); - }).on("move.info-background", function() { - selection2.call(debouncedGetMetadata); - }); - }; - panel.off = function() { - context.map().on("drawn.info-background", null).on("move.info-background", null); - }; - panel.id = "background"; - panel.label = _t.append("info_panels.background.title"); - panel.key = _t("info_panels.background.key"); - return panel; - } - - // modules/ui/panels/history.js - function uiPanelHistory(context) { - var osm; - function displayTimestamp(timestamp) { - if (!timestamp) - return _t("info_panels.history.unknown"); - var options2 = { - day: "numeric", - month: "short", - year: "numeric", - hour: "numeric", - minute: "numeric", - second: "numeric" - }; - var d2 = new Date(timestamp); - if (isNaN(d2.getTime())) - return _t("info_panels.history.unknown"); - return d2.toLocaleString(_mainLocalizer.localeCode(), options2); - } - function displayUser(selection2, userName) { - if (!userName) { - selection2.append("span").call(_t.append("info_panels.history.unknown")); - return; } - selection2.append("span").attr("class", "user-name").text(userName); - var links = selection2.append("div").attr("class", "links"); - if (osm) { - links.append("a").attr("class", "user-osm-link").attr("href", osm.userURL(userName)).attr("target", "_blank").call(_t.append("info_panels.history.profile_link")); + if (source) { + _lastPointerEvent = event; + } + _isTransformed = true; + _transformLast = eventTransform; + utilSetTransform(supersurface, tX, tY, scale); + scheduleRedraw(); + dispatch14.call("move", this, map2); + function isInteger(val) { + return typeof val === "number" && isFinite(val) && Math.floor(val) === val; } - links.append("a").attr("class", "user-hdyc-link").attr("href", "https://hdyc.neis-one.org/?" + userName).attr("target", "_blank").attr("tabindex", -1).text("HDYC"); } - function displayChangeset(selection2, changeset) { - if (!changeset) { - selection2.append("span").call(_t.append("info_panels.history.unknown")); + function resetTransform() { + if (!_isTransformed) + return false; + utilSetTransform(supersurface, 0, 0); + _isTransformed = false; + if (context.inIntro()) { + curtainProjection.transform(projection2.transform()); + } + return true; + } + function redraw(difference2, extent) { + if (surface.empty() || !_redrawEnabled) return; + if (resetTransform()) { + difference2 = extent = void 0; } - selection2.append("span").attr("class", "changeset-id").text(changeset); - var links = selection2.append("div").attr("class", "links"); - if (osm) { - links.append("a").attr("class", "changeset-osm-link").attr("href", osm.changesetURL(changeset)).attr("target", "_blank").call(_t.append("info_panels.history.changeset_link")); + var zoom = map2.zoom(); + var z2 = String(~~zoom); + if (surface.attr("data-zoom") !== z2) { + surface.attr("data-zoom", z2); + } + var lat = map2.center()[1]; + var lowzoom = linear3().domain([-60, 0, 60]).range([17, 18.5, 17]).clamp(true); + surface.classed("low-zoom", zoom <= lowzoom(lat)); + if (!difference2) { + supersurface.call(context.background()); + wrapper.call(drawLayers); } - links.append("a").attr("class", "changeset-osmcha-link").attr("href", "https://osmcha.org/changesets/" + changeset).attr("target", "_blank").text("OSMCha"); - links.append("a").attr("class", "changeset-achavi-link").attr("href", "https://overpass-api.de/achavi/?changeset=" + changeset).attr("target", "_blank").text("Achavi"); - } - function redraw(selection2) { - var selectedNoteID = context.selectedNoteID(); - osm = context.connection(); - var selected, note, entity; - if (selectedNoteID && osm) { - selected = [_t.html("note.note") + " " + selectedNoteID]; - note = osm.getNote(selectedNoteID); + if (map2.editableDataEnabled() || map2.isInWideSelection()) { + context.loadTiles(projection2); + drawEditable(difference2, extent); } else { - selected = context.selectedIDs().filter(function(e3) { - return context.hasEntity(e3); - }); - if (selected.length) { - entity = context.entity(selected[0]); + editOff(); + } + _transformStart = projection2.transform(); + return map2; + } + var immediateRedraw = function(difference2, extent) { + if (!difference2 && !extent) + cancelPendingRedraw(); + redraw(difference2, extent); + }; + map2.lastPointerEvent = function() { + return _lastPointerEvent; + }; + map2.mouse = function(d3_event) { + var event = d3_event || _lastPointerEvent; + if (event) { + var s2; + while (s2 = event.sourceEvent) { + event = s2; } + return _getMouseCoords(event); } - var singular = selected.length === 1 ? selected[0] : null; - selection2.html(""); - if (singular) { - selection2.append("h4").attr("class", "history-heading").html(singular); + return null; + }; + map2.mouseCoordinates = function() { + var coord2 = map2.mouse() || pxCenter(); + return projection2.invert(coord2); + }; + map2.dblclickZoomEnable = function(val) { + if (!arguments.length) + return _dblClickZoomEnabled; + _dblClickZoomEnabled = val; + return map2; + }; + map2.redrawEnable = function(val) { + if (!arguments.length) + return _redrawEnabled; + _redrawEnabled = val; + return map2; + }; + map2.isTransformed = function() { + return _isTransformed; + }; + function setTransform(t2, duration, force) { + var t3 = projection2.transform(); + if (!force && t2.k === t3.k && t2.x === t3.x && t2.y === t3.y) + return false; + if (duration) { + _selection.transition().duration(duration).on("start", function() { + map2.startEase(); + }).call(_zoomerPanner.transform, identity2.translate(t2.x, t2.y).scale(t2.k)); } else { - selection2.append("h4").attr("class", "history-heading").call(_t.append("info_panels.selected", { n: selected.length })); + projection2.transform(t2); + _transformStart = t2; + _selection.call(_zoomerPanner.transform, _transformStart); } - if (!singular) - return; - if (entity) { - selection2.call(redrawEntity, entity); - } else if (note) { - selection2.call(redrawNote, note); + return true; + } + function setCenterZoom(loc2, z2, duration, force) { + var c2 = map2.center(); + var z3 = map2.zoom(); + if (loc2[0] === c2[0] && loc2[1] === c2[1] && z2 === z3 && !force) + return false; + var proj = geoRawMercator().transform(projection2.transform()); + var k2 = clamp2(geoZoomToScale(z2, TILESIZE), kMin, kMax); + proj.scale(k2); + var t2 = proj.translate(); + var point2 = proj(loc2); + var center = pxCenter(); + t2[0] += center[0] - point2[0]; + t2[1] += center[1] - point2[1]; + return setTransform(identity2.translate(t2[0], t2[1]).scale(k2), duration, force); + } + map2.pan = function(delta, duration) { + var t2 = projection2.translate(); + var k2 = projection2.scale(); + t2[0] += delta[0]; + t2[1] += delta[1]; + if (duration) { + _selection.transition().duration(duration).on("start", function() { + map2.startEase(); + }).call(_zoomerPanner.transform, identity2.translate(t2[0], t2[1]).scale(k2)); + } else { + projection2.translate(t2); + _transformStart = projection2.transform(); + _selection.call(_zoomerPanner.transform, _transformStart); + dispatch14.call("move", this, map2); + immediateRedraw(); } + return map2; + }; + map2.dimensions = function(val) { + if (!arguments.length) + return _dimensions; + _dimensions = val; + drawLayers.dimensions(_dimensions); + context.background().dimensions(_dimensions); + projection2.clipExtent([[0, 0], _dimensions]); + _getMouseCoords = utilFastMouse(supersurface.node()); + scheduleRedraw(); + return map2; + }; + function zoomIn(delta) { + setCenterZoom(map2.center(), ~~map2.zoom() + delta, 250, true); } - function redrawNote(selection2, note) { - if (!note || note.isNew()) { - selection2.append("div").call(_t.append("info_panels.history.note_no_history")); - return; + function zoomOut(delta) { + setCenterZoom(map2.center(), ~~map2.zoom() - delta, 250, true); + } + map2.zoomIn = function() { + zoomIn(1); + }; + map2.zoomInFurther = function() { + zoomIn(4); + }; + map2.canZoomIn = function() { + return map2.zoom() < maxZoom; + }; + map2.zoomOut = function() { + zoomOut(1); + }; + map2.zoomOutFurther = function() { + zoomOut(4); + }; + map2.canZoomOut = function() { + return map2.zoom() > minZoom2; + }; + map2.center = function(loc2) { + if (!arguments.length) { + return projection2.invert(pxCenter()); } - var list = selection2.append("ul"); - list.append("li").call(_t.append("info_panels.history.note_comments", { suffix: ":" })).append("span").text(note.comments.length); - if (note.comments.length) { - list.append("li").call(_t.append("info_panels.history.note_created_date", { suffix: ":" })).append("span").text(displayTimestamp(note.comments[0].date)); - list.append("li").call(_t.append("info_panels.history.note_created_user", { suffix: ":" })).call(displayUser, note.comments[0].user); + if (setCenterZoom(loc2, map2.zoom())) { + dispatch14.call("move", this, map2); } - if (osm) { - selection2.append("a").attr("class", "view-history-on-osm").attr("target", "_blank").attr("href", osm.noteURL(note)).call(svgIcon("#iD-icon-out-link", "inline")).append("span").call(_t.append("info_panels.history.note_link_text")); + scheduleRedraw(); + return map2; + }; + map2.unobscuredCenterZoomEase = function(loc, zoom) { + var offset = map2.unobscuredOffsetPx(); + var proj = geoRawMercator().transform(projection2.transform()); + proj.scale(geoZoomToScale(zoom, TILESIZE)); + var locPx = proj(loc); + var offsetLocPx = [locPx[0] + offset[0], locPx[1] + offset[1]]; + var offsetLoc = proj.invert(offsetLocPx); + map2.centerZoomEase(offsetLoc, zoom); + }; + map2.unobscuredOffsetPx = function() { + var openPane = context.container().select(".map-panes .map-pane.shown"); + if (!openPane.empty()) { + return [openPane.node().offsetWidth / 2, 0]; } - } - function redrawEntity(selection2, entity) { - if (!entity || entity.isNew()) { - selection2.append("div").call(_t.append("info_panels.history.no_history")); - return; + return [0, 0]; + }; + map2.zoom = function(z2) { + if (!arguments.length) { + return Math.max(geoScaleToZoom(projection2.scale(), TILESIZE), 0); } - var links = selection2.append("div").attr("class", "links"); - if (osm) { - links.append("a").attr("class", "view-history-on-osm").attr("href", osm.historyURL(entity)).attr("target", "_blank").call(_t.append("info_panels.history.history_link")); + if (z2 < _minzoom) { + surface.interrupt(); + dispatch14.call("hitMinZoom", this, map2); + z2 = context.minEditableZoom(); } - links.append("a").attr("class", "pewu-history-viewer-link").attr("href", "https://pewu.github.io/osm-history/#/" + entity.type + "/" + entity.osmId()).attr("target", "_blank").attr("tabindex", -1).text("PeWu"); - var list = selection2.append("ul"); - list.append("li").call(_t.append("info_panels.history.version", { suffix: ":" })).append("span").text(entity.version); - list.append("li").call(_t.append("info_panels.history.last_edit", { suffix: ":" })).append("span").text(displayTimestamp(entity.timestamp)); - list.append("li").call(_t.append("info_panels.history.edited_by", { suffix: ":" })).call(displayUser, entity.user); - list.append("li").call(_t.append("info_panels.history.changeset", { suffix: ":" })).call(displayChangeset, entity.changeset); - } - var panel = function(selection2) { - selection2.call(redraw); - context.map().on("drawn.info-history", function() { - selection2.call(redraw); - }); - context.on("enter.info-history", function() { - selection2.call(redraw); - }); + if (setCenterZoom(map2.center(), z2)) { + dispatch14.call("move", this, map2); + } + scheduleRedraw(); + return map2; }; - panel.off = function() { - context.map().on("drawn.info-history", null); - context.on("enter.info-history", null); + map2.centerZoom = function(loc2, z2) { + if (setCenterZoom(loc2, z2)) { + dispatch14.call("move", this, map2); + } + scheduleRedraw(); + return map2; }; - panel.id = "history"; - panel.label = _t.append("info_panels.history.title"); - panel.key = _t("info_panels.history.key"); - return panel; - } - - // modules/util/units.js - var OSM_PRECISION = 7; - function displayLength(m2, isImperial) { - var d2 = m2 * (isImperial ? 3.28084 : 1); - var unit2; - if (isImperial) { - if (d2 >= 5280) { - d2 /= 5280; - unit2 = "miles"; + map2.zoomTo = function(entity) { + var extent = entity.extent(context.graph()); + if (!isFinite(extent.area())) + return map2; + var z2 = clamp2(map2.trimmedExtentZoom(extent), 0, 20); + return map2.centerZoom(extent.center(), z2); + }; + map2.centerEase = function(loc2, duration) { + duration = duration || 250; + setCenterZoom(loc2, map2.zoom(), duration); + return map2; + }; + map2.zoomEase = function(z2, duration) { + duration = duration || 250; + setCenterZoom(map2.center(), z2, duration, false); + return map2; + }; + map2.centerZoomEase = function(loc2, z2, duration) { + duration = duration || 250; + setCenterZoom(loc2, z2, duration, false); + return map2; + }; + map2.transformEase = function(t2, duration) { + duration = duration || 250; + setTransform( + t2, + duration, + false + /* don't force */ + ); + return map2; + }; + map2.zoomToEase = function(obj, duration) { + var extent; + if (Array.isArray(obj)) { + obj.forEach(function(entity) { + var entityExtent = entity.extent(context.graph()); + if (!extent) { + extent = entityExtent; + } else { + extent = extent.extend(entityExtent); + } + }); } else { - unit2 = "feet"; + extent = obj.extent(context.graph()); } - } else { - if (d2 >= 1e3) { - d2 /= 1e3; - unit2 = "kilometers"; + if (!isFinite(extent.area())) + return map2; + var z2 = clamp2(map2.trimmedExtentZoom(extent), 0, 20); + return map2.centerZoomEase(extent.center(), z2, duration); + }; + map2.startEase = function() { + utilBindOnce(surface, _pointerPrefix + "down.ease", function() { + map2.cancelEase(); + }); + return map2; + }; + map2.cancelEase = function() { + _selection.interrupt(); + return map2; + }; + map2.extent = function(val) { + if (!arguments.length) { + return new geoExtent( + projection2.invert([0, _dimensions[1]]), + projection2.invert([_dimensions[0], 0]) + ); } else { - unit2 = "meters"; + var extent = geoExtent(val); + map2.centerZoom(extent.center(), map2.extentZoom(extent)); } - } - return _t("units." + unit2, { - quantity: d2.toLocaleString(_mainLocalizer.localeCode(), { - maximumSignificantDigits: 4 - }) - }); - } - function displayArea(m2, isImperial) { - var locale2 = _mainLocalizer.localeCode(); - var d2 = m2 * (isImperial ? 10.7639111056 : 1); - var d1, d22, area; - var unit1 = ""; - var unit2 = ""; - if (isImperial) { - if (d2 >= 6969600) { - d1 = d2 / 27878400; - unit1 = "square_miles"; + }; + map2.trimmedExtent = function(val) { + if (!arguments.length) { + var headerY = 71; + var footerY = 30; + var pad2 = 10; + return new geoExtent( + projection2.invert([pad2, _dimensions[1] - footerY - pad2]), + projection2.invert([_dimensions[0] - pad2, headerY + pad2]) + ); } else { - d1 = d2; - unit1 = "square_feet"; + var extent = geoExtent(val); + map2.centerZoom(extent.center(), map2.trimmedExtentZoom(extent)); } - if (d2 > 4356 && d2 < 4356e4) { - d22 = d2 / 43560; - unit2 = "acres"; + }; + function calcExtentZoom(extent, dim) { + var tl = projection2([extent[0][0], extent[1][1]]); + var br2 = projection2([extent[1][0], extent[0][1]]); + var hFactor = (br2[0] - tl[0]) / dim[0]; + var vFactor = (br2[1] - tl[1]) / dim[1]; + var hZoomDiff = Math.log(Math.abs(hFactor)) / Math.LN2; + var vZoomDiff = Math.log(Math.abs(vFactor)) / Math.LN2; + var newZoom = map2.zoom() - Math.max(hZoomDiff, vZoomDiff); + return newZoom; + } + map2.extentZoom = function(val) { + return calcExtentZoom(geoExtent(val), _dimensions); + }; + map2.trimmedExtentZoom = function(val) { + var trimY = 120; + var trimX = 40; + var trimmed = [_dimensions[0] - trimX, _dimensions[1] - trimY]; + return calcExtentZoom(geoExtent(val), trimmed); + }; + map2.withinEditableZoom = function() { + return map2.zoom() >= context.minEditableZoom(); + }; + map2.isInWideSelection = function() { + return !map2.withinEditableZoom() && context.selectedIDs().length; + }; + map2.editableDataEnabled = function(skipZoomCheck) { + var layer = context.layers().layer("osm"); + if (!layer || !layer.enabled()) + return false; + return skipZoomCheck || map2.withinEditableZoom(); + }; + map2.notesEditable = function() { + var layer = context.layers().layer("notes"); + if (!layer || !layer.enabled()) + return false; + return map2.withinEditableZoom(); + }; + map2.minzoom = function(val) { + if (!arguments.length) + return _minzoom; + _minzoom = val; + return map2; + }; + map2.toggleHighlightEdited = function() { + surface.classed("highlight-edited", !surface.classed("highlight-edited")); + map2.pan([0, 0]); + dispatch14.call("changeHighlighting", this); + }; + map2.areaFillOptions = ["wireframe", "partial", "full"]; + map2.activeAreaFill = function(val) { + if (!arguments.length) + return corePreferences("area-fill") || "partial"; + corePreferences("area-fill", val); + if (val !== "wireframe") { + corePreferences("area-fill-toggle", val); } - } else { - if (d2 >= 25e4) { - d1 = d2 / 1e6; - unit1 = "square_kilometers"; + updateAreaFill(); + map2.pan([0, 0]); + dispatch14.call("changeAreaFill", this); + return map2; + }; + map2.toggleWireframe = function() { + var activeFill = map2.activeAreaFill(); + if (activeFill === "wireframe") { + activeFill = corePreferences("area-fill-toggle") || "partial"; } else { - d1 = d2; - unit1 = "square_meters"; - } - if (d2 > 1e3 && d2 < 1e7) { - d22 = d2 / 1e4; - unit2 = "hectares"; + activeFill = "wireframe"; } - } - area = _t("units." + unit1, { - quantity: d1.toLocaleString(locale2, { - maximumSignificantDigits: 4 - }) - }); - if (d22) { - return _t("units.area_pair", { - area1: area, - area2: _t("units." + unit2, { - quantity: d22.toLocaleString(locale2, { - maximumSignificantDigits: 2 - }) - }) - }); - } else { - return area; - } - } - function wrap(x2, min3, max3) { - var d2 = max3 - min3; - return ((x2 - min3) % d2 + d2) % d2 + min3; - } - function clamp2(x2, min3, max3) { - return Math.max(min3, Math.min(x2, max3)); - } - function displayCoordinate(deg, pos, neg) { - var locale2 = _mainLocalizer.localeCode(); - var min3 = (Math.abs(deg) - Math.floor(Math.abs(deg))) * 60; - var sec = (min3 - Math.floor(min3)) * 60; - var displayDegrees = _t("units.arcdegrees", { - quantity: Math.floor(Math.abs(deg)).toLocaleString(locale2) - }); - var displayCoordinate2; - if (Math.floor(sec) > 0) { - displayCoordinate2 = displayDegrees + _t("units.arcminutes", { - quantity: Math.floor(min3).toLocaleString(locale2) - }) + _t("units.arcseconds", { - quantity: Math.round(sec).toLocaleString(locale2) - }); - } else if (Math.floor(min3) > 0) { - displayCoordinate2 = displayDegrees + _t("units.arcminutes", { - quantity: Math.round(min3).toLocaleString(locale2) - }); - } else { - displayCoordinate2 = _t("units.arcdegrees", { - quantity: Math.round(Math.abs(deg)).toLocaleString(locale2) - }); - } - if (deg === 0) { - return displayCoordinate2; - } else { - return _t("units.coordinate", { - coordinate: displayCoordinate2, - direction: _t("units." + (deg > 0 ? pos : neg)) + map2.activeAreaFill(activeFill); + }; + function updateAreaFill() { + var activeFill = map2.activeAreaFill(); + map2.areaFillOptions.forEach(function(opt) { + surface.classed("fill-" + opt, Boolean(opt === activeFill)); }); } - } - function dmsCoordinatePair(coord2) { - return _t("units.coordinate_pair", { - latitude: displayCoordinate(clamp2(coord2[1], -90, 90), "north", "south"), - longitude: displayCoordinate(wrap(coord2[0], -180, 180), "east", "west") - }); - } - function decimalCoordinatePair(coord2) { - return _t("units.coordinate_pair", { - latitude: clamp2(coord2[1], -90, 90).toFixed(OSM_PRECISION), - longitude: wrap(coord2[0], -180, 180).toFixed(OSM_PRECISION) - }); + map2.layers = () => drawLayers; + map2.doubleUpHandler = function() { + return _doubleUpHandler; + }; + return utilRebind(map2, dispatch14, "on"); } - // modules/ui/panels/location.js - function uiPanelLocation(context) { - var currLocation = ""; - function redraw(selection2) { - selection2.html(""); - var list = selection2.append("ul"); - var coord2 = context.map().mouseCoordinates(); - if (coord2.some(isNaN)) { - coord2 = context.map().center(); - } - list.append("li").text(dmsCoordinatePair(coord2)).append("li").text(decimalCoordinatePair(coord2)); - selection2.append("div").attr("class", "location-info").text(currLocation || " "); - debouncedGetLocation(selection2, coord2); + // modules/renderer/photos.js + function rendererPhotos(context) { + var dispatch14 = dispatch_default("change"); + var _layerIDs = ["streetside", "mapillary", "mapillary-map-features", "mapillary-signs", "kartaview", "mapilio", "vegbilder"]; + var _allPhotoTypes = ["flat", "panoramic"]; + var _shownPhotoTypes = _allPhotoTypes.slice(); + var _dateFilters = ["fromDate", "toDate"]; + var _fromDate; + var _toDate; + var _usernames; + function photos() { } - var debouncedGetLocation = debounce_default(getLocation, 250); - function getLocation(selection2, coord2) { - if (!services.geocoder) { - currLocation = _t("info_panels.location.unknown_location"); - selection2.selectAll(".location-info").text(currLocation); + function updateStorage() { + if (window.mocha) + return; + var hash = utilStringQs(window.location.hash); + var enabled = context.layers().all().filter(function(d2) { + return _layerIDs.indexOf(d2.id) !== -1 && d2.layer && d2.layer.supported() && d2.layer.enabled(); + }).map(function(d2) { + return d2.id; + }); + if (enabled.length) { + hash.photo_overlay = enabled.join(","); } else { - services.geocoder.reverse(coord2, function(err, result) { - currLocation = result ? result.display_name : _t("info_panels.location.unknown_location"); - selection2.selectAll(".location-info").text(currLocation); - }); + delete hash.photo_overlay; } + window.location.replace("#" + utilQsString(hash, true)); } - var panel = function(selection2) { - selection2.call(redraw); - context.surface().on(("PointerEvent" in window ? "pointer" : "mouse") + "move.info-location", function() { - selection2.call(redraw); - }); + photos.overlayLayerIDs = function() { + return _layerIDs; }; - panel.off = function() { - context.surface().on(".info-location", null); + photos.allPhotoTypes = function() { + return _allPhotoTypes; }; - panel.id = "location"; - panel.label = _t.append("info_panels.location.title"); - panel.key = _t("info_panels.location.key"); - return panel; - } - - // modules/ui/panels/measurement.js - function uiPanelMeasurement(context) { - function radiansToMeters(r2) { - return r2 * 63710071809e-4; - } - function steradiansToSqmeters(r2) { - return r2 / (4 * Math.PI) * 510065621724e3; - } - function toLineString(feature3) { - if (feature3.type === "LineString") - return feature3; - var result = { type: "LineString", coordinates: [] }; - if (feature3.type === "Polygon") { - result.coordinates = feature3.coordinates[0]; - } else if (feature3.type === "MultiPolygon") { - result.coordinates = feature3.coordinates[0][0]; - } - return result; - } - var _isImperial = !_mainLocalizer.usesMetric(); - function redraw(selection2) { - var graph = context.graph(); - var selectedNoteID = context.selectedNoteID(); - var osm = services.osm; - var localeCode = _mainLocalizer.localeCode(); - var heading; - var center, location, centroid; - var closed, geometry; - var totalNodeCount, length = 0, area = 0, distance; - if (selectedNoteID && osm) { - var note = osm.getNote(selectedNoteID); - heading = _t.html("note.note") + " " + selectedNoteID; - location = note.loc; - geometry = "note"; + photos.dateFilters = function() { + return _dateFilters; + }; + photos.dateFilterValue = function(val) { + return val === _dateFilters[0] ? _fromDate : _toDate; + }; + photos.setDateFilter = function(type2, val, updateUrl) { + var date = val && new Date(val); + if (date && !isNaN(date)) { + val = date.toISOString().slice(0, 10); } else { - var selectedIDs = context.selectedIDs().filter(function(id2) { - return context.hasEntity(id2); - }); - var selected = selectedIDs.map(function(id2) { - return context.entity(id2); - }); - heading = selected.length === 1 ? selected[0].id : _t.html("info_panels.selected", { n: selected.length }); - if (selected.length) { - var extent = geoExtent(); - for (var i3 in selected) { - var entity = selected[i3]; - extent._extend(entity.extent(graph)); - geometry = entity.geometry(graph); - if (geometry === "line" || geometry === "area") { - closed = entity.type === "relation" || entity.isClosed() && !entity.isDegenerate(); - var feature3 = entity.asGeoJSON(graph); - length += radiansToMeters(length_default(toLineString(feature3))); - centroid = path_default(context.projection).centroid(entity.asGeoJSON(graph)); - centroid = centroid && context.projection.invert(centroid); - if (!centroid || !isFinite(centroid[0]) || !isFinite(centroid[1])) { - centroid = entity.extent(graph).center(); - } - if (closed) { - area += steradiansToSqmeters(entity.area(graph)); - } - } - } - if (selected.length > 1) { - geometry = null; - closed = null; - centroid = null; - } - if (selected.length === 2 && selected[0].type === "node" && selected[1].type === "node") { - distance = geoSphericalDistance(selected[0].loc, selected[1].loc); - } - if (selected.length === 1 && selected[0].type === "node") { - location = selected[0].loc; - } else { - totalNodeCount = utilGetAllNodes(selectedIDs, context.graph()).length; - } - if (!location && !centroid) { - center = extent.center(); - } - } - } - selection2.html(""); - if (heading) { - selection2.append("h4").attr("class", "measurement-heading").html(heading); - } - var list = selection2.append("ul"); - var coordItem; - if (geometry) { - list.append("li").call(_t.append("info_panels.measurement.geometry", { suffix: ":" })).append("span").html( - closed ? _t.html("info_panels.measurement.closed_" + geometry) : _t.html("geometry." + geometry) - ); - } - if (totalNodeCount) { - list.append("li").call(_t.append("info_panels.measurement.node_count", { suffix: ":" })).append("span").text(totalNodeCount.toLocaleString(localeCode)); - } - if (area) { - list.append("li").call(_t.append("info_panels.measurement.area", { suffix: ":" })).append("span").text(displayArea(area, _isImperial)); + val = null; } - if (length) { - list.append("li").call(_t.append("info_panels.measurement." + (closed ? "perimeter" : "length"), { suffix: ":" })).append("span").text(displayLength(length, _isImperial)); + if (type2 === _dateFilters[0]) { + _fromDate = val; + if (_fromDate && _toDate && new Date(_toDate) < new Date(_fromDate)) { + _toDate = _fromDate; + } } - if (typeof distance === "number") { - list.append("li").call(_t.append("info_panels.measurement.distance", { suffix: ":" })).append("span").text(displayLength(distance, _isImperial)); + if (type2 === _dateFilters[1]) { + _toDate = val; + if (_fromDate && _toDate && new Date(_toDate) < new Date(_fromDate)) { + _fromDate = _toDate; + } } - if (location) { - coordItem = list.append("li").call(_t.append("info_panels.measurement.location", { suffix: ":" })); - coordItem.append("span").text(dmsCoordinatePair(location)); - coordItem.append("span").text(decimalCoordinatePair(location)); + dispatch14.call("change", this); + if (updateUrl) { + var rangeString; + if (_fromDate || _toDate) { + rangeString = (_fromDate || "") + "_" + (_toDate || ""); + } + setUrlFilterValue("photo_dates", rangeString); } - if (centroid) { - coordItem = list.append("li").call(_t.append("info_panels.measurement.centroid", { suffix: ":" })); - coordItem.append("span").text(dmsCoordinatePair(centroid)); - coordItem.append("span").text(decimalCoordinatePair(centroid)); + }; + photos.setUsernameFilter = function(val, updateUrl) { + if (val && typeof val === "string") + val = val.replace(/;/g, ",").split(","); + if (val) { + val = val.map((d2) => d2.trim()).filter(Boolean); + if (!val.length) { + val = null; + } } - if (center) { - coordItem = list.append("li").call(_t.append("info_panels.measurement.center", { suffix: ":" })); - coordItem.append("span").text(dmsCoordinatePair(center)); - coordItem.append("span").text(decimalCoordinatePair(center)); + _usernames = val; + dispatch14.call("change", this); + if (updateUrl) { + var hashString; + if (_usernames) { + hashString = _usernames.join(","); + } + setUrlFilterValue("photo_username", hashString); } - if (length || area || typeof distance === "number") { - var toggle = _isImperial ? "imperial" : "metric"; - selection2.append("a").call(_t.append("info_panels.measurement." + toggle)).attr("href", "#").attr("class", "button button-toggle-units").on("click", function(d3_event) { - d3_event.preventDefault(); - _isImperial = !_isImperial; - selection2.call(redraw); - }); + }; + function setUrlFilterValue(property, val) { + if (!window.mocha) { + var hash = utilStringQs(window.location.hash); + if (val) { + if (hash[property] === val) + return; + hash[property] = val; + } else { + if (!(property in hash)) + return; + delete hash[property]; + } + window.location.replace("#" + utilQsString(hash, true)); } } - var panel = function(selection2) { - selection2.call(redraw); - context.map().on("drawn.info-measurement", function() { - selection2.call(redraw); - }); - context.on("enter.info-measurement", function() { - selection2.call(redraw); - }); + function showsLayer(id2) { + var layer = context.layers().layer(id2); + return layer && layer.supported() && layer.enabled(); + } + photos.shouldFilterByDate = function() { + return showsLayer("mapillary") || showsLayer("kartaview") || showsLayer("streetside") || showsLayer("vegbilder"); }; - panel.off = function() { - context.map().on("drawn.info-measurement", null); - context.on("enter.info-measurement", null); + photos.shouldFilterByPhotoType = function() { + return showsLayer("mapillary") || showsLayer("streetside") && showsLayer("kartaview") || showsLayer("vegbilder"); }; - panel.id = "measurement"; - panel.label = _t.append("info_panels.measurement.title"); - panel.key = _t("info_panels.measurement.key"); - return panel; - } - - // modules/ui/panels/index.js - var uiInfoPanels = { - background: uiPanelBackground, - history: uiPanelHistory, - location: uiPanelLocation, - measurement: uiPanelMeasurement - }; - - // modules/ui/info.js - function uiInfo(context) { - var ids = Object.keys(uiInfoPanels); - var wasActive = ["measurement"]; - var panels = {}; - var active = {}; - ids.forEach(function(k2) { - if (!panels[k2]) { - panels[k2] = uiInfoPanels[k2](context); - active[k2] = false; + photos.shouldFilterByUsername = function() { + return !showsLayer("mapillary") && showsLayer("kartaview") && !showsLayer("streetside"); + }; + photos.showsPhotoType = function(val) { + if (!photos.shouldFilterByPhotoType()) + return true; + return _shownPhotoTypes.indexOf(val) !== -1; + }; + photos.showsFlat = function() { + return photos.showsPhotoType("flat"); + }; + photos.showsPanoramic = function() { + return photos.showsPhotoType("panoramic"); + }; + photos.fromDate = function() { + return _fromDate; + }; + photos.toDate = function() { + return _toDate; + }; + photos.togglePhotoType = function(val) { + var index = _shownPhotoTypes.indexOf(val); + if (index !== -1) { + _shownPhotoTypes.splice(index, 1); + } else { + _shownPhotoTypes.push(val); } - }); - function info(selection2) { - function redraw() { - var activeids = ids.filter(function(k2) { - return active[k2]; - }).sort(); - var containers = infoPanels.selectAll(".panel-container").data(activeids, function(k2) { - return k2; - }); - containers.exit().style("opacity", 1).transition().duration(200).style("opacity", 0).on("end", function(d2) { - select_default2(this).call(panels[d2].off).remove(); - }); - var enter = containers.enter().append("div").attr("class", function(d2) { - return "fillD2 panel-container panel-container-" + d2; - }); - enter.style("opacity", 0).transition().duration(200).style("opacity", 1); - var title = enter.append("div").attr("class", "panel-title fillD2"); - title.append("h3").each(function(d2) { - return panels[d2].label(select_default2(this)); - }); - title.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function(d3_event, d2) { - d3_event.stopImmediatePropagation(); - d3_event.preventDefault(); - info.toggle(d2); - }).call(svgIcon("#iD-icon-close")); - enter.append("div").attr("class", function(d2) { - return "panel-content panel-content-" + d2; - }); - infoPanels.selectAll(".panel-content").each(function(d2) { - select_default2(this).call(panels[d2]); - }); + dispatch14.call("change", this); + return photos; + }; + photos.usernames = function() { + return _usernames; + }; + photos.init = function() { + var hash = utilStringQs(window.location.hash); + if (hash.photo_dates) { + var parts = /^(.*)[–_](.*)$/g.exec(hash.photo_dates.trim()); + this.setDateFilter("fromDate", parts && parts.length >= 2 && parts[1], false); + this.setDateFilter("toDate", parts && parts.length >= 3 && parts[2], false); } - info.toggle = function(which) { - var activeids = ids.filter(function(k2) { - return active[k2]; + if (hash.photo_username) { + this.setUsernameFilter(hash.photo_username, false); + } + if (hash.photo_overlay) { + var hashOverlayIDs = hash.photo_overlay.replace(/;/g, ",").split(","); + hashOverlayIDs.forEach(function(id2) { + if (id2 === "openstreetcam") + id2 = "kartaview"; + var layer2 = _layerIDs.indexOf(id2) !== -1 && context.layers().layer(id2); + if (layer2 && !layer2.enabled()) + layer2.enabled(true); }); - if (which) { - active[which] = !active[which]; - if (activeids.length === 1 && activeids[0] === which) { - wasActive = [which]; - } - context.container().select("." + which + "-panel-toggle-item").classed("active", active[which]).select("input").property("checked", active[which]); - } else { - if (activeids.length) { - wasActive = activeids; - activeids.forEach(function(k2) { - active[k2] = false; - }); - } else { - wasActive.forEach(function(k2) { - active[k2] = true; + } + if (hash.photo) { + var photoIds = hash.photo.replace(/;/g, ",").split(","); + var photoId = photoIds.length && photoIds[0].trim(); + var results = /(.*)\/(.*)/g.exec(photoId); + if (results && results.length >= 3) { + var serviceId = results[1]; + if (serviceId === "openstreetcam") + serviceId = "kartaview"; + var photoKey = results[2]; + var service = services[serviceId]; + if (service && service.ensureViewerLoaded) { + var layer = _layerIDs.indexOf(serviceId) !== -1 && context.layers().layer(serviceId); + if (layer && !layer.enabled()) + layer.enabled(true); + var baselineTime = Date.now(); + service.on("loadedImages.rendererPhotos", function() { + if (Date.now() - baselineTime > 45e3) { + service.on("loadedImages.rendererPhotos", null); + return; + } + if (!service.cachedImage(photoKey)) + return; + service.on("loadedImages.rendererPhotos", null); + service.ensureViewerLoaded(context).then(function() { + service.selectImage(context, photoKey).showViewer(context); + }); }); } } - redraw(); - }; - var infoPanels = selection2.selectAll(".info-panels").data([0]); - infoPanels = infoPanels.enter().append("div").attr("class", "info-panels").merge(infoPanels); - redraw(); - context.keybinding().on(uiCmd("\u2318" + _t("info_panels.key")), function(d3_event) { - d3_event.stopImmediatePropagation(); - d3_event.preventDefault(); - info.toggle(); - }); - ids.forEach(function(k2) { - var key = _t("info_panels." + k2 + ".key", { default: null }); - if (!key) - return; - context.keybinding().on(uiCmd("\u2318\u21E7" + key), function(d3_event) { - d3_event.stopImmediatePropagation(); - d3_event.preventDefault(); - info.toggle(k2); - }); - }); - } - return info; - } - - // modules/ui/intro/helper.js - function pointBox(loc, context) { - var rect = context.surfaceRect(); - var point2 = context.curtainProjection(loc); - return { - left: point2[0] + rect.left - 40, - top: point2[1] + rect.top - 60, - width: 80, - height: 90 + } + context.layers().on("change.rendererPhotos", updateStorage); }; + return utilRebind(photos, dispatch14, "on"); } - function pad(locOrBox, padding, context) { - var box; - if (locOrBox instanceof Array) { - var rect = context.surfaceRect(); - var point2 = context.curtainProjection(locOrBox); - box = { - left: point2[0] + rect.left, - top: point2[1] + rect.top - }; - } else { - box = locOrBox; + + // modules/ui/account.js + function uiAccount(context) { + const osm = context.connection(); + function updateUserDetails(selection2) { + if (!osm) + return; + if (!osm.authenticated()) { + render(selection2, null); + } else { + osm.userDetails((err, user) => render(selection2, user)); + } } - return { - left: box.left - padding, - top: box.top - padding, - width: (box.width || 0) + 2 * padding, - height: (box.width || 0) + 2 * padding - }; - } - function icon(name, svgklass, useklass) { - return '"; - } - var helpStringReplacements; - function helpHtml(id2, replacements) { - if (!helpStringReplacements) { - helpStringReplacements = { - // insert icons corresponding to various UI elements - point_icon: icon("#iD-icon-point", "inline"), - line_icon: icon("#iD-icon-line", "inline"), - area_icon: icon("#iD-icon-area", "inline"), - note_icon: icon("#iD-icon-note", "inline add-note"), - plus: icon("#iD-icon-plus", "inline"), - minus: icon("#iD-icon-minus", "inline"), - layers_icon: icon("#iD-icon-layers", "inline"), - data_icon: icon("#iD-icon-data", "inline"), - inspect: icon("#iD-icon-inspect", "inline"), - help_icon: icon("#iD-icon-help", "inline"), - undo_icon: icon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-redo" : "#iD-icon-undo", "inline"), - redo_icon: icon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-undo" : "#iD-icon-redo", "inline"), - save_icon: icon("#iD-icon-save", "inline"), - // operation icons - circularize_icon: icon("#iD-operation-circularize", "inline operation"), - continue_icon: icon("#iD-operation-continue", "inline operation"), - copy_icon: icon("#iD-operation-copy", "inline operation"), - delete_icon: icon("#iD-operation-delete", "inline operation"), - disconnect_icon: icon("#iD-operation-disconnect", "inline operation"), - downgrade_icon: icon("#iD-operation-downgrade", "inline operation"), - extract_icon: icon("#iD-operation-extract", "inline operation"), - merge_icon: icon("#iD-operation-merge", "inline operation"), - move_icon: icon("#iD-operation-move", "inline operation"), - orthogonalize_icon: icon("#iD-operation-orthogonalize", "inline operation"), - paste_icon: icon("#iD-operation-paste", "inline operation"), - reflect_long_icon: icon("#iD-operation-reflect-long", "inline operation"), - reflect_short_icon: icon("#iD-operation-reflect-short", "inline operation"), - reverse_icon: icon("#iD-operation-reverse", "inline operation"), - rotate_icon: icon("#iD-operation-rotate", "inline operation"), - split_icon: icon("#iD-operation-split", "inline operation"), - straighten_icon: icon("#iD-operation-straighten", "inline operation"), - // interaction icons - leftclick: icon("#iD-walkthrough-mouse-left", "inline operation"), - rightclick: icon("#iD-walkthrough-mouse-right", "inline operation"), - mousewheel_icon: icon("#iD-walkthrough-mousewheel", "inline operation"), - tap_icon: icon("#iD-walkthrough-tap", "inline operation"), - doubletap_icon: icon("#iD-walkthrough-doubletap", "inline operation"), - longpress_icon: icon("#iD-walkthrough-longpress", "inline operation"), - touchdrag_icon: icon("#iD-walkthrough-touchdrag", "inline operation"), - pinch_icon: icon("#iD-walkthrough-pinch-apart", "inline operation"), - // insert keys; may be localized and platform-dependent - shift: uiCmd.display("\u21E7"), - alt: uiCmd.display("\u2325"), - return: uiCmd.display("\u21B5"), - esc: _t.html("shortcuts.key.esc"), - space: _t.html("shortcuts.key.space"), - add_note_key: _t.html("modes.add_note.key"), - help_key: _t.html("help.key"), - shortcuts_key: _t.html("shortcuts.toggle.key"), - // reference localized UI labels directly so that they'll always match - save: _t.html("save.title"), - undo: _t.html("undo.title"), - redo: _t.html("redo.title"), - upload: _t.html("commit.save"), - point: _t.html("modes.add_point.title"), - line: _t.html("modes.add_line.title"), - area: _t.html("modes.add_area.title"), - note: _t.html("modes.add_note.label"), - circularize: _t.html("operations.circularize.title"), - continue: _t.html("operations.continue.title"), - copy: _t.html("operations.copy.title"), - delete: _t.html("operations.delete.title"), - disconnect: _t.html("operations.disconnect.title"), - downgrade: _t.html("operations.downgrade.title"), - extract: _t.html("operations.extract.title"), - merge: _t.html("operations.merge.title"), - move: _t.html("operations.move.title"), - orthogonalize: _t.html("operations.orthogonalize.title"), - paste: _t.html("operations.paste.title"), - reflect_long: _t.html("operations.reflect.title.long"), - reflect_short: _t.html("operations.reflect.title.short"), - reverse: _t.html("operations.reverse.title"), - rotate: _t.html("operations.rotate.title"), - split: _t.html("operations.split.title"), - straighten: _t.html("operations.straighten.title"), - map_data: _t.html("map_data.title"), - osm_notes: _t.html("map_data.layers.notes.title"), - fields: _t.html("inspector.fields"), - tags: _t.html("inspector.tags"), - relations: _t.html("inspector.relations"), - new_relation: _t.html("inspector.new_relation"), - turn_restrictions: _t.html("_tagging.presets.fields.restrictions.label"), - background_settings: _t.html("background.description"), - imagery_offset: _t.html("background.fix_misalignment"), - start_the_walkthrough: _t.html("splash.walkthrough"), - help: _t.html("help.title"), - ok: _t.html("intro.ok") - }; - for (var key in helpStringReplacements) { - helpStringReplacements[key] = { html: helpStringReplacements[key] }; + function render(selection2, user) { + let userInfo = selection2.select(".userInfo"); + let loginLogout = selection2.select(".loginLogout"); + if (user) { + userInfo.html("").classed("hide", false); + let userLink = userInfo.append("a").attr("href", osm.userURL(user.display_name)).attr("target", "_blank"); + if (user.image_url) { + userLink.append("img").attr("class", "icon pre-text user-icon").attr("src", user.image_url); + } else { + userLink.call(svgIcon("#iD-icon-avatar", "pre-text light")); + } + userLink.append("span").attr("class", "label").text(user.display_name); + loginLogout.classed("hide", false).select("a").text(_t("logout")).on("click", (e3) => { + e3.preventDefault(); + osm.logout(); + tryLogout(); + }); + } else { + userInfo.html("").classed("hide", true); + loginLogout.classed("hide", false).select("a").text(_t("login")).on("click", (e3) => { + e3.preventDefault(); + osm.authenticate(); + }); } } - var reps; - if (replacements) { - reps = Object.assign(replacements, helpStringReplacements); - } else { - reps = helpStringReplacements; - } - return _t.html(id2, reps).replace(/\`(.*?)\`/g, "$1"); - } - function slugify(text2) { - return text2.toString().toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]+/g, "").replace(/\-\-+/g, "-").replace(/^-+/, "").replace(/-+$/, ""); - } - var missingStrings = {}; - function checkKey(key, text2) { - if (_t(key, { default: void 0 }) === void 0) { - if (missingStrings.hasOwnProperty(key)) + function tryLogout() { + if (!osm) return; - missingStrings[key] = text2; - var missing = key + ": " + text2; - if (typeof console !== "undefined") - console.log(missing); + const url = osm.getUrlRoot() + "/logout?referer=%2Flogin"; + const w2 = 600; + const h2 = 550; + const settings = [ + ["width", w2], + ["height", h2], + ["left", window.screen.width / 2 - w2 / 2], + ["top", window.screen.height / 2 - h2 / 2] + ].map((x2) => x2.join("=")).join(","); + window.open(url, "_blank", settings); } + return function(selection2) { + if (!osm) + return; + selection2.append("li").attr("class", "userInfo").classed("hide", true); + selection2.append("li").attr("class", "loginLogout").classed("hide", true).append("a").attr("href", "#"); + osm.on("change.account", () => updateUserDetails(selection2)); + updateUserDetails(selection2); + }; } - function localize(obj) { - var key; - var name = obj.tags && obj.tags.name; - if (name) { - key = "intro.graph.name." + slugify(name); - obj.tags.name = _t(key, { default: name }); - checkKey(key, name); - } - var street = obj.tags && obj.tags["addr:street"]; - if (street) { - key = "intro.graph.name." + slugify(street); - obj.tags["addr:street"] = _t(key, { default: street }); - checkKey(key, street); - var addrTags = [ - "block_number", - "city", - "county", - "district", - "hamlet", - "neighbourhood", - "postcode", - "province", - "quarter", - "state", - "subdistrict", - "suburb" - ]; - addrTags.forEach(function(k2) { - var key2 = "intro.graph." + k2; - var tag = "addr:" + k2; - var val = obj.tags && obj.tags[tag]; - var str2 = _t(key2, { default: val }); - if (str2) { - if (str2.match(/^<.*>$/) !== null) { - delete obj.tags[tag]; - } else { - obj.tags[tag] = str2; - } + + // modules/ui/attribution.js + function uiAttribution(context) { + let _selection = select_default2(null); + function render(selection2, data, klass) { + let div = selection2.selectAll(".".concat(klass)).data([0]); + div = div.enter().append("div").attr("class", klass).merge(div); + let attributions = div.selectAll(".attribution").data(data, (d2) => d2.id); + attributions.exit().remove(); + attributions = attributions.enter().append("span").attr("class", "attribution").each((d2, i3, nodes) => { + let attribution = select_default2(nodes[i3]); + if (d2.terms_html) { + attribution.html(d2.terms_html); + return; + } + if (d2.terms_url) { + attribution = attribution.append("a").attr("href", d2.terms_url).attr("target", "_blank"); + } + const sourceID = d2.id.replace(/\./g, ""); + const terms_text = _t( + "imagery.".concat(sourceID, ".attribution.text"), + { default: d2.terms_text || d2.id || d2.name() } + ); + if (d2.icon && !d2.overlay) { + attribution.append("img").attr("class", "source-image").attr("src", d2.icon); } + attribution.append("span").attr("class", "attribution-text").text(terms_text); + }).merge(attributions); + let copyright = attributions.selectAll(".copyright-notice").data((d2) => { + let notice = d2.copyrightNotices(context.map().zoom(), context.map().extent()); + return notice ? [notice] : []; }); + copyright.exit().remove(); + copyright = copyright.enter().append("span").attr("class", "copyright-notice").merge(copyright); + copyright.text(String); } - return obj; - } - function isMostlySquare(points) { - var threshold = 15; - var lowerBound = Math.cos((90 - threshold) * Math.PI / 180); - var upperBound = Math.cos(threshold * Math.PI / 180); - for (var i3 = 0; i3 < points.length; i3++) { - var a2 = points[(i3 - 1 + points.length) % points.length]; - var origin = points[i3]; - var b2 = points[(i3 + 1) % points.length]; - var dotp = geoVecNormalizedDot(a2, b2, origin); - var mag = Math.abs(dotp); - if (mag > lowerBound && mag < upperBound) { - return false; - } - } - return true; - } - function selectMenuItem(context, operation) { - return context.container().select(".edit-menu .edit-menu-item-" + operation); - } - function transitionTime(point1, point2) { - var distance = geoSphericalDistance(point1, point2); - if (distance === 0) { - return 0; - } else if (distance < 80) { - return 500; - } else { - return 1e3; + function update() { + let baselayer = context.background().baseLayerSource(); + _selection.call(render, baselayer ? [baselayer] : [], "base-layer-attribution"); + const z2 = context.map().zoom(); + let overlays = context.background().overlayLayerSources() || []; + _selection.call(render, overlays.filter((s2) => s2.validZoom(z2)), "overlay-layer-attribution"); } + return function(selection2) { + _selection = selection2; + context.background().on("change.attribution", update); + context.map().on("move.attribution", throttle_default(update, 400, { leading: false })); + update(); + }; } - // modules/ui/toggle.js - function uiToggle(show, callback) { - return function(selection2) { - selection2.style("opacity", show ? 0 : 1).classed("hide", false).transition().style("opacity", show ? 1 : 0).on("end", function() { - select_default2(this).classed("hide", !show).style("opacity", null); - if (callback) - callback.apply(this); + // modules/ui/contributors.js + function uiContributors(context) { + var osm = context.connection(), debouncedUpdate = debounce_default(function() { + update(); + }, 1e3), limit = 4, hidden = false, wrap2 = select_default2(null); + function update() { + if (!osm) + return; + var users = {}, entities = context.history().intersects(context.map().extent()); + entities.forEach(function(entity) { + if (entity && entity.user) + users[entity.user] = true; }); + var u2 = Object.keys(users), subset = u2.slice(0, u2.length > limit ? limit - 1 : limit); + wrap2.html("").call(svgIcon("#iD-icon-nearby", "pre-text light")); + var userList = select_default2(document.createElement("span")); + userList.selectAll().data(subset).enter().append("a").attr("class", "user-link").attr("href", function(d2) { + return osm.userURL(d2); + }).attr("target", "_blank").text(String); + if (u2.length > limit) { + var count = select_default2(document.createElement("span")); + var othersNum = u2.length - limit + 1; + count.append("a").attr("target", "_blank").attr("href", function() { + return osm.changesetsURL(context.map().center(), context.map().zoom()); + }).text(othersNum); + wrap2.append("span").html(_t.html("contributors.truncated_list", { n: othersNum, users: { html: userList.html() }, count: { html: count.html() } })); + } else { + wrap2.append("span").html(_t.html("contributors.list", { users: { html: userList.html() } })); + } + if (!u2.length) { + hidden = true; + wrap2.transition().style("opacity", 0); + } else if (hidden) { + wrap2.transition().style("opacity", 1); + } + } + return function(selection2) { + if (!osm) + return; + wrap2 = selection2; + update(); + osm.on("loaded.contributors", debouncedUpdate); + context.map().on("move.contributors", debouncedUpdate); }; } - // modules/ui/curtain.js - function uiCurtain(containerNode) { - var surface = select_default2(null), tooltip = select_default2(null), darkness = select_default2(null); - function curtain(selection2) { - surface = selection2.append("svg").attr("class", "curtain").style("top", 0).style("left", 0); - darkness = surface.append("path").attr("x", 0).attr("y", 0).attr("class", "curtain-darkness"); - select_default2(window).on("resize.curtain", resize); - tooltip = selection2.append("div").attr("class", "tooltip"); - tooltip.append("div").attr("class", "popover-arrow"); - tooltip.append("div").attr("class", "popover-inner"); - resize(); - function resize() { - surface.attr("width", containerNode.clientWidth).attr("height", containerNode.clientHeight); - curtain.cut(darkness.datum()); + // modules/ui/popover.js + var _popoverID = 0; + function uiPopover(klass) { + var _id = _popoverID++; + var _anchorSelection = select_default2(null); + var popover = function(selection2) { + _anchorSelection = selection2; + selection2.each(setup); + }; + var _animation = utilFunctor(false); + var _placement = utilFunctor("top"); + var _alignment = utilFunctor("center"); + var _scrollContainer = utilFunctor(select_default2(null)); + var _content; + var _displayType = utilFunctor(""); + var _hasArrow = utilFunctor(true); + var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; + popover.displayType = function(val) { + if (arguments.length) { + _displayType = utilFunctor(val); + return popover; + } else { + return _displayType; } - } - curtain.reveal = function(box, html2, options2) { - options2 = options2 || {}; - if (typeof box === "string") { - box = select_default2(box).node(); + }; + popover.hasArrow = function(val) { + if (arguments.length) { + _hasArrow = utilFunctor(val); + return popover; + } else { + return _hasArrow; } - if (box && box.getBoundingClientRect) { - box = copyBox(box.getBoundingClientRect()); - var containerRect = containerNode.getBoundingClientRect(); - box.top -= containerRect.top; - box.left -= containerRect.left; + }; + popover.placement = function(val) { + if (arguments.length) { + _placement = utilFunctor(val); + return popover; + } else { + return _placement; } - if (box && options2.padding) { - box.top -= options2.padding; - box.left -= options2.padding; - box.bottom += options2.padding; - box.right += options2.padding; - box.height += options2.padding * 2; - box.width += options2.padding * 2; + }; + popover.alignment = function(val) { + if (arguments.length) { + _alignment = utilFunctor(val); + return popover; + } else { + return _alignment; } - var tooltipBox; - if (options2.tooltipBox) { - tooltipBox = options2.tooltipBox; - if (typeof tooltipBox === "string") { - tooltipBox = select_default2(tooltipBox).node(); - } - if (tooltipBox && tooltipBox.getBoundingClientRect) { - tooltipBox = copyBox(tooltipBox.getBoundingClientRect()); - } + }; + popover.scrollContainer = function(val) { + if (arguments.length) { + _scrollContainer = utilFunctor(val); + return popover; } else { - tooltipBox = box; + return _scrollContainer; } - if (tooltipBox && html2) { - if (html2.indexOf("**") !== -1) { - if (html2.indexOf(")(.+?)(\*\*)/, "$1$2$3"); - } else { - html2 = html2.replace(/^(.+?)(\*\*)/, "$1$2"); - } - html2 = html2.replace(/\*\*(.*?)\*\*/g, '$1'); - } - html2 = html2.replace(/\*(.*?)\*/g, "$1"); - html2 = html2.replace(/\{br\}/g, "

    "); - if (options2.buttonText && options2.buttonCallback) { - html2 += '
    "; - } - var classes = "curtain-tooltip popover tooltip arrowed in " + (options2.tooltipClass || ""); - tooltip.classed(classes, true).selectAll(".popover-inner").html(html2); - if (options2.buttonText && options2.buttonCallback) { - var button = tooltip.selectAll(".button-section .button.action"); - button.on("click", function(d3_event) { - d3_event.preventDefault(); - options2.buttonCallback(); - }); - } - var tip = copyBox(tooltip.node().getBoundingClientRect()), w2 = containerNode.clientWidth, h2 = containerNode.clientHeight, tooltipWidth = 200, tooltipArrow = 5, side, pos; - if (options2.tooltipClass === "intro-mouse") { - tip.height += 80; - } - if (tooltipBox.top + tooltipBox.height > h2) { - tooltipBox.height -= tooltipBox.top + tooltipBox.height - h2; - } - if (tooltipBox.left + tooltipBox.width > w2) { - tooltipBox.width -= tooltipBox.left + tooltipBox.width - w2; - } - if (tooltipBox.top + tooltipBox.height < 100) { - side = "bottom"; - pos = [ - tooltipBox.left + tooltipBox.width / 2 - tip.width / 2, - tooltipBox.top + tooltipBox.height - ]; - } else if (tooltipBox.top > h2 - 140) { - side = "top"; - pos = [ - tooltipBox.left + tooltipBox.width / 2 - tip.width / 2, - tooltipBox.top - tip.height - ]; - } else { - var tipY = tooltipBox.top + tooltipBox.height / 2 - tip.height / 2; - if (_mainLocalizer.textDirection() === "rtl") { - if (tooltipBox.left - tooltipWidth - tooltipArrow < 70) { - side = "right"; - pos = [tooltipBox.left + tooltipBox.width + tooltipArrow, tipY]; - } else { - side = "left"; - pos = [tooltipBox.left - tooltipWidth - tooltipArrow, tipY]; - } - } else { - if (tooltipBox.left + tooltipBox.width + tooltipArrow + tooltipWidth > w2 - 70) { - side = "left"; - pos = [tooltipBox.left - tooltipWidth - tooltipArrow, tipY]; - } else { - side = "right"; - pos = [tooltipBox.left + tooltipBox.width + tooltipArrow, tipY]; + }; + popover.content = function(val) { + if (arguments.length) { + _content = val; + return popover; + } else { + return _content; + } + }; + popover.isShown = function() { + var popoverSelection = _anchorSelection.select(".popover-" + _id); + return !popoverSelection.empty() && popoverSelection.classed("in"); + }; + popover.show = function() { + _anchorSelection.each(show); + }; + popover.updateContent = function() { + _anchorSelection.each(updateContent); + }; + popover.hide = function() { + _anchorSelection.each(hide); + }; + popover.toggle = function() { + _anchorSelection.each(toggle); + }; + popover.destroy = function(selection2, selector) { + selector = selector || ".popover-" + _id; + selection2.on(_pointerPrefix + "enter.popover", null).on(_pointerPrefix + "leave.popover", null).on(_pointerPrefix + "up.popover", null).on(_pointerPrefix + "down.popover", null).on("click.popover", null).attr("title", function() { + return this.getAttribute("data-original-title") || this.getAttribute("title"); + }).attr("data-original-title", null).selectAll(selector).remove(); + }; + popover.destroyAny = function(selection2) { + selection2.call(popover.destroy, ".popover"); + }; + function setup() { + var anchor = select_default2(this); + var animate = _animation.apply(this, arguments); + var popoverSelection = anchor.selectAll(".popover-" + _id).data([0]); + var enter = popoverSelection.enter().append("div").attr("class", "popover popover-" + _id + " " + (klass ? klass : "")).classed("arrowed", _hasArrow.apply(this, arguments)); + enter.append("div").attr("class", "popover-arrow"); + enter.append("div").attr("class", "popover-inner"); + popoverSelection = enter.merge(popoverSelection); + if (animate) { + popoverSelection.classed("fade", true); + } + var display = _displayType.apply(this, arguments); + if (display === "hover") { + var _lastNonMouseEnterTime; + anchor.on(_pointerPrefix + "enter.popover", function(d3_event) { + if (d3_event.pointerType) { + if (d3_event.pointerType !== "mouse") { + _lastNonMouseEnterTime = d3_event.timeStamp; + return; + } else if (_lastNonMouseEnterTime && d3_event.timeStamp - _lastNonMouseEnterTime < 1500) { + return; } } - } - if (options2.duration !== 0 || !tooltip.classed(side)) { - tooltip.call(uiToggle(true)); - } - tooltip.style("top", pos[1] + "px").style("left", pos[0] + "px").attr("class", classes + " " + side); - var shiftY = 0; - if (side === "left" || side === "right") { - if (pos[1] < 60) { - shiftY = 60 - pos[1]; - } else if (pos[1] + tip.height > h2 - 100) { - shiftY = h2 - pos[1] - tip.height - 100; + if (d3_event.buttons !== 0) + return; + show.apply(this, arguments); + }).on(_pointerPrefix + "leave.popover", function() { + hide.apply(this, arguments); + }).on("focus.popover", function() { + show.apply(this, arguments); + }).on("blur.popover", function() { + hide.apply(this, arguments); + }); + } else if (display === "clickFocus") { + anchor.on(_pointerPrefix + "down.popover", function(d3_event) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + }).on(_pointerPrefix + "up.popover", function(d3_event) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + }).on("click.popover", toggle); + popoverSelection.attr("tabindex", 0).on("blur.popover", function() { + anchor.each(function() { + hide.apply(this, arguments); + }); + }); + } + } + function show() { + var anchor = select_default2(this); + var popoverSelection = anchor.selectAll(".popover-" + _id); + if (popoverSelection.empty()) { + anchor.call(popover.destroy); + anchor.each(setup); + popoverSelection = anchor.selectAll(".popover-" + _id); + } + popoverSelection.classed("in", true); + var displayType = _displayType.apply(this, arguments); + if (displayType === "clickFocus") { + anchor.classed("active", true); + popoverSelection.node().focus(); + } + anchor.each(updateContent); + } + function updateContent() { + var anchor = select_default2(this); + if (_content) { + anchor.selectAll(".popover-" + _id + " > .popover-inner").call(_content.apply(this, arguments)); + } + updatePosition.apply(this, arguments); + updatePosition.apply(this, arguments); + updatePosition.apply(this, arguments); + } + function updatePosition() { + var anchor = select_default2(this); + var popoverSelection = anchor.selectAll(".popover-" + _id); + var scrollContainer = _scrollContainer && _scrollContainer.apply(this, arguments); + var scrollNode = scrollContainer && !scrollContainer.empty() && scrollContainer.node(); + var scrollLeft = scrollNode ? scrollNode.scrollLeft : 0; + var scrollTop = scrollNode ? scrollNode.scrollTop : 0; + var placement = _placement.apply(this, arguments); + popoverSelection.classed("left", false).classed("right", false).classed("top", false).classed("bottom", false).classed(placement, true); + var alignment = _alignment.apply(this, arguments); + var alignFactor = 0.5; + if (alignment === "leading") { + alignFactor = 0; + } else if (alignment === "trailing") { + alignFactor = 1; + } + var anchorFrame = getFrame(anchor.node()); + var popoverFrame = getFrame(popoverSelection.node()); + var position; + switch (placement) { + case "top": + position = { + x: anchorFrame.x + (anchorFrame.w - popoverFrame.w) * alignFactor, + y: anchorFrame.y - popoverFrame.h + }; + break; + case "bottom": + position = { + x: anchorFrame.x + (anchorFrame.w - popoverFrame.w) * alignFactor, + y: anchorFrame.y + anchorFrame.h + }; + break; + case "left": + position = { + x: anchorFrame.x - popoverFrame.w, + y: anchorFrame.y + (anchorFrame.h - popoverFrame.h) * alignFactor + }; + break; + case "right": + position = { + x: anchorFrame.x + anchorFrame.w, + y: anchorFrame.y + (anchorFrame.h - popoverFrame.h) * alignFactor + }; + break; + } + if (position) { + if (scrollNode && (placement === "top" || placement === "bottom")) { + var initialPosX = position.x; + if (position.x + popoverFrame.w > scrollNode.offsetWidth - 10) { + position.x = scrollNode.offsetWidth - 10 - popoverFrame.w; + } else if (position.x < 10) { + position.x = 10; } + var arrow = anchor.selectAll(".popover-" + _id + " > .popover-arrow"); + var arrowPosX = Math.min(Math.max(popoverFrame.w / 2 - (position.x - initialPosX), 10), popoverFrame.w - 10); + arrow.style("left", ~~arrowPosX + "px"); } - tooltip.selectAll(".popover-inner").style("top", shiftY + "px"); + popoverSelection.style("left", ~~position.x + "px").style("top", ~~position.y + "px"); } else { - tooltip.classed("in", false).call(uiToggle(false)); + popoverSelection.style("left", null).style("top", null); } - curtain.cut(box, options2.duration); - return tooltip; - }; - curtain.cut = function(datum2, duration) { - darkness.datum(datum2).interrupt(); - var selection2; - if (duration === 0) { - selection2 = darkness; + function getFrame(node) { + var positionStyle = select_default2(node).style("position"); + if (positionStyle === "absolute" || positionStyle === "static") { + return { + x: node.offsetLeft - scrollLeft, + y: node.offsetTop - scrollTop, + w: node.offsetWidth, + h: node.offsetHeight + }; + } else { + return { + x: 0, + y: 0, + w: node.offsetWidth, + h: node.offsetHeight + }; + } + } + } + function hide() { + var anchor = select_default2(this); + if (_displayType.apply(this, arguments) === "clickFocus") { + anchor.classed("active", false); + } + anchor.selectAll(".popover-" + _id).classed("in", false); + } + function toggle() { + if (select_default2(this).select(".popover-" + _id).classed("in")) { + hide.apply(this, arguments); } else { - selection2 = darkness.transition().duration(duration || 600).ease(linear2); + show.apply(this, arguments); } - selection2.attr("d", function(d2) { - var containerWidth = containerNode.clientWidth; - var containerHeight = containerNode.clientHeight; - var string = "M 0,0 L 0," + containerHeight + " L " + containerWidth + "," + containerHeight + "L" + containerWidth + ",0 Z"; - if (!d2) - return string; - return string + "M" + d2.left + "," + d2.top + "L" + d2.left + "," + (d2.top + d2.height) + "L" + (d2.left + d2.width) + "," + (d2.top + d2.height) + "L" + (d2.left + d2.width) + "," + d2.top + "Z"; - }); - }; - curtain.remove = function() { - surface.remove(); - tooltip.remove(); - select_default2(window).on("resize.curtain", null); - }; - function copyBox(src) { - return { - top: src.top, - right: src.right, - bottom: src.bottom, - left: src.left, - width: src.width, - height: src.height - }; } - return curtain; + return popover; } - // modules/ui/intro/welcome.js - function uiIntroWelcome(context, reveal) { - var dispatch14 = dispatch_default("done"); - var chapter = { - title: "intro.welcome.title" + // modules/ui/tooltip.js + function uiTooltip(klass) { + var tooltip = uiPopover((klass || "") + " tooltip").displayType("hover"); + var _title = function() { + var title = this.getAttribute("data-original-title"); + if (title) { + return title; + } else { + title = this.getAttribute("title"); + this.removeAttribute("title"); + this.setAttribute("data-original-title", title); + } + return title; }; - function welcome() { - context.map().centerZoom([-85.63591, 41.94285], 19); - reveal( - ".intro-nav-wrap .chapter-welcome", - helpHtml("intro.welcome.welcome"), - { buttonText: _t.html("intro.ok"), buttonCallback: practice } - ); - } - function practice() { - reveal( - ".intro-nav-wrap .chapter-welcome", - helpHtml("intro.welcome.practice"), - { buttonText: _t.html("intro.ok"), buttonCallback: words } - ); - } - function words() { - reveal( - ".intro-nav-wrap .chapter-welcome", - helpHtml("intro.welcome.words"), - { buttonText: _t.html("intro.ok"), buttonCallback: chapters } - ); - } - function chapters() { - dispatch14.call("done"); - reveal( - ".intro-nav-wrap .chapter-navigation", - helpHtml("intro.welcome.chapters", { next: _t("intro.navigation.title") }) - ); - } - chapter.enter = function() { - welcome(); + var _heading = utilFunctor(null); + var _keys = utilFunctor(null); + tooltip.title = function(val) { + if (!arguments.length) + return _title; + _title = utilFunctor(val); + return tooltip; }; - chapter.exit = function() { - context.container().select(".curtain-tooltip.intro-mouse").selectAll(".counter").remove(); + tooltip.heading = function(val) { + if (!arguments.length) + return _heading; + _heading = utilFunctor(val); + return tooltip; }; - chapter.restart = function() { - chapter.exit(); - chapter.enter(); + tooltip.keys = function(val) { + if (!arguments.length) + return _keys; + _keys = utilFunctor(val); + return tooltip; }; - return utilRebind(chapter, dispatch14, "on"); + tooltip.content(function() { + var heading2 = _heading.apply(this, arguments); + var text = _title.apply(this, arguments); + var keys2 = _keys.apply(this, arguments); + var headingCallback = typeof heading2 === "function" ? heading2 : (s2) => s2.text(heading2); + var textCallback = typeof text === "function" ? text : (s2) => s2.text(text); + return function(selection2) { + var headingSelect = selection2.selectAll(".tooltip-heading").data(heading2 ? [heading2] : []); + headingSelect.exit().remove(); + headingSelect.enter().append("div").attr("class", "tooltip-heading").merge(headingSelect).text("").call(headingCallback); + var textSelect = selection2.selectAll(".tooltip-text").data(text ? [text] : []); + textSelect.exit().remove(); + textSelect.enter().append("div").attr("class", "tooltip-text").merge(textSelect).text("").call(textCallback); + var keyhintWrap = selection2.selectAll(".keyhint-wrap").data(keys2 && keys2.length ? [0] : []); + keyhintWrap.exit().remove(); + var keyhintWrapEnter = keyhintWrap.enter().append("div").attr("class", "keyhint-wrap"); + keyhintWrapEnter.append("span").call(_t.append("tooltip_keyhint")); + keyhintWrap = keyhintWrapEnter.merge(keyhintWrap); + keyhintWrap.selectAll("kbd.shortcut").data(keys2 && keys2.length ? keys2 : []).enter().append("kbd").attr("class", "shortcut").text(function(d2) { + return d2; + }); + }; + }); + return tooltip; } - // modules/ui/intro/navigation.js - function uiIntroNavigation(context, reveal) { - var dispatch14 = dispatch_default("done"); - var timeouts = []; - var hallId = "n2061"; - var townHall = [-85.63591, 41.94285]; - var springStreetId = "w397"; - var springStreetEndId = "n1834"; - var springStreet = [-85.63582, 41.94255]; - var onewayField = _mainPresetIndex.field("oneway"); - var maxspeedField = _mainPresetIndex.field("maxspeed"); - var chapter = { - title: "intro.navigation.title" - }; - function timeout2(f3, t2) { - timeouts.push(window.setTimeout(f3, t2)); - } - function eventCancel(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - } - function isTownHallSelected() { - var ids = context.selectedIDs(); - return ids.length === 1 && ids[0] === hallId; - } - function dragMap() { - context.enter(modeBrowse(context)); - context.history().reset("initial"); - var msec = transitionTime(townHall, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); + // modules/ui/edit_menu.js + function uiEditMenu(context) { + var dispatch14 = dispatch_default("toggled"); + var _menu = select_default2(null); + var _operations = []; + var _anchorLoc = [0, 0]; + var _anchorLocLonLat = [0, 0]; + var _triggerType = ""; + var _vpTopMargin = 85; + var _vpBottomMargin = 45; + var _vpSideMargin = 35; + var _menuTop = false; + var _menuHeight; + var _menuWidth; + var _verticalPadding = 4; + var _tooltipWidth = 210; + var _menuSideMargin = 10; + var _tooltips = []; + var editMenu = function(selection2) { + var isTouchMenu = _triggerType.includes("touch") || _triggerType.includes("pen"); + var ops = _operations.filter(function(op) { + return !isTouchMenu || !op.mouseOnly; + }); + if (!ops.length) + return; + _tooltips = []; + _menuTop = isTouchMenu; + var showLabels = isTouchMenu; + var buttonHeight = showLabels ? 32 : 34; + if (showLabels) { + _menuWidth = 52 + Math.min(120, 6 * Math.max.apply(Math, ops.map(function(op) { + return op.title.length; + }))); + } else { + _menuWidth = 44; } - context.map().centerZoomEase(townHall, 19, msec); - timeout2(function() { - var centerStart = context.map().center(); - var textId = context.lastPointerType() === "mouse" ? "drag" : "drag_touch"; - var dragString = helpHtml("intro.navigation.map_info") + "{br}" + helpHtml("intro.navigation." + textId); - reveal(".surface", dragString); - context.map().on("drawn.intro", function() { - reveal(".surface", dragString, { duration: 0 }); - }); - context.map().on("move.intro", function() { - var centerNow = context.map().center(); - if (centerStart[0] !== centerNow[0] || centerStart[1] !== centerNow[1]) { - context.map().on("move.intro", null); - timeout2(function() { - continueTo(zoomMap); - }, 3e3); - } + _menuHeight = _verticalPadding * 2 + ops.length * buttonHeight; + _menu = selection2.append("div").attr("class", "edit-menu").classed("touch-menu", isTouchMenu).style("padding", _verticalPadding + "px 0"); + var buttons = _menu.selectAll(".edit-menu-item").data(ops); + var buttonsEnter = buttons.enter().append("button").attr("class", function(d2) { + return "edit-menu-item edit-menu-item-" + d2.id; + }).style("height", buttonHeight + "px").on("click", click).on("pointerup", pointerup).on("pointerdown mousedown", function pointerdown(d3_event) { + d3_event.stopPropagation(); + }).on("mouseenter.highlight", function(d3_event, d2) { + if (!d2.relatedEntityIds || select_default2(this).classed("disabled")) + return; + utilHighlightEntities(d2.relatedEntityIds(), true, context); + }).on("mouseleave.highlight", function(d3_event, d2) { + if (!d2.relatedEntityIds) + return; + utilHighlightEntities(d2.relatedEntityIds(), false, context); + }); + buttonsEnter.each(function(d2) { + var tooltip = uiTooltip().heading(() => d2.title).title(d2.tooltip).keys([d2.keys[0]]); + _tooltips.push(tooltip); + select_default2(this).call(tooltip).append("div").attr("class", "icon-wrap").call(svgIcon(d2.icon && d2.icon() || "#iD-operation-" + d2.id, "operation")); + }); + if (showLabels) { + buttonsEnter.append("span").attr("class", "label").each(function(d2) { + select_default2(this).call(d2.title); }); - }, msec + 100); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - nextStep(); } - } - function zoomMap() { - var zoomStart = context.map().zoom(); - var textId = context.lastPointerType() === "mouse" ? "zoom" : "zoom_touch"; - var zoomString = helpHtml("intro.navigation." + textId); - reveal(".surface", zoomString); - context.map().on("drawn.intro", function() { - reveal(".surface", zoomString, { duration: 0 }); + buttonsEnter.merge(buttons).classed("disabled", function(d2) { + return d2.disabled(); }); - context.map().on("move.intro", function() { - if (context.map().zoom() !== zoomStart) { - context.map().on("move.intro", null); - timeout2(function() { - continueTo(features); - }, 3e3); + updatePosition(); + var initialScale = context.projection.scale(); + context.map().on("move.edit-menu", function() { + if (initialScale !== context.projection.scale()) { + editMenu.close(); } + }).on("drawn.edit-menu", function(info) { + if (info.full) + updatePosition(); }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - nextStep(); + var lastPointerUpType; + function pointerup(d3_event) { + lastPointerUpType = d3_event.pointerType; } - } - function features() { - var onClick = function() { - continueTo(pointsLinesAreas); - }; - reveal( - ".surface", - helpHtml("intro.navigation.features"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.map().on("drawn.intro", function() { - reveal( - ".surface", - helpHtml("intro.navigation.features"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - }); - function continueTo(nextStep) { - context.map().on("drawn.intro", null); - nextStep(); + function click(d3_event, operation2) { + d3_event.stopPropagation(); + if (operation2.relatedEntityIds) { + utilHighlightEntities(operation2.relatedEntityIds(), false, context); + } + if (operation2.disabled()) { + if (lastPointerUpType === "touch" || lastPointerUpType === "pen") { + context.ui().flash.duration(4e3).iconName("#iD-operation-" + operation2.id).iconClass("operation disabled").label(operation2.tooltip())(); + } + } else { + if (lastPointerUpType === "touch" || lastPointerUpType === "pen") { + context.ui().flash.duration(2e3).iconName("#iD-operation-" + operation2.id).iconClass("operation").label(operation2.annotation() || operation2.title)(); + } + operation2(); + editMenu.close(); + } + lastPointerUpType = null; } - } - function pointsLinesAreas() { - var onClick = function() { - continueTo(nodesWays); - }; - reveal( - ".surface", - helpHtml("intro.navigation.points_lines_areas"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.map().on("drawn.intro", function() { - reveal( - ".surface", - helpHtml("intro.navigation.points_lines_areas"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - }); - function continueTo(nextStep) { - context.map().on("drawn.intro", null); - nextStep(); + dispatch14.call("toggled", this, true); + }; + function updatePosition() { + if (!_menu || _menu.empty()) + return; + var anchorLoc = context.projection(_anchorLocLonLat); + var viewport = context.surfaceRect(); + if (anchorLoc[0] < 0 || anchorLoc[0] > viewport.width || anchorLoc[1] < 0 || anchorLoc[1] > viewport.height) { + editMenu.close(); + return; } - } - function nodesWays() { - var onClick = function() { - continueTo(clickTownHall); - }; - reveal( - ".surface", - helpHtml("intro.navigation.nodes_ways"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.map().on("drawn.intro", function() { - reveal( - ".surface", - helpHtml("intro.navigation.nodes_ways"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); + var menuLeft = displayOnLeft(viewport); + var offset = [0, 0]; + offset[0] = menuLeft ? -1 * (_menuSideMargin + _menuWidth) : _menuSideMargin; + if (_menuTop) { + if (anchorLoc[1] - _menuHeight < _vpTopMargin) { + offset[1] = -anchorLoc[1] + _vpTopMargin; + } else { + offset[1] = -_menuHeight; + } + } else { + if (anchorLoc[1] + _menuHeight > viewport.height - _vpBottomMargin) { + offset[1] = -anchorLoc[1] - _menuHeight + viewport.height - _vpBottomMargin; + } else { + offset[1] = 0; + } + } + var origin = geoVecAdd(anchorLoc, offset); + _menu.style("left", origin[0] + "px").style("top", origin[1] + "px"); + var tooltipSide = tooltipPosition(viewport, menuLeft); + _tooltips.forEach(function(tooltip) { + tooltip.placement(tooltipSide); }); - function continueTo(nextStep) { - context.map().on("drawn.intro", null); - nextStep(); + function displayOnLeft(viewport2) { + if (_mainLocalizer.textDirection() === "ltr") { + if (anchorLoc[0] + _menuSideMargin + _menuWidth > viewport2.width - _vpSideMargin) { + return true; + } + return false; + } else { + if (anchorLoc[0] - _menuSideMargin - _menuWidth < _vpSideMargin) { + return false; + } + return true; + } + } + function tooltipPosition(viewport2, menuLeft2) { + if (_mainLocalizer.textDirection() === "ltr") { + if (menuLeft2) { + return "left"; + } + if (anchorLoc[0] + _menuSideMargin + _menuWidth + _tooltipWidth > viewport2.width - _vpSideMargin) { + return "left"; + } + return "right"; + } else { + if (!menuLeft2) { + return "right"; + } + if (anchorLoc[0] - _menuSideMargin - _menuWidth - _tooltipWidth < _vpSideMargin) { + return "right"; + } + return "left"; + } } } - function clickTownHall() { - context.enter(modeBrowse(context)); - context.history().reset("initial"); - var entity = context.hasEntity(hallId); - if (!entity) - return; - reveal(null, null, { duration: 0 }); - context.map().centerZoomEase(entity.loc, 19, 500); - timeout2(function() { - var entity2 = context.hasEntity(hallId); - if (!entity2) - return; - var box = pointBox(entity2.loc, context); - var textId = context.lastPointerType() === "mouse" ? "click_townhall" : "tap_townhall"; - reveal(box, helpHtml("intro.navigation." + textId)); - context.map().on("move.intro drawn.intro", function() { - var entity3 = context.hasEntity(hallId); - if (!entity3) - return; - var box2 = pointBox(entity3.loc, context); - reveal(box2, helpHtml("intro.navigation." + textId), { duration: 0 }); + editMenu.close = function() { + context.map().on("move.edit-menu", null).on("drawn.edit-menu", null); + _menu.remove(); + _tooltips = []; + dispatch14.call("toggled", this, false); + }; + editMenu.anchorLoc = function(val) { + if (!arguments.length) + return _anchorLoc; + _anchorLoc = val; + _anchorLocLonLat = context.projection.invert(_anchorLoc); + return editMenu; + }; + editMenu.triggerType = function(val) { + if (!arguments.length) + return _triggerType; + _triggerType = val; + return editMenu; + }; + editMenu.operations = function(val) { + if (!arguments.length) + return _operations; + _operations = val; + return editMenu; + }; + return utilRebind(editMenu, dispatch14, "on"); + } + + // modules/ui/feature_info.js + function uiFeatureInfo(context) { + function update(selection2) { + var features = context.features(); + var stats = features.stats(); + var count = 0; + var hiddenList = features.hidden().map(function(k2) { + if (stats[k2]) { + count += stats[k2]; + return _t.append("inspector.title_count", { + title: _t("feature." + k2 + ".description"), + count: stats[k2] + }); + } + return null; + }).filter(Boolean); + selection2.text(""); + if (hiddenList.length) { + var tooltipBehavior = uiTooltip().placement("top").title(function() { + return (selection3) => { + hiddenList.forEach((hiddenFeature) => { + selection3.append("div").call(hiddenFeature); + }); + }; }); - context.on("enter.intro", function() { - if (isTownHallSelected()) - continueTo(selectedTownHall); + selection2.append("a").attr("class", "chip").attr("href", "#").call(_t.append("feature_info.hidden_warning", { count })).call(tooltipBehavior).on("click", function(d3_event) { + tooltipBehavior.hide(); + d3_event.preventDefault(); + context.ui().togglePanes(context.container().select(".map-panes .map-data-pane")); }); - }, 550); - context.history().on("change.intro", function() { - if (!context.hasEntity(hallId)) { - continueTo(clickTownHall); - } - }); - function continueTo(nextStep) { - context.on("enter.intro", null); - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - nextStep(); } + selection2.classed("hide", !hiddenList.length); } - function selectedTownHall() { - if (!isTownHallSelected()) - return clickTownHall(); - var entity = context.hasEntity(hallId); - if (!entity) - return clickTownHall(); - var box = pointBox(entity.loc, context); - var onClick = function() { - continueTo(editorTownHall); - }; - reveal( - box, - helpHtml("intro.navigation.selected_townhall"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.map().on("move.intro drawn.intro", function() { - var entity2 = context.hasEntity(hallId); - if (!entity2) - return; - var box2 = pointBox(entity2.loc, context); - reveal( - box2, - helpHtml("intro.navigation.selected_townhall"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - }); - context.history().on("change.intro", function() { - if (!context.hasEntity(hallId)) { - continueTo(clickTownHall); - } + return function(selection2) { + update(selection2); + context.features().on("change.feature_info", function() { + update(selection2); }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - nextStep(); + }; + } + + // modules/ui/flash.js + function uiFlash(context) { + var _flashTimer; + var _duration = 2e3; + var _iconName = "#iD-icon-no"; + var _iconClass = "disabled"; + var _label = (s2) => s2.text(""); + function flash() { + if (_flashTimer) { + _flashTimer.stop(); } + context.container().select(".main-footer-wrap").classed("footer-hide", true).classed("footer-show", false); + context.container().select(".flash-wrap").classed("footer-hide", false).classed("footer-show", true); + var content = context.container().select(".flash-wrap").selectAll(".flash-content").data([0]); + var contentEnter = content.enter().append("div").attr("class", "flash-content"); + var iconEnter = contentEnter.append("svg").attr("class", "flash-icon icon").append("g").attr("transform", "translate(10,10)"); + iconEnter.append("circle").attr("r", 9); + iconEnter.append("use").attr("transform", "translate(-7,-7)").attr("width", "14").attr("height", "14"); + contentEnter.append("div").attr("class", "flash-text"); + content = content.merge(contentEnter); + content.selectAll(".flash-icon").attr("class", "icon flash-icon " + (_iconClass || "")); + content.selectAll(".flash-icon use").attr("xlink:href", _iconName); + content.selectAll(".flash-text").attr("class", "flash-text").call(_label); + _flashTimer = timeout_default(function() { + _flashTimer = null; + context.container().select(".main-footer-wrap").classed("footer-hide", false).classed("footer-show", true); + context.container().select(".flash-wrap").classed("footer-hide", true).classed("footer-show", false); + }, _duration); + return content; } - function editorTownHall() { - if (!isTownHallSelected()) - return clickTownHall(); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - var onClick = function() { - continueTo(presetTownHall); - }; - reveal( - ".entity-editor-pane", - helpHtml("intro.navigation.editor_townhall"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.on("exit.intro", function() { - continueTo(clickTownHall); - }); - context.history().on("change.intro", function() { - if (!context.hasEntity(hallId)) { - continueTo(clickTownHall); - } - }); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); - nextStep(); + flash.duration = function(_2) { + if (!arguments.length) + return _duration; + _duration = _2; + return flash; + }; + flash.label = function(_2) { + if (!arguments.length) + return _label; + if (typeof _2 !== "function") { + _label = (selection2) => selection2.text(_2); + } else { + _label = (selection2) => selection2.text("").call(_2); + } + return flash; + }; + flash.iconName = function(_2) { + if (!arguments.length) + return _iconName; + _iconName = _2; + return flash; + }; + flash.iconClass = function(_2) { + if (!arguments.length) + return _iconClass; + _iconClass = _2; + return flash; + }; + return flash; + } + + // modules/ui/full_screen.js + function uiFullScreen(context) { + var element = context.container().node(); + function getFullScreenFn() { + if (element.requestFullscreen) { + return element.requestFullscreen; + } else if (element.msRequestFullscreen) { + return element.msRequestFullscreen; + } else if (element.mozRequestFullScreen) { + return element.mozRequestFullScreen; + } else if (element.webkitRequestFullscreen) { + return element.webkitRequestFullscreen; } } - function presetTownHall() { - if (!isTownHallSelected()) - return clickTownHall(); - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - var entity = context.entity(context.selectedIDs()[0]); - var preset = _mainPresetIndex.match(entity, context.graph()); - var onClick = function() { - continueTo(fieldsTownHall); - }; - reveal( - ".entity-editor-pane .section-feature-type", - helpHtml("intro.navigation.preset_townhall", { preset: preset.name() }), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.on("exit.intro", function() { - continueTo(clickTownHall); - }); - context.history().on("change.intro", function() { - if (!context.hasEntity(hallId)) { - continueTo(clickTownHall); - } - }); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); - nextStep(); + function getExitFullScreenFn() { + if (document.exitFullscreen) { + return document.exitFullscreen; + } else if (document.msExitFullscreen) { + return document.msExitFullscreen; + } else if (document.mozCancelFullScreen) { + return document.mozCancelFullScreen; + } else if (document.webkitExitFullscreen) { + return document.webkitExitFullscreen; } } - function fieldsTownHall() { - if (!isTownHallSelected()) - return clickTownHall(); - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - var onClick = function() { - continueTo(closeTownHall); - }; - reveal( - ".entity-editor-pane .section-preset-fields", - helpHtml("intro.navigation.fields_townhall"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.on("exit.intro", function() { - continueTo(clickTownHall); - }); - context.history().on("change.intro", function() { - if (!context.hasEntity(hallId)) { - continueTo(clickTownHall); - } - }); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); - nextStep(); + function isFullScreen() { + return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement; + } + function isSupported() { + return !!getFullScreenFn(); + } + function fullScreen(d3_event) { + d3_event.preventDefault(); + if (!isFullScreen()) { + getFullScreenFn().apply(element); + } else { + getExitFullScreenFn().apply(document); } } - function closeTownHall() { - if (!isTownHallSelected()) - return clickTownHall(); - var selector = ".entity-editor-pane button.close svg use"; - var href = select_default2(selector).attr("href") || "#iD-icon-close"; - reveal( - ".entity-editor-pane", - helpHtml("intro.navigation.close_townhall", { button: { html: icon(href, "inline") } }) - ); - context.on("exit.intro", function() { - continueTo(searchStreet); - }); - context.history().on("change.intro", function() { - var selector2 = ".entity-editor-pane button.close svg use"; - var href2 = select_default2(selector2).attr("href") || "#iD-icon-close"; - reveal( - ".entity-editor-pane", - helpHtml("intro.navigation.close_townhall", { button: { html: icon(href2, "inline") } }), - { duration: 0 } + return function() { + if (!isSupported()) + return; + var detected = utilDetect(); + var keys2 = detected.os === "mac" ? [uiCmd("\u2303\u2318F"), "f11"] : ["f11"]; + context.keybinding().on(keys2, fullScreen); + }; + } + + // modules/ui/geolocate.js + function uiGeolocate(context) { + var _geolocationOptions = { + // prioritize speed and power usage over precision + enableHighAccuracy: false, + // don't hang indefinitely getting the location + timeout: 6e3 + // 6sec + }; + var _locating = uiLoading(context).message(_t.html("geolocate.locating")).blocking(true); + var _layer = context.layers().layer("geolocate"); + var _position; + var _extent; + var _timeoutID; + var _button = select_default2(null); + function click() { + if (context.inIntro()) + return; + if (!_layer.enabled() && !_locating.isShown()) { + _timeoutID = setTimeout( + error, + 1e4 + /* 10sec */ ); - }); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - nextStep(); + context.container().call(_locating); + navigator.geolocation.getCurrentPosition(success, error, _geolocationOptions); + } else { + _locating.close(); + _layer.enabled(null, false); + updateButtonState(); } } - function searchStreet() { + function zoomTo() { context.enter(modeBrowse(context)); - context.history().reset("initial"); - var msec = transitionTime(springStreet, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); - } - context.map().centerZoomEase(springStreet, 19, msec); - timeout2(function() { - reveal( - ".search-header input", - helpHtml("intro.navigation.search_street", { name: _t("intro.graph.name.spring-street") }) - ); - context.container().select(".search-header input").on("keyup.intro", checkSearchResult); - }, msec + 100); + var map2 = context.map(); + _layer.enabled(_position, true); + updateButtonState(); + map2.centerZoomEase(_extent.center(), Math.min(20, map2.extentZoom(_extent))); } - function checkSearchResult() { - var first = context.container().select(".feature-list-item:nth-child(0n+2)"); - var firstName = first.select(".entity-name"); - var name = _t("intro.graph.name.spring-street"); - if (!firstName.empty() && firstName.html() === name) { - reveal( - first.node(), - helpHtml("intro.navigation.choose_street", { name }), - { duration: 300 } - ); - context.on("exit.intro", function() { - continueTo(selectedStreet); - }); - context.container().select(".search-header input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); - } - function continueTo(nextStep) { - context.on("exit.intro", null); - context.container().select(".search-header input").on("keydown.intro", null).on("keyup.intro", null); - nextStep(); + function success(geolocation) { + _position = geolocation; + var coords = _position.coords; + _extent = geoExtent([coords.longitude, coords.latitude]).padByMeters(coords.accuracy); + zoomTo(); + finish(); + } + function error() { + if (_position) { + zoomTo(); + } else { + context.ui().flash.label(_t.append("geolocate.location_unavailable")).iconName("#iD-icon-geolocate")(); } + finish(); } - function selectedStreet() { - if (!context.hasEntity(springStreetEndId) || !context.hasEntity(springStreetId)) { - return searchStreet(); + function finish() { + _locating.close(); + if (_timeoutID) { + clearTimeout(_timeoutID); } - var onClick = function() { - continueTo(editorStreet); - }; - var entity = context.entity(springStreetEndId); - var box = pointBox(entity.loc, context); - box.height = 500; - reveal( - box, - helpHtml("intro.navigation.selected_street", { name: _t("intro.graph.name.spring-street") }), - { duration: 600, buttonText: _t.html("intro.ok"), buttonCallback: onClick } + _timeoutID = void 0; + } + function updateButtonState() { + _button.classed("active", _layer.enabled()); + _button.attr("aria-pressed", _layer.enabled()); + } + return function(selection2) { + if (!navigator.geolocation || !navigator.geolocation.getCurrentPosition) + return; + _button = selection2.append("button").on("click", click).attr("aria-pressed", false).call(svgIcon("#iD-icon-geolocate", "light")).call( + uiTooltip().placement(_mainLocalizer.textDirection() === "rtl" ? "right" : "left").title(() => _t.append("geolocate.title")).keys([_t("geolocate.key")]) ); - timeout2(function() { - context.map().on("move.intro drawn.intro", function() { - var entity2 = context.hasEntity(springStreetEndId); - if (!entity2) - return; - var box2 = pointBox(entity2.loc, context); - box2.height = 500; - reveal( - box2, - helpHtml("intro.navigation.selected_street", { name: _t("intro.graph.name.spring-street") }), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - }); - }, 600); - context.on("enter.intro", function(mode) { - if (!context.hasEntity(springStreetId)) { - return continueTo(searchStreet); - } - var ids = context.selectedIDs(); - if (mode.id !== "select" || !ids.length || ids[0] !== springStreetId) { - context.enter(modeSelect(context, [springStreetId])); - } - }); - context.history().on("change.intro", function() { - if (!context.hasEntity(springStreetEndId) || !context.hasEntity(springStreetId)) { - timeout2(function() { - continueTo(searchStreet); - }, 300); - } - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - context.history().on("change.intro", null); - nextStep(); + context.keybinding().on(_t("geolocate.key"), click); + }; + } + + // modules/ui/panels/background.js + function uiPanelBackground(context) { + var background = context.background(); + var _currSourceName = null; + var _metadata = {}; + var _metadataKeys = [ + "zoom", + "vintage", + "source", + "description", + "resolution", + "accuracy" + ]; + var debouncedRedraw = debounce_default(redraw, 250); + function redraw(selection2) { + var source = background.baseLayerSource(); + if (!source) + return; + var isDG = source.id.match(/^DigitalGlobe/i) !== null; + var sourceLabel = source.label(); + if (_currSourceName !== sourceLabel) { + _currSourceName = sourceLabel; + _metadata = {}; } - } - function editorStreet() { - var selector = ".entity-editor-pane button.close svg use"; - var href = select_default2(selector).attr("href") || "#iD-icon-close"; - reveal(".entity-editor-pane", helpHtml("intro.navigation.street_different_fields") + "{br}" + helpHtml("intro.navigation.editor_street", { - button: { html: icon(href, "inline") }, - field1: onewayField.title(), - field2: maxspeedField.title() - })); - context.on("exit.intro", function() { - continueTo(play); + selection2.text(""); + var list2 = selection2.append("ul").attr("class", "background-info"); + list2.append("li").call(_currSourceName); + _metadataKeys.forEach(function(k2) { + if (isDG && k2 === "vintage") + return; + list2.append("li").attr("class", "background-info-list-" + k2).classed("hide", !_metadata[k2]).call(_t.append("info_panels.background." + k2, { suffix: ":" })).append("span").attr("class", "background-info-span-" + k2).text(_metadata[k2]); }); - context.history().on("change.intro", function() { - var selector2 = ".entity-editor-pane button.close svg use"; - var href2 = select_default2(selector2).attr("href") || "#iD-icon-close"; - reveal( - ".entity-editor-pane", - helpHtml("intro.navigation.street_different_fields") + "{br}" + helpHtml("intro.navigation.editor_street", { - button: { html: icon(href2, "inline") }, - field1: onewayField.title(), - field2: maxspeedField.title() - }), - { duration: 0 } - ); + debouncedGetMetadata(selection2); + var toggleTiles = context.getDebug("tile") ? "hide_tiles" : "show_tiles"; + selection2.append("a").call(_t.append("info_panels.background." + toggleTiles)).attr("href", "#").attr("class", "button button-toggle-tiles").on("click", function(d3_event) { + d3_event.preventDefault(); + context.setDebug("tile", !context.getDebug("tile")); + selection2.call(redraw); }); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - nextStep(); + if (isDG) { + var key = source.id + "-vintage"; + var sourceVintage = context.background().findSource(key); + var showsVintage = context.background().showsLayer(sourceVintage); + var toggleVintage = showsVintage ? "hide_vintage" : "show_vintage"; + selection2.append("a").call(_t.append("info_panels.background." + toggleVintage)).attr("href", "#").attr("class", "button button-toggle-vintage").on("click", function(d3_event) { + d3_event.preventDefault(); + context.background().toggleOverlayLayer(sourceVintage); + selection2.call(redraw); + }); } - } - function play() { - dispatch14.call("done"); - reveal( - ".ideditor", - helpHtml("intro.navigation.play", { next: _t("intro.points.title") }), - { - tooltipBox: ".intro-nav-wrap .chapter-point", - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - reveal(".ideditor"); + ["DigitalGlobe-Premium", "DigitalGlobe-Standard"].forEach(function(layerId) { + if (source.id !== layerId) { + var key2 = layerId + "-vintage"; + var sourceVintage2 = context.background().findSource(key2); + if (context.background().showsLayer(sourceVintage2)) { + context.background().toggleOverlayLayer(sourceVintage2); } } - ); + }); + } + var debouncedGetMetadata = debounce_default(getMetadata, 250); + function getMetadata(selection2) { + var tile = context.container().select(".layer-background img.tile-center"); + if (tile.empty()) + return; + var sourceName = _currSourceName; + var d2 = tile.datum(); + var zoom = d2 && d2.length >= 3 && d2[2] || Math.floor(context.map().zoom()); + var center = context.map().center(); + _metadata.zoom = String(zoom); + selection2.selectAll(".background-info-list-zoom").classed("hide", false).selectAll(".background-info-span-zoom").text(_metadata.zoom); + if (!d2 || !d2.length >= 3) + return; + background.baseLayerSource().getMetadata(center, d2, function(err, result) { + if (err || _currSourceName !== sourceName) + return; + var vintage = result.vintage; + _metadata.vintage = vintage && vintage.range || _t("info_panels.background.unknown"); + selection2.selectAll(".background-info-list-vintage").classed("hide", false).selectAll(".background-info-span-vintage").text(_metadata.vintage); + _metadataKeys.forEach(function(k2) { + if (k2 === "zoom" || k2 === "vintage") + return; + var val = result[k2]; + _metadata[k2] = val; + selection2.selectAll(".background-info-list-" + k2).classed("hide", !val).selectAll(".background-info-span-" + k2).text(val); + }); + }); } - chapter.enter = function() { - dragMap(); - }; - chapter.exit = function() { - timeouts.forEach(window.clearTimeout); - context.on("enter.intro exit.intro", null); - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".search-header input").on("keydown.intro keyup.intro", null); + var panel = function(selection2) { + selection2.call(redraw); + context.map().on("drawn.info-background", function() { + selection2.call(debouncedRedraw); + }).on("move.info-background", function() { + selection2.call(debouncedGetMetadata); + }); }; - chapter.restart = function() { - chapter.exit(); - chapter.enter(); + panel.off = function() { + context.map().on("drawn.info-background", null).on("move.info-background", null); }; - return utilRebind(chapter, dispatch14, "on"); + panel.id = "background"; + panel.label = _t.append("info_panels.background.title"); + panel.key = _t("info_panels.background.key"); + return panel; } - // modules/ui/intro/point.js - function uiIntroPoint(context, reveal) { - var dispatch14 = dispatch_default("done"); - var timeouts = []; - var intersection = [-85.63279, 41.94394]; - var building = [-85.632422, 41.944045]; - var cafePreset = _mainPresetIndex.item("amenity/cafe"); - var _pointID = null; - var chapter = { - title: "intro.points.title" - }; - function timeout2(f3, t2) { - timeouts.push(window.setTimeout(f3, t2)); - } - function eventCancel(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - } - function addPoint() { - context.enter(modeBrowse(context)); - context.history().reset("initial"); - var msec = transitionTime(intersection, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); - } - context.map().centerZoomEase(intersection, 19, msec); - timeout2(function() { - var tooltip = reveal( - "button.add-point", - helpHtml("intro.points.points_info") + "{br}" + helpHtml("intro.points.add_point") - ); - _pointID = null; - tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-points"); - context.on("enter.intro", function(mode) { - if (mode.id !== "add-point") - return; - continueTo(placePoint); - }); - }, msec + 100); - function continueTo(nextStep) { - context.on("enter.intro", null); - nextStep(); - } + // modules/ui/panels/history.js + function uiPanelHistory(context) { + var osm; + function displayTimestamp(timestamp) { + if (!timestamp) + return _t("info_panels.history.unknown"); + var options2 = { + day: "numeric", + month: "short", + year: "numeric", + hour: "numeric", + minute: "numeric", + second: "numeric" + }; + var d2 = new Date(timestamp); + if (isNaN(d2.getTime())) + return _t("info_panels.history.unknown"); + return d2.toLocaleString(_mainLocalizer.localeCode(), options2); } - function placePoint() { - if (context.mode().id !== "add-point") { - return chapter.restart(); + function displayUser(selection2, userName) { + if (!userName) { + selection2.append("span").call(_t.append("info_panels.history.unknown")); + return; } - var pointBox2 = pad(building, 150, context); - var textId = context.lastPointerType() === "mouse" ? "place_point" : "place_point_touch"; - reveal(pointBox2, helpHtml("intro.points." + textId)); - context.map().on("move.intro drawn.intro", function() { - pointBox2 = pad(building, 150, context); - reveal(pointBox2, helpHtml("intro.points." + textId), { duration: 0 }); - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") - return chapter.restart(); - _pointID = context.mode().selectedIDs()[0]; - continueTo(searchPreset); - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); + selection2.append("span").attr("class", "user-name").text(userName); + var links = selection2.append("div").attr("class", "links"); + if (osm) { + links.append("a").attr("class", "user-osm-link").attr("href", osm.userURL(userName)).attr("target", "_blank").call(_t.append("info_panels.history.profile_link")); } + links.append("a").attr("class", "user-hdyc-link").attr("href", "https://hdyc.neis-one.org/?" + userName).attr("target", "_blank").attr("tabindex", -1).text("HDYC"); } - function searchPreset() { - if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { - return addPoint(); - } - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); - reveal( - ".preset-search-input", - helpHtml("intro.points.search_cafe", { preset: cafePreset.name() }) - ); - context.on("enter.intro", function(mode) { - if (!_pointID || !context.hasEntity(_pointID)) { - return continueTo(addPoint); - } - var ids = context.selectedIDs(); - if (mode.id !== "select" || !ids.length || ids[0] !== _pointID) { - context.enter(modeSelect(context, [_pointID])); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); - reveal( - ".preset-search-input", - helpHtml("intro.points.search_cafe", { preset: cafePreset.name() }) - ); - context.history().on("change.intro", null); - } - }); - function checkPresetSearch() { - var first = context.container().select(".preset-list-item:first-child"); - if (first.classed("preset-amenity-cafe")) { - context.container().select(".preset-search-input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); - reveal( - first.select(".preset-list-button").node(), - helpHtml("intro.points.choose_cafe", { preset: cafePreset.name() }), - { duration: 300 } - ); - context.history().on("change.intro", function() { - continueTo(aboutFeatureEditor); - }); - } + function displayChangeset(selection2, changeset) { + if (!changeset) { + selection2.append("span").call(_t.append("info_panels.history.unknown")); + return; } - function continueTo(nextStep) { - context.on("enter.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); - nextStep(); + selection2.append("span").attr("class", "changeset-id").text(changeset); + var links = selection2.append("div").attr("class", "links"); + if (osm) { + links.append("a").attr("class", "changeset-osm-link").attr("href", osm.changesetURL(changeset)).attr("target", "_blank").call(_t.append("info_panels.history.changeset_link")); } + links.append("a").attr("class", "changeset-osmcha-link").attr("href", "https://osmcha.org/changesets/" + changeset).attr("target", "_blank").text("OSMCha"); + links.append("a").attr("class", "changeset-achavi-link").attr("href", "https://overpass-api.de/achavi/?changeset=" + changeset).attr("target", "_blank").text("Achavi"); } - function aboutFeatureEditor() { - if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { - return addPoint(); - } - timeout2(function() { - reveal(".entity-editor-pane", helpHtml("intro.points.feature_editor"), { - tooltipClass: "intro-points-describe", - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(addName); - } + function redraw(selection2) { + var selectedNoteID = context.selectedNoteID(); + osm = context.connection(); + var selected, note, entity; + if (selectedNoteID && osm) { + selected = [_t.html("note.note") + " " + selectedNoteID]; + note = osm.getNote(selectedNoteID); + } else { + selected = context.selectedIDs().filter(function(e3) { + return context.hasEntity(e3); }); - }, 400); - context.on("exit.intro", function() { - continueTo(reselectPoint); - }); - function continueTo(nextStep) { - context.on("exit.intro", null); - nextStep(); + if (selected.length) { + entity = context.entity(selected[0]); + } } - } - function addName() { - if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { - return addPoint(); + var singular = selected.length === 1 ? selected[0] : null; + selection2.html(""); + if (singular) { + selection2.append("h4").attr("class", "history-heading").html(singular); + } else { + selection2.append("h4").attr("class", "history-heading").call(_t.append("info_panels.selected", { n: selected.length })); } - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - var addNameString = helpHtml("intro.points.fields_info") + "{br}" + helpHtml("intro.points.add_name"); - timeout2(function() { - var entity = context.entity(_pointID); - if (entity.tags.name) { - var tooltip = reveal(".entity-editor-pane", addNameString, { - tooltipClass: "intro-points-describe", - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(addCloseEditor); - } - }); - tooltip.select(".instruction").style("display", "none"); - } else { - reveal( - ".entity-editor-pane", - addNameString, - { tooltipClass: "intro-points-describe" } - ); - } - }, 400); - context.history().on("change.intro", function() { - continueTo(addCloseEditor); - }); - context.on("exit.intro", function() { - continueTo(reselectPoint); - }); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - nextStep(); + if (!singular) + return; + if (entity) { + selection2.call(redrawEntity, entity); + } else if (note) { + selection2.call(redrawNote, note); } } - function addCloseEditor() { - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - var selector = ".entity-editor-pane button.close svg use"; - var href = select_default2(selector).attr("href") || "#iD-icon-close"; - context.on("exit.intro", function() { - continueTo(reselectPoint); - }); - reveal( - ".entity-editor-pane", - helpHtml("intro.points.add_close", { button: { html: icon(href, "inline") } }) - ); - function continueTo(nextStep) { - context.on("exit.intro", null); - nextStep(); + function redrawNote(selection2, note) { + if (!note || note.isNew()) { + selection2.append("div").call(_t.append("info_panels.history.note_no_history")); + return; } - } - function reselectPoint() { - if (!_pointID) - return chapter.restart(); - var entity = context.hasEntity(_pointID); - if (!entity) - return chapter.restart(); - var oldPreset = _mainPresetIndex.match(entity, context.graph()); - context.replace(actionChangePreset(_pointID, oldPreset, cafePreset)); - context.enter(modeBrowse(context)); - var msec = transitionTime(entity.loc, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); + var list2 = selection2.append("ul"); + list2.append("li").call(_t.append("info_panels.history.note_comments", { suffix: ":" })).append("span").text(note.comments.length); + if (note.comments.length) { + list2.append("li").call(_t.append("info_panels.history.note_created_date", { suffix: ":" })).append("span").text(displayTimestamp(note.comments[0].date)); + list2.append("li").call(_t.append("info_panels.history.note_created_user", { suffix: ":" })).call(displayUser, note.comments[0].user); } - context.map().centerEase(entity.loc, msec); - timeout2(function() { - var box = pointBox(entity.loc, context); - reveal(box, helpHtml("intro.points.reselect"), { duration: 600 }); - timeout2(function() { - context.map().on("move.intro drawn.intro", function() { - var entity2 = context.hasEntity(_pointID); - if (!entity2) - return chapter.restart(); - var box2 = pointBox(entity2.loc, context); - reveal(box2, helpHtml("intro.points.reselect"), { duration: 0 }); - }); - }, 600); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") - return; - continueTo(updatePoint); - }); - }, msec + 100); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); + if (osm) { + selection2.append("a").attr("class", "view-history-on-osm").attr("target", "_blank").attr("href", osm.noteURL(note)).call(svgIcon("#iD-icon-out-link", "inline")).append("span").call(_t.append("info_panels.history.note_link_text")); } } - function updatePoint() { - if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { - return continueTo(reselectPoint); + function redrawEntity(selection2, entity) { + if (!entity || entity.isNew()) { + selection2.append("div").call(_t.append("info_panels.history.no_history")); + return; } - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - context.on("exit.intro", function() { - continueTo(reselectPoint); - }); - context.history().on("change.intro", function() { - continueTo(updateCloseEditor); - }); - timeout2(function() { - reveal( - ".entity-editor-pane", - helpHtml("intro.points.update"), - { tooltipClass: "intro-points-describe" } - ); - }, 400); - function continueTo(nextStep) { - context.on("exit.intro", null); - context.history().on("change.intro", null); - nextStep(); + var links = selection2.append("div").attr("class", "links"); + if (osm) { + links.append("a").attr("class", "view-history-on-osm").attr("href", osm.historyURL(entity)).attr("target", "_blank").call(_t.append("info_panels.history.history_link")); } + links.append("a").attr("class", "pewu-history-viewer-link").attr("href", "https://pewu.github.io/osm-history/#/" + entity.type + "/" + entity.osmId()).attr("target", "_blank").attr("tabindex", -1).text("PeWu"); + var list2 = selection2.append("ul"); + list2.append("li").call(_t.append("info_panels.history.version", { suffix: ":" })).append("span").text(entity.version); + list2.append("li").call(_t.append("info_panels.history.last_edit", { suffix: ":" })).append("span").text(displayTimestamp(entity.timestamp)); + list2.append("li").call(_t.append("info_panels.history.edited_by", { suffix: ":" })).call(displayUser, entity.user); + list2.append("li").call(_t.append("info_panels.history.changeset", { suffix: ":" })).call(displayChangeset, entity.changeset); } - function updateCloseEditor() { - if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { - return continueTo(reselectPoint); - } - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - context.on("exit.intro", function() { - continueTo(rightClickPoint); + var panel = function(selection2) { + selection2.call(redraw); + context.map().on("drawn.info-history", function() { + selection2.call(redraw); }); - timeout2(function() { - reveal( - ".entity-editor-pane", - helpHtml("intro.points.update_close", { button: { html: icon("#iD-icon-close", "inline") } }) - ); - }, 500); - function continueTo(nextStep) { - context.on("exit.intro", null); - nextStep(); - } - } - function rightClickPoint() { - if (!_pointID) - return chapter.restart(); - var entity = context.hasEntity(_pointID); - if (!entity) - return chapter.restart(); - context.enter(modeBrowse(context)); - var box = pointBox(entity.loc, context); - var textId = context.lastPointerType() === "mouse" ? "rightclick" : "edit_menu_touch"; - reveal(box, helpHtml("intro.points." + textId), { duration: 600 }); - timeout2(function() { - context.map().on("move.intro", function() { - var entity2 = context.hasEntity(_pointID); - if (!entity2) - return chapter.restart(); - var box2 = pointBox(entity2.loc, context); - reveal(box2, helpHtml("intro.points." + textId), { duration: 0 }); - }); - }, 600); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") - return; - var ids = context.selectedIDs(); - if (ids.length !== 1 || ids[0] !== _pointID) - return; - timeout2(function() { - var node = selectMenuItem(context, "delete").node(); - if (!node) - return; - continueTo(enterDelete); - }, 50); + context.on("enter.info-history", function() { + selection2.call(redraw); }); - function continueTo(nextStep) { - context.on("enter.intro", null); - context.map().on("move.intro", null); - nextStep(); + }; + panel.off = function() { + context.map().on("drawn.info-history", null); + context.on("enter.info-history", null); + }; + panel.id = "history"; + panel.label = _t.append("info_panels.history.title"); + panel.key = _t("info_panels.history.key"); + return panel; + } + + // modules/ui/panels/location.js + function uiPanelLocation(context) { + var currLocation = ""; + function redraw(selection2) { + selection2.html(""); + var list2 = selection2.append("ul"); + var coord2 = context.map().mouseCoordinates(); + if (coord2.some(isNaN)) { + coord2 = context.map().center(); } + list2.append("li").text(dmsCoordinatePair(coord2)).append("li").text(decimalCoordinatePair(coord2)); + selection2.append("div").attr("class", "location-info").text(currLocation || " "); + debouncedGetLocation(selection2, coord2); } - function enterDelete() { - if (!_pointID) - return chapter.restart(); - var entity = context.hasEntity(_pointID); - if (!entity) - return chapter.restart(); - var node = selectMenuItem(context, "delete").node(); - if (!node) { - return continueTo(rightClickPoint); - } - reveal( - ".edit-menu", - helpHtml("intro.points.delete"), - { padding: 50 } - ); - timeout2(function() { - context.map().on("move.intro", function() { - reveal( - ".edit-menu", - helpHtml("intro.points.delete"), - { duration: 0, padding: 50 } - ); + var debouncedGetLocation = debounce_default(getLocation, 250); + function getLocation(selection2, coord2) { + if (!services.geocoder) { + currLocation = _t("info_panels.location.unknown_location"); + selection2.selectAll(".location-info").text(currLocation); + } else { + services.geocoder.reverse(coord2, function(err, result) { + currLocation = result ? result.display_name : _t("info_panels.location.unknown_location"); + selection2.selectAll(".location-info").text(currLocation); }); - }, 300); - context.on("exit.intro", function() { - if (!_pointID) - return chapter.restart(); - var entity2 = context.hasEntity(_pointID); - if (entity2) - return continueTo(rightClickPoint); - }); - context.history().on("change.intro", function(changed) { - if (changed.deleted().length) { - continueTo(undo); - } - }); - function continueTo(nextStep) { - context.map().on("move.intro", null); - context.history().on("change.intro", null); - context.on("exit.intro", null); - nextStep(); } } - function undo() { - context.history().on("change.intro", function() { - continueTo(play); + var panel = function(selection2) { + selection2.call(redraw); + context.surface().on(("PointerEvent" in window ? "pointer" : "mouse") + "move.info-location", function() { + selection2.call(redraw); }); - reveal( - ".top-toolbar button.undo-button", - helpHtml("intro.points.undo") - ); - function continueTo(nextStep) { - context.history().on("change.intro", null); - nextStep(); - } - } - function play() { - dispatch14.call("done"); - reveal( - ".ideditor", - helpHtml("intro.points.play", { next: _t("intro.areas.title") }), - { - tooltipBox: ".intro-nav-wrap .chapter-area", - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - reveal(".ideditor"); - } - } - ); - } - chapter.enter = function() { - addPoint(); - }; - chapter.exit = function() { - timeouts.forEach(window.clearTimeout); - context.on("enter.intro exit.intro", null); - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); }; - chapter.restart = function() { - chapter.exit(); - chapter.enter(); + panel.off = function() { + context.surface().on(".info-location", null); }; - return utilRebind(chapter, dispatch14, "on"); + panel.id = "location"; + panel.label = _t.append("info_panels.location.title"); + panel.key = _t("info_panels.location.key"); + return panel; } - // modules/ui/intro/area.js - function uiIntroArea(context, reveal) { - var dispatch14 = dispatch_default("done"); - var playground = [-85.63552, 41.94159]; - var playgroundPreset = _mainPresetIndex.item("leisure/playground"); - var nameField = _mainPresetIndex.field("name"); - var descriptionField = _mainPresetIndex.field("description"); - var timeouts = []; - var _areaID; - var chapter = { - title: "intro.areas.title" - }; - function timeout2(f3, t2) { - timeouts.push(window.setTimeout(f3, t2)); - } - function eventCancel(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); + // modules/ui/panels/measurement.js + function uiPanelMeasurement(context) { + function radiansToMeters(r2) { + return r2 * 63710071809e-4; } - function revealPlayground(center, text2, options2) { - var padding = 180 * Math.pow(2, context.map().zoom() - 19.5); - var box = pad(center, padding, context); - reveal(box, text2, options2); + function steradiansToSqmeters(r2) { + return r2 / (4 * Math.PI) * 510065621724e3; } - function addArea() { - context.enter(modeBrowse(context)); - context.history().reset("initial"); - _areaID = null; - var msec = transitionTime(playground, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); + function toLineString(feature3) { + if (feature3.type === "LineString") + return feature3; + var result = { type: "LineString", coordinates: [] }; + if (feature3.type === "Polygon") { + result.coordinates = feature3.coordinates[0]; + } else if (feature3.type === "MultiPolygon") { + result.coordinates = feature3.coordinates[0][0]; } - context.map().centerZoomEase(playground, 19, msec); - timeout2(function() { - var tooltip = reveal( - "button.add-area", - helpHtml("intro.areas.add_playground") - ); - tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-areas"); - context.on("enter.intro", function(mode) { - if (mode.id !== "add-area") - return; - continueTo(startPlayground); + return result; + } + var _isImperial = !_mainLocalizer.usesMetric(); + function redraw(selection2) { + var graph = context.graph(); + var selectedNoteID = context.selectedNoteID(); + var osm = services.osm; + var localeCode = _mainLocalizer.localeCode(); + var heading2; + var center, location, centroid; + var closed, geometry; + var totalNodeCount, length2 = 0, area = 0, distance; + if (selectedNoteID && osm) { + var note = osm.getNote(selectedNoteID); + heading2 = _t.html("note.note") + " " + selectedNoteID; + location = note.loc; + geometry = "note"; + } else { + var selectedIDs = context.selectedIDs().filter(function(id2) { + return context.hasEntity(id2); }); - }, msec + 100); - function continueTo(nextStep) { - context.on("enter.intro", null); - nextStep(); + var selected = selectedIDs.map(function(id2) { + return context.entity(id2); + }); + heading2 = selected.length === 1 ? selected[0].id : _t.html("info_panels.selected", { n: selected.length }); + if (selected.length) { + var extent = geoExtent(); + for (var i3 in selected) { + var entity = selected[i3]; + extent._extend(entity.extent(graph)); + geometry = entity.geometry(graph); + if (geometry === "line" || geometry === "area") { + closed = entity.type === "relation" || entity.isClosed() && !entity.isDegenerate(); + var feature3 = entity.asGeoJSON(graph); + length2 += radiansToMeters(length_default(toLineString(feature3))); + centroid = path_default(context.projection).centroid(entity.asGeoJSON(graph)); + centroid = centroid && context.projection.invert(centroid); + if (!centroid || !isFinite(centroid[0]) || !isFinite(centroid[1])) { + centroid = entity.extent(graph).center(); + } + if (closed) { + area += steradiansToSqmeters(entity.area(graph)); + } + } + } + if (selected.length > 1) { + geometry = null; + closed = null; + centroid = null; + } + if (selected.length === 2 && selected[0].type === "node" && selected[1].type === "node") { + distance = geoSphericalDistance(selected[0].loc, selected[1].loc); + } + if (selected.length === 1 && selected[0].type === "node") { + location = selected[0].loc; + } else { + totalNodeCount = utilGetAllNodes(selectedIDs, context.graph()).length; + } + if (!location && !centroid) { + center = extent.center(); + } + } } - } - function startPlayground() { - if (context.mode().id !== "add-area") { - return chapter.restart(); + selection2.html(""); + if (heading2) { + selection2.append("h4").attr("class", "measurement-heading").html(heading2); } - _areaID = null; - context.map().zoomEase(19.5, 500); - timeout2(function() { - var textId = context.lastPointerType() === "mouse" ? "starting_node_click" : "starting_node_tap"; - var startDrawString = helpHtml("intro.areas.start_playground") + helpHtml("intro.areas." + textId); - revealPlayground( - playground, - startDrawString, - { duration: 250 } + var list2 = selection2.append("ul"); + var coordItem; + if (geometry) { + list2.append("li").call(_t.append("info_panels.measurement.geometry", { suffix: ":" })).append("span").html( + closed ? _t.html("info_panels.measurement.closed_" + geometry) : _t.html("geometry." + geometry) ); - timeout2(function() { - context.map().on("move.intro drawn.intro", function() { - revealPlayground( - playground, - startDrawString, - { duration: 0 } - ); - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "draw-area") - return chapter.restart(); - continueTo(continuePlayground); - }); - }, 250); - }, 550); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); } - } - function continuePlayground() { - if (context.mode().id !== "draw-area") { - return chapter.restart(); + if (totalNodeCount) { + list2.append("li").call(_t.append("info_panels.measurement.node_count", { suffix: ":" })).append("span").text(totalNodeCount.toLocaleString(localeCode)); } - _areaID = null; - revealPlayground( - playground, - helpHtml("intro.areas.continue_playground"), - { duration: 250 } - ); - timeout2(function() { - context.map().on("move.intro drawn.intro", function() { - revealPlayground( - playground, - helpHtml("intro.areas.continue_playground"), - { duration: 0 } - ); - }); - }, 250); - context.on("enter.intro", function(mode) { - if (mode.id === "draw-area") { - var entity = context.hasEntity(context.selectedIDs()[0]); - if (entity && entity.nodes.length >= 6) { - return continueTo(finishPlayground); - } else { - return; - } - } else if (mode.id === "select") { - _areaID = context.selectedIDs()[0]; - return continueTo(searchPresets); - } else { - return chapter.restart(); - } - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); + if (area) { + list2.append("li").call(_t.append("info_panels.measurement.area", { suffix: ":" })).append("span").text(displayArea(area, _isImperial)); } - } - function finishPlayground() { - if (context.mode().id !== "draw-area") { - return chapter.restart(); + if (length2) { + list2.append("li").call(_t.append("info_panels.measurement." + (closed ? "perimeter" : "length"), { suffix: ":" })).append("span").text(displayLength(length2, _isImperial)); } - _areaID = null; - var finishString = helpHtml("intro.areas.finish_area_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.areas.finish_playground"); - revealPlayground( - playground, - finishString, - { duration: 250 } - ); - timeout2(function() { - context.map().on("move.intro drawn.intro", function() { - revealPlayground( - playground, - finishString, - { duration: 0 } - ); + if (typeof distance === "number") { + list2.append("li").call(_t.append("info_panels.measurement.distance", { suffix: ":" })).append("span").text(displayLength(distance, _isImperial)); + } + if (location) { + coordItem = list2.append("li").call(_t.append("info_panels.measurement.location", { suffix: ":" })); + coordItem.append("span").text(dmsCoordinatePair(location)); + coordItem.append("span").text(decimalCoordinatePair(location)); + } + if (centroid) { + coordItem = list2.append("li").call(_t.append("info_panels.measurement.centroid", { suffix: ":" })); + coordItem.append("span").text(dmsCoordinatePair(centroid)); + coordItem.append("span").text(decimalCoordinatePair(centroid)); + } + if (center) { + coordItem = list2.append("li").call(_t.append("info_panels.measurement.center", { suffix: ":" })); + coordItem.append("span").text(dmsCoordinatePair(center)); + coordItem.append("span").text(decimalCoordinatePair(center)); + } + if (length2 || area || typeof distance === "number") { + var toggle = _isImperial ? "imperial" : "metric"; + selection2.append("a").call(_t.append("info_panels.measurement." + toggle)).attr("href", "#").attr("class", "button button-toggle-units").on("click", function(d3_event) { + d3_event.preventDefault(); + _isImperial = !_isImperial; + selection2.call(redraw); }); - }, 250); - context.on("enter.intro", function(mode) { - if (mode.id === "draw-area") { - return; - } else if (mode.id === "select") { - _areaID = context.selectedIDs()[0]; - return continueTo(searchPresets); - } else { - return chapter.restart(); - } - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); } } - function searchPresets() { - if (!_areaID || !context.hasEntity(_areaID)) { - return addArea(); + var panel = function(selection2) { + selection2.call(redraw); + context.map().on("drawn.info-measurement", function() { + selection2.call(redraw); + }); + context.on("enter.info-measurement", function() { + selection2.call(redraw); + }); + }; + panel.off = function() { + context.map().on("drawn.info-measurement", null); + context.on("enter.info-measurement", null); + }; + panel.id = "measurement"; + panel.label = _t.append("info_panels.measurement.title"); + panel.key = _t("info_panels.measurement.key"); + return panel; + } + + // modules/ui/panels/index.js + var uiInfoPanels = { + background: uiPanelBackground, + history: uiPanelHistory, + location: uiPanelLocation, + measurement: uiPanelMeasurement + }; + + // modules/ui/info.js + function uiInfo(context) { + var ids = Object.keys(uiInfoPanels); + var wasActive = ["measurement"]; + var panels = {}; + var active = {}; + ids.forEach(function(k2) { + if (!panels[k2]) { + panels[k2] = uiInfoPanels[k2](context); + active[k2] = false; } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { - context.enter(modeSelect(context, [_areaID])); + }); + function info(selection2) { + function redraw() { + var activeids = ids.filter(function(k2) { + return active[k2]; + }).sort(); + var containers = infoPanels.selectAll(".panel-container").data(activeids, function(k2) { + return k2; + }); + containers.exit().style("opacity", 1).transition().duration(200).style("opacity", 0).on("end", function(d2) { + select_default2(this).call(panels[d2].off).remove(); + }); + var enter = containers.enter().append("div").attr("class", function(d2) { + return "fillD2 panel-container panel-container-" + d2; + }); + enter.style("opacity", 0).transition().duration(200).style("opacity", 1); + var title = enter.append("div").attr("class", "panel-title fillD2"); + title.append("h3").each(function(d2) { + return panels[d2].label(select_default2(this)); + }); + title.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function(d3_event, d2) { + d3_event.stopImmediatePropagation(); + d3_event.preventDefault(); + info.toggle(d2); + }).call(svgIcon("#iD-icon-close")); + enter.append("div").attr("class", function(d2) { + return "panel-content panel-content-" + d2; + }); + infoPanels.selectAll(".panel-content").each(function(d2) { + select_default2(this).call(panels[d2]); + }); } - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - timeout2(function() { - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); - reveal( - ".preset-search-input", - helpHtml("intro.areas.search_playground", { preset: playgroundPreset.name() }) - ); - }, 400); - context.on("enter.intro", function(mode) { - if (!_areaID || !context.hasEntity(_areaID)) { - return continueTo(addArea); - } - var ids2 = context.selectedIDs(); - if (mode.id !== "select" || !ids2.length || ids2[0] !== _areaID) { - context.enter(modeSelect(context, [_areaID])); - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); - reveal( - ".preset-search-input", - helpHtml("intro.areas.search_playground", { preset: playgroundPreset.name() }) - ); - context.history().on("change.intro", null); + info.toggle = function(which) { + var activeids = ids.filter(function(k2) { + return active[k2]; + }); + if (which) { + active[which] = !active[which]; + if (activeids.length === 1 && activeids[0] === which) { + wasActive = [which]; + } + context.container().select("." + which + "-panel-toggle-item").classed("active", active[which]).select("input").property("checked", active[which]); + } else { + if (activeids.length) { + wasActive = activeids; + activeids.forEach(function(k2) { + active[k2] = false; + }); + } else { + wasActive.forEach(function(k2) { + active[k2] = true; + }); + } } + redraw(); + }; + var infoPanels = selection2.selectAll(".info-panels").data([0]); + infoPanels = infoPanels.enter().append("div").attr("class", "info-panels").merge(infoPanels); + redraw(); + context.keybinding().on(uiCmd("\u2318" + _t("info_panels.key")), function(d3_event) { + d3_event.stopImmediatePropagation(); + d3_event.preventDefault(); + info.toggle(); }); - function checkPresetSearch() { - var first = context.container().select(".preset-list-item:first-child"); - if (first.classed("preset-leisure-playground")) { - reveal( - first.select(".preset-list-button").node(), - helpHtml("intro.areas.choose_playground", { preset: playgroundPreset.name() }), - { duration: 300 } - ); - context.container().select(".preset-search-input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); - context.history().on("change.intro", function() { - continueTo(clickAddField); - }); - } - } - function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.on("enter.intro", null); - context.history().on("change.intro", null); - context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); - nextStep(); + ids.forEach(function(k2) { + var key = _t("info_panels." + k2 + ".key", { default: null }); + if (!key) + return; + context.keybinding().on(uiCmd("\u2318\u21E7" + key), function(d3_event) { + d3_event.stopImmediatePropagation(); + d3_event.preventDefault(); + info.toggle(k2); + }); + }); + } + return info; + } + + // modules/ui/intro/helper.js + function pointBox(loc, context) { + var rect = context.surfaceRect(); + var point2 = context.curtainProjection(loc); + return { + left: point2[0] + rect.left - 40, + top: point2[1] + rect.top - 60, + width: 80, + height: 90 + }; + } + function pad(locOrBox, padding, context) { + var box; + if (locOrBox instanceof Array) { + var rect = context.surfaceRect(); + var point2 = context.curtainProjection(locOrBox); + box = { + left: point2[0] + rect.left, + top: point2[1] + rect.top + }; + } else { + box = locOrBox; + } + return { + left: box.left - padding, + top: box.top - padding, + width: (box.width || 0) + 2 * padding, + height: (box.width || 0) + 2 * padding + }; + } + function icon(name, svgklass, useklass) { + return '"; + } + var helpStringReplacements; + function helpHtml(id2, replacements) { + if (!helpStringReplacements) { + helpStringReplacements = { + // insert icons corresponding to various UI elements + point_icon: icon("#iD-icon-point", "inline"), + line_icon: icon("#iD-icon-line", "inline"), + area_icon: icon("#iD-icon-area", "inline"), + note_icon: icon("#iD-icon-note", "inline add-note"), + plus: icon("#iD-icon-plus", "inline"), + minus: icon("#iD-icon-minus", "inline"), + layers_icon: icon("#iD-icon-layers", "inline"), + data_icon: icon("#iD-icon-data", "inline"), + inspect: icon("#iD-icon-inspect", "inline"), + help_icon: icon("#iD-icon-help", "inline"), + undo_icon: icon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-redo" : "#iD-icon-undo", "inline"), + redo_icon: icon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-undo" : "#iD-icon-redo", "inline"), + save_icon: icon("#iD-icon-save", "inline"), + // operation icons + circularize_icon: icon("#iD-operation-circularize", "inline operation"), + continue_icon: icon("#iD-operation-continue", "inline operation"), + copy_icon: icon("#iD-operation-copy", "inline operation"), + delete_icon: icon("#iD-operation-delete", "inline operation"), + disconnect_icon: icon("#iD-operation-disconnect", "inline operation"), + downgrade_icon: icon("#iD-operation-downgrade", "inline operation"), + extract_icon: icon("#iD-operation-extract", "inline operation"), + merge_icon: icon("#iD-operation-merge", "inline operation"), + move_icon: icon("#iD-operation-move", "inline operation"), + orthogonalize_icon: icon("#iD-operation-orthogonalize", "inline operation"), + paste_icon: icon("#iD-operation-paste", "inline operation"), + reflect_long_icon: icon("#iD-operation-reflect-long", "inline operation"), + reflect_short_icon: icon("#iD-operation-reflect-short", "inline operation"), + reverse_icon: icon("#iD-operation-reverse", "inline operation"), + rotate_icon: icon("#iD-operation-rotate", "inline operation"), + split_icon: icon("#iD-operation-split", "inline operation"), + straighten_icon: icon("#iD-operation-straighten", "inline operation"), + // interaction icons + leftclick: icon("#iD-walkthrough-mouse-left", "inline operation"), + rightclick: icon("#iD-walkthrough-mouse-right", "inline operation"), + mousewheel_icon: icon("#iD-walkthrough-mousewheel", "inline operation"), + tap_icon: icon("#iD-walkthrough-tap", "inline operation"), + doubletap_icon: icon("#iD-walkthrough-doubletap", "inline operation"), + longpress_icon: icon("#iD-walkthrough-longpress", "inline operation"), + touchdrag_icon: icon("#iD-walkthrough-touchdrag", "inline operation"), + pinch_icon: icon("#iD-walkthrough-pinch-apart", "inline operation"), + // insert keys; may be localized and platform-dependent + shift: uiCmd.display("\u21E7"), + alt: uiCmd.display("\u2325"), + return: uiCmd.display("\u21B5"), + esc: _t.html("shortcuts.key.esc"), + space: _t.html("shortcuts.key.space"), + add_note_key: _t.html("modes.add_note.key"), + help_key: _t.html("help.key"), + shortcuts_key: _t.html("shortcuts.toggle.key"), + // reference localized UI labels directly so that they'll always match + save: _t.html("save.title"), + undo: _t.html("undo.title"), + redo: _t.html("redo.title"), + upload: _t.html("commit.save"), + point: _t.html("modes.add_point.title"), + line: _t.html("modes.add_line.title"), + area: _t.html("modes.add_area.title"), + note: _t.html("modes.add_note.label"), + circularize: _t.html("operations.circularize.title"), + continue: _t.html("operations.continue.title"), + copy: _t.html("operations.copy.title"), + delete: _t.html("operations.delete.title"), + disconnect: _t.html("operations.disconnect.title"), + downgrade: _t.html("operations.downgrade.title"), + extract: _t.html("operations.extract.title"), + merge: _t.html("operations.merge.title"), + move: _t.html("operations.move.title"), + orthogonalize: _t.html("operations.orthogonalize.title"), + paste: _t.html("operations.paste.title"), + reflect_long: _t.html("operations.reflect.title.long"), + reflect_short: _t.html("operations.reflect.title.short"), + reverse: _t.html("operations.reverse.title"), + rotate: _t.html("operations.rotate.title"), + split: _t.html("operations.split.title"), + straighten: _t.html("operations.straighten.title"), + map_data: _t.html("map_data.title"), + osm_notes: _t.html("map_data.layers.notes.title"), + fields: _t.html("inspector.fields"), + tags: _t.html("inspector.tags"), + relations: _t.html("inspector.relations"), + new_relation: _t.html("inspector.new_relation"), + turn_restrictions: _t.html("_tagging.presets.fields.restrictions.label"), + background_settings: _t.html("background.description"), + imagery_offset: _t.html("background.fix_misalignment"), + start_the_walkthrough: _t.html("splash.walkthrough"), + help: _t.html("help.title"), + ok: _t.html("intro.ok") + }; + for (var key in helpStringReplacements) { + helpStringReplacements[key] = { html: helpStringReplacements[key] }; } } - function clickAddField() { - if (!_areaID || !context.hasEntity(_areaID)) { - return addArea(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { - return searchPresets(); - } - if (!context.container().select(".form-field-description").empty()) { - return continueTo(describePlayground); - } - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - timeout2(function() { - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - var entity = context.entity(_areaID); - if (entity.tags.description) { - return continueTo(play); - } - var box = context.container().select(".more-fields").node().getBoundingClientRect(); - if (box.top > 300) { - var pane = context.container().select(".entity-editor-pane .inspector-body"); - var start2 = pane.node().scrollTop; - var end = start2 + (box.top - 300); - pane.transition().duration(250).tween("scroll.inspector", function() { - var node = this; - var i3 = number_default(start2, end); - return function(t2) { - node.scrollTop = i3(t2); - }; - }); - } - timeout2(function() { - reveal( - ".more-fields .combobox-input", - helpHtml("intro.areas.add_field", { - name: nameField.title(), - description: descriptionField.title() - }), - { duration: 300 } - ); - context.container().select(".more-fields .combobox-input").on("click.intro", function() { - var watcher; - watcher = window.setInterval(function() { - if (!context.container().select("div.combobox").empty()) { - window.clearInterval(watcher); - continueTo(chooseDescriptionField); - } - }, 300); - }); - }, 300); - }, 400); - context.on("exit.intro", function() { - return continueTo(searchPresets); - }); - function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".more-fields .combobox-input").on("click.intro", null); - context.on("exit.intro", null); - nextStep(); - } + var reps; + if (replacements) { + reps = Object.assign(replacements, helpStringReplacements); + } else { + reps = helpStringReplacements; } - function chooseDescriptionField() { - if (!_areaID || !context.hasEntity(_areaID)) { - return addArea(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { - return searchPresets(); - } - if (!context.container().select(".form-field-description").empty()) { - return continueTo(describePlayground); - } - if (context.container().select("div.combobox").empty()) { - return continueTo(clickAddField); - } - var watcher; - watcher = window.setInterval(function() { - if (context.container().select("div.combobox").empty()) { - window.clearInterval(watcher); - timeout2(function() { - if (context.container().select(".form-field-description").empty()) { - continueTo(retryChooseDescription); - } else { - continueTo(describePlayground); - } - }, 300); - } - }, 300); - reveal( - "div.combobox", - helpHtml("intro.areas.choose_field", { field: descriptionField.title() }), - { duration: 300 } - ); - context.on("exit.intro", function() { - return continueTo(searchPresets); - }); - function continueTo(nextStep) { - if (watcher) - window.clearInterval(watcher); - context.on("exit.intro", null); - nextStep(); - } + return _t.html(id2, reps).replace(/\`(.*?)\`/g, "$1"); + } + function slugify(text) { + return text.toString().toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]+/g, "").replace(/\-\-+/g, "-").replace(/^-+/, "").replace(/-+$/, ""); + } + var missingStrings = {}; + function checkKey(key, text) { + if (_t(key, { default: void 0 }) === void 0) { + if (missingStrings.hasOwnProperty(key)) + return; + missingStrings[key] = text; + var missing = key + ": " + text; + if (typeof console !== "undefined") + console.log(missing); } - function describePlayground() { - if (!_areaID || !context.hasEntity(_areaID)) { - return addArea(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { - return searchPresets(); - } - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - if (context.container().select(".form-field-description").empty()) { - return continueTo(retryChooseDescription); - } - context.on("exit.intro", function() { - continueTo(play); - }); - reveal( - ".entity-editor-pane", - helpHtml("intro.areas.describe_playground", { button: { html: icon("#iD-icon-close", "inline") } }), - { duration: 300 } - ); - function continueTo(nextStep) { - context.on("exit.intro", null); - nextStep(); - } + } + function localize(obj) { + var key; + var name = obj.tags && obj.tags.name; + if (name) { + key = "intro.graph.name." + slugify(name); + obj.tags.name = _t(key, { default: name }); + checkKey(key, name); } - function retryChooseDescription() { - if (!_areaID || !context.hasEntity(_areaID)) { - return addArea(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { - return searchPresets(); - } - context.container().select(".inspector-wrap .panewrap").style("right", "0%"); - reveal( - ".entity-editor-pane", - helpHtml("intro.areas.retry_add_field", { field: descriptionField.title() }), - { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(clickAddField); + var street = obj.tags && obj.tags["addr:street"]; + if (street) { + key = "intro.graph.name." + slugify(street); + obj.tags["addr:street"] = _t(key, { default: street }); + checkKey(key, street); + var addrTags = [ + "block_number", + "city", + "county", + "district", + "hamlet", + "neighbourhood", + "postcode", + "province", + "quarter", + "state", + "subdistrict", + "suburb" + ]; + addrTags.forEach(function(k2) { + var key2 = "intro.graph." + k2; + var tag2 = "addr:" + k2; + var val = obj.tags && obj.tags[tag2]; + var str = _t(key2, { default: val }); + if (str) { + if (str.match(/^<.*>$/) !== null) { + delete obj.tags[tag2]; + } else { + obj.tags[tag2] = str; } } - ); - context.on("exit.intro", function() { - return continueTo(searchPresets); }); - function continueTo(nextStep) { - context.on("exit.intro", null); - nextStep(); + } + return obj; + } + function isMostlySquare(points) { + var threshold = 15; + var lowerBound = Math.cos((90 - threshold) * Math.PI / 180); + var upperBound = Math.cos(threshold * Math.PI / 180); + for (var i3 = 0; i3 < points.length; i3++) { + var a2 = points[(i3 - 1 + points.length) % points.length]; + var origin = points[i3]; + var b2 = points[(i3 + 1) % points.length]; + var dotp = geoVecNormalizedDot(a2, b2, origin); + var mag = Math.abs(dotp); + if (mag > lowerBound && mag < upperBound) { + return false; } } - function play() { - dispatch14.call("done"); - reveal( - ".ideditor", - helpHtml("intro.areas.play", { next: _t("intro.lines.title") }), - { - tooltipBox: ".intro-nav-wrap .chapter-line", - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - reveal(".ideditor"); - } - } - ); + return true; + } + function selectMenuItem(context, operation2) { + return context.container().select(".edit-menu .edit-menu-item-" + operation2); + } + function transitionTime(point1, point2) { + var distance = geoSphericalDistance(point1, point2); + if (distance === 0) { + return 0; + } else if (distance < 80) { + return 500; + } else { + return 1e3; } - chapter.enter = function() { - addArea(); - }; - chapter.exit = function() { - timeouts.forEach(window.clearTimeout); - context.on("enter.intro exit.intro", null); - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); - context.container().select(".more-fields .combobox-input").on("click.intro", null); - }; - chapter.restart = function() { - chapter.exit(); - chapter.enter(); - }; - return utilRebind(chapter, dispatch14, "on"); } - // modules/ui/intro/line.js - function uiIntroLine(context, reveal) { - var dispatch14 = dispatch_default("done"); - var timeouts = []; - var _tulipRoadID = null; - var flowerRoadID = "w646"; - var tulipRoadStart = [-85.6297754121684, 41.95805253325314]; - var tulipRoadMidpoint = [-85.62975395449628, 41.95787501510204]; - var tulipRoadIntersection = [-85.62974496187628, 41.95742515554585]; - var roadCategory = _mainPresetIndex.item("category-road_minor"); - var residentialPreset = _mainPresetIndex.item("highway/residential"); - var woodRoadID = "w525"; - var woodRoadEndID = "n2862"; - var woodRoadAddNode = [-85.62390110349587, 41.95397111462291]; - var woodRoadDragEndpoint = [-85.623867390213, 41.95466987786487]; - var woodRoadDragMidpoint = [-85.62386254803509, 41.95430395953872]; - var washingtonStreetID = "w522"; - var twelfthAvenueID = "w1"; - var eleventhAvenueEndID = "n3550"; - var twelfthAvenueEndID = "n5"; - var _washingtonSegmentID = null; - var eleventhAvenueEnd = context.entity(eleventhAvenueEndID).loc; - var twelfthAvenueEnd = context.entity(twelfthAvenueEndID).loc; - var deleteLinesLoc = [-85.6219395542764, 41.95228033922477]; - var twelfthAvenue = [-85.62219310052491, 41.952505413152956]; - var chapter = { - title: "intro.lines.title" + // modules/ui/toggle.js + function uiToggle(show, callback) { + return function(selection2) { + selection2.style("opacity", show ? 0 : 1).classed("hide", false).transition().style("opacity", show ? 1 : 0).on("end", function() { + select_default2(this).classed("hide", !show).style("opacity", null); + if (callback) + callback.apply(this); + }); }; - function timeout2(f3, t2) { - timeouts.push(window.setTimeout(f3, t2)); - } - function eventCancel(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); + } + + // modules/ui/curtain.js + function uiCurtain(containerNode) { + var surface = select_default2(null), tooltip = select_default2(null), darkness = select_default2(null); + function curtain(selection2) { + surface = selection2.append("svg").attr("class", "curtain").style("top", 0).style("left", 0); + darkness = surface.append("path").attr("x", 0).attr("y", 0).attr("class", "curtain-darkness"); + select_default2(window).on("resize.curtain", resize); + tooltip = selection2.append("div").attr("class", "tooltip"); + tooltip.append("div").attr("class", "popover-arrow"); + tooltip.append("div").attr("class", "popover-inner"); + resize(); + function resize() { + surface.attr("width", containerNode.clientWidth).attr("height", containerNode.clientHeight); + curtain.cut(darkness.datum()); + } } - function addLine() { - context.enter(modeBrowse(context)); - context.history().reset("initial"); - var msec = transitionTime(tulipRoadStart, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); + curtain.reveal = function(box, html3, options2) { + options2 = options2 || {}; + if (typeof box === "string") { + box = select_default2(box).node(); } - context.map().centerZoomEase(tulipRoadStart, 18.5, msec); - timeout2(function() { - var tooltip = reveal( - "button.add-line", - helpHtml("intro.lines.add_line") - ); - tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-lines"); - context.on("enter.intro", function(mode) { - if (mode.id !== "add-line") - return; - continueTo(startLine); - }); - }, msec + 100); - function continueTo(nextStep) { - context.on("enter.intro", null); - nextStep(); + if (box && box.getBoundingClientRect) { + box = copyBox(box.getBoundingClientRect()); + var containerRect = containerNode.getBoundingClientRect(); + box.top -= containerRect.top; + box.left -= containerRect.left; } - } - function startLine() { - if (context.mode().id !== "add-line") - return chapter.restart(); - _tulipRoadID = null; - var padding = 70 * Math.pow(2, context.map().zoom() - 18); - var box = pad(tulipRoadStart, padding, context); - box.height = box.height + 100; - var textId = context.lastPointerType() === "mouse" ? "start_line" : "start_line_tap"; - var startLineString = helpHtml("intro.lines.missing_road") + "{br}" + helpHtml("intro.lines.line_draw_info") + helpHtml("intro.lines." + textId); - reveal(box, startLineString); - context.map().on("move.intro drawn.intro", function() { - padding = 70 * Math.pow(2, context.map().zoom() - 18); - box = pad(tulipRoadStart, padding, context); - box.height = box.height + 100; - reveal(box, startLineString, { duration: 0 }); - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "draw-line") - return chapter.restart(); - continueTo(drawLine); - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); + if (box && options2.padding) { + box.top -= options2.padding; + box.left -= options2.padding; + box.bottom += options2.padding; + box.right += options2.padding; + box.height += options2.padding * 2; + box.width += options2.padding * 2; } - } - function drawLine() { - if (context.mode().id !== "draw-line") - return chapter.restart(); - _tulipRoadID = context.mode().selectedIDs()[0]; - context.map().centerEase(tulipRoadMidpoint, 500); - timeout2(function() { - var padding = 200 * Math.pow(2, context.map().zoom() - 18.5); - var box = pad(tulipRoadMidpoint, padding, context); - box.height = box.height * 2; - reveal( - box, - helpHtml("intro.lines.intersect", { name: _t("intro.graph.name.flower-street") }) - ); - context.map().on("move.intro drawn.intro", function() { - padding = 200 * Math.pow(2, context.map().zoom() - 18.5); - box = pad(tulipRoadMidpoint, padding, context); - box.height = box.height * 2; - reveal( - box, - helpHtml("intro.lines.intersect", { name: _t("intro.graph.name.flower-street") }), - { duration: 0 } - ); - }); - }, 550); - context.history().on("change.intro", function() { - if (isLineConnected()) { - continueTo(continueLine); + var tooltipBox; + if (options2.tooltipBox) { + tooltipBox = options2.tooltipBox; + if (typeof tooltipBox === "string") { + tooltipBox = select_default2(tooltipBox).node(); } - }); - context.on("enter.intro", function(mode) { - if (mode.id === "draw-line") { - return; - } else if (mode.id === "select") { - continueTo(retryIntersect); - return; + if (tooltipBox && tooltipBox.getBoundingClientRect) { + tooltipBox = copyBox(tooltipBox.getBoundingClientRect()); + } + } else { + tooltipBox = box; + } + if (tooltipBox && html3) { + if (html3.indexOf("**") !== -1) { + if (html3.indexOf(")(.+?)(\*\*)/, "$1$2$3"); + } else { + html3 = html3.replace(/^(.+?)(\*\*)/, "$1$2"); + } + html3 = html3.replace(/\*\*(.*?)\*\*/g, '$1'); + } + html3 = html3.replace(/\*(.*?)\*/g, "$1"); + html3 = html3.replace(/\{br\}/g, "

    "); + if (options2.buttonText && options2.buttonCallback) { + html3 += '
    "; + } + var classes = "curtain-tooltip popover tooltip arrowed in " + (options2.tooltipClass || ""); + tooltip.classed(classes, true).selectAll(".popover-inner").html(html3); + if (options2.buttonText && options2.buttonCallback) { + var button = tooltip.selectAll(".button-section .button.action"); + button.on("click", function(d3_event) { + d3_event.preventDefault(); + options2.buttonCallback(); + }); + } + var tip = copyBox(tooltip.node().getBoundingClientRect()), w2 = containerNode.clientWidth, h2 = containerNode.clientHeight, tooltipWidth = 200, tooltipArrow = 5, side, pos; + if (options2.tooltipClass === "intro-mouse") { + tip.height += 80; + } + if (tooltipBox.top + tooltipBox.height > h2) { + tooltipBox.height -= tooltipBox.top + tooltipBox.height - h2; + } + if (tooltipBox.left + tooltipBox.width > w2) { + tooltipBox.width -= tooltipBox.left + tooltipBox.width - w2; + } + if (tooltipBox.top + tooltipBox.height < 100) { + side = "bottom"; + pos = [ + tooltipBox.left + tooltipBox.width / 2 - tip.width / 2, + tooltipBox.top + tooltipBox.height + ]; + } else if (tooltipBox.top > h2 - 140) { + side = "top"; + pos = [ + tooltipBox.left + tooltipBox.width / 2 - tip.width / 2, + tooltipBox.top - tip.height + ]; } else { - return chapter.restart(); + var tipY = tooltipBox.top + tooltipBox.height / 2 - tip.height / 2; + if (_mainLocalizer.textDirection() === "rtl") { + if (tooltipBox.left - tooltipWidth - tooltipArrow < 70) { + side = "right"; + pos = [tooltipBox.left + tooltipBox.width + tooltipArrow, tipY]; + } else { + side = "left"; + pos = [tooltipBox.left - tooltipWidth - tooltipArrow, tipY]; + } + } else { + if (tooltipBox.left + tooltipBox.width + tooltipArrow + tooltipWidth > w2 - 70) { + side = "left"; + pos = [tooltipBox.left - tooltipWidth - tooltipArrow, tipY]; + } else { + side = "right"; + pos = [tooltipBox.left + tooltipBox.width + tooltipArrow, tipY]; + } + } } - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - context.on("enter.intro", null); - nextStep(); + if (options2.duration !== 0 || !tooltip.classed(side)) { + tooltip.call(uiToggle(true)); + } + tooltip.style("top", pos[1] + "px").style("left", pos[0] + "px").attr("class", classes + " " + side); + var shiftY = 0; + if (side === "left" || side === "right") { + if (pos[1] < 60) { + shiftY = 60 - pos[1]; + } else if (pos[1] + tip.height > h2 - 100) { + shiftY = h2 - pos[1] - tip.height - 100; + } + } + tooltip.selectAll(".popover-inner").style("top", shiftY + "px"); + } else { + tooltip.classed("in", false).call(uiToggle(false)); } - } - function isLineConnected() { - var entity = _tulipRoadID && context.hasEntity(_tulipRoadID); - if (!entity) - return false; - var drawNodes = context.graph().childNodes(entity); - return drawNodes.some(function(node) { - return context.graph().parentWays(node).some(function(parent) { - return parent.id === flowerRoadID; - }); + curtain.cut(box, options2.duration); + return tooltip; + }; + curtain.cut = function(datum2, duration) { + darkness.datum(datum2).interrupt(); + var selection2; + if (duration === 0) { + selection2 = darkness; + } else { + selection2 = darkness.transition().duration(duration || 600).ease(linear2); + } + selection2.attr("d", function(d2) { + var containerWidth = containerNode.clientWidth; + var containerHeight = containerNode.clientHeight; + var string = "M 0,0 L 0," + containerHeight + " L " + containerWidth + "," + containerHeight + "L" + containerWidth + ",0 Z"; + if (!d2) + return string; + return string + "M" + d2.left + "," + d2.top + "L" + d2.left + "," + (d2.top + d2.height) + "L" + (d2.left + d2.width) + "," + (d2.top + d2.height) + "L" + (d2.left + d2.width) + "," + d2.top + "Z"; }); + }; + curtain.remove = function() { + surface.remove(); + tooltip.remove(); + select_default2(window).on("resize.curtain", null); + }; + function copyBox(src) { + return { + top: src.top, + right: src.right, + bottom: src.bottom, + left: src.left, + width: src.width, + height: src.height + }; } - function retryIntersect() { - select_default2(window).on("pointerdown.intro mousedown.intro", eventCancel, true); - var box = pad(tulipRoadIntersection, 80, context); + return curtain; + } + + // modules/ui/intro/welcome.js + function uiIntroWelcome(context, reveal) { + var dispatch14 = dispatch_default("done"); + var chapter = { + title: "intro.welcome.title" + }; + function welcome() { + context.map().centerZoom([-85.63591, 41.94285], 19); reveal( - box, - helpHtml("intro.lines.retry_intersect", { name: _t("intro.graph.name.flower-street") }) + ".intro-nav-wrap .chapter-welcome", + helpHtml("intro.welcome.welcome"), + { buttonText: _t.html("intro.ok"), buttonCallback: practice } ); - timeout2(chapter.restart, 3e3); } - function continueLine() { - if (context.mode().id !== "draw-line") - return chapter.restart(); - var entity = _tulipRoadID && context.hasEntity(_tulipRoadID); - if (!entity) - return chapter.restart(); - context.map().centerEase(tulipRoadIntersection, 500); - var continueLineText = helpHtml("intro.lines.continue_line") + "{br}" + helpHtml("intro.lines.finish_line_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.lines.finish_road"); - reveal(".surface", continueLineText); - context.on("enter.intro", function(mode) { - if (mode.id === "draw-line") { - return; - } else if (mode.id === "select") { - return continueTo(chooseCategoryRoad); - } else { - return chapter.restart(); - } - }); - function continueTo(nextStep) { - context.on("enter.intro", null); - nextStep(); - } + function practice() { + reveal( + ".intro-nav-wrap .chapter-welcome", + helpHtml("intro.welcome.practice"), + { buttonText: _t.html("intro.ok"), buttonCallback: words } + ); } - function chooseCategoryRoad() { - if (context.mode().id !== "select") - return chapter.restart(); - context.on("exit.intro", function() { - return chapter.restart(); - }); - var button = context.container().select(".preset-category-road_minor .preset-list-button"); - if (button.empty()) - return chapter.restart(); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - timeout2(function() { - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - reveal( - button.node(), - helpHtml("intro.lines.choose_category_road", { category: roadCategory.name() }) - ); - button.on("click.intro", function() { - continueTo(choosePresetResidential); - }); - }, 400); - function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-list-button").on("click.intro", null); - context.on("exit.intro", null); - nextStep(); - } + function words() { + reveal( + ".intro-nav-wrap .chapter-welcome", + helpHtml("intro.welcome.words"), + { buttonText: _t.html("intro.ok"), buttonCallback: chapters } + ); } - function choosePresetResidential() { - if (context.mode().id !== "select") - return chapter.restart(); - context.on("exit.intro", function() { - return chapter.restart(); - }); - var subgrid = context.container().select(".preset-category-road_minor .subgrid"); - if (subgrid.empty()) - return chapter.restart(); - subgrid.selectAll(":not(.preset-highway-residential) .preset-list-button").on("click.intro", function() { - continueTo(retryPresetResidential); - }); - subgrid.selectAll(".preset-highway-residential .preset-list-button").on("click.intro", function() { - continueTo(nameRoad); - }); - timeout2(function() { - reveal( - subgrid.node(), - helpHtml("intro.lines.choose_preset_residential", { preset: residentialPreset.name() }), - { tooltipBox: ".preset-highway-residential .preset-list-button", duration: 300 } - ); - }, 300); - function continueTo(nextStep) { - context.container().select(".preset-list-button").on("click.intro", null); - context.on("exit.intro", null); - nextStep(); - } + function chapters() { + dispatch14.call("done"); + reveal( + ".intro-nav-wrap .chapter-navigation", + helpHtml("intro.welcome.chapters", { next: _t("intro.navigation.title") }) + ); } - function retryPresetResidential() { - if (context.mode().id !== "select") - return chapter.restart(); - context.on("exit.intro", function() { - return chapter.restart(); - }); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - timeout2(function() { - var button = context.container().select(".entity-editor-pane .preset-list-button"); - reveal( - button.node(), - helpHtml("intro.lines.retry_preset_residential", { preset: residentialPreset.name() }) - ); - button.on("click.intro", function() { - continueTo(chooseCategoryRoad); - }); - }, 500); - function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-list-button").on("click.intro", null); - context.on("exit.intro", null); - nextStep(); - } + chapter.enter = function() { + welcome(); + }; + chapter.exit = function() { + context.container().select(".curtain-tooltip.intro-mouse").selectAll(".counter").remove(); + }; + chapter.restart = function() { + chapter.exit(); + chapter.enter(); + }; + return utilRebind(chapter, dispatch14, "on"); + } + + // modules/ui/intro/navigation.js + function uiIntroNavigation(context, reveal) { + var dispatch14 = dispatch_default("done"); + var timeouts = []; + var hallId = "n2061"; + var townHall = [-85.63591, 41.94285]; + var springStreetId = "w397"; + var springStreetEndId = "n1834"; + var springStreet = [-85.63582, 41.94255]; + var onewayField = _mainPresetIndex.field("oneway"); + var maxspeedField = _mainPresetIndex.field("maxspeed"); + var chapter = { + title: "intro.navigation.title" + }; + function timeout2(f2, t2) { + timeouts.push(window.setTimeout(f2, t2)); } - function nameRoad() { - context.on("exit.intro", function() { - continueTo(didNameRoad); - }); - timeout2(function() { - reveal( - ".entity-editor-pane", - helpHtml("intro.lines.name_road", { button: { html: icon("#iD-icon-close", "inline") } }), - { tooltipClass: "intro-lines-name_road" } - ); - }, 500); - function continueTo(nextStep) { - context.on("exit.intro", null); - nextStep(); - } + function eventCancel(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); } - function didNameRoad() { - context.history().checkpoint("doneAddLine"); - timeout2(function() { - reveal(".surface", helpHtml("intro.lines.did_name_road"), { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(updateLine); - } - }); - }, 500); - function continueTo(nextStep) { - nextStep(); - } + function isTownHallSelected() { + var ids = context.selectedIDs(); + return ids.length === 1 && ids[0] === hallId; } - function updateLine() { - context.history().reset("doneAddLine"); - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return chapter.restart(); - } - var msec = transitionTime(woodRoadDragMidpoint, context.map().center()); + function dragMap() { + context.enter(modeBrowse(context)); + context.history().reset("initial"); + var msec = transitionTime(townHall, context.map().center()); if (msec) { reveal(null, null, { duration: 0 }); } - context.map().centerZoomEase(woodRoadDragMidpoint, 19, msec); + context.map().centerZoomEase(townHall, 19, msec); timeout2(function() { - var padding = 250 * Math.pow(2, context.map().zoom() - 19); - var box = pad(woodRoadDragMidpoint, padding, context); - var advance = function() { - continueTo(addNode); - }; - reveal( - box, - helpHtml("intro.lines.update_line"), - { buttonText: _t.html("intro.ok"), buttonCallback: advance } - ); - context.map().on("move.intro drawn.intro", function() { - var padding2 = 250 * Math.pow(2, context.map().zoom() - 19); - var box2 = pad(woodRoadDragMidpoint, padding2, context); - reveal( - box2, - helpHtml("intro.lines.update_line"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } - ); + var centerStart = context.map().center(); + var textId = context.lastPointerType() === "mouse" ? "drag" : "drag_touch"; + var dragString = helpHtml("intro.navigation.map_info") + "{br}" + helpHtml("intro.navigation." + textId); + reveal(".surface", dragString); + context.map().on("drawn.intro", function() { + reveal(".surface", dragString, { duration: 0 }); + }); + context.map().on("move.intro", function() { + var centerNow = context.map().center(); + if (centerStart[0] !== centerNow[0] || centerStart[1] !== centerNow[1]) { + context.map().on("move.intro", null); + timeout2(function() { + continueTo(zoomMap); + }, 3e3); + } }); }, msec + 100); function continueTo(nextStep) { @@ -59195,302 +60129,159 @@ nextStep(); } } - function addNode() { - context.history().reset("doneAddLine"); - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return chapter.restart(); - } - var padding = 40 * Math.pow(2, context.map().zoom() - 19); - var box = pad(woodRoadAddNode, padding, context); - var addNodeString = helpHtml("intro.lines.add_node" + (context.lastPointerType() === "mouse" ? "" : "_touch")); - reveal(box, addNodeString); - context.map().on("move.intro drawn.intro", function() { - var padding2 = 40 * Math.pow(2, context.map().zoom() - 19); - var box2 = pad(woodRoadAddNode, padding2, context); - reveal(box2, addNodeString, { duration: 0 }); + function zoomMap() { + var zoomStart = context.map().zoom(); + var textId = context.lastPointerType() === "mouse" ? "zoom" : "zoom_touch"; + var zoomString = helpHtml("intro.navigation." + textId); + reveal(".surface", zoomString); + context.map().on("drawn.intro", function() { + reveal(".surface", zoomString, { duration: 0 }); }); - context.history().on("change.intro", function(changed) { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - if (changed.created().length === 1) { + context.map().on("move.intro", function() { + if (context.map().zoom() !== zoomStart) { + context.map().on("move.intro", null); timeout2(function() { - continueTo(startDragEndpoint); - }, 500); - } - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") { - continueTo(updateLine); - } - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - context.on("enter.intro", null); - nextStep(); - } - } - function startDragEndpoint() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding = 100 * Math.pow(2, context.map().zoom() - 19); - var box = pad(woodRoadDragEndpoint, padding, context); - var startDragString = helpHtml("intro.lines.start_drag_endpoint" + (context.lastPointerType() === "mouse" ? "" : "_touch")) + helpHtml("intro.lines.drag_to_intersection"); - reveal(box, startDragString); - context.map().on("move.intro drawn.intro", function() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding2 = 100 * Math.pow(2, context.map().zoom() - 19); - var box2 = pad(woodRoadDragEndpoint, padding2, context); - reveal(box2, startDragString, { duration: 0 }); - var entity = context.entity(woodRoadEndID); - if (geoSphericalDistance(entity.loc, woodRoadDragEndpoint) <= 4) { - continueTo(finishDragEndpoint); - } - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - nextStep(); - } - } - function finishDragEndpoint() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding = 100 * Math.pow(2, context.map().zoom() - 19); - var box = pad(woodRoadDragEndpoint, padding, context); - var finishDragString = helpHtml("intro.lines.spot_looks_good") + helpHtml("intro.lines.finish_drag_endpoint" + (context.lastPointerType() === "mouse" ? "" : "_touch")); - reveal(box, finishDragString); - context.map().on("move.intro drawn.intro", function() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding2 = 100 * Math.pow(2, context.map().zoom() - 19); - var box2 = pad(woodRoadDragEndpoint, padding2, context); - reveal(box2, finishDragString, { duration: 0 }); - var entity = context.entity(woodRoadEndID); - if (geoSphericalDistance(entity.loc, woodRoadDragEndpoint) > 4) { - continueTo(startDragEndpoint); + continueTo(features); + }, 3e3); } }); - context.on("enter.intro", function() { - continueTo(startDragMidpoint); - }); function continueTo(nextStep) { context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); nextStep(); } } - function startDragMidpoint() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - if (context.selectedIDs().indexOf(woodRoadID) === -1) { - context.enter(modeSelect(context, [woodRoadID])); - } - var padding = 80 * Math.pow(2, context.map().zoom() - 19); - var box = pad(woodRoadDragMidpoint, padding, context); - reveal(box, helpHtml("intro.lines.start_drag_midpoint")); - context.map().on("move.intro drawn.intro", function() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding2 = 80 * Math.pow(2, context.map().zoom() - 19); - var box2 = pad(woodRoadDragMidpoint, padding2, context); - reveal(box2, helpHtml("intro.lines.start_drag_midpoint"), { duration: 0 }); - }); - context.history().on("change.intro", function(changed) { - if (changed.created().length === 1) { - continueTo(continueDragMidpoint); - } - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") { - context.enter(modeSelect(context, [woodRoadID])); - } + function features() { + var onClick = function() { + continueTo(pointsLinesAreas); + }; + reveal( + ".surface", + helpHtml("intro.navigation.features"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + context.map().on("drawn.intro", function() { + reveal( + ".surface", + helpHtml("intro.navigation.features"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - context.on("enter.intro", null); + context.map().on("drawn.intro", null); nextStep(); } } - function continueDragMidpoint() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding = 100 * Math.pow(2, context.map().zoom() - 19); - var box = pad(woodRoadDragEndpoint, padding, context); - box.height += 400; - var advance = function() { - context.history().checkpoint("doneUpdateLine"); - continueTo(deleteLines); + function pointsLinesAreas() { + var onClick = function() { + continueTo(nodesWays); }; reveal( - box, - helpHtml("intro.lines.continue_drag_midpoint"), - { buttonText: _t.html("intro.ok"), buttonCallback: advance } + ".surface", + helpHtml("intro.navigation.points_lines_areas"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } ); - context.map().on("move.intro drawn.intro", function() { - if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { - return continueTo(updateLine); - } - var padding2 = 100 * Math.pow(2, context.map().zoom() - 19); - var box2 = pad(woodRoadDragEndpoint, padding2, context); - box2.height += 400; + context.map().on("drawn.intro", function() { reveal( - box2, - helpHtml("intro.lines.continue_drag_midpoint"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } + ".surface", + helpHtml("intro.navigation.points_lines_areas"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } ); }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); + context.map().on("drawn.intro", null); nextStep(); } } - function deleteLines() { - context.history().reset("doneUpdateLine"); - context.enter(modeBrowse(context)); - if (!context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return chapter.restart(); - } - var msec = transitionTime(deleteLinesLoc, context.map().center()); - if (msec) { - reveal(null, null, { duration: 0 }); - } - context.map().centerZoomEase(deleteLinesLoc, 18, msec); - timeout2(function() { - var padding = 200 * Math.pow(2, context.map().zoom() - 18); - var box = pad(deleteLinesLoc, padding, context); - box.top -= 200; - box.height += 400; - var advance = function() { - continueTo(rightClickIntersection); - }; + function nodesWays() { + var onClick = function() { + continueTo(clickTownHall); + }; + reveal( + ".surface", + helpHtml("intro.navigation.nodes_ways"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + context.map().on("drawn.intro", function() { reveal( - box, - helpHtml("intro.lines.delete_lines", { street: _t("intro.graph.name.12th-avenue") }), - { buttonText: _t.html("intro.ok"), buttonCallback: advance } - ); - context.map().on("move.intro drawn.intro", function() { - var padding2 = 200 * Math.pow(2, context.map().zoom() - 18); - var box2 = pad(deleteLinesLoc, padding2, context); - box2.top -= 200; - box2.height += 400; - reveal( - box2, - helpHtml("intro.lines.delete_lines", { street: _t("intro.graph.name.12th-avenue") }), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } - ); - }); - context.history().on("change.intro", function() { - timeout2(function() { - continueTo(deleteLines); - }, 500); - }); - }, msec + 100); + ".surface", + helpHtml("intro.navigation.nodes_ways"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); + context.map().on("drawn.intro", null); nextStep(); } } - function rightClickIntersection() { - context.history().reset("doneUpdateLine"); + function clickTownHall() { context.enter(modeBrowse(context)); - context.map().centerZoomEase(eleventhAvenueEnd, 18, 500); - var rightClickString = helpHtml("intro.lines.split_street", { - street1: _t("intro.graph.name.11th-avenue"), - street2: _t("intro.graph.name.washington-street") - }) + helpHtml("intro.lines." + (context.lastPointerType() === "mouse" ? "rightclick_intersection" : "edit_menu_intersection_touch")); + context.history().reset("initial"); + var entity = context.hasEntity(hallId); + if (!entity) + return; + reveal(null, null, { duration: 0 }); + context.map().centerZoomEase(entity.loc, 19, 500); timeout2(function() { - var padding = 60 * Math.pow(2, context.map().zoom() - 18); - var box = pad(eleventhAvenueEnd, padding, context); - reveal(box, rightClickString); + var entity2 = context.hasEntity(hallId); + if (!entity2) + return; + var box = pointBox(entity2.loc, context); + var textId = context.lastPointerType() === "mouse" ? "click_townhall" : "tap_townhall"; + reveal(box, helpHtml("intro.navigation." + textId)); context.map().on("move.intro drawn.intro", function() { - var padding2 = 60 * Math.pow(2, context.map().zoom() - 18); - var box2 = pad(eleventhAvenueEnd, padding2, context); - reveal( - box2, - rightClickString, - { duration: 0 } - ); - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") - return; - var ids = context.selectedIDs(); - if (ids.length !== 1 || ids[0] !== eleventhAvenueEndID) + var entity3 = context.hasEntity(hallId); + if (!entity3) return; - timeout2(function() { - var node = selectMenuItem(context, "split").node(); - if (!node) - return; - continueTo(splitIntersection); - }, 50); + var box2 = pointBox(entity3.loc, context); + reveal(box2, helpHtml("intro.navigation." + textId), { duration: 0 }); }); - context.history().on("change.intro", function() { - timeout2(function() { - continueTo(deleteLines); - }, 300); + context.on("enter.intro", function() { + if (isTownHallSelected()) + continueTo(selectedTownHall); }); - }, 600); + }, 550); + context.history().on("change.intro", function() { + if (!context.hasEntity(hallId)) { + continueTo(clickTownHall); + } + }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); context.on("enter.intro", null); + context.map().on("move.intro drawn.intro", null); context.history().on("change.intro", null); nextStep(); } } - function splitIntersection() { - if (!context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(deleteLines); - } - var node = selectMenuItem(context, "split").node(); - if (!node) { - return continueTo(rightClickIntersection); - } - var wasChanged = false; - _washingtonSegmentID = null; + function selectedTownHall() { + if (!isTownHallSelected()) + return clickTownHall(); + var entity = context.hasEntity(hallId); + if (!entity) + return clickTownHall(); + var box = pointBox(entity.loc, context); + var onClick = function() { + continueTo(editorTownHall); + }; reveal( - ".edit-menu", - helpHtml( - "intro.lines.split_intersection", - { street: _t("intro.graph.name.washington-street") } - ), - { padding: 50 } + box, + helpHtml("intro.navigation.selected_townhall"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } ); context.map().on("move.intro drawn.intro", function() { - var node2 = selectMenuItem(context, "split").node(); - if (!wasChanged && !node2) { - return continueTo(rightClickIntersection); - } + var entity2 = context.hasEntity(hallId); + if (!entity2) + return; + var box2 = pointBox(entity2.loc, context); reveal( - ".edit-menu", - helpHtml( - "intro.lines.split_intersection", - { street: _t("intro.graph.name.washington-street") } - ), - { duration: 0, padding: 50 } + box2, + helpHtml("intro.navigation.selected_townhall"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } ); }); - context.history().on("change.intro", function(changed) { - wasChanged = true; - timeout2(function() { - if (context.history().undoAnnotation() === _t("operations.split.annotation.line", { n: 1 })) { - _washingtonSegmentID = changed.created()[0].id; - continueTo(didSplit); - } else { - _washingtonSegmentID = null; - continueTo(retrySplit); - } - }, 300); + context.history().on("change.intro", function() { + if (!context.hasEntity(hallId)) { + continueTo(clickTownHall); + } }); function continueTo(nextStep) { context.map().on("move.intro drawn.intro", null); @@ -59498,250 +60289,234 @@ nextStep(); } } - function retrySplit() { - context.enter(modeBrowse(context)); - context.map().centerZoomEase(eleventhAvenueEnd, 18, 500); - var advance = function() { - continueTo(rightClickIntersection); + function editorTownHall() { + if (!isTownHallSelected()) + return clickTownHall(); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + var onClick = function() { + continueTo(presetTownHall); }; - var padding = 60 * Math.pow(2, context.map().zoom() - 18); - var box = pad(eleventhAvenueEnd, padding, context); reveal( - box, - helpHtml("intro.lines.retry_split"), - { buttonText: _t.html("intro.ok"), buttonCallback: advance } + ".entity-editor-pane", + helpHtml("intro.navigation.editor_townhall"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } ); - context.map().on("move.intro drawn.intro", function() { - var padding2 = 60 * Math.pow(2, context.map().zoom() - 18); - var box2 = pad(eleventhAvenueEnd, padding2, context); - reveal( - box2, - helpHtml("intro.lines.retry_split"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } - ); + context.on("exit.intro", function() { + continueTo(clickTownHall); + }); + context.history().on("change.intro", function() { + if (!context.hasEntity(hallId)) { + continueTo(clickTownHall); + } }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); + context.on("exit.intro", null); + context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); nextStep(); } } - function didSplit() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); - } - var ids = context.selectedIDs(); - var string = "intro.lines.did_split_" + (ids.length > 1 ? "multi" : "single"); - var street = _t("intro.graph.name.washington-street"); - var padding = 200 * Math.pow(2, context.map().zoom() - 18); - var box = pad(twelfthAvenue, padding, context); - box.width = box.width / 2; + function presetTownHall() { + if (!isTownHallSelected()) + return clickTownHall(); + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + var entity = context.entity(context.selectedIDs()[0]); + var preset = _mainPresetIndex.match(entity, context.graph()); + var onClick = function() { + continueTo(fieldsTownHall); + }; reveal( - box, - helpHtml(string, { street1: street, street2: street }), - { duration: 500 } + ".entity-editor-pane .section-feature-type", + helpHtml("intro.navigation.preset_townhall", { preset: preset.name() }), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } ); - timeout2(function() { - context.map().centerZoomEase(twelfthAvenue, 18, 500); - context.map().on("move.intro drawn.intro", function() { - var padding2 = 200 * Math.pow(2, context.map().zoom() - 18); - var box2 = pad(twelfthAvenue, padding2, context); - box2.width = box2.width / 2; - reveal( - box2, - helpHtml(string, { street1: street, street2: street }), - { duration: 0 } - ); - }); - }, 600); - context.on("enter.intro", function() { - var ids2 = context.selectedIDs(); - if (ids2.length === 1 && ids2[0] === _washingtonSegmentID) { - continueTo(multiSelect); - } + context.on("exit.intro", function() { + continueTo(clickTownHall); }); context.history().on("change.intro", function() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); + if (!context.hasEntity(hallId)) { + continueTo(clickTownHall); } }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); + context.on("exit.intro", null); context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); nextStep(); } } - function multiSelect() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); - } - var ids = context.selectedIDs(); - var hasWashington = ids.indexOf(_washingtonSegmentID) !== -1; - var hasTwelfth = ids.indexOf(twelfthAvenueID) !== -1; - if (hasWashington && hasTwelfth) { - return continueTo(multiRightClick); - } else if (!hasWashington && !hasTwelfth) { - return continueTo(didSplit); - } - context.map().centerZoomEase(twelfthAvenue, 18, 500); - timeout2(function() { - var selected, other, padding, box; - if (hasWashington) { - selected = _t("intro.graph.name.washington-street"); - other = _t("intro.graph.name.12th-avenue"); - padding = 60 * Math.pow(2, context.map().zoom() - 18); - box = pad(twelfthAvenueEnd, padding, context); - box.width *= 3; - } else { - selected = _t("intro.graph.name.12th-avenue"); - other = _t("intro.graph.name.washington-street"); - padding = 200 * Math.pow(2, context.map().zoom() - 18); - box = pad(twelfthAvenue, padding, context); - box.width /= 2; + function fieldsTownHall() { + if (!isTownHallSelected()) + return clickTownHall(); + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + var onClick = function() { + continueTo(closeTownHall); + }; + reveal( + ".entity-editor-pane .section-preset-fields", + helpHtml("intro.navigation.fields_townhall"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + context.on("exit.intro", function() { + continueTo(clickTownHall); + }); + context.history().on("change.intro", function() { + if (!context.hasEntity(hallId)) { + continueTo(clickTownHall); } - reveal( - box, - helpHtml( - "intro.lines.multi_select", - { selected, other1: other } - ) + " " + helpHtml( - "intro.lines.add_to_selection_" + (context.lastPointerType() === "mouse" ? "click" : "touch"), - { selected, other2: other } - ) - ); - context.map().on("move.intro drawn.intro", function() { - if (hasWashington) { - selected = _t("intro.graph.name.washington-street"); - other = _t("intro.graph.name.12th-avenue"); - padding = 60 * Math.pow(2, context.map().zoom() - 18); - box = pad(twelfthAvenueEnd, padding, context); - box.width *= 3; - } else { - selected = _t("intro.graph.name.12th-avenue"); - other = _t("intro.graph.name.washington-street"); - padding = 200 * Math.pow(2, context.map().zoom() - 18); - box = pad(twelfthAvenue, padding, context); - box.width /= 2; - } - reveal( - box, - helpHtml( - "intro.lines.multi_select", - { selected, other1: other } - ) + " " + helpHtml( - "intro.lines.add_to_selection_" + (context.lastPointerType() === "mouse" ? "click" : "touch"), - { selected, other2: other } - ), - { duration: 0 } - ); - }); - context.on("enter.intro", function() { - continueTo(multiSelect); - }); - context.history().on("change.intro", function() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); - } - }); - }, 600); + }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); + context.on("exit.intro", null); context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); nextStep(); } } - function multiRightClick() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); - } - var padding = 200 * Math.pow(2, context.map().zoom() - 18); - var box = pad(twelfthAvenue, padding, context); - var rightClickString = helpHtml("intro.lines.multi_select_success") + helpHtml("intro.lines.multi_" + (context.lastPointerType() === "mouse" ? "rightclick" : "edit_menu_touch")); - reveal(box, rightClickString); - context.map().on("move.intro drawn.intro", function() { - var padding2 = 200 * Math.pow(2, context.map().zoom() - 18); - var box2 = pad(twelfthAvenue, padding2, context); - reveal(box2, rightClickString, { duration: 0 }); - }); - context.ui().editMenu().on("toggled.intro", function(open) { - if (!open) - return; - timeout2(function() { - var ids = context.selectedIDs(); - if (ids.length === 2 && ids.indexOf(twelfthAvenueID) !== -1 && ids.indexOf(_washingtonSegmentID) !== -1) { - var node = selectMenuItem(context, "delete").node(); - if (!node) - return; - continueTo(multiDelete); - } else if (ids.length === 1 && ids.indexOf(_washingtonSegmentID) !== -1) { - return continueTo(multiSelect); - } else { - return continueTo(didSplit); - } - }, 300); + function closeTownHall() { + if (!isTownHallSelected()) + return clickTownHall(); + var selector = ".entity-editor-pane button.close svg use"; + var href = select_default2(selector).attr("href") || "#iD-icon-close"; + reveal( + ".entity-editor-pane", + helpHtml("intro.navigation.close_townhall", { button: { html: icon(href, "inline") } }) + ); + context.on("exit.intro", function() { + continueTo(searchStreet); }); context.history().on("change.intro", function() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); - } + var selector2 = ".entity-editor-pane button.close svg use"; + var href2 = select_default2(selector2).attr("href") || "#iD-icon-close"; + reveal( + ".entity-editor-pane", + helpHtml("intro.navigation.close_townhall", { button: { html: icon(href2, "inline") } }), + { duration: 0 } + ); }); function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.ui().editMenu().on("toggled.intro", null); + context.on("exit.intro", null); context.history().on("change.intro", null); nextStep(); } } - function multiDelete() { - if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { - return continueTo(rightClickIntersection); + function searchStreet() { + context.enter(modeBrowse(context)); + context.history().reset("initial"); + var msec = transitionTime(springStreet, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); } - var node = selectMenuItem(context, "delete").node(); - if (!node) - return continueTo(multiRightClick); - reveal( - ".edit-menu", - helpHtml("intro.lines.multi_delete"), - { padding: 50 } - ); - context.map().on("move.intro drawn.intro", function() { + context.map().centerZoomEase(springStreet, 19, msec); + timeout2(function() { reveal( - ".edit-menu", - helpHtml("intro.lines.multi_delete"), - { duration: 0, padding: 50 } + ".search-header input", + helpHtml("intro.navigation.search_street", { name: _t("intro.graph.name.spring-street") }) ); - }); - context.on("exit.intro", function() { - if (context.hasEntity(_washingtonSegmentID) || context.hasEntity(twelfthAvenueID)) { - return continueTo(multiSelect); + context.container().select(".search-header input").on("keyup.intro", checkSearchResult); + }, msec + 100); + } + function checkSearchResult() { + var first = context.container().select(".feature-list-item:nth-child(0n+2)"); + var firstName = first.select(".entity-name"); + var name = _t("intro.graph.name.spring-street"); + if (!firstName.empty() && firstName.html() === name) { + reveal( + first.node(), + helpHtml("intro.navigation.choose_street", { name }), + { duration: 300 } + ); + context.on("exit.intro", function() { + continueTo(selectedStreet); + }); + context.container().select(".search-header input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); + } + function continueTo(nextStep) { + context.on("exit.intro", null); + context.container().select(".search-header input").on("keydown.intro", null).on("keyup.intro", null); + nextStep(); + } + } + function selectedStreet() { + if (!context.hasEntity(springStreetEndId) || !context.hasEntity(springStreetId)) { + return searchStreet(); + } + var onClick = function() { + continueTo(editorStreet); + }; + var entity = context.entity(springStreetEndId); + var box = pointBox(entity.loc, context); + box.height = 500; + reveal( + box, + helpHtml("intro.navigation.selected_street", { name: _t("intro.graph.name.spring-street") }), + { duration: 600, buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + timeout2(function() { + context.map().on("move.intro drawn.intro", function() { + var entity2 = context.hasEntity(springStreetEndId); + if (!entity2) + return; + var box2 = pointBox(entity2.loc, context); + box2.height = 500; + reveal( + box2, + helpHtml("intro.navigation.selected_street", { name: _t("intro.graph.name.spring-street") }), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + }); + }, 600); + context.on("enter.intro", function(mode) { + if (!context.hasEntity(springStreetId)) { + return continueTo(searchStreet); + } + var ids = context.selectedIDs(); + if (mode.id !== "select" || !ids.length || ids[0] !== springStreetId) { + context.enter(modeSelect(context, [springStreetId])); } }); context.history().on("change.intro", function() { - if (context.hasEntity(_washingtonSegmentID) || context.hasEntity(twelfthAvenueID)) { - continueTo(retryDelete); - } else { - continueTo(play); + if (!context.hasEntity(springStreetEndId) || !context.hasEntity(springStreetId)) { + timeout2(function() { + continueTo(searchStreet); + }, 300); } }); function continueTo(nextStep) { context.map().on("move.intro drawn.intro", null); - context.on("exit.intro", null); + context.on("enter.intro", null); context.history().on("change.intro", null); nextStep(); } } - function retryDelete() { - context.enter(modeBrowse(context)); - var padding = 200 * Math.pow(2, context.map().zoom() - 18); - var box = pad(twelfthAvenue, padding, context); - reveal(box, helpHtml("intro.lines.retry_delete"), { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(multiSelect); - } + function editorStreet() { + var selector = ".entity-editor-pane button.close svg use"; + var href = select_default2(selector).attr("href") || "#iD-icon-close"; + reveal(".entity-editor-pane", helpHtml("intro.navigation.street_different_fields") + "{br}" + helpHtml("intro.navigation.editor_street", { + button: { html: icon(href, "inline") }, + field1: onewayField.title(), + field2: maxspeedField.title() + })); + context.on("exit.intro", function() { + continueTo(play); + }); + context.history().on("change.intro", function() { + var selector2 = ".entity-editor-pane button.close svg use"; + var href2 = select_default2(selector2).attr("href") || "#iD-icon-close"; + reveal( + ".entity-editor-pane", + helpHtml("intro.navigation.street_different_fields") + "{br}" + helpHtml("intro.navigation.editor_street", { + button: { html: icon(href2, "inline") }, + field1: onewayField.title(), + field2: maxspeedField.title() + }), + { duration: 0 } + ); }); function continueTo(nextStep) { + context.on("exit.intro", null); + context.history().on("change.intro", null); nextStep(); } } @@ -59749,9 +60524,9 @@ dispatch14.call("done"); reveal( ".ideditor", - helpHtml("intro.lines.play", { next: _t("intro.buildings.title") }), + helpHtml("intro.navigation.play", { next: _t("intro.points.title") }), { - tooltipBox: ".intro-nav-wrap .chapter-building", + tooltipBox: ".intro-nav-wrap .chapter-point", buttonText: _t.html("intro.ok"), buttonCallback: function() { reveal(".ideditor"); @@ -59760,16 +60535,15 @@ ); } chapter.enter = function() { - addLine(); + dragMap(); }; chapter.exit = function() { timeouts.forEach(window.clearTimeout); - select_default2(window).on("pointerdown.intro mousedown.intro", null, true); context.on("enter.intro exit.intro", null); context.map().on("move.intro drawn.intro", null); context.history().on("change.intro", null); context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-list-button").on("click.intro", null); + context.container().select(".search-header input").on("keydown.intro keyup.intro", null); }; chapter.restart = function() { chapter.exit(); @@ -59778,56 +60552,43 @@ return utilRebind(chapter, dispatch14, "on"); } - // modules/ui/intro/building.js - function uiIntroBuilding(context, reveal) { + // modules/ui/intro/point.js + function uiIntroPoint(context, reveal) { var dispatch14 = dispatch_default("done"); - var house = [-85.62815, 41.95638]; - var tank = [-85.62732, 41.95347]; - var buildingCatetory = _mainPresetIndex.item("category-building"); - var housePreset = _mainPresetIndex.item("building/house"); - var tankPreset = _mainPresetIndex.item("man_made/storage_tank"); var timeouts = []; - var _houseID = null; - var _tankID = null; + var intersection2 = [-85.63279, 41.94394]; + var building = [-85.632422, 41.944045]; + var cafePreset = _mainPresetIndex.item("amenity/cafe"); + var _pointID = null; var chapter = { - title: "intro.buildings.title" + title: "intro.points.title" }; - function timeout2(f3, t2) { - timeouts.push(window.setTimeout(f3, t2)); + function timeout2(f2, t2) { + timeouts.push(window.setTimeout(f2, t2)); } function eventCancel(d3_event) { d3_event.stopPropagation(); d3_event.preventDefault(); } - function revealHouse(center, text2, options2) { - var padding = 160 * Math.pow(2, context.map().zoom() - 20); - var box = pad(center, padding, context); - reveal(box, text2, options2); - } - function revealTank(center, text2, options2) { - var padding = 190 * Math.pow(2, context.map().zoom() - 19.5); - var box = pad(center, padding, context); - reveal(box, text2, options2); - } - function addHouse() { + function addPoint() { context.enter(modeBrowse(context)); context.history().reset("initial"); - _houseID = null; - var msec = transitionTime(house, context.map().center()); + var msec = transitionTime(intersection2, context.map().center()); if (msec) { reveal(null, null, { duration: 0 }); } - context.map().centerZoomEase(house, 19, msec); + context.map().centerZoomEase(intersection2, 19, msec); timeout2(function() { var tooltip = reveal( - "button.add-area", - helpHtml("intro.buildings.add_building") + "button.add-point", + helpHtml("intro.points.points_info") + "{br}" + helpHtml("intro.points.add_point") ); - tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-buildings"); + _pointID = null; + tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-points"); context.on("enter.intro", function(mode) { - if (mode.id !== "add-area") + if (mode.id !== "add-point") return; - continueTo(startHouse); + continueTo(placePoint); }); }, msec + 100); function continueTo(nextStep) { @@ -59835,59 +60596,22 @@ nextStep(); } } - function startHouse() { - if (context.mode().id !== "add-area") { - return continueTo(addHouse); - } - _houseID = null; - context.map().zoomEase(20, 500); - timeout2(function() { - var startString = helpHtml("intro.buildings.start_building") + helpHtml("intro.buildings.building_corner_" + (context.lastPointerType() === "mouse" ? "click" : "tap")); - revealHouse(house, startString); - context.map().on("move.intro drawn.intro", function() { - revealHouse(house, startString, { duration: 0 }); - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "draw-area") - return chapter.restart(); - continueTo(continueHouse); - }); - }, 550); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); - } - } - function continueHouse() { - if (context.mode().id !== "draw-area") { - return continueTo(addHouse); + function placePoint() { + if (context.mode().id !== "add-point") { + return chapter.restart(); } - _houseID = null; - var continueString = helpHtml("intro.buildings.continue_building") + "{br}" + helpHtml("intro.areas.finish_area_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.buildings.finish_building"); - revealHouse(house, continueString); + var pointBox2 = pad(building, 150, context); + var textId = context.lastPointerType() === "mouse" ? "place_point" : "place_point_touch"; + reveal(pointBox2, helpHtml("intro.points." + textId)); context.map().on("move.intro drawn.intro", function() { - revealHouse(house, continueString, { duration: 0 }); + pointBox2 = pad(building, 150, context); + reveal(pointBox2, helpHtml("intro.points." + textId), { duration: 0 }); }); context.on("enter.intro", function(mode) { - if (mode.id === "draw-area") { - return; - } else if (mode.id === "select") { - var graph = context.graph(); - var way = context.entity(context.selectedIDs()[0]); - var nodes = graph.childNodes(way); - var points = utilArrayUniq(nodes).map(function(n3) { - return context.projection(n3.loc); - }); - if (isMostlySquare(points)) { - _houseID = way.id; - return continueTo(chooseCategoryBuilding); - } else { - return continueTo(retryHouse); - } - } else { + if (mode.id !== "select") return chapter.restart(); - } + _pointID = context.mode().selectedIDs()[0]; + continueTo(searchPreset); }); function continueTo(nextStep) { context.map().on("move.intro drawn.intro", null); @@ -59895,384 +60619,202 @@ nextStep(); } } - function retryHouse() { - var onClick = function() { - continueTo(addHouse); - }; - revealHouse( - house, - helpHtml("intro.buildings.retry_building"), - { buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - context.map().on("move.intro drawn.intro", function() { - revealHouse( - house, - helpHtml("intro.buildings.retry_building"), - { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } - ); - }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - nextStep(); - } - } - function chooseCategoryBuilding() { - if (!_houseID || !context.hasEntity(_houseID)) { - return addHouse(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _houseID) { - context.enter(modeSelect(context, [_houseID])); + function searchPreset() { + if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { + return addPoint(); } context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - timeout2(function() { - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - var button = context.container().select(".preset-category-building .preset-list-button"); - reveal( - button.node(), - helpHtml("intro.buildings.choose_category_building", { category: buildingCatetory.name() }) - ); - button.on("click.intro", function() { - button.on("click.intro", null); - continueTo(choosePresetHouse); - }); - }, 400); + context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); + reveal( + ".preset-search-input", + helpHtml("intro.points.search_cafe", { preset: cafePreset.name() }) + ); context.on("enter.intro", function(mode) { - if (!_houseID || !context.hasEntity(_houseID)) { - return continueTo(addHouse); + if (!_pointID || !context.hasEntity(_pointID)) { + return continueTo(addPoint); } - var ids2 = context.selectedIDs(); - if (mode.id !== "select" || !ids2.length || ids2[0] !== _houseID) { - return continueTo(chooseCategoryBuilding); + var ids = context.selectedIDs(); + if (mode.id !== "select" || !ids.length || ids[0] !== _pointID) { + context.enter(modeSelect(context, [_pointID])); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); + reveal( + ".preset-search-input", + helpHtml("intro.points.search_cafe", { preset: cafePreset.name() }) + ); + context.history().on("change.intro", null); } }); + function checkPresetSearch() { + var first = context.container().select(".preset-list-item:first-child"); + if (first.classed("preset-amenity-cafe")) { + context.container().select(".preset-search-input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); + reveal( + first.select(".preset-list-button").node(), + helpHtml("intro.points.choose_cafe", { preset: cafePreset.name() }), + { duration: 300 } + ); + context.history().on("change.intro", function() { + continueTo(aboutFeatureEditor); + }); + } + } function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-list-button").on("click.intro", null); context.on("enter.intro", null); + context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); nextStep(); } } - function choosePresetHouse() { - if (!_houseID || !context.hasEntity(_houseID)) { - return addHouse(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _houseID) { - context.enter(modeSelect(context, [_houseID])); + function aboutFeatureEditor() { + if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { + return addPoint(); } - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); timeout2(function() { - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - var button = context.container().select(".preset-building-house .preset-list-button"); - reveal( - button.node(), - helpHtml("intro.buildings.choose_preset_house", { preset: housePreset.name() }), - { duration: 300 } - ); - button.on("click.intro", function() { - button.on("click.intro", null); - continueTo(closeEditorHouse); + reveal(".entity-editor-pane", helpHtml("intro.points.feature_editor"), { + tooltipClass: "intro-points-describe", + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(addName); + } }); }, 400); - context.on("enter.intro", function(mode) { - if (!_houseID || !context.hasEntity(_houseID)) { - return continueTo(addHouse); - } - var ids2 = context.selectedIDs(); - if (mode.id !== "select" || !ids2.length || ids2[0] !== _houseID) { - return continueTo(chooseCategoryBuilding); - } - }); - function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.container().select(".preset-list-button").on("click.intro", null); - context.on("enter.intro", null); - nextStep(); - } - } - function closeEditorHouse() { - if (!_houseID || !context.hasEntity(_houseID)) { - return addHouse(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _houseID) { - context.enter(modeSelect(context, [_houseID])); - } - context.history().checkpoint("hasHouse"); context.on("exit.intro", function() { - continueTo(rightClickHouse); + continueTo(reselectPoint); }); - timeout2(function() { - reveal( - ".entity-editor-pane", - helpHtml("intro.buildings.close", { button: { html: icon("#iD-icon-close", "inline") } }) - ); - }, 500); function continueTo(nextStep) { context.on("exit.intro", null); nextStep(); } } - function rightClickHouse() { - if (!_houseID) - return chapter.restart(); - context.enter(modeBrowse(context)); - context.history().reset("hasHouse"); - var zoom = context.map().zoom(); - if (zoom < 20) { - zoom = 20; - } - context.map().centerZoomEase(house, zoom, 500); - context.on("enter.intro", function(mode) { - if (mode.id !== "select") - return; - var ids = context.selectedIDs(); - if (ids.length !== 1 || ids[0] !== _houseID) - return; - timeout2(function() { - var node = selectMenuItem(context, "orthogonalize").node(); - if (!node) - return; - continueTo(clickSquare); - }, 50); - }); - context.map().on("move.intro drawn.intro", function() { - var rightclickString = helpHtml("intro.buildings." + (context.lastPointerType() === "mouse" ? "rightclick_building" : "edit_menu_building_touch")); - revealHouse(house, rightclickString, { duration: 0 }); - }); - context.history().on("change.intro", function() { - continueTo(rightClickHouse); - }); - function continueTo(nextStep) { - context.on("enter.intro", null); - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); - nextStep(); - } - } - function clickSquare() { - if (!_houseID) - return chapter.restart(); - var entity = context.hasEntity(_houseID); - if (!entity) - return continueTo(rightClickHouse); - var node = selectMenuItem(context, "orthogonalize").node(); - if (!node) { - return continueTo(rightClickHouse); + function addName() { + if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { + return addPoint(); } - var wasChanged = false; - reveal( - ".edit-menu", - helpHtml("intro.buildings.square_building"), - { padding: 50 } - ); - context.on("enter.intro", function(mode) { - if (mode.id === "browse") { - continueTo(rightClickHouse); - } else if (mode.id === "move" || mode.id === "rotate") { - continueTo(retryClickSquare); - } - }); - context.map().on("move.intro", function() { - var node2 = selectMenuItem(context, "orthogonalize").node(); - if (!wasChanged && !node2) { - return continueTo(rightClickHouse); + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + var addNameString = helpHtml("intro.points.fields_info") + "{br}" + helpHtml("intro.points.add_name"); + timeout2(function() { + var entity = context.entity(_pointID); + if (entity.tags.name) { + var tooltip = reveal(".entity-editor-pane", addNameString, { + tooltipClass: "intro-points-describe", + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(addCloseEditor); + } + }); + tooltip.select(".instruction").style("display", "none"); + } else { + reveal( + ".entity-editor-pane", + addNameString, + { tooltipClass: "intro-points-describe" } + ); } - reveal( - ".edit-menu", - helpHtml("intro.buildings.square_building"), - { duration: 0, padding: 50 } - ); - }); + }, 400); context.history().on("change.intro", function() { - wasChanged = true; - context.history().on("change.intro", null); - timeout2(function() { - if (context.history().undoAnnotation() === _t("operations.orthogonalize.annotation.feature", { n: 1 })) { - continueTo(doneSquare); - } else { - continueTo(retryClickSquare); - } - }, 500); + continueTo(addCloseEditor); }); - function continueTo(nextStep) { - context.on("enter.intro", null); - context.map().on("move.intro", null); - context.history().on("change.intro", null); - nextStep(); - } - } - function retryClickSquare() { - context.enter(modeBrowse(context)); - revealHouse(house, helpHtml("intro.buildings.retry_square"), { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(rightClickHouse); - } + context.on("exit.intro", function() { + continueTo(reselectPoint); }); function continueTo(nextStep) { + context.on("exit.intro", null); + context.history().on("change.intro", null); nextStep(); } } - function doneSquare() { - context.history().checkpoint("doneSquare"); - revealHouse(house, helpHtml("intro.buildings.done_square"), { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(addTank); - } + function addCloseEditor() { + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + var selector = ".entity-editor-pane button.close svg use"; + var href = select_default2(selector).attr("href") || "#iD-icon-close"; + context.on("exit.intro", function() { + continueTo(reselectPoint); }); + reveal( + ".entity-editor-pane", + helpHtml("intro.points.add_close", { button: { html: icon(href, "inline") } }) + ); function continueTo(nextStep) { + context.on("exit.intro", null); nextStep(); } } - function addTank() { + function reselectPoint() { + if (!_pointID) + return chapter.restart(); + var entity = context.hasEntity(_pointID); + if (!entity) + return chapter.restart(); + var oldPreset = _mainPresetIndex.match(entity, context.graph()); + context.replace(actionChangePreset(_pointID, oldPreset, cafePreset)); context.enter(modeBrowse(context)); - context.history().reset("doneSquare"); - _tankID = null; - var msec = transitionTime(tank, context.map().center()); + var msec = transitionTime(entity.loc, context.map().center()); if (msec) { reveal(null, null, { duration: 0 }); } - context.map().centerZoomEase(tank, 19.5, msec); + context.map().centerEase(entity.loc, msec); timeout2(function() { - reveal( - "button.add-area", - helpHtml("intro.buildings.add_tank") - ); + var box = pointBox(entity.loc, context); + reveal(box, helpHtml("intro.points.reselect"), { duration: 600 }); + timeout2(function() { + context.map().on("move.intro drawn.intro", function() { + var entity2 = context.hasEntity(_pointID); + if (!entity2) + return chapter.restart(); + var box2 = pointBox(entity2.loc, context); + reveal(box2, helpHtml("intro.points.reselect"), { duration: 0 }); + }); + }, 600); context.on("enter.intro", function(mode) { - if (mode.id !== "add-area") + if (mode.id !== "select") return; - continueTo(startTank); + continueTo(updatePoint); }); }, msec + 100); - function continueTo(nextStep) { - context.on("enter.intro", null); - nextStep(); - } - } - function startTank() { - if (context.mode().id !== "add-area") { - return continueTo(addTank); - } - _tankID = null; - timeout2(function() { - var startString = helpHtml("intro.buildings.start_tank") + helpHtml("intro.buildings.tank_edge_" + (context.lastPointerType() === "mouse" ? "click" : "tap")); - revealTank(tank, startString); - context.map().on("move.intro drawn.intro", function() { - revealTank(tank, startString, { duration: 0 }); - }); - context.on("enter.intro", function(mode) { - if (mode.id !== "draw-area") - return chapter.restart(); - continueTo(continueTank); - }); - }, 550); function continueTo(nextStep) { context.map().on("move.intro drawn.intro", null); context.on("enter.intro", null); nextStep(); } } - function continueTank() { - if (context.mode().id !== "draw-area") { - return continueTo(addTank); + function updatePoint() { + if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { + return continueTo(reselectPoint); } - _tankID = null; - var continueString = helpHtml("intro.buildings.continue_tank") + "{br}" + helpHtml("intro.areas.finish_area_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.buildings.finish_tank"); - revealTank(tank, continueString); - context.map().on("move.intro drawn.intro", function() { - revealTank(tank, continueString, { duration: 0 }); + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + context.on("exit.intro", function() { + continueTo(reselectPoint); }); - context.on("enter.intro", function(mode) { - if (mode.id === "draw-area") { - return; - } else if (mode.id === "select") { - _tankID = context.selectedIDs()[0]; - return continueTo(searchPresetTank); - } else { - return continueTo(addTank); - } + context.history().on("change.intro", function() { + continueTo(updateCloseEditor); }); - function continueTo(nextStep) { - context.map().on("move.intro drawn.intro", null); - context.on("enter.intro", null); - nextStep(); - } - } - function searchPresetTank() { - if (!_tankID || !context.hasEntity(_tankID)) { - return addTank(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _tankID) { - context.enter(modeSelect(context, [_tankID])); - } - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); timeout2(function() { - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); reveal( - ".preset-search-input", - helpHtml("intro.buildings.search_tank", { preset: tankPreset.name() }) - ); - }, 400); - context.on("enter.intro", function(mode) { - if (!_tankID || !context.hasEntity(_tankID)) { - return continueTo(addTank); - } - var ids2 = context.selectedIDs(); - if (mode.id !== "select" || !ids2.length || ids2[0] !== _tankID) { - context.enter(modeSelect(context, [_tankID])); - context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); - context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); - context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); - reveal( - ".preset-search-input", - helpHtml("intro.buildings.search_tank", { preset: tankPreset.name() }) - ); - context.history().on("change.intro", null); - } - }); - function checkPresetSearch() { - var first = context.container().select(".preset-list-item:first-child"); - if (first.classed("preset-man_made-storage_tank")) { - reveal( - first.select(".preset-list-button").node(), - helpHtml("intro.buildings.choose_tank", { preset: tankPreset.name() }), - { duration: 300 } - ); - context.container().select(".preset-search-input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); - context.history().on("change.intro", function() { - continueTo(closeEditorTank); - }); - } - } + ".entity-editor-pane", + helpHtml("intro.points.update"), + { tooltipClass: "intro-points-describe" } + ); + }, 400); function continueTo(nextStep) { - context.container().select(".inspector-wrap").on("wheel.intro", null); - context.on("enter.intro", null); + context.on("exit.intro", null); context.history().on("change.intro", null); - context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); nextStep(); } } - function closeEditorTank() { - if (!_tankID || !context.hasEntity(_tankID)) { - return addTank(); - } - var ids = context.selectedIDs(); - if (context.mode().id !== "select" || !ids.length || ids[0] !== _tankID) { - context.enter(modeSelect(context, [_tankID])); + function updateCloseEditor() { + if (context.mode().id !== "select" || !_pointID || !context.hasEntity(_pointID)) { + return continueTo(reselectPoint); } - context.history().checkpoint("hasTank"); + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); context.on("exit.intro", function() { - continueTo(rightClickTank); + continueTo(rightClickPoint); }); timeout2(function() { reveal( ".entity-editor-pane", - helpHtml("intro.buildings.close", { button: { html: icon("#iD-icon-close", "inline") } }) + helpHtml("intro.points.update_close", { button: { html: icon("#iD-icon-close", "inline") } }) ); }, 500); function continueTo(nextStep) { @@ -60280,103 +60822,97 @@ nextStep(); } } - function rightClickTank() { - if (!_tankID) - return continueTo(addTank); + function rightClickPoint() { + if (!_pointID) + return chapter.restart(); + var entity = context.hasEntity(_pointID); + if (!entity) + return chapter.restart(); context.enter(modeBrowse(context)); - context.history().reset("hasTank"); - context.map().centerEase(tank, 500); + var box = pointBox(entity.loc, context); + var textId = context.lastPointerType() === "mouse" ? "rightclick" : "edit_menu_touch"; + reveal(box, helpHtml("intro.points." + textId), { duration: 600 }); timeout2(function() { - context.on("enter.intro", function(mode) { - if (mode.id !== "select") - return; - var ids = context.selectedIDs(); - if (ids.length !== 1 || ids[0] !== _tankID) - return; - timeout2(function() { - var node = selectMenuItem(context, "circularize").node(); - if (!node) - return; - continueTo(clickCircle); - }, 50); - }); - var rightclickString = helpHtml("intro.buildings." + (context.lastPointerType() === "mouse" ? "rightclick_tank" : "edit_menu_tank_touch")); - revealTank(tank, rightclickString); - context.map().on("move.intro drawn.intro", function() { - revealTank(tank, rightclickString, { duration: 0 }); - }); - context.history().on("change.intro", function() { - continueTo(rightClickTank); + context.map().on("move.intro", function() { + var entity2 = context.hasEntity(_pointID); + if (!entity2) + return chapter.restart(); + var box2 = pointBox(entity2.loc, context); + reveal(box2, helpHtml("intro.points." + textId), { duration: 0 }); }); }, 600); + context.on("enter.intro", function(mode) { + if (mode.id !== "select") + return; + var ids = context.selectedIDs(); + if (ids.length !== 1 || ids[0] !== _pointID) + return; + timeout2(function() { + var node = selectMenuItem(context, "delete").node(); + if (!node) + return; + continueTo(enterDelete); + }, 50); + }); function continueTo(nextStep) { context.on("enter.intro", null); - context.map().on("move.intro drawn.intro", null); - context.history().on("change.intro", null); + context.map().on("move.intro", null); nextStep(); } } - function clickCircle() { - if (!_tankID) + function enterDelete() { + if (!_pointID) return chapter.restart(); - var entity = context.hasEntity(_tankID); + var entity = context.hasEntity(_pointID); if (!entity) - return continueTo(rightClickTank); - var node = selectMenuItem(context, "circularize").node(); + return chapter.restart(); + var node = selectMenuItem(context, "delete").node(); if (!node) { - return continueTo(rightClickTank); + return continueTo(rightClickPoint); } - var wasChanged = false; reveal( ".edit-menu", - helpHtml("intro.buildings.circle_tank"), + helpHtml("intro.points.delete"), { padding: 50 } ); - context.on("enter.intro", function(mode) { - if (mode.id === "browse") { - continueTo(rightClickTank); - } else if (mode.id === "move" || mode.id === "rotate") { - continueTo(retryClickCircle); - } + timeout2(function() { + context.map().on("move.intro", function() { + reveal( + ".edit-menu", + helpHtml("intro.points.delete"), + { duration: 0, padding: 50 } + ); + }); + }, 300); + context.on("exit.intro", function() { + if (!_pointID) + return chapter.restart(); + var entity2 = context.hasEntity(_pointID); + if (entity2) + return continueTo(rightClickPoint); }); - context.map().on("move.intro", function() { - var node2 = selectMenuItem(context, "circularize").node(); - if (!wasChanged && !node2) { - return continueTo(rightClickTank); + context.history().on("change.intro", function(changed) { + if (changed.deleted().length) { + continueTo(undo); } - reveal( - ".edit-menu", - helpHtml("intro.buildings.circle_tank"), - { duration: 0, padding: 50 } - ); - }); - context.history().on("change.intro", function() { - wasChanged = true; - context.history().on("change.intro", null); - timeout2(function() { - if (context.history().undoAnnotation() === _t("operations.circularize.annotation.feature", { n: 1 })) { - continueTo(play); - } else { - continueTo(retryClickCircle); - } - }, 500); }); function continueTo(nextStep) { - context.on("enter.intro", null); context.map().on("move.intro", null); context.history().on("change.intro", null); + context.on("exit.intro", null); nextStep(); } } - function retryClickCircle() { - context.enter(modeBrowse(context)); - revealTank(tank, helpHtml("intro.buildings.retry_circle"), { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - continueTo(rightClickTank); - } + function undo() { + context.history().on("change.intro", function() { + continueTo(play); }); + reveal( + ".top-toolbar button.undo-button", + helpHtml("intro.points.undo") + ); function continueTo(nextStep) { + context.history().on("change.intro", null); nextStep(); } } @@ -60384,9 +60920,9 @@ dispatch14.call("done"); reveal( ".ideditor", - helpHtml("intro.buildings.play", { next: _t("intro.startediting.title") }), + helpHtml("intro.points.play", { next: _t("intro.areas.title") }), { - tooltipBox: ".intro-nav-wrap .chapter-startEditing", + tooltipBox: ".intro-nav-wrap .chapter-area", buttonText: _t.html("intro.ok"), buttonCallback: function() { reveal(".ideditor"); @@ -60395,16 +60931,15 @@ ); } chapter.enter = function() { - addHouse(); + addPoint(); }; chapter.exit = function() { timeouts.forEach(window.clearTimeout); context.on("enter.intro exit.intro", null); context.map().on("move.intro drawn.intro", null); context.history().on("change.intro", null); - context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); - context.container().select(".more-fields .combobox-input").on("click.intro", null); }; chapter.restart = function() { chapter.exit(); @@ -60413,9006 +60948,9988 @@ return utilRebind(chapter, dispatch14, "on"); } - // modules/ui/intro/start_editing.js - function uiIntroStartEditing(context, reveal) { - var dispatch14 = dispatch_default("done", "startEditing"); - var modalSelection = select_default2(null); + // modules/ui/intro/area.js + function uiIntroArea(context, reveal) { + var dispatch14 = dispatch_default("done"); + var playground = [-85.63552, 41.94159]; + var playgroundPreset = _mainPresetIndex.item("leisure/playground"); + var nameField = _mainPresetIndex.field("name"); + var descriptionField = _mainPresetIndex.field("description"); + var timeouts = []; + var _areaID; var chapter = { - title: "intro.startediting.title" + title: "intro.areas.title" }; - function showHelp() { - reveal( - ".map-control.help-control", - helpHtml("intro.startediting.help"), - { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - shortcuts(); - } - } - ); + function timeout2(f2, t2) { + timeouts.push(window.setTimeout(f2, t2)); } - function shortcuts() { - reveal( - ".map-control.help-control", - helpHtml("intro.startediting.shortcuts"), - { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - showSave(); - } - } - ); - } - function showSave() { - context.container().selectAll(".shaded").remove(); - reveal( - ".top-toolbar button.save", - helpHtml("intro.startediting.save"), - { - buttonText: _t.html("intro.ok"), - buttonCallback: function() { - showStart(); - } - } - ); - } - function showStart() { - context.container().selectAll(".shaded").remove(); - modalSelection = uiModal(context.container()); - modalSelection.select(".modal").attr("class", "modal-splash modal"); - modalSelection.selectAll(".close").remove(); - var startbutton = modalSelection.select(".content").attr("class", "fillL").append("button").attr("class", "modal-section huge-modal-button").on("click", function() { - modalSelection.remove(); - }); - startbutton.append("svg").attr("class", "illustration").append("use").attr("xlink:href", "#iD-logo-walkthrough"); - startbutton.append("h2").call(_t.append("intro.startediting.start")); - dispatch14.call("startEditing"); + function eventCancel(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); } - chapter.enter = function() { - showHelp(); - }; - chapter.exit = function() { - modalSelection.remove(); - context.container().selectAll(".shaded").remove(); - }; - return utilRebind(chapter, dispatch14, "on"); - } - - // modules/ui/intro/intro.js - var chapterUi = { - welcome: uiIntroWelcome, - navigation: uiIntroNavigation, - point: uiIntroPoint, - area: uiIntroArea, - line: uiIntroLine, - building: uiIntroBuilding, - startEditing: uiIntroStartEditing - }; - var chapterFlow = [ - "welcome", - "navigation", - "point", - "area", - "line", - "building", - "startEditing" - ]; - function uiIntro(context) { - const INTRO_IMAGERY = "EsriWorldImageryClarity"; - let _introGraph = {}; - let _currChapter; - function intro(selection2) { - _mainFileFetcher.get("intro_graph").then((dataIntroGraph) => { - for (let id2 in dataIntroGraph) { - if (!_introGraph[id2]) { - _introGraph[id2] = osmEntity(localize(dataIntroGraph[id2])); - } - } - selection2.call(startIntro); - }).catch(function() { - }); + function revealPlayground(center, text, options2) { + var padding = 180 * Math.pow(2, context.map().zoom() - 19.5); + var box = pad(center, padding, context); + reveal(box, text, options2); } - function startIntro(selection2) { + function addArea() { context.enter(modeBrowse(context)); - let osm = context.connection(); - let history = context.history().toJSON(); - let hash = window.location.hash; - let center = context.map().center(); - let zoom = context.map().zoom(); - let background = context.background().baseLayerSource(); - let overlays = context.background().overlayLayerSources(); - let opacity = context.container().selectAll(".main-map .layer-background").style("opacity"); - let caches = osm && osm.caches(); - let baseEntities = context.history().graph().base().entities; - context.ui().sidebar.expand(); - context.container().selectAll("button.sidebar-toggle").classed("disabled", true); - context.inIntro(true); - if (osm) { - osm.toggle(false).reset(); + context.history().reset("initial"); + _areaID = null; + var msec = transitionTime(playground, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); } - context.history().reset(); - context.history().merge(Object.values(coreGraph().load(_introGraph).entities)); - context.history().checkpoint("initial"); - let imagery = context.background().findSource(INTRO_IMAGERY); - if (imagery) { - context.background().baseLayerSource(imagery); - } else { - context.background().bing(); + context.map().centerZoomEase(playground, 19, msec); + timeout2(function() { + var tooltip = reveal( + "button.add-area", + helpHtml("intro.areas.add_playground") + ); + tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-areas"); + context.on("enter.intro", function(mode) { + if (mode.id !== "add-area") + return; + continueTo(startPlayground); + }); + }, msec + 100); + function continueTo(nextStep) { + context.on("enter.intro", null); + nextStep(); } - overlays.forEach((d2) => context.background().toggleOverlayLayer(d2)); - let layers = context.layers(); - layers.all().forEach((item) => { - if (typeof item.layer.enabled === "function") { - item.layer.enabled(item.id === "osm"); - } - }); - context.container().selectAll(".main-map .layer-background").style("opacity", 1); - let curtain = uiCurtain(context.container().node()); - selection2.call(curtain); - corePreferences("walkthrough_started", "yes"); - let storedProgress = corePreferences("walkthrough_progress") || ""; - let progress = storedProgress.split(";").filter(Boolean); - let chapters = chapterFlow.map((chapter, i3) => { - let s2 = chapterUi[chapter](context, curtain.reveal).on("done", () => { - buttons.filter((d2) => d2.title === s2.title).classed("finished", true); - if (i3 < chapterFlow.length - 1) { - const next = chapterFlow[i3 + 1]; - context.container().select("button.chapter-".concat(next)).classed("next", true); - } - progress.push(chapter); - corePreferences("walkthrough_progress", utilArrayUniq(progress).join(";")); + } + function startPlayground() { + if (context.mode().id !== "add-area") { + return chapter.restart(); + } + _areaID = null; + context.map().zoomEase(19.5, 500); + timeout2(function() { + var textId = context.lastPointerType() === "mouse" ? "starting_node_click" : "starting_node_tap"; + var startDrawString = helpHtml("intro.areas.start_playground") + helpHtml("intro.areas." + textId); + revealPlayground( + playground, + startDrawString, + { duration: 250 } + ); + timeout2(function() { + context.map().on("move.intro drawn.intro", function() { + revealPlayground( + playground, + startDrawString, + { duration: 0 } + ); + }); + context.on("enter.intro", function(mode) { + if (mode.id !== "draw-area") + return chapter.restart(); + continueTo(continuePlayground); + }); + }, 250); + }, 550); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); + } + } + function continuePlayground() { + if (context.mode().id !== "draw-area") { + return chapter.restart(); + } + _areaID = null; + revealPlayground( + playground, + helpHtml("intro.areas.continue_playground"), + { duration: 250 } + ); + timeout2(function() { + context.map().on("move.intro drawn.intro", function() { + revealPlayground( + playground, + helpHtml("intro.areas.continue_playground"), + { duration: 0 } + ); }); - return s2; - }); - chapters[chapters.length - 1].on("startEditing", () => { - progress.push("startEditing"); - corePreferences("walkthrough_progress", utilArrayUniq(progress).join(";")); - let incomplete = utilArrayDifference(chapterFlow, progress); - if (!incomplete.length) { - corePreferences("walkthrough_completed", "yes"); - } - curtain.remove(); - navwrap.remove(); - context.container().selectAll(".main-map .layer-background").style("opacity", opacity); - context.container().selectAll("button.sidebar-toggle").classed("disabled", false); - if (osm) { - osm.toggle(true).reset().caches(caches); - } - context.history().reset().merge(Object.values(baseEntities)); - context.background().baseLayerSource(background); - overlays.forEach((d2) => context.background().toggleOverlayLayer(d2)); - if (history) { - context.history().fromJSON(history, false); + }, 250); + context.on("enter.intro", function(mode) { + if (mode.id === "draw-area") { + var entity = context.hasEntity(context.selectedIDs()[0]); + if (entity && entity.nodes.length >= 6) { + return continueTo(finishPlayground); + } else { + return; + } + } else if (mode.id === "select") { + _areaID = context.selectedIDs()[0]; + return continueTo(searchPresets); + } else { + return chapter.restart(); } - context.map().centerZoom(center, zoom); - window.location.replace(hash); - context.inIntro(false); }); - let navwrap = selection2.append("div").attr("class", "intro-nav-wrap fillD"); - navwrap.append("svg").attr("class", "intro-nav-wrap-logo").append("use").attr("xlink:href", "#iD-logo-walkthrough"); - let buttonwrap = navwrap.append("div").attr("class", "joined").selectAll("button.chapter"); - let buttons = buttonwrap.data(chapters).enter().append("button").attr("class", (d2, i3) => "chapter chapter-".concat(chapterFlow[i3])).on("click", enterChapter); - buttons.append("span").html((d2) => _t.html(d2.title)); - buttons.append("span").attr("class", "status").call(svgIcon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward", "inline")); - enterChapter(null, chapters[0]); - function enterChapter(d3_event, newChapter) { - if (_currChapter) { - _currChapter.exit(); - } - context.enter(modeBrowse(context)); - _currChapter = newChapter; - _currChapter.enter(); - buttons.classed("next", false).classed("active", (d2) => d2.title === _currChapter.title); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); } } - return intro; - } - - // modules/ui/issues_info.js - function uiIssuesInfo(context) { - var warningsItem = { - id: "warnings", - count: 0, - iconID: "iD-icon-alert", - descriptionID: "issues.warnings_and_errors" - }; - var resolvedItem = { - id: "resolved", - count: 0, - iconID: "iD-icon-apply", - descriptionID: "issues.user_resolved_issues" - }; - function update(selection2) { - var shownItems = []; - var liveIssues = context.validator().getIssues({ - what: corePreferences("validate-what") || "edited", - where: corePreferences("validate-where") || "all" - }); - if (liveIssues.length) { - warningsItem.count = liveIssues.length; - shownItems.push(warningsItem); - } - if (corePreferences("validate-what") === "all") { - var resolvedIssues = context.validator().getResolvedIssues(); - if (resolvedIssues.length) { - resolvedItem.count = resolvedIssues.length; - shownItems.push(resolvedItem); - } + function finishPlayground() { + if (context.mode().id !== "draw-area") { + return chapter.restart(); } - var chips = selection2.selectAll(".chip").data(shownItems, function(d2) { - return d2.id; - }); - chips.exit().remove(); - var enter = chips.enter().append("a").attr("class", function(d2) { - return "chip " + d2.id + "-count"; - }).attr("href", "#").each(function(d2) { - var chipSelection = select_default2(this); - var tooltipBehavior = uiTooltip().placement("top").title(() => _t.append(d2.descriptionID)); - chipSelection.call(tooltipBehavior).on("click", function(d3_event) { - d3_event.preventDefault(); - tooltipBehavior.hide(select_default2(this)); - context.ui().togglePanes(context.container().select(".map-panes .issues-pane")); + _areaID = null; + var finishString = helpHtml("intro.areas.finish_area_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.areas.finish_playground"); + revealPlayground( + playground, + finishString, + { duration: 250 } + ); + timeout2(function() { + context.map().on("move.intro drawn.intro", function() { + revealPlayground( + playground, + finishString, + { duration: 0 } + ); }); - chipSelection.call(svgIcon("#" + d2.iconID)); - }); - enter.append("span").attr("class", "count"); - enter.merge(chips).selectAll("span.count").text(function(d2) { - return d2.count.toString(); + }, 250); + context.on("enter.intro", function(mode) { + if (mode.id === "draw-area") { + return; + } else if (mode.id === "select") { + _areaID = context.selectedIDs()[0]; + return continueTo(searchPresets); + } else { + return chapter.restart(); + } }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); + } } - return function(selection2) { - update(selection2); - context.validator().on("validated.infobox", function() { - update(selection2); - }); - }; - } - - // modules/ui/map_in_map.js - function uiMapInMap(context) { - function mapInMap(selection2) { - var backgroundLayer = rendererTileLayer(context); - var overlayLayers = {}; - var projection2 = geoRawMercator(); - var dataLayer = svgData(projection2, context).showLabels(false); - var debugLayer = svgDebug(projection2, context); - var zoom = zoom_default2().scaleExtent([geoZoomToScale(0.5), geoZoomToScale(24)]).on("start", zoomStarted).on("zoom", zoomed).on("end", zoomEnded); - var wrap2 = select_default2(null); - var tiles = select_default2(null); - var viewport = select_default2(null); - var _isTransformed = false; - var _isHidden = true; - var _skipEvents = false; - var _gesture = null; - var _zDiff = 6; - var _dMini; - var _cMini; - var _tStart; - var _tCurr; - var _timeoutID; - function zoomStarted() { - if (_skipEvents) - return; - _tStart = _tCurr = projection2.transform(); - _gesture = null; + function searchPresets() { + if (!_areaID || !context.hasEntity(_areaID)) { + return addArea(); } - function zoomed(d3_event) { - if (_skipEvents) - return; - var x2 = d3_event.transform.x; - var y2 = d3_event.transform.y; - var k2 = d3_event.transform.k; - var isZooming = k2 !== _tStart.k; - var isPanning = x2 !== _tStart.x || y2 !== _tStart.y; - if (!isZooming && !isPanning) { - return; + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { + context.enter(modeSelect(context, [_areaID])); + } + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); + reveal( + ".preset-search-input", + helpHtml("intro.areas.search_playground", { preset: playgroundPreset.name() }) + ); + }, 400); + context.on("enter.intro", function(mode) { + if (!_areaID || !context.hasEntity(_areaID)) { + return continueTo(addArea); } - if (!_gesture) { - _gesture = isZooming ? "zoom" : "pan"; + var ids2 = context.selectedIDs(); + if (mode.id !== "select" || !ids2.length || ids2[0] !== _areaID) { + context.enter(modeSelect(context, [_areaID])); + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); + reveal( + ".preset-search-input", + helpHtml("intro.areas.search_playground", { preset: playgroundPreset.name() }) + ); + context.history().on("change.intro", null); } - var tMini = projection2.transform(); - var tX, tY, scale; - if (_gesture === "zoom") { - scale = k2 / tMini.k; - tX = (_cMini[0] / scale - _cMini[0]) * scale; - tY = (_cMini[1] / scale - _cMini[1]) * scale; - } else { - k2 = tMini.k; - scale = 1; - tX = x2 - tMini.x; - tY = y2 - tMini.y; + }); + function checkPresetSearch() { + var first = context.container().select(".preset-list-item:first-child"); + if (first.classed("preset-leisure-playground")) { + reveal( + first.select(".preset-list-button").node(), + helpHtml("intro.areas.choose_playground", { preset: playgroundPreset.name() }), + { duration: 300 } + ); + context.container().select(".preset-search-input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); + context.history().on("change.intro", function() { + continueTo(clickAddField); + }); } - utilSetTransform(tiles, tX, tY, scale); - utilSetTransform(viewport, 0, 0, scale); - _isTransformed = true; - _tCurr = identity2.translate(x2, y2).scale(k2); - var zMain = geoScaleToZoom(context.projection.scale()); - var zMini = geoScaleToZoom(k2); - _zDiff = zMain - zMini; - queueRedraw(); } - function zoomEnded() { - if (_skipEvents) - return; - if (_gesture !== "pan") - return; - updateProjection(); - _gesture = null; - context.map().center(projection2.invert(_cMini)); + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.on("enter.intro", null); + context.history().on("change.intro", null); + context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); + nextStep(); } - function updateProjection() { - var loc = context.map().center(); - var tMain = context.projection.transform(); - var zMain = geoScaleToZoom(tMain.k); - var zMini = Math.max(zMain - _zDiff, 0.5); - var kMini = geoZoomToScale(zMini); - projection2.translate([tMain.x, tMain.y]).scale(kMini); - var point2 = projection2(loc); - var mouse = _gesture === "pan" ? geoVecSubtract([_tCurr.x, _tCurr.y], [_tStart.x, _tStart.y]) : [0, 0]; - var xMini = _cMini[0] - point2[0] + tMain.x + mouse[0]; - var yMini = _cMini[1] - point2[1] + tMain.y + mouse[1]; - projection2.translate([xMini, yMini]).clipExtent([[0, 0], _dMini]); - _tCurr = projection2.transform(); - if (_isTransformed) { - utilSetTransform(tiles, 0, 0); - utilSetTransform(viewport, 0, 0); - _isTransformed = false; - } - zoom.scaleExtent([geoZoomToScale(0.5), geoZoomToScale(zMain - 3)]); - _skipEvents = true; - wrap2.call(zoom.transform, _tCurr); - _skipEvents = false; + } + function clickAddField() { + if (!_areaID || !context.hasEntity(_areaID)) { + return addArea(); } - function redraw() { - clearTimeout(_timeoutID); - if (_isHidden) - return; - updateProjection(); - var zMini = geoScaleToZoom(projection2.scale()); - tiles = wrap2.selectAll(".map-in-map-tiles").data([0]); - tiles = tiles.enter().append("div").attr("class", "map-in-map-tiles").merge(tiles); - backgroundLayer.source(context.background().baseLayerSource()).projection(projection2).dimensions(_dMini); - var background = tiles.selectAll(".map-in-map-background").data([0]); - background.enter().append("div").attr("class", "map-in-map-background").merge(background).call(backgroundLayer); - var overlaySources = context.background().overlayLayerSources(); - var activeOverlayLayers = []; - for (var i3 = 0; i3 < overlaySources.length; i3++) { - if (overlaySources[i3].validZoom(zMini)) { - if (!overlayLayers[i3]) - overlayLayers[i3] = rendererTileLayer(context); - activeOverlayLayers.push(overlayLayers[i3].source(overlaySources[i3]).projection(projection2).dimensions(_dMini)); - } + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { + return searchPresets(); + } + if (!context.container().select(".form-field-description").empty()) { + return continueTo(describePlayground); + } + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + var entity = context.entity(_areaID); + if (entity.tags.description) { + return continueTo(play); } - var overlay = tiles.selectAll(".map-in-map-overlay").data([0]); - overlay = overlay.enter().append("div").attr("class", "map-in-map-overlay").merge(overlay); - var overlays = overlay.selectAll("div").data(activeOverlayLayers, function(d2) { - return d2.source().name(); - }); - overlays.exit().remove(); - overlays = overlays.enter().append("div").merge(overlays).each(function(layer) { - select_default2(this).call(layer); - }); - var dataLayers = tiles.selectAll(".map-in-map-data").data([0]); - dataLayers.exit().remove(); - dataLayers = dataLayers.enter().append("svg").attr("class", "map-in-map-data").merge(dataLayers).call(dataLayer).call(debugLayer); - if (_gesture !== "pan") { - var getPath = path_default(projection2); - var bbox2 = { type: "Polygon", coordinates: [context.map().extent().polygon()] }; - viewport = wrap2.selectAll(".map-in-map-viewport").data([0]); - viewport = viewport.enter().append("svg").attr("class", "map-in-map-viewport").merge(viewport); - var path = viewport.selectAll(".map-in-map-bbox").data([bbox2]); - path.enter().append("path").attr("class", "map-in-map-bbox").merge(path).attr("d", getPath).classed("thick", function(d2) { - return getPath.area(d2) < 30; + var box = context.container().select(".more-fields").node().getBoundingClientRect(); + if (box.top > 300) { + var pane = context.container().select(".entity-editor-pane .inspector-body"); + var start2 = pane.node().scrollTop; + var end = start2 + (box.top - 300); + pane.transition().duration(250).tween("scroll.inspector", function() { + var node = this; + var i3 = number_default(start2, end); + return function(t2) { + node.scrollTop = i3(t2); + }; }); } + timeout2(function() { + reveal( + ".more-fields .combobox-input", + helpHtml("intro.areas.add_field", { + name: nameField.title(), + description: descriptionField.title() + }), + { duration: 300 } + ); + context.container().select(".more-fields .combobox-input").on("click.intro", function() { + var watcher; + watcher = window.setInterval(function() { + if (!context.container().select("div.combobox").empty()) { + window.clearInterval(watcher); + continueTo(chooseDescriptionField); + } + }, 300); + }); + }, 300); + }, 400); + context.on("exit.intro", function() { + return continueTo(searchPresets); + }); + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".more-fields .combobox-input").on("click.intro", null); + context.on("exit.intro", null); + nextStep(); } - function queueRedraw() { - clearTimeout(_timeoutID); - _timeoutID = setTimeout(function() { - redraw(); - }, 750); + } + function chooseDescriptionField() { + if (!_areaID || !context.hasEntity(_areaID)) { + return addArea(); } - function toggle(d3_event) { - if (d3_event) - d3_event.preventDefault(); - _isHidden = !_isHidden; - context.container().select(".minimap-toggle-item").classed("active", !_isHidden).select("input").property("checked", !_isHidden); - if (_isHidden) { - wrap2.style("display", "block").style("opacity", "1").transition().duration(200).style("opacity", "0").on("end", function() { - selection2.selectAll(".map-in-map").style("display", "none"); - }); - } else { - wrap2.style("display", "block").style("opacity", "0").transition().duration(200).style("opacity", "1").on("end", function() { - redraw(); - }); - } + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { + return searchPresets(); } - uiMapInMap.toggle = toggle; - wrap2 = selection2.selectAll(".map-in-map").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "map-in-map").style("display", _isHidden ? "none" : "block").call(zoom).on("dblclick.zoom", null).merge(wrap2); - _dMini = [200, 150]; - _cMini = geoVecScale(_dMini, 0.5); - context.map().on("drawn.map-in-map", function(drawn) { - if (drawn.full === true) { - redraw(); + if (!context.container().select(".form-field-description").empty()) { + return continueTo(describePlayground); + } + if (context.container().select("div.combobox").empty()) { + return continueTo(clickAddField); + } + var watcher; + watcher = window.setInterval(function() { + if (context.container().select("div.combobox").empty()) { + window.clearInterval(watcher); + timeout2(function() { + if (context.container().select(".form-field-description").empty()) { + continueTo(retryChooseDescription); + } else { + continueTo(describePlayground); + } + }, 300); } + }, 300); + reveal( + "div.combobox", + helpHtml("intro.areas.choose_field", { field: descriptionField.title() }), + { duration: 300 } + ); + context.on("exit.intro", function() { + return continueTo(searchPresets); }); - redraw(); - context.keybinding().on(_t("background.minimap.key"), toggle); + function continueTo(nextStep) { + if (watcher) + window.clearInterval(watcher); + context.on("exit.intro", null); + nextStep(); + } } - return mapInMap; - } - - // modules/ui/notice.js - function uiNotice(context) { - return function(selection2) { - var div = selection2.append("div").attr("class", "notice"); - var button = div.append("button").attr("class", "zoom-to notice fillD").on("click", function() { - context.map().zoomEase(context.minEditableZoom()); - }).on("wheel", function(d3_event) { - var e22 = new WheelEvent(d3_event.type, d3_event); - context.surface().node().dispatchEvent(e22); - }); - button.call(svgIcon("#iD-icon-plus", "pre-text")).append("span").attr("class", "label").call(_t.append("zoom_in_edit")); - function disableTooHigh() { - var canEdit = context.map().zoom() >= context.minEditableZoom(); - div.style("display", canEdit ? "none" : "block"); + function describePlayground() { + if (!_areaID || !context.hasEntity(_areaID)) { + return addArea(); } - context.map().on("move.notice", debounce_default(disableTooHigh, 500)); - disableTooHigh(); - }; - } - - // modules/ui/photoviewer.js - function uiPhotoviewer(context) { - var dispatch14 = dispatch_default("resize"); - var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; - function photoviewer(selection2) { - selection2.append("button").attr("class", "thumb-hide").attr("title", _t("icons.close")).on("click", function() { - if (services.streetside) { - services.streetside.hideViewer(context); - } - if (services.mapillary) { - services.mapillary.hideViewer(context); - } - if (services.kartaview) { - services.kartaview.hideViewer(context); - } - if (services.mapilio) { - services.mapilio.hideViewer(context); - } - if (services.vegbilder) { - services.vegbilder.hideViewer(context); - } - }).append("div").call(svgIcon("#iD-icon-close")); - function preventDefault(d3_event) { - d3_event.preventDefault(); + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { + return searchPresets(); } - selection2.append("button").attr("class", "resize-handle-xy").on("touchstart touchdown touchend", preventDefault).on( - _pointerPrefix + "down", - buildResizeListener(selection2, "resize", dispatch14, { resizeOnX: true, resizeOnY: true }) - ); - selection2.append("button").attr("class", "resize-handle-x").on("touchstart touchdown touchend", preventDefault).on( - _pointerPrefix + "down", - buildResizeListener(selection2, "resize", dispatch14, { resizeOnX: true }) - ); - selection2.append("button").attr("class", "resize-handle-y").on("touchstart touchdown touchend", preventDefault).on( - _pointerPrefix + "down", - buildResizeListener(selection2, "resize", dispatch14, { resizeOnY: true }) + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + if (context.container().select(".form-field-description").empty()) { + return continueTo(retryChooseDescription); + } + context.on("exit.intro", function() { + continueTo(play); + }); + reveal( + ".entity-editor-pane", + helpHtml("intro.areas.describe_playground", { button: { html: icon("#iD-icon-close", "inline") } }), + { duration: 300 } ); - function buildResizeListener(target, eventName, dispatch15, options2) { - var resizeOnX = !!options2.resizeOnX; - var resizeOnY = !!options2.resizeOnY; - var minHeight = options2.minHeight || 240; - var minWidth = options2.minWidth || 320; - var pointerId; - var startX; - var startY; - var startWidth; - var startHeight; - function startResize(d3_event) { - if (pointerId !== (d3_event.pointerId || "mouse")) - return; - d3_event.preventDefault(); - d3_event.stopPropagation(); - var mapSize = context.map().dimensions(); - if (resizeOnX) { - var maxWidth = mapSize[0]; - var newWidth = clamp3(startWidth + d3_event.clientX - startX, minWidth, maxWidth); - target.style("width", newWidth + "px"); - } - if (resizeOnY) { - var maxHeight = mapSize[1] - 90; - var newHeight = clamp3(startHeight + startY - d3_event.clientY, minHeight, maxHeight); - target.style("height", newHeight + "px"); + function continueTo(nextStep) { + context.on("exit.intro", null); + nextStep(); + } + } + function retryChooseDescription() { + if (!_areaID || !context.hasEntity(_areaID)) { + return addArea(); + } + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _areaID) { + return searchPresets(); + } + context.container().select(".inspector-wrap .panewrap").style("right", "0%"); + reveal( + ".entity-editor-pane", + helpHtml("intro.areas.retry_add_field", { field: descriptionField.title() }), + { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(clickAddField); } - dispatch15.call(eventName, target, subtractPadding(utilGetDimensions(target, true), target)); - } - function clamp3(num, min3, max3) { - return Math.max(min3, Math.min(num, max3)); } - function stopResize(d3_event) { - if (pointerId !== (d3_event.pointerId || "mouse")) - return; - d3_event.preventDefault(); - d3_event.stopPropagation(); - select_default2(window).on("." + eventName, null); - } - return function initResize(d3_event) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - pointerId = d3_event.pointerId || "mouse"; - startX = d3_event.clientX; - startY = d3_event.clientY; - var targetRect = target.node().getBoundingClientRect(); - startWidth = targetRect.width; - startHeight = targetRect.height; - select_default2(window).on(_pointerPrefix + "move." + eventName, startResize, false).on(_pointerPrefix + "up." + eventName, stopResize, false); - if (_pointerPrefix === "pointer") { - select_default2(window).on("pointercancel." + eventName, stopResize, false); - } - }; + ); + context.on("exit.intro", function() { + return continueTo(searchPresets); + }); + function continueTo(nextStep) { + context.on("exit.intro", null); + nextStep(); } } - photoviewer.onMapResize = function() { - var photoviewer2 = context.container().select(".photoviewer"); - var content = context.container().select(".main-content"); - var mapDimensions = utilGetDimensions(content, true); - var photoDimensions = utilGetDimensions(photoviewer2, true); - if (photoDimensions[0] > mapDimensions[0] || photoDimensions[1] > mapDimensions[1] - 90) { - var setPhotoDimensions = [ - Math.min(photoDimensions[0], mapDimensions[0]), - Math.min(photoDimensions[1], mapDimensions[1] - 90) - ]; - photoviewer2.style("width", setPhotoDimensions[0] + "px").style("height", setPhotoDimensions[1] + "px"); - dispatch14.call("resize", photoviewer2, subtractPadding(setPhotoDimensions, photoviewer2)); - } - }; - function subtractPadding(dimensions, selection2) { - return [ - dimensions[0] - parseFloat(selection2.style("padding-left")) - parseFloat(selection2.style("padding-right")), - dimensions[1] - parseFloat(selection2.style("padding-top")) - parseFloat(selection2.style("padding-bottom")) - ]; + function play() { + dispatch14.call("done"); + reveal( + ".ideditor", + helpHtml("intro.areas.play", { next: _t("intro.lines.title") }), + { + tooltipBox: ".intro-nav-wrap .chapter-line", + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + reveal(".ideditor"); + } + } + ); } - return utilRebind(photoviewer, dispatch14, "on"); + chapter.enter = function() { + addArea(); + }; + chapter.exit = function() { + timeouts.forEach(window.clearTimeout); + context.on("enter.intro exit.intro", null); + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); + context.container().select(".more-fields .combobox-input").on("click.intro", null); + }; + chapter.restart = function() { + chapter.exit(); + chapter.enter(); + }; + return utilRebind(chapter, dispatch14, "on"); } - // modules/ui/restore.js - function uiRestore(context) { - return function(selection2) { - if (!context.history().hasRestorableChanges()) - return; - let modalSelection = uiModal(selection2, true); - modalSelection.select(".modal").attr("class", "modal fillL"); - let introModal = modalSelection.select(".content"); - introModal.append("div").attr("class", "modal-section").append("h3").call(_t.append("restore.heading")); - introModal.append("div").attr("class", "modal-section").append("p").call(_t.append("restore.description")); - let buttonWrap = introModal.append("div").attr("class", "modal-actions"); - let restore = buttonWrap.append("button").attr("class", "restore").on("click", () => { - context.history().restore(); - modalSelection.remove(); + // modules/ui/intro/line.js + function uiIntroLine(context, reveal) { + var dispatch14 = dispatch_default("done"); + var timeouts = []; + var _tulipRoadID = null; + var flowerRoadID = "w646"; + var tulipRoadStart = [-85.6297754121684, 41.95805253325314]; + var tulipRoadMidpoint = [-85.62975395449628, 41.95787501510204]; + var tulipRoadIntersection = [-85.62974496187628, 41.95742515554585]; + var roadCategory = _mainPresetIndex.item("category-road_minor"); + var residentialPreset = _mainPresetIndex.item("highway/residential"); + var woodRoadID = "w525"; + var woodRoadEndID = "n2862"; + var woodRoadAddNode = [-85.62390110349587, 41.95397111462291]; + var woodRoadDragEndpoint = [-85.623867390213, 41.95466987786487]; + var woodRoadDragMidpoint = [-85.62386254803509, 41.95430395953872]; + var washingtonStreetID = "w522"; + var twelfthAvenueID = "w1"; + var eleventhAvenueEndID = "n3550"; + var twelfthAvenueEndID = "n5"; + var _washingtonSegmentID = null; + var eleventhAvenueEnd = context.entity(eleventhAvenueEndID).loc; + var twelfthAvenueEnd = context.entity(twelfthAvenueEndID).loc; + var deleteLinesLoc = [-85.6219395542764, 41.95228033922477]; + var twelfthAvenue = [-85.62219310052491, 41.952505413152956]; + var chapter = { + title: "intro.lines.title" + }; + function timeout2(f2, t2) { + timeouts.push(window.setTimeout(f2, t2)); + } + function eventCancel(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + } + function addLine() { + context.enter(modeBrowse(context)); + context.history().reset("initial"); + var msec = transitionTime(tulipRoadStart, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); + } + context.map().centerZoomEase(tulipRoadStart, 18.5, msec); + timeout2(function() { + var tooltip = reveal( + "button.add-line", + helpHtml("intro.lines.add_line") + ); + tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-lines"); + context.on("enter.intro", function(mode) { + if (mode.id !== "add-line") + return; + continueTo(startLine); + }); + }, msec + 100); + function continueTo(nextStep) { + context.on("enter.intro", null); + nextStep(); + } + } + function startLine() { + if (context.mode().id !== "add-line") + return chapter.restart(); + _tulipRoadID = null; + var padding = 70 * Math.pow(2, context.map().zoom() - 18); + var box = pad(tulipRoadStart, padding, context); + box.height = box.height + 100; + var textId = context.lastPointerType() === "mouse" ? "start_line" : "start_line_tap"; + var startLineString = helpHtml("intro.lines.missing_road") + "{br}" + helpHtml("intro.lines.line_draw_info") + helpHtml("intro.lines." + textId); + reveal(box, startLineString); + context.map().on("move.intro drawn.intro", function() { + padding = 70 * Math.pow(2, context.map().zoom() - 18); + box = pad(tulipRoadStart, padding, context); + box.height = box.height + 100; + reveal(box, startLineString, { duration: 0 }); }); - restore.append("svg").attr("class", "logo logo-restore").append("use").attr("xlink:href", "#iD-logo-restore"); - restore.append("div").call(_t.append("restore.restore")); - let reset = buttonWrap.append("button").attr("class", "reset").on("click", () => { - context.history().clearSaved(); - modalSelection.remove(); + context.on("enter.intro", function(mode) { + if (mode.id !== "draw-line") + return chapter.restart(); + continueTo(drawLine); }); - reset.append("svg").attr("class", "logo logo-reset").append("use").attr("xlink:href", "#iD-logo-reset"); - reset.append("div").call(_t.append("restore.reset")); - restore.node().focus(); - }; - } - - // modules/ui/scale.js - function uiScale(context) { - var projection2 = context.projection, isImperial = !_mainLocalizer.usesMetric(), maxLength = 180, tickHeight = 8; - function scaleDefs(loc1, loc2) { - var lat = (loc2[1] + loc1[1]) / 2, conversion = isImperial ? 3.28084 : 1, dist = geoLonToMeters(loc2[0] - loc1[0], lat) * conversion, scale = { dist: 0, px: 0, text: "" }, buckets, i3, val, dLon; - if (isImperial) { - buckets = [528e4, 528e3, 52800, 5280, 500, 50, 5, 1]; - } else { - buckets = [5e6, 5e5, 5e4, 5e3, 500, 50, 5, 1]; + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); } - for (i3 = 0; i3 < buckets.length; i3++) { - val = buckets[i3]; - if (dist >= val) { - scale.dist = Math.floor(dist / val) * val; - break; + } + function drawLine() { + if (context.mode().id !== "draw-line") + return chapter.restart(); + _tulipRoadID = context.mode().selectedIDs()[0]; + context.map().centerEase(tulipRoadMidpoint, 500); + timeout2(function() { + var padding = 200 * Math.pow(2, context.map().zoom() - 18.5); + var box = pad(tulipRoadMidpoint, padding, context); + box.height = box.height * 2; + reveal( + box, + helpHtml("intro.lines.intersect", { name: _t("intro.graph.name.flower-street") }) + ); + context.map().on("move.intro drawn.intro", function() { + padding = 200 * Math.pow(2, context.map().zoom() - 18.5); + box = pad(tulipRoadMidpoint, padding, context); + box.height = box.height * 2; + reveal( + box, + helpHtml("intro.lines.intersect", { name: _t("intro.graph.name.flower-street") }), + { duration: 0 } + ); + }); + }, 550); + context.history().on("change.intro", function() { + if (isLineConnected()) { + continueTo(continueLine); + } + }); + context.on("enter.intro", function(mode) { + if (mode.id === "draw-line") { + return; + } else if (mode.id === "select") { + continueTo(retryIntersect); + return; } else { - scale.dist = +dist.toFixed(2); + return chapter.restart(); } + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + context.on("enter.intro", null); + nextStep(); } - dLon = geoMetersToLon(scale.dist / conversion, lat); - scale.px = Math.round(projection2([loc1[0] + dLon, loc1[1]])[0]); - scale.text = displayLength(scale.dist / conversion, isImperial); - return scale; - } - function update(selection2) { - var dims = context.map().dimensions(), loc1 = projection2.invert([0, dims[1]]), loc2 = projection2.invert([maxLength, dims[1]]), scale = scaleDefs(loc1, loc2); - selection2.select(".scale-path").attr("d", "M0.5,0.5v" + tickHeight + "h" + scale.px + "v-" + tickHeight); - selection2.select(".scale-text").style(_mainLocalizer.textDirection() === "ltr" ? "left" : "right", scale.px + 16 + "px").text(scale.text); } - return function(selection2) { - function switchUnits() { - isImperial = !isImperial; - selection2.call(update); - } - var scalegroup = selection2.append("svg").attr("class", "scale").on("click", switchUnits).append("g").attr("transform", "translate(10,11)"); - scalegroup.append("path").attr("class", "scale-path"); - selection2.append("div").attr("class", "scale-text"); - selection2.call(update); - context.map().on("move.scale", function() { - update(selection2); - }); - }; - } - - // modules/ui/shortcuts.js - function uiShortcuts(context) { - var detected = utilDetect(); - var _activeTab = 0; - var _modalSelection; - var _selection = select_default2(null); - var _dataShortcuts; - function shortcutsModal(_modalSelection2) { - _modalSelection2.select(".modal").classed("modal-shortcuts", true); - var content = _modalSelection2.select(".content"); - content.append("div").attr("class", "modal-section header").append("h2").call(_t.append("shortcuts.title")); - _mainFileFetcher.get("shortcuts").then(function(data) { - _dataShortcuts = data; - content.call(render); - }).catch(function() { + function isLineConnected() { + var entity = _tulipRoadID && context.hasEntity(_tulipRoadID); + if (!entity) + return false; + var drawNodes = context.graph().childNodes(entity); + return drawNodes.some(function(node) { + return context.graph().parentWays(node).some(function(parent) { + return parent.id === flowerRoadID; + }); }); } - function render(selection2) { - if (!_dataShortcuts) - return; - var wrapper = selection2.selectAll(".wrapper").data([0]); - var wrapperEnter = wrapper.enter().append("div").attr("class", "wrapper modal-section"); - var tabsBar = wrapperEnter.append("div").attr("class", "tabs-bar"); - var shortcutsList = wrapperEnter.append("div").attr("class", "shortcuts-list"); - wrapper = wrapper.merge(wrapperEnter); - var tabs = tabsBar.selectAll(".tab").data(_dataShortcuts); - var tabsEnter = tabs.enter().append("a").attr("class", "tab").attr("href", "#").on("click", function(d3_event, d2) { - d3_event.preventDefault(); - var i3 = _dataShortcuts.indexOf(d2); - _activeTab = i3; - render(selection2); + function retryIntersect() { + select_default2(window).on("pointerdown.intro mousedown.intro", eventCancel, true); + var box = pad(tulipRoadIntersection, 80, context); + reveal( + box, + helpHtml("intro.lines.retry_intersect", { name: _t("intro.graph.name.flower-street") }) + ); + timeout2(chapter.restart, 3e3); + } + function continueLine() { + if (context.mode().id !== "draw-line") + return chapter.restart(); + var entity = _tulipRoadID && context.hasEntity(_tulipRoadID); + if (!entity) + return chapter.restart(); + context.map().centerEase(tulipRoadIntersection, 500); + var continueLineText = helpHtml("intro.lines.continue_line") + "{br}" + helpHtml("intro.lines.finish_line_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.lines.finish_road"); + reveal(".surface", continueLineText); + context.on("enter.intro", function(mode) { + if (mode.id === "draw-line") { + return; + } else if (mode.id === "select") { + return continueTo(chooseCategoryRoad); + } else { + return chapter.restart(); + } }); - tabsEnter.append("span").html(function(d2) { - return _t.html(d2.text); + function continueTo(nextStep) { + context.on("enter.intro", null); + nextStep(); + } + } + function chooseCategoryRoad() { + if (context.mode().id !== "select") + return chapter.restart(); + context.on("exit.intro", function() { + return chapter.restart(); }); - wrapper.selectAll(".tab").classed("active", function(d2, i3) { - return i3 === _activeTab; + var button = context.container().select(".preset-category-road_minor .preset-list-button"); + if (button.empty()) + return chapter.restart(); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + reveal( + button.node(), + helpHtml("intro.lines.choose_category_road", { category: roadCategory.name() }) + ); + button.on("click.intro", function() { + continueTo(choosePresetResidential); + }); + }, 400); + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-list-button").on("click.intro", null); + context.on("exit.intro", null); + nextStep(); + } + } + function choosePresetResidential() { + if (context.mode().id !== "select") + return chapter.restart(); + context.on("exit.intro", function() { + return chapter.restart(); }); - var shortcuts = shortcutsList.selectAll(".shortcut-tab").data(_dataShortcuts); - var shortcutsEnter = shortcuts.enter().append("div").attr("class", function(d2) { - return "shortcut-tab shortcut-tab-" + d2.tab; + var subgrid = context.container().select(".preset-category-road_minor .subgrid"); + if (subgrid.empty()) + return chapter.restart(); + subgrid.selectAll(":not(.preset-highway-residential) .preset-list-button").on("click.intro", function() { + continueTo(retryPresetResidential); }); - var columnsEnter = shortcutsEnter.selectAll(".shortcut-column").data(function(d2) { - return d2.columns; - }).enter().append("table").attr("class", "shortcut-column"); - var rowsEnter = columnsEnter.selectAll(".shortcut-row").data(function(d2) { - return d2.rows; - }).enter().append("tr").attr("class", "shortcut-row"); - var sectionRows = rowsEnter.filter(function(d2) { - return !d2.shortcuts; + subgrid.selectAll(".preset-highway-residential .preset-list-button").on("click.intro", function() { + continueTo(nameRoad); }); - sectionRows.append("td"); - sectionRows.append("td").attr("class", "shortcut-section").append("h3").html(function(d2) { - return _t.html(d2.text); + timeout2(function() { + reveal( + subgrid.node(), + helpHtml("intro.lines.choose_preset_residential", { preset: residentialPreset.name() }), + { tooltipBox: ".preset-highway-residential .preset-list-button", duration: 300 } + ); + }, 300); + function continueTo(nextStep) { + context.container().select(".preset-list-button").on("click.intro", null); + context.on("exit.intro", null); + nextStep(); + } + } + function retryPresetResidential() { + if (context.mode().id !== "select") + return chapter.restart(); + context.on("exit.intro", function() { + return chapter.restart(); }); - var shortcutRows = rowsEnter.filter(function(d2) { - return d2.shortcuts; + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + var button = context.container().select(".entity-editor-pane .preset-list-button"); + reveal( + button.node(), + helpHtml("intro.lines.retry_preset_residential", { preset: residentialPreset.name() }) + ); + button.on("click.intro", function() { + continueTo(chooseCategoryRoad); + }); + }, 500); + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-list-button").on("click.intro", null); + context.on("exit.intro", null); + nextStep(); + } + } + function nameRoad() { + context.on("exit.intro", function() { + continueTo(didNameRoad); }); - var shortcutKeys = shortcutRows.append("td").attr("class", "shortcut-keys"); - var modifierKeys = shortcutKeys.filter(function(d2) { - return d2.modifiers; + timeout2(function() { + reveal( + ".entity-editor-pane", + helpHtml("intro.lines.name_road", { button: { html: icon("#iD-icon-close", "inline") } }), + { tooltipClass: "intro-lines-name_road" } + ); + }, 500); + function continueTo(nextStep) { + context.on("exit.intro", null); + nextStep(); + } + } + function didNameRoad() { + context.history().checkpoint("doneAddLine"); + timeout2(function() { + reveal(".surface", helpHtml("intro.lines.did_name_road"), { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(updateLine); + } + }); + }, 500); + function continueTo(nextStep) { + nextStep(); + } + } + function updateLine() { + context.history().reset("doneAddLine"); + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return chapter.restart(); + } + var msec = transitionTime(woodRoadDragMidpoint, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); + } + context.map().centerZoomEase(woodRoadDragMidpoint, 19, msec); + timeout2(function() { + var padding = 250 * Math.pow(2, context.map().zoom() - 19); + var box = pad(woodRoadDragMidpoint, padding, context); + var advance = function() { + continueTo(addNode); + }; + reveal( + box, + helpHtml("intro.lines.update_line"), + { buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 250 * Math.pow(2, context.map().zoom() - 19); + var box2 = pad(woodRoadDragMidpoint, padding2, context); + reveal( + box2, + helpHtml("intro.lines.update_line"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + }); + }, msec + 100); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + nextStep(); + } + } + function addNode() { + context.history().reset("doneAddLine"); + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return chapter.restart(); + } + var padding = 40 * Math.pow(2, context.map().zoom() - 19); + var box = pad(woodRoadAddNode, padding, context); + var addNodeString = helpHtml("intro.lines.add_node" + (context.lastPointerType() === "mouse" ? "" : "_touch")); + reveal(box, addNodeString); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 40 * Math.pow(2, context.map().zoom() - 19); + var box2 = pad(woodRoadAddNode, padding2, context); + reveal(box2, addNodeString, { duration: 0 }); }); - modifierKeys.selectAll("kbd.modifier").data(function(d2) { - if (detected.os === "win" && d2.text === "shortcuts.editing.commands.redo") { - return ["\u2318"]; - } else if (detected.os !== "mac" && d2.text === "shortcuts.browsing.display_options.fullscreen") { - return []; - } else { - return d2.modifiers; + context.history().on("change.intro", function(changed) { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); + } + if (changed.created().length === 1) { + timeout2(function() { + continueTo(startDragEndpoint); + }, 500); } - }).enter().each(function() { - var selection3 = select_default2(this); - selection3.append("kbd").attr("class", "modifier").text(function(d2) { - return uiCmd.display(d2); - }); - selection3.append("span").text("+"); }); - shortcutKeys.selectAll("kbd.shortcut").data(function(d2) { - var arr = d2.shortcuts; - if (detected.os === "win" && d2.text === "shortcuts.editing.commands.redo") { - arr = ["Y"]; - } else if (detected.os !== "mac" && d2.text === "shortcuts.browsing.display_options.fullscreen") { - arr = ["F11"]; + context.on("enter.intro", function(mode) { + if (mode.id !== "select") { + continueTo(updateLine); } - arr = arr.map(function(s2) { - return uiCmd.display(s2.indexOf(".") !== -1 ? _t(s2) : s2); - }); - return utilArrayUniq(arr).map(function(s2) { - return { - shortcut: s2, - separator: d2.separator, - suffix: d2.suffix - }; - }); - }).enter().each(function(d2, i3, nodes) { - var selection3 = select_default2(this); - var click = d2.shortcut.toLowerCase().match(/(.*).click/); - if (click && click[1]) { - selection3.call(svgIcon("#iD-walkthrough-mouse-" + click[1], "operation")); - } else if (d2.shortcut.toLowerCase() === "long-press") { - selection3.call(svgIcon("#iD-walkthrough-longpress", "longpress operation")); - } else if (d2.shortcut.toLowerCase() === "tap") { - selection3.call(svgIcon("#iD-walkthrough-tap", "tap operation")); - } else { - selection3.append("kbd").attr("class", "shortcut").text(function(d4) { - return d4.shortcut; - }); + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + context.on("enter.intro", null); + nextStep(); + } + } + function startDragEndpoint() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); + } + var padding = 100 * Math.pow(2, context.map().zoom() - 19); + var box = pad(woodRoadDragEndpoint, padding, context); + var startDragString = helpHtml("intro.lines.start_drag_endpoint" + (context.lastPointerType() === "mouse" ? "" : "_touch")) + helpHtml("intro.lines.drag_to_intersection"); + reveal(box, startDragString); + context.map().on("move.intro drawn.intro", function() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); } - if (i3 < nodes.length - 1) { - selection3.append("span").html(d2.separator || "\xA0" + _t.html("shortcuts.or") + "\xA0"); - } else if (i3 === nodes.length - 1 && d2.suffix) { - selection3.append("span").text(d2.suffix); + var padding2 = 100 * Math.pow(2, context.map().zoom() - 19); + var box2 = pad(woodRoadDragEndpoint, padding2, context); + reveal(box2, startDragString, { duration: 0 }); + var entity = context.entity(woodRoadEndID); + if (geoSphericalDistance(entity.loc, woodRoadDragEndpoint) <= 4) { + continueTo(finishDragEndpoint); } }); - shortcutKeys.filter(function(d2) { - return d2.gesture; - }).each(function() { - var selection3 = select_default2(this); - selection3.append("span").text("+"); - selection3.append("span").attr("class", "gesture").html(function(d2) { - return _t.html(d2.gesture); - }); - }); - shortcutRows.append("td").attr("class", "shortcut-desc").html(function(d2) { - return d2.text ? _t.html(d2.text) : "\xA0"; + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + nextStep(); + } + } + function finishDragEndpoint() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); + } + var padding = 100 * Math.pow(2, context.map().zoom() - 19); + var box = pad(woodRoadDragEndpoint, padding, context); + var finishDragString = helpHtml("intro.lines.spot_looks_good") + helpHtml("intro.lines.finish_drag_endpoint" + (context.lastPointerType() === "mouse" ? "" : "_touch")); + reveal(box, finishDragString); + context.map().on("move.intro drawn.intro", function() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); + } + var padding2 = 100 * Math.pow(2, context.map().zoom() - 19); + var box2 = pad(woodRoadDragEndpoint, padding2, context); + reveal(box2, finishDragString, { duration: 0 }); + var entity = context.entity(woodRoadEndID); + if (geoSphericalDistance(entity.loc, woodRoadDragEndpoint) > 4) { + continueTo(startDragEndpoint); + } }); - wrapper.selectAll(".shortcut-tab").style("display", function(d2, i3) { - return i3 === _activeTab ? "flex" : "none"; + context.on("enter.intro", function() { + continueTo(startDragMidpoint); }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); + } } - return function(selection2, show) { - _selection = selection2; - if (show) { - _modalSelection = uiModal(selection2); - _modalSelection.call(shortcutsModal); - } else { - context.keybinding().on([_t("shortcuts.toggle.key"), "?"], function() { - if (context.container().selectAll(".modal-shortcuts").size()) { - if (_modalSelection) { - _modalSelection.close(); - _modalSelection = null; - } - } else { - _modalSelection = uiModal(_selection); - _modalSelection.call(shortcutsModal); - } - }); + function startDragMidpoint() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); } - }; - } - - // modules/ui/data_header.js - function uiDataHeader() { - var _datum; - function dataHeader(selection2) { - var header = selection2.selectAll(".data-header").data( - _datum ? [_datum] : [], - function(d2) { - return d2.__featurehash__; + if (context.selectedIDs().indexOf(woodRoadID) === -1) { + context.enter(modeSelect(context, [woodRoadID])); + } + var padding = 80 * Math.pow(2, context.map().zoom() - 19); + var box = pad(woodRoadDragMidpoint, padding, context); + reveal(box, helpHtml("intro.lines.start_drag_midpoint")); + context.map().on("move.intro drawn.intro", function() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); } - ); - header.exit().remove(); - var headerEnter = header.enter().append("div").attr("class", "data-header"); - var iconEnter = headerEnter.append("div").attr("class", "data-header-icon"); - iconEnter.append("div").attr("class", "preset-icon-28").call(svgIcon("#iD-icon-data", "note-fill")); - headerEnter.append("div").attr("class", "data-header-label").call(_t.append("map_data.layers.custom.title")); - } - dataHeader.datum = function(val) { - if (!arguments.length) - return _datum; - _datum = val; - return this; - }; - return dataHeader; - } - - // modules/ui/combobox.js - var _comboHideTimerID; - function uiCombobox(context, klass) { - var dispatch14 = dispatch_default("accept", "cancel", "update"); - var container = context.container(); - var _suggestions = []; - var _data = []; - var _fetched = {}; - var _selected = null; - var _canAutocomplete = true; - var _caseSensitive = false; - var _cancelFetch = false; - var _minItems = 2; - var _tDown = 0; - var _mouseEnterHandler, _mouseLeaveHandler; - var _fetcher = function(val, cb) { - cb(_data.filter(function(d2) { - var terms = d2.terms || []; - terms.push(d2.value); - if (d2.key) { - terms.push(d2.key); + var padding2 = 80 * Math.pow(2, context.map().zoom() - 19); + var box2 = pad(woodRoadDragMidpoint, padding2, context); + reveal(box2, helpHtml("intro.lines.start_drag_midpoint"), { duration: 0 }); + }); + context.history().on("change.intro", function(changed) { + if (changed.created().length === 1) { + continueTo(continueDragMidpoint); } - return terms.some(function(term) { - return term.toString().toLowerCase().indexOf(val.toLowerCase()) !== -1; - }); - })); - }; - var combobox = function(input, attachTo) { - if (!input || input.empty()) - return; - input.classed("combobox-input", true).on("focus.combo-input", focus).on("blur.combo-input", blur).on("keydown.combo-input", keydown).on("keyup.combo-input", keyup).on("input.combo-input", change).on("mousedown.combo-input", mousedown).each(function() { - var parent = this.parentNode; - var sibling = this.nextSibling; - select_default2(parent).selectAll(".combobox-caret").filter(function(d2) { - return d2 === input.node(); - }).data([input.node()]).enter().insert("div", function() { - return sibling; - }).attr("class", "combobox-caret").on("mousedown.combo-caret", function(d3_event) { - d3_event.preventDefault(); - input.node().focus(); - mousedown(d3_event); - }).on("mouseup.combo-caret", function(d3_event) { - d3_event.preventDefault(); - mouseup(d3_event); - }); }); - function mousedown(d3_event) { - if (d3_event.button !== 0) - return; - if (input.classed("disabled")) - return; - _tDown = +/* @__PURE__ */ new Date(); - var start2 = input.property("selectionStart"); - var end = input.property("selectionEnd"); - if (start2 !== end) { - var val = utilGetSetValue(input); - input.node().setSelectionRange(val.length, val.length); - return; + context.on("enter.intro", function(mode) { + if (mode.id !== "select") { + context.enter(modeSelect(context, [woodRoadID])); } - input.on("mouseup.combo-input", mouseup); + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + context.on("enter.intro", null); + nextStep(); } - function mouseup(d3_event) { - input.on("mouseup.combo-input", null); - if (d3_event.button !== 0) - return; - if (input.classed("disabled")) - return; - if (input.node() !== document.activeElement) - return; - var start2 = input.property("selectionStart"); - var end = input.property("selectionEnd"); - if (start2 !== end) - return; - var combo = container.selectAll(".combobox"); - if (combo.empty() || combo.datum() !== input.node()) { - var tOrig = _tDown; - window.setTimeout(function() { - if (tOrig !== _tDown) - return; - fetchComboData("", function() { - show(); - render(); - }); - }, 250); - } else { - hide(); + } + function continueDragMidpoint() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); + } + var padding = 100 * Math.pow(2, context.map().zoom() - 19); + var box = pad(woodRoadDragEndpoint, padding, context); + box.height += 400; + var advance = function() { + context.history().checkpoint("doneUpdateLine"); + continueTo(deleteLines); + }; + reveal( + box, + helpHtml("intro.lines.continue_drag_midpoint"), + { buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + context.map().on("move.intro drawn.intro", function() { + if (!context.hasEntity(woodRoadID) || !context.hasEntity(woodRoadEndID)) { + return continueTo(updateLine); } + var padding2 = 100 * Math.pow(2, context.map().zoom() - 19); + var box2 = pad(woodRoadDragEndpoint, padding2, context); + box2.height += 400; + reveal( + box2, + helpHtml("intro.lines.continue_drag_midpoint"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + nextStep(); } - function focus() { - fetchComboData(""); + } + function deleteLines() { + context.history().reset("doneUpdateLine"); + context.enter(modeBrowse(context)); + if (!context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return chapter.restart(); } - function blur() { - _comboHideTimerID = window.setTimeout(hide, 75); + var msec = transitionTime(deleteLinesLoc, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); } - function show() { - hide(); - container.insert("div", ":first-child").datum(input.node()).attr("class", "combobox" + (klass ? " combobox-" + klass : "")).style("position", "absolute").style("display", "block").style("left", "0px").on("mousedown.combo-container", function(d3_event) { - d3_event.preventDefault(); + context.map().centerZoomEase(deleteLinesLoc, 18, msec); + timeout2(function() { + var padding = 200 * Math.pow(2, context.map().zoom() - 18); + var box = pad(deleteLinesLoc, padding, context); + box.top -= 200; + box.height += 400; + var advance = function() { + continueTo(rightClickIntersection); + }; + reveal( + box, + helpHtml("intro.lines.delete_lines", { street: _t("intro.graph.name.12th-avenue") }), + { buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 200 * Math.pow(2, context.map().zoom() - 18); + var box2 = pad(deleteLinesLoc, padding2, context); + box2.top -= 200; + box2.height += 400; + reveal( + box2, + helpHtml("intro.lines.delete_lines", { street: _t("intro.graph.name.12th-avenue") }), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); }); - container.on("scroll.combo-scroll", render, true); - } - function hide() { - if (_comboHideTimerID) { - window.clearTimeout(_comboHideTimerID); - _comboHideTimerID = void 0; - } - container.selectAll(".combobox").remove(); - container.on("scroll.combo-scroll", null); + context.history().on("change.intro", function() { + timeout2(function() { + continueTo(deleteLines); + }, 500); + }); + }, msec + 100); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + nextStep(); } - function keydown(d3_event) { - var shown = !container.selectAll(".combobox").empty(); - var tagName = input.node() ? input.node().tagName.toLowerCase() : ""; - switch (d3_event.keyCode) { - case 8: - case 46: - d3_event.stopPropagation(); - _selected = null; - render(); - input.on("input.combo-input", function() { - var start2 = input.property("selectionStart"); - input.node().setSelectionRange(start2, start2); - input.on("input.combo-input", change); - change(false); - }); - break; - case 9: - accept(d3_event); - break; - case 13: - d3_event.preventDefault(); - d3_event.stopPropagation(); - accept(d3_event); - break; - case 38: - if (tagName === "textarea" && !shown) - return; - d3_event.preventDefault(); - if (tagName === "input" && !shown) { - show(); - } - nav(-1); - break; - case 40: - if (tagName === "textarea" && !shown) + } + function rightClickIntersection() { + context.history().reset("doneUpdateLine"); + context.enter(modeBrowse(context)); + context.map().centerZoomEase(eleventhAvenueEnd, 18, 500); + var rightClickString = helpHtml("intro.lines.split_street", { + street1: _t("intro.graph.name.11th-avenue"), + street2: _t("intro.graph.name.washington-street") + }) + helpHtml("intro.lines." + (context.lastPointerType() === "mouse" ? "rightclick_intersection" : "edit_menu_intersection_touch")); + timeout2(function() { + var padding = 60 * Math.pow(2, context.map().zoom() - 18); + var box = pad(eleventhAvenueEnd, padding, context); + reveal(box, rightClickString); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 60 * Math.pow(2, context.map().zoom() - 18); + var box2 = pad(eleventhAvenueEnd, padding2, context); + reveal( + box2, + rightClickString, + { duration: 0 } + ); + }); + context.on("enter.intro", function(mode) { + if (mode.id !== "select") + return; + var ids = context.selectedIDs(); + if (ids.length !== 1 || ids[0] !== eleventhAvenueEndID) + return; + timeout2(function() { + var node = selectMenuItem(context, "split").node(); + if (!node) return; - d3_event.preventDefault(); - if (tagName === "input" && !shown) { - show(); - } - nav(1); - break; - } + continueTo(splitIntersection); + }, 50); + }); + context.history().on("change.intro", function() { + timeout2(function() { + continueTo(deleteLines); + }, 300); + }); + }, 600); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + context.history().on("change.intro", null); + nextStep(); } - function keyup(d3_event) { - switch (d3_event.keyCode) { - case 27: - cancel(); - break; - } + } + function splitIntersection() { + if (!context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(deleteLines); } - function change(doAutoComplete) { - if (doAutoComplete === void 0) - doAutoComplete = true; - fetchComboData(value(), function(skipAutosuggest) { - _selected = null; - var val = input.property("value"); - if (_suggestions.length) { - if (doAutoComplete && !skipAutosuggest && input.property("selectionEnd") === val.length) { - _selected = tryAutocomplete(); - } - if (!_selected) { - _selected = val; - } - } - if (val.length) { - var combo = container.selectAll(".combobox"); - if (combo.empty()) { - show(); - } + var node = selectMenuItem(context, "split").node(); + if (!node) { + return continueTo(rightClickIntersection); + } + var wasChanged = false; + _washingtonSegmentID = null; + reveal( + ".edit-menu", + helpHtml( + "intro.lines.split_intersection", + { street: _t("intro.graph.name.washington-street") } + ), + { padding: 50 } + ); + context.map().on("move.intro drawn.intro", function() { + var node2 = selectMenuItem(context, "split").node(); + if (!wasChanged && !node2) { + return continueTo(rightClickIntersection); + } + reveal( + ".edit-menu", + helpHtml( + "intro.lines.split_intersection", + { street: _t("intro.graph.name.washington-street") } + ), + { duration: 0, padding: 50 } + ); + }); + context.history().on("change.intro", function(changed) { + wasChanged = true; + timeout2(function() { + if (context.history().undoAnnotation() === _t("operations.split.annotation.line", { n: 1 })) { + _washingtonSegmentID = changed.created()[0].id; + continueTo(didSplit); } else { - hide(); + _washingtonSegmentID = null; + continueTo(retrySplit); } - render(); - }); + }, 300); + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + nextStep(); } - function nav(dir) { - if (_suggestions.length) { - var index = -1; - for (var i3 = 0; i3 < _suggestions.length; i3++) { - if (_selected && _suggestions[i3].value === _selected) { - index = i3; - break; - } - } - index = Math.max(Math.min(index + dir, _suggestions.length - 1), 0); - _selected = _suggestions[index].value; - utilGetSetValue(input, _selected); - dispatch14.call("update"); - } - render(); - ensureVisible(); + } + function retrySplit() { + context.enter(modeBrowse(context)); + context.map().centerZoomEase(eleventhAvenueEnd, 18, 500); + var advance = function() { + continueTo(rightClickIntersection); + }; + var padding = 60 * Math.pow(2, context.map().zoom() - 18); + var box = pad(eleventhAvenueEnd, padding, context); + reveal( + box, + helpHtml("intro.lines.retry_split"), + { buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 60 * Math.pow(2, context.map().zoom() - 18); + var box2 = pad(eleventhAvenueEnd, padding2, context); + reveal( + box2, + helpHtml("intro.lines.retry_split"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: advance } + ); + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + nextStep(); } - function ensureVisible() { - var combo = container.selectAll(".combobox"); - if (combo.empty()) - return; - var containerRect = container.node().getBoundingClientRect(); - var comboRect = combo.node().getBoundingClientRect(); - if (comboRect.bottom > containerRect.bottom) { - var node = attachTo ? attachTo.node() : input.node(); - node.scrollIntoView({ behavior: "instant", block: "center" }); - render(); + } + function didSplit() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); + } + var ids = context.selectedIDs(); + var string = "intro.lines.did_split_" + (ids.length > 1 ? "multi" : "single"); + var street = _t("intro.graph.name.washington-street"); + var padding = 200 * Math.pow(2, context.map().zoom() - 18); + var box = pad(twelfthAvenue, padding, context); + box.width = box.width / 2; + reveal( + box, + helpHtml(string, { street1: street, street2: street }), + { duration: 500 } + ); + timeout2(function() { + context.map().centerZoomEase(twelfthAvenue, 18, 500); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 200 * Math.pow(2, context.map().zoom() - 18); + var box2 = pad(twelfthAvenue, padding2, context); + box2.width = box2.width / 2; + reveal( + box2, + helpHtml(string, { street1: street, street2: street }), + { duration: 0 } + ); + }); + }, 600); + context.on("enter.intro", function() { + var ids2 = context.selectedIDs(); + if (ids2.length === 1 && ids2[0] === _washingtonSegmentID) { + continueTo(multiSelect); } - var selected = combo.selectAll(".combobox-option.selected").node(); - if (selected) { - selected.scrollIntoView({ behavior: "smooth", block: "nearest" }); + }); + context.history().on("change.intro", function() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); } + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + context.history().on("change.intro", null); + nextStep(); } - function value() { - var value2 = input.property("value"); - var start2 = input.property("selectionStart"); - var end = input.property("selectionEnd"); - if (start2 && end) { - value2 = value2.substring(0, start2); - } - return value2; + } + function multiSelect() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); } - function fetchComboData(v2, cb) { - _cancelFetch = false; - _fetcher.call(input, v2, function(results, skipAutosuggest) { - if (_cancelFetch) - return; - _suggestions = results; - results.forEach(function(d2) { - _fetched[d2.value] = d2; - }); - if (cb) { - cb(skipAutosuggest); - } - }); + var ids = context.selectedIDs(); + var hasWashington = ids.indexOf(_washingtonSegmentID) !== -1; + var hasTwelfth = ids.indexOf(twelfthAvenueID) !== -1; + if (hasWashington && hasTwelfth) { + return continueTo(multiRightClick); + } else if (!hasWashington && !hasTwelfth) { + return continueTo(didSplit); } - function tryAutocomplete() { - if (!_canAutocomplete) - return; - var val = _caseSensitive ? value() : value().toLowerCase(); - if (!val) - return; - if (isFinite(val)) - return; - const suggestionValues = []; - _suggestions.forEach((s2) => { - suggestionValues.push(s2.value); - if (s2.key && s2.key !== s2.value) { - suggestionValues.push(s2.key); + context.map().centerZoomEase(twelfthAvenue, 18, 500); + timeout2(function() { + var selected, other, padding, box; + if (hasWashington) { + selected = _t("intro.graph.name.washington-street"); + other = _t("intro.graph.name.12th-avenue"); + padding = 60 * Math.pow(2, context.map().zoom() - 18); + box = pad(twelfthAvenueEnd, padding, context); + box.width *= 3; + } else { + selected = _t("intro.graph.name.12th-avenue"); + other = _t("intro.graph.name.washington-street"); + padding = 200 * Math.pow(2, context.map().zoom() - 18); + box = pad(twelfthAvenue, padding, context); + box.width /= 2; + } + reveal( + box, + helpHtml( + "intro.lines.multi_select", + { selected, other1: other } + ) + " " + helpHtml( + "intro.lines.add_to_selection_" + (context.lastPointerType() === "mouse" ? "click" : "touch"), + { selected, other2: other } + ) + ); + context.map().on("move.intro drawn.intro", function() { + if (hasWashington) { + selected = _t("intro.graph.name.washington-street"); + other = _t("intro.graph.name.12th-avenue"); + padding = 60 * Math.pow(2, context.map().zoom() - 18); + box = pad(twelfthAvenueEnd, padding, context); + box.width *= 3; + } else { + selected = _t("intro.graph.name.12th-avenue"); + other = _t("intro.graph.name.washington-street"); + padding = 200 * Math.pow(2, context.map().zoom() - 18); + box = pad(twelfthAvenue, padding, context); + box.width /= 2; } + reveal( + box, + helpHtml( + "intro.lines.multi_select", + { selected, other1: other } + ) + " " + helpHtml( + "intro.lines.add_to_selection_" + (context.lastPointerType() === "mouse" ? "click" : "touch"), + { selected, other2: other } + ), + { duration: 0 } + ); }); - var bestIndex = -1; - for (var i3 = 0; i3 < suggestionValues.length; i3++) { - var suggestion = suggestionValues[i3]; - var compare = _caseSensitive ? suggestion : suggestion.toLowerCase(); - if (compare === val) { - bestIndex = i3; - break; - } else if (bestIndex === -1 && compare.indexOf(val) === 0) { - bestIndex = i3; + context.on("enter.intro", function() { + continueTo(multiSelect); + }); + context.history().on("change.intro", function() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); } - } - if (bestIndex !== -1) { - var bestVal = suggestionValues[bestIndex]; - input.property("value", bestVal); - input.node().setSelectionRange(val.length, bestVal.length); - dispatch14.call("update"); - return bestVal; - } + }); + }, 600); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + context.history().on("change.intro", null); + nextStep(); } - function render() { - if (_suggestions.length < _minItems || document.activeElement !== input.node()) { - hide(); - return; - } - var shown = !container.selectAll(".combobox").empty(); - if (!shown) + } + function multiRightClick() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); + } + var padding = 200 * Math.pow(2, context.map().zoom() - 18); + var box = pad(twelfthAvenue, padding, context); + var rightClickString = helpHtml("intro.lines.multi_select_success") + helpHtml("intro.lines.multi_" + (context.lastPointerType() === "mouse" ? "rightclick" : "edit_menu_touch")); + reveal(box, rightClickString); + context.map().on("move.intro drawn.intro", function() { + var padding2 = 200 * Math.pow(2, context.map().zoom() - 18); + var box2 = pad(twelfthAvenue, padding2, context); + reveal(box2, rightClickString, { duration: 0 }); + }); + context.ui().editMenu().on("toggled.intro", function(open) { + if (!open) return; - var combo = container.selectAll(".combobox"); - var options2 = combo.selectAll(".combobox-option").data(_suggestions, function(d2) { - return d2.value; - }); - options2.exit().remove(); - options2.enter().append("a").attr("class", function(d2) { - return "combobox-option " + (d2.klass || ""); - }).attr("title", function(d2) { - return d2.title; - }).each(function(d2) { - if (d2.display) { - d2.display(select_default2(this)); + timeout2(function() { + var ids = context.selectedIDs(); + if (ids.length === 2 && ids.indexOf(twelfthAvenueID) !== -1 && ids.indexOf(_washingtonSegmentID) !== -1) { + var node = selectMenuItem(context, "delete").node(); + if (!node) + return; + continueTo(multiDelete); + } else if (ids.length === 1 && ids.indexOf(_washingtonSegmentID) !== -1) { + return continueTo(multiSelect); } else { - select_default2(this).text(d2.value); + return continueTo(didSplit); } - }).on("mouseenter", _mouseEnterHandler).on("mouseleave", _mouseLeaveHandler).merge(options2).classed("selected", function(d2) { - return d2.value === _selected || d2.key === _selected; - }).on("click.combo-option", accept).order(); - var node = attachTo ? attachTo.node() : input.node(); - var containerRect = container.node().getBoundingClientRect(); - var rect = node.getBoundingClientRect(); - combo.style("left", rect.left + 5 - containerRect.left + "px").style("width", rect.width - 10 + "px").style("top", rect.height + rect.top - containerRect.top + "px"); - } - function accept(d3_event, d2) { - _cancelFetch = true; - var thiz = input.node(); - if (d2) { - utilGetSetValue(input, d2.value); - utilTriggerEvent(input, "change"); + }, 300); + }); + context.history().on("change.intro", function() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); } - var val = utilGetSetValue(input); - thiz.setSelectionRange(val.length, val.length); - d2 = _fetched[val]; - dispatch14.call("accept", thiz, d2, val); - hide(); - } - function cancel() { - _cancelFetch = true; - var thiz = input.node(); - var val = utilGetSetValue(input); - var start2 = input.property("selectionStart"); - var end = input.property("selectionEnd"); - val = val.slice(0, start2) + val.slice(end); - utilGetSetValue(input, val); - thiz.setSelectionRange(val.length, val.length); - dispatch14.call("cancel", thiz); - hide(); - } - }; - combobox.canAutocomplete = function(val) { - if (!arguments.length) - return _canAutocomplete; - _canAutocomplete = val; - return combobox; - }; - combobox.caseSensitive = function(val) { - if (!arguments.length) - return _caseSensitive; - _caseSensitive = val; - return combobox; - }; - combobox.data = function(val) { - if (!arguments.length) - return _data; - _data = val; - return combobox; - }; - combobox.fetcher = function(val) { - if (!arguments.length) - return _fetcher; - _fetcher = val; - return combobox; - }; - combobox.minItems = function(val) { - if (!arguments.length) - return _minItems; - _minItems = val; - return combobox; - }; - combobox.itemsMouseEnter = function(val) { - if (!arguments.length) - return _mouseEnterHandler; - _mouseEnterHandler = val; - return combobox; - }; - combobox.itemsMouseLeave = function(val) { - if (!arguments.length) - return _mouseLeaveHandler; - _mouseLeaveHandler = val; - return combobox; - }; - return utilRebind(combobox, dispatch14, "on"); - } - uiCombobox.off = function(input, context) { - input.on("focus.combo-input", null).on("blur.combo-input", null).on("keydown.combo-input", null).on("keyup.combo-input", null).on("input.combo-input", null).on("mousedown.combo-input", null).on("mouseup.combo-input", null); - context.container().on("scroll.combo-scroll", null); - }; - - // modules/ui/disclosure.js - function uiDisclosure(context, key, expandedDefault) { - var dispatch14 = dispatch_default("toggled"); - var _expanded; - var _label = utilFunctor(""); - var _updatePreference = true; - var _content = function() { - }; - var disclosure = function(selection2) { - if (_expanded === void 0 || _expanded === null) { - var preference = corePreferences("disclosure." + key + ".expanded"); - _expanded = preference === null ? !!expandedDefault : preference === "true"; + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.ui().editMenu().on("toggled.intro", null); + context.history().on("change.intro", null); + nextStep(); } - var hideToggle = selection2.selectAll(".hide-toggle-" + key).data([0]); - var hideToggleEnter = hideToggle.enter().append("h3").append("a").attr("role", "button").attr("href", "#").attr("class", "hide-toggle hide-toggle-" + key).call(svgIcon("", "pre-text", "hide-toggle-icon")); - hideToggleEnter.append("span").attr("class", "hide-toggle-text"); - hideToggle = hideToggleEnter.merge(hideToggle); - hideToggle.on("click", toggle).attr("title", _t("icons.".concat(_expanded ? "collapse" : "expand"))).attr("aria-expanded", _expanded).classed("expanded", _expanded); - const label = _label(); - const labelSelection = hideToggle.selectAll(".hide-toggle-text"); - if (typeof label !== "function") { - labelSelection.text(_label()); - } else { - labelSelection.text("").call(label); + } + function multiDelete() { + if (!_washingtonSegmentID || !context.hasEntity(_washingtonSegmentID) || !context.hasEntity(washingtonStreetID) || !context.hasEntity(twelfthAvenueID) || !context.hasEntity(eleventhAvenueEndID)) { + return continueTo(rightClickIntersection); } - hideToggle.selectAll(".hide-toggle-icon").attr( - "xlink:href", - _expanded ? "#iD-icon-down" : _mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward" + var node = selectMenuItem(context, "delete").node(); + if (!node) + return continueTo(multiRightClick); + reveal( + ".edit-menu", + helpHtml("intro.lines.multi_delete"), + { padding: 50 } ); - var wrap2 = selection2.selectAll(".disclosure-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "disclosure-wrap disclosure-wrap-" + key).merge(wrap2).classed("hide", !_expanded); - if (_expanded) { - wrap2.call(_content); - } - function toggle(d3_event) { - d3_event.preventDefault(); - _expanded = !_expanded; - if (_updatePreference) { - corePreferences("disclosure." + key + ".expanded", _expanded); - } - hideToggle.classed("expanded", _expanded).attr("aria-expanded", _expanded).attr("title", _t("icons.".concat(_expanded ? "collapse" : "expand"))); - hideToggle.selectAll(".hide-toggle-icon").attr( - "xlink:href", - _expanded ? "#iD-icon-down" : _mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward" + context.map().on("move.intro drawn.intro", function() { + reveal( + ".edit-menu", + helpHtml("intro.lines.multi_delete"), + { duration: 0, padding: 50 } ); - wrap2.call(uiToggle(_expanded)); - if (_expanded) { - wrap2.call(_content); + }); + context.on("exit.intro", function() { + if (context.hasEntity(_washingtonSegmentID) || context.hasEntity(twelfthAvenueID)) { + return continueTo(multiSelect); } - dispatch14.call("toggled", this, _expanded); + }); + context.history().on("change.intro", function() { + if (context.hasEntity(_washingtonSegmentID) || context.hasEntity(twelfthAvenueID)) { + continueTo(retryDelete); + } else { + continueTo(play); + } + }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("exit.intro", null); + context.history().on("change.intro", null); + nextStep(); } - }; - disclosure.label = function(val) { - if (!arguments.length) - return _label; - _label = utilFunctor(val); - return disclosure; - }; - disclosure.expanded = function(val) { - if (!arguments.length) - return _expanded; - _expanded = val; - return disclosure; - }; - disclosure.updatePreference = function(val) { - if (!arguments.length) - return _updatePreference; - _updatePreference = val; - return disclosure; - }; - disclosure.content = function(val) { - if (!arguments.length) - return _content; - _content = val; - return disclosure; - }; - return utilRebind(disclosure, dispatch14, "on"); - } - - // modules/ui/section.js - function uiSection(id2, context) { - var _classes = utilFunctor(""); - var _shouldDisplay; - var _content; - var _disclosure; - var _label; - var _expandedByDefault = utilFunctor(true); - var _disclosureContent; - var _disclosureExpanded; - var _containerSelection = select_default2(null); - var section = { - id: id2 - }; - section.classes = function(val) { - if (!arguments.length) - return _classes; - _classes = utilFunctor(val); - return section; - }; - section.label = function(val) { - if (!arguments.length) - return _label; - _label = utilFunctor(val); - return section; - }; - section.expandedByDefault = function(val) { - if (!arguments.length) - return _expandedByDefault; - _expandedByDefault = utilFunctor(val); - return section; - }; - section.shouldDisplay = function(val) { - if (!arguments.length) - return _shouldDisplay; - _shouldDisplay = utilFunctor(val); - return section; - }; - section.content = function(val) { - if (!arguments.length) - return _content; - _content = val; - return section; - }; - section.disclosureContent = function(val) { - if (!arguments.length) - return _disclosureContent; - _disclosureContent = val; - return section; - }; - section.disclosureExpanded = function(val) { - if (!arguments.length) - return _disclosureExpanded; - _disclosureExpanded = val; - return section; - }; - section.render = function(selection2) { - _containerSelection = selection2.selectAll(".section-" + id2).data([0]); - var sectionEnter = _containerSelection.enter().append("div").attr("class", "section section-" + id2 + " " + (_classes && _classes() || "")); - _containerSelection = sectionEnter.merge(_containerSelection); - _containerSelection.call(renderContent); - }; - section.reRender = function() { - _containerSelection.call(renderContent); - }; - section.selection = function() { - return _containerSelection; - }; - section.disclosure = function() { - return _disclosure; - }; - function renderContent(selection2) { - if (_shouldDisplay) { - var shouldDisplay = _shouldDisplay(); - selection2.classed("hide", !shouldDisplay); - if (!shouldDisplay) { - selection2.html(""); - return; + } + function retryDelete() { + context.enter(modeBrowse(context)); + var padding = 200 * Math.pow(2, context.map().zoom() - 18); + var box = pad(twelfthAvenue, padding, context); + reveal(box, helpHtml("intro.lines.retry_delete"), { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(multiSelect); } + }); + function continueTo(nextStep) { + nextStep(); } - if (_disclosureContent) { - if (!_disclosure) { - _disclosure = uiDisclosure(context, id2.replace(/-/g, "_"), _expandedByDefault()).label(_label || "").content(_disclosureContent); - } - if (_disclosureExpanded !== void 0) { - _disclosure.expanded(_disclosureExpanded); - _disclosureExpanded = void 0; + } + function play() { + dispatch14.call("done"); + reveal( + ".ideditor", + helpHtml("intro.lines.play", { next: _t("intro.buildings.title") }), + { + tooltipBox: ".intro-nav-wrap .chapter-building", + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + reveal(".ideditor"); + } } - selection2.call(_disclosure); - return; - } - if (_content) { - selection2.call(_content); - } + ); } - return section; + chapter.enter = function() { + addLine(); + }; + chapter.exit = function() { + timeouts.forEach(window.clearTimeout); + select_default2(window).on("pointerdown.intro mousedown.intro", null, true); + context.on("enter.intro exit.intro", null); + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-list-button").on("click.intro", null); + }; + chapter.restart = function() { + chapter.exit(); + chapter.enter(); + }; + return utilRebind(chapter, dispatch14, "on"); } - // modules/ui/tag_reference.js - function uiTagReference(what) { - var wikibase = what.qid ? services.wikidata : services.osmWikibase; - var tagReference = {}; - var _button = select_default2(null); - var _body = select_default2(null); - var _loaded; - var _showing; - function load() { - if (!wikibase) - return; - _button.classed("tag-reference-loading", true); - wikibase.getDocs(what, gotDocs); + // modules/ui/intro/building.js + function uiIntroBuilding(context, reveal) { + var dispatch14 = dispatch_default("done"); + var house = [-85.62815, 41.95638]; + var tank = [-85.62732, 41.95347]; + var buildingCatetory = _mainPresetIndex.item("category-building"); + var housePreset = _mainPresetIndex.item("building/house"); + var tankPreset = _mainPresetIndex.item("man_made/storage_tank"); + var timeouts = []; + var _houseID = null; + var _tankID = null; + var chapter = { + title: "intro.buildings.title" + }; + function timeout2(f2, t2) { + timeouts.push(window.setTimeout(f2, t2)); } - function gotDocs(err, docs) { - _body.html(""); - if (!docs || !docs.title) { - _body.append("p").attr("class", "tag-reference-description").call(_t.append("inspector.no_documentation_key")); - done(); - return; + function eventCancel(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + } + function revealHouse(center, text, options2) { + var padding = 160 * Math.pow(2, context.map().zoom() - 20); + var box = pad(center, padding, context); + reveal(box, text, options2); + } + function revealTank(center, text, options2) { + var padding = 190 * Math.pow(2, context.map().zoom() - 19.5); + var box = pad(center, padding, context); + reveal(box, text, options2); + } + function addHouse() { + context.enter(modeBrowse(context)); + context.history().reset("initial"); + _houseID = null; + var msec = transitionTime(house, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); } - if (docs.imageURL) { - _body.append("img").attr("class", "tag-reference-wiki-image").attr("alt", docs.description).attr("src", docs.imageURL).on("load", function() { - done(); - }).on("error", function() { - select_default2(this).remove(); - done(); + context.map().centerZoomEase(house, 19, msec); + timeout2(function() { + var tooltip = reveal( + "button.add-area", + helpHtml("intro.buildings.add_building") + ); + tooltip.selectAll(".popover-inner").insert("svg", "span").attr("class", "tooltip-illustration").append("use").attr("xlink:href", "#iD-graphic-buildings"); + context.on("enter.intro", function(mode) { + if (mode.id !== "add-area") + return; + continueTo(startHouse); }); - } else { - done(); - } - var tagReferenceDescription = _body.append("p").attr("class", "tag-reference-description").append("span"); - if (docs.description) { - tagReferenceDescription = tagReferenceDescription.attr("class", "localized-text").attr("lang", docs.descriptionLocaleCode || "und").text(docs.description); - } else { - tagReferenceDescription = tagReferenceDescription.call(_t.append("inspector.no_documentation_key")); + }, msec + 100); + function continueTo(nextStep) { + context.on("enter.intro", null); + nextStep(); } - tagReferenceDescription.append("a").attr("class", "tag-reference-edit").attr("target", "_blank").attr("title", _t("inspector.edit_reference")).attr("href", docs.editURL).call(svgIcon("#iD-icon-edit", "inline")); - if (docs.wiki) { - _body.append("a").attr("class", "tag-reference-link").attr("target", "_blank").attr("href", docs.wiki.url).call(svgIcon("#iD-icon-out-link", "inline")).append("span").call(_t.append(docs.wiki.text)); + } + function startHouse() { + if (context.mode().id !== "add-area") { + return continueTo(addHouse); } - if (what.key === "comment") { - _body.append("a").attr("class", "tag-reference-comment-link").attr("target", "_blank").call(svgIcon("#iD-icon-out-link", "inline")).attr("href", _t("commit.about_changeset_comments_link")).append("span").call(_t.append("commit.about_changeset_comments")); + _houseID = null; + context.map().zoomEase(20, 500); + timeout2(function() { + var startString = helpHtml("intro.buildings.start_building") + helpHtml("intro.buildings.building_corner_" + (context.lastPointerType() === "mouse" ? "click" : "tap")); + revealHouse(house, startString); + context.map().on("move.intro drawn.intro", function() { + revealHouse(house, startString, { duration: 0 }); + }); + context.on("enter.intro", function(mode) { + if (mode.id !== "draw-area") + return chapter.restart(); + continueTo(continueHouse); + }); + }, 550); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); } } - function done() { - _loaded = true; - _button.classed("tag-reference-loading", false); - _body.classed("expanded", true).transition().duration(200).style("max-height", "200px").style("opacity", "1"); - _showing = true; - _button.selectAll("svg.icon use").each(function() { - var iconUse = select_default2(this); - if (iconUse.attr("href") === "#iD-icon-info") { - iconUse.attr("href", "#iD-icon-info-filled"); + function continueHouse() { + if (context.mode().id !== "draw-area") { + return continueTo(addHouse); + } + _houseID = null; + var continueString = helpHtml("intro.buildings.continue_building") + "{br}" + helpHtml("intro.areas.finish_area_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.buildings.finish_building"); + revealHouse(house, continueString); + context.map().on("move.intro drawn.intro", function() { + revealHouse(house, continueString, { duration: 0 }); + }); + context.on("enter.intro", function(mode) { + if (mode.id === "draw-area") { + return; + } else if (mode.id === "select") { + var graph = context.graph(); + var way = context.entity(context.selectedIDs()[0]); + var nodes = graph.childNodes(way); + var points = utilArrayUniq(nodes).map(function(n3) { + return context.projection(n3.loc); + }); + if (isMostlySquare(points)) { + _houseID = way.id; + return continueTo(chooseCategoryBuilding); + } else { + return continueTo(retryHouse); + } + } else { + return chapter.restart(); } }); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); + } } - function hide() { - _body.transition().duration(200).style("max-height", "0px").style("opacity", "0").on("end", function() { - _body.classed("expanded", false); + function retryHouse() { + var onClick = function() { + continueTo(addHouse); + }; + revealHouse( + house, + helpHtml("intro.buildings.retry_building"), + { buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); + context.map().on("move.intro drawn.intro", function() { + revealHouse( + house, + helpHtml("intro.buildings.retry_building"), + { duration: 0, buttonText: _t.html("intro.ok"), buttonCallback: onClick } + ); }); - _showing = false; - _button.selectAll("svg.icon use").each(function() { - var iconUse = select_default2(this); - if (iconUse.attr("href") === "#iD-icon-info-filled") { - iconUse.attr("href", "#iD-icon-info"); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + nextStep(); + } + } + function chooseCategoryBuilding() { + if (!_houseID || !context.hasEntity(_houseID)) { + return addHouse(); + } + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _houseID) { + context.enter(modeSelect(context, [_houseID])); + } + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + var button = context.container().select(".preset-category-building .preset-list-button"); + reveal( + button.node(), + helpHtml("intro.buildings.choose_category_building", { category: buildingCatetory.name() }) + ); + button.on("click.intro", function() { + button.on("click.intro", null); + continueTo(choosePresetHouse); + }); + }, 400); + context.on("enter.intro", function(mode) { + if (!_houseID || !context.hasEntity(_houseID)) { + return continueTo(addHouse); + } + var ids2 = context.selectedIDs(); + if (mode.id !== "select" || !ids2.length || ids2[0] !== _houseID) { + return continueTo(chooseCategoryBuilding); } }); + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-list-button").on("click.intro", null); + context.on("enter.intro", null); + nextStep(); + } } - tagReference.button = function(selection2, klass, iconName) { - _button = selection2.selectAll(".tag-reference-button").data([0]); - _button = _button.enter().append("button").attr("class", "tag-reference-button " + (klass || "")).attr("title", _t("icons.information")).call(svgIcon("#iD-icon-" + (iconName || "inspect"))).merge(_button); - _button.on("click", function(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - this.blur(); - if (_showing) { - hide(); - } else if (_loaded) { - done(); - } else { - load(); + function choosePresetHouse() { + if (!_houseID || !context.hasEntity(_houseID)) { + return addHouse(); + } + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _houseID) { + context.enter(modeSelect(context, [_houseID])); + } + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + var button = context.container().select(".preset-building-house .preset-list-button"); + reveal( + button.node(), + helpHtml("intro.buildings.choose_preset_house", { preset: housePreset.name() }), + { duration: 300 } + ); + button.on("click.intro", function() { + button.on("click.intro", null); + continueTo(closeEditorHouse); + }); + }, 400); + context.on("enter.intro", function(mode) { + if (!_houseID || !context.hasEntity(_houseID)) { + return continueTo(addHouse); + } + var ids2 = context.selectedIDs(); + if (mode.id !== "select" || !ids2.length || ids2[0] !== _houseID) { + return continueTo(chooseCategoryBuilding); } }); - }; - tagReference.body = function(selection2) { - var itemID = what.qid || what.key + "-" + (what.value || ""); - _body = selection2.selectAll(".tag-reference-body").data([itemID], function(d2) { - return d2; + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-list-button").on("click.intro", null); + context.on("enter.intro", null); + nextStep(); + } + } + function closeEditorHouse() { + if (!_houseID || !context.hasEntity(_houseID)) { + return addHouse(); + } + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _houseID) { + context.enter(modeSelect(context, [_houseID])); + } + context.history().checkpoint("hasHouse"); + context.on("exit.intro", function() { + continueTo(rightClickHouse); }); - _body.exit().remove(); - _body = _body.enter().append("div").attr("class", "tag-reference-body").style("max-height", "0").style("opacity", "0").merge(_body); - if (_showing === false) { - hide(); + timeout2(function() { + reveal( + ".entity-editor-pane", + helpHtml("intro.buildings.close", { button: { html: icon("#iD-icon-close", "inline") } }) + ); + }, 500); + function continueTo(nextStep) { + context.on("exit.intro", null); + nextStep(); } - }; - tagReference.showing = function(val) { - if (!arguments.length) - return _showing; - _showing = val; - return tagReference; - }; - return tagReference; - } - - // modules/ui/field_help.js - function uiFieldHelp(context, fieldName) { - var fieldHelp = {}; - var _inspector = select_default2(null); - var _wrap = select_default2(null); - var _body = select_default2(null); - var fieldHelpKeys = { - restrictions: [ - ["about", [ - "about", - "from_via_to", - "maxdist", - "maxvia" - ]], - ["inspecting", [ - "about", - "from_shadow", - "allow_shadow", - "restrict_shadow", - "only_shadow", - "restricted", - "only" - ]], - ["modifying", [ - "about", - "indicators", - "allow_turn", - "restrict_turn", - "only_turn" - ]], - ["tips", [ - "simple", - "simple_example", - "indirect", - "indirect_example", - "indirect_noedit" - ]] - ] - }; - var fieldHelpHeadings = {}; - var replacements = { - distField: { html: _t.html("restriction.controls.distance") }, - viaField: { html: _t.html("restriction.controls.via") }, - fromShadow: { html: icon("#iD-turn-shadow", "inline shadow from") }, - allowShadow: { html: icon("#iD-turn-shadow", "inline shadow allow") }, - restrictShadow: { html: icon("#iD-turn-shadow", "inline shadow restrict") }, - onlyShadow: { html: icon("#iD-turn-shadow", "inline shadow only") }, - allowTurn: { html: icon("#iD-turn-yes", "inline turn") }, - restrictTurn: { html: icon("#iD-turn-no", "inline turn") }, - onlyTurn: { html: icon("#iD-turn-only", "inline turn") } - }; - var docs = fieldHelpKeys[fieldName].map(function(key) { - var helpkey = "help.field." + fieldName + "." + key[0]; - var text2 = key[1].reduce(function(all, part) { - var subkey = helpkey + "." + part; - var depth = fieldHelpHeadings[subkey]; - var hhh = depth ? Array(depth + 1).join("#") + " " : ""; - return all + hhh + _t.html(subkey, replacements) + "\n\n"; - }, ""); - return { - key: helpkey, - title: _t.html(helpkey + ".title"), - html: marked(text2.trim()) - }; - }); - function show() { - updatePosition(); - _body.classed("hide", false).style("opacity", "0").transition().duration(200).style("opacity", "1"); } - function hide() { - _body.classed("hide", true).transition().duration(200).style("opacity", "0").on("end", function() { - _body.classed("hide", true); + function rightClickHouse() { + if (!_houseID) + return chapter.restart(); + context.enter(modeBrowse(context)); + context.history().reset("hasHouse"); + var zoom = context.map().zoom(); + if (zoom < 20) { + zoom = 20; + } + context.map().centerZoomEase(house, zoom, 500); + context.on("enter.intro", function(mode) { + if (mode.id !== "select") + return; + var ids = context.selectedIDs(); + if (ids.length !== 1 || ids[0] !== _houseID) + return; + timeout2(function() { + var node = selectMenuItem(context, "orthogonalize").node(); + if (!node) + return; + continueTo(clickSquare); + }, 50); + }); + context.map().on("move.intro drawn.intro", function() { + var rightclickString = helpHtml("intro.buildings." + (context.lastPointerType() === "mouse" ? "rightclick_building" : "edit_menu_building_touch")); + revealHouse(house, rightclickString, { duration: 0 }); + }); + context.history().on("change.intro", function() { + continueTo(rightClickHouse); }); + function continueTo(nextStep) { + context.on("enter.intro", null); + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + nextStep(); + } } - function clickHelp(index) { - var d2 = docs[index]; - var tkeys = fieldHelpKeys[fieldName][index][1]; - _body.selectAll(".field-help-nav-item").classed("active", function(d4, i3) { - return i3 === index; + function clickSquare() { + if (!_houseID) + return chapter.restart(); + var entity = context.hasEntity(_houseID); + if (!entity) + return continueTo(rightClickHouse); + var node = selectMenuItem(context, "orthogonalize").node(); + if (!node) { + return continueTo(rightClickHouse); + } + var wasChanged = false; + reveal( + ".edit-menu", + helpHtml("intro.buildings.square_building"), + { padding: 50 } + ); + context.on("enter.intro", function(mode) { + if (mode.id === "browse") { + continueTo(rightClickHouse); + } else if (mode.id === "move" || mode.id === "rotate") { + continueTo(retryClickSquare); + } }); - var content = _body.selectAll(".field-help-content").html(d2.html); - content.selectAll("p").attr("class", function(d4, i3) { - return tkeys[i3]; + context.map().on("move.intro", function() { + var node2 = selectMenuItem(context, "orthogonalize").node(); + if (!wasChanged && !node2) { + return continueTo(rightClickHouse); + } + reveal( + ".edit-menu", + helpHtml("intro.buildings.square_building"), + { duration: 0, padding: 50 } + ); }); - if (d2.key === "help.field.restrictions.inspecting") { - content.insert("img", "p.from_shadow").attr("class", "field-help-image cf").attr("src", context.imagePath("tr_inspect.gif")); - } else if (d2.key === "help.field.restrictions.modifying") { - content.insert("img", "p.allow_turn").attr("class", "field-help-image cf").attr("src", context.imagePath("tr_modify.gif")); + context.history().on("change.intro", function() { + wasChanged = true; + context.history().on("change.intro", null); + timeout2(function() { + if (context.history().undoAnnotation() === _t("operations.orthogonalize.annotation.feature", { n: 1 })) { + continueTo(doneSquare); + } else { + continueTo(retryClickSquare); + } + }, 500); + }); + function continueTo(nextStep) { + context.on("enter.intro", null); + context.map().on("move.intro", null); + context.history().on("change.intro", null); + nextStep(); } } - fieldHelp.button = function(selection2) { - if (_body.empty()) - return; - var button = selection2.selectAll(".field-help-button").data([0]); - button.enter().append("button").attr("class", "field-help-button").call(svgIcon("#iD-icon-help")).merge(button).on("click", function(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - if (_body.classed("hide")) { - show(); - } else { - hide(); + function retryClickSquare() { + context.enter(modeBrowse(context)); + revealHouse(house, helpHtml("intro.buildings.retry_square"), { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(rightClickHouse); } }); - }; - function updatePosition() { - var wrap2 = _wrap.node(); - var inspector = _inspector.node(); - var wRect = wrap2.getBoundingClientRect(); - var iRect = inspector.getBoundingClientRect(); - _body.style("top", wRect.top + inspector.scrollTop - iRect.top + "px"); + function continueTo(nextStep) { + nextStep(); + } } - fieldHelp.body = function(selection2) { - _wrap = selection2.selectAll(".form-field-input-wrap"); - if (_wrap.empty()) - return; - _inspector = context.container().select(".sidebar .entity-editor-pane .inspector-body"); - if (_inspector.empty()) - return; - _body = _inspector.selectAll(".field-help-body").data([0]); - var enter = _body.enter().append("div").attr("class", "field-help-body hide"); - var titleEnter = enter.append("div").attr("class", "field-help-title cf"); - titleEnter.append("h2").attr("class", _mainLocalizer.textDirection() === "rtl" ? "fr" : "fl").call(_t.append("help.field." + fieldName + ".title")); - titleEnter.append("button").attr("class", "fr close").attr("title", _t("icons.close")).on("click", function(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - hide(); - }).call(svgIcon("#iD-icon-close")); - var navEnter = enter.append("div").attr("class", "field-help-nav cf"); - var titles = docs.map(function(d2) { - return d2.title; - }); - navEnter.selectAll(".field-help-nav-item").data(titles).enter().append("div").attr("class", "field-help-nav-item").html(function(d2) { - return d2; - }).on("click", function(d3_event, d2) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - clickHelp(titles.indexOf(d2)); + function doneSquare() { + context.history().checkpoint("doneSquare"); + revealHouse(house, helpHtml("intro.buildings.done_square"), { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(addTank); + } }); - enter.append("div").attr("class", "field-help-content"); - _body = _body.merge(enter); - clickHelp(0); - }; - return fieldHelp; - } - - // modules/ui/fields/check.js - function uiFieldCheck(field, context) { - var dispatch14 = dispatch_default("change"); - var options2 = field.options; - var values = []; - var texts = []; - var _tags; - var input = select_default2(null); - var text2 = select_default2(null); - var label = select_default2(null); - var reverser = select_default2(null); - var _impliedYes; - var _entityIDs = []; - var _value; - var stringsField = field.resolveReference("stringsCrossReference"); - if (!options2 && stringsField.options) { - options2 = stringsField.options; + function continueTo(nextStep) { + nextStep(); + } } - if (options2) { - for (var i3 in options2) { - var v2 = options2[i3]; - values.push(v2 === "undefined" ? void 0 : v2); - texts.push(stringsField.t.html("options." + v2, { "default": v2 })); + function addTank() { + context.enter(modeBrowse(context)); + context.history().reset("doneSquare"); + _tankID = null; + var msec = transitionTime(tank, context.map().center()); + if (msec) { + reveal(null, null, { duration: 0 }); } - } else { - values = [void 0, "yes"]; - texts = [_t.html("inspector.unknown"), _t.html("inspector.check.yes")]; - if (field.type !== "defaultCheck") { - values.push("no"); - texts.push(_t.html("inspector.check.no")); + context.map().centerZoomEase(tank, 19.5, msec); + timeout2(function() { + reveal( + "button.add-area", + helpHtml("intro.buildings.add_tank") + ); + context.on("enter.intro", function(mode) { + if (mode.id !== "add-area") + return; + continueTo(startTank); + }); + }, msec + 100); + function continueTo(nextStep) { + context.on("enter.intro", null); + nextStep(); } } - function checkImpliedYes() { - _impliedYes = field.id === "oneway_yes"; - if (field.id === "oneway") { - var entity = context.entity(_entityIDs[0]); - for (var key in entity.tags) { - if (key in osmOneWayTags && entity.tags[key] in osmOneWayTags[key]) { - _impliedYes = true; - texts[0] = _t.html("_tagging.presets.fields.oneway_yes.options.undefined"); - break; - } - } + function startTank() { + if (context.mode().id !== "add-area") { + return continueTo(addTank); + } + _tankID = null; + timeout2(function() { + var startString = helpHtml("intro.buildings.start_tank") + helpHtml("intro.buildings.tank_edge_" + (context.lastPointerType() === "mouse" ? "click" : "tap")); + revealTank(tank, startString); + context.map().on("move.intro drawn.intro", function() { + revealTank(tank, startString, { duration: 0 }); + }); + context.on("enter.intro", function(mode) { + if (mode.id !== "draw-area") + return chapter.restart(); + continueTo(continueTank); + }); + }, 550); + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); } } - function reverserHidden() { - if (!context.container().select("div.inspector-hover").empty()) - return true; - return !(_value === "yes" || _impliedYes && !_value); - } - function reverserSetText(selection2) { - var entity = _entityIDs.length && context.hasEntity(_entityIDs[0]); - if (reverserHidden() || !entity) - return selection2; - var first = entity.first(); - var last = entity.isClosed() ? entity.nodes[entity.nodes.length - 2] : entity.last(); - var pseudoDirection = first < last; - var icon2 = pseudoDirection ? "#iD-icon-forward" : "#iD-icon-backward"; - selection2.selectAll(".reverser-span").html("").call(_t.append("inspector.check.reverser")).call(svgIcon(icon2, "inline")); - return selection2; - } - var check = function(selection2) { - checkImpliedYes(); - label = selection2.selectAll(".form-field-input-wrap").data([0]); - var enter = label.enter().append("label").attr("class", "form-field-input-wrap form-field-input-check"); - enter.append("input").property("indeterminate", field.type !== "defaultCheck").attr("type", "checkbox").attr("id", field.domId); - enter.append("span").html(texts[0]).attr("class", "value"); - if (field.type === "onewayCheck") { - enter.append("button").attr("class", "reverser" + (reverserHidden() ? " hide" : "")).append("span").attr("class", "reverser-span"); + function continueTank() { + if (context.mode().id !== "draw-area") { + return continueTo(addTank); } - label = label.merge(enter); - input = label.selectAll("input"); - text2 = label.selectAll("span.value"); - input.on("click", function(d3_event) { - d3_event.stopPropagation(); - var t2 = {}; - if (Array.isArray(_tags[field.key])) { - if (values.indexOf("yes") !== -1) { - t2[field.key] = "yes"; - } else { - t2[field.key] = values[0]; - } + _tankID = null; + var continueString = helpHtml("intro.buildings.continue_tank") + "{br}" + helpHtml("intro.areas.finish_area_" + (context.lastPointerType() === "mouse" ? "click" : "tap")) + helpHtml("intro.buildings.finish_tank"); + revealTank(tank, continueString); + context.map().on("move.intro drawn.intro", function() { + revealTank(tank, continueString, { duration: 0 }); + }); + context.on("enter.intro", function(mode) { + if (mode.id === "draw-area") { + return; + } else if (mode.id === "select") { + _tankID = context.selectedIDs()[0]; + return continueTo(searchPresetTank); } else { - t2[field.key] = values[(values.indexOf(_value) + 1) % values.length]; - } - if (t2[field.key] === "reversible" || t2[field.key] === "alternating") { - t2[field.key] = values[0]; + return continueTo(addTank); } - dispatch14.call("change", this, t2); }); - if (field.type === "onewayCheck") { - reverser = label.selectAll(".reverser"); - reverser.call(reverserSetText).on("click", function(d3_event) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - context.perform( - function(graph) { - for (var i4 in _entityIDs) { - graph = actionReverse(_entityIDs[i4])(graph); - } - return graph; - }, - _t("operations.reverse.annotation.line", { n: 1 }) - ); - context.validator().validate(); - select_default2(this).call(reverserSetText); - }); - } - }; - check.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return check; - }; - check.tags = function(tags) { - _tags = tags; - function isChecked(val) { - return val !== "no" && val !== "" && val !== void 0 && val !== null; + function continueTo(nextStep) { + context.map().on("move.intro drawn.intro", null); + context.on("enter.intro", null); + nextStep(); } - function textFor(val) { - if (val === "") - val = void 0; - var index = values.indexOf(val); - return index !== -1 ? texts[index] : '"' + val + '"'; + } + function searchPresetTank() { + if (!_tankID || !context.hasEntity(_tankID)) { + return addTank(); } - checkImpliedYes(); - var isMixed = Array.isArray(tags[field.key]); - _value = !isMixed && tags[field.key] && tags[field.key].toLowerCase(); - if (field.type === "onewayCheck" && (_value === "1" || _value === "-1")) { - _value = "yes"; + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _tankID) { + context.enter(modeSelect(context, [_tankID])); } - input.property("indeterminate", isMixed || field.type !== "defaultCheck" && !_value).property("checked", isChecked(_value)); - text2.html(isMixed ? _t.html("inspector.multiple_values") : textFor(_value)).classed("mixed", isMixed); - label.classed("set", !!_value); - if (field.type === "onewayCheck") { - reverser.classed("hide", reverserHidden()).call(reverserSetText); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + timeout2(function() { + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); + reveal( + ".preset-search-input", + helpHtml("intro.buildings.search_tank", { preset: tankPreset.name() }) + ); + }, 400); + context.on("enter.intro", function(mode) { + if (!_tankID || !context.hasEntity(_tankID)) { + return continueTo(addTank); + } + var ids2 = context.selectedIDs(); + if (mode.id !== "select" || !ids2.length || ids2[0] !== _tankID) { + context.enter(modeSelect(context, [_tankID])); + context.container().select(".inspector-wrap .panewrap").style("right", "-100%"); + context.container().select(".inspector-wrap").on("wheel.intro", eventCancel); + context.container().select(".preset-search-input").on("keydown.intro", null).on("keyup.intro", checkPresetSearch); + reveal( + ".preset-search-input", + helpHtml("intro.buildings.search_tank", { preset: tankPreset.name() }) + ); + context.history().on("change.intro", null); + } + }); + function checkPresetSearch() { + var first = context.container().select(".preset-list-item:first-child"); + if (first.classed("preset-man_made-storage_tank")) { + reveal( + first.select(".preset-list-button").node(), + helpHtml("intro.buildings.choose_tank", { preset: tankPreset.name() }), + { duration: 300 } + ); + context.container().select(".preset-search-input").on("keydown.intro", eventCancel, true).on("keyup.intro", null); + context.history().on("change.intro", function() { + continueTo(closeEditorTank); + }); + } } - }; - check.focus = function() { - input.node().focus(); - }; - return utilRebind(check, dispatch14, "on"); - } - - // modules/ui/length_indicator.js - function uiLengthIndicator(maxChars) { - var _wrap = select_default2(null); - var _tooltip = uiPopover("tooltip max-length-warning").placement("bottom").hasArrow(true).content(() => (selection2) => { - selection2.text(""); - selection2.call(svgIcon("#iD-icon-alert", "inline")); - selection2.call(_t.append("inspector.max_length_reached", { maxChars })); - }); - var _silent = false; - var lengthIndicator = function(selection2) { - _wrap = selection2.selectAll("span.length-indicator-wrap").data([0]); - _wrap = _wrap.enter().append("span").merge(_wrap).classed("length-indicator-wrap", true); - selection2.call(_tooltip); - }; - lengthIndicator.update = function(val) { - const strLen = utilUnicodeCharsCount(utilCleanOsmString(val, Number.POSITIVE_INFINITY)); - let indicator = _wrap.selectAll("span.length-indicator").data([strLen]); - indicator.enter().append("span").merge(indicator).classed("length-indicator", true).classed("limit-reached", (d2) => d2 > maxChars).style("border-right-width", (d2) => "".concat(Math.abs(maxChars - d2) * 2, "px")).style("margin-right", (d2) => d2 > maxChars ? "".concat((maxChars - d2) * 2, "px") : 0).style("opacity", (d2) => d2 > maxChars * 0.8 ? Math.min(1, (d2 / maxChars - 0.8) / (1 - 0.8)) : 0).style("pointer-events", (d2) => d2 > maxChars * 0.8 ? null : "none"); - if (_silent) - return; - if (strLen > maxChars) { - _tooltip.show(); - } else { - _tooltip.hide(); + function continueTo(nextStep) { + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.on("enter.intro", null); + context.history().on("change.intro", null); + context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); + nextStep(); } - }; - lengthIndicator.silent = function(val) { - if (!arguments.length) - return _silent; - _silent = val; - return lengthIndicator; - }; - return lengthIndicator; - } - - // modules/ui/fields/combo.js - function uiFieldCombo(field, context) { - var dispatch14 = dispatch_default("change"); - var _isMulti = field.type === "multiCombo" || field.type === "manyCombo"; - var _isNetwork = field.type === "networkCombo"; - var _isSemi = field.type === "semiCombo"; - var _showTagInfoSuggestions = field.type !== "manyCombo" && field.autoSuggestions !== false; - var _allowCustomValues = field.type !== "manyCombo" && field.customValues !== false; - var _snake_case = field.snake_case || field.snake_case === void 0; - var _combobox = uiCombobox(context, "combo-" + field.safeid).caseSensitive(field.caseSensitive).minItems(1); - var _container = select_default2(null); - var _inputWrap = select_default2(null); - var _input = select_default2(null); - var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()); - var _comboData = []; - var _multiData = []; - var _entityIDs = []; - var _tags; - var _countryCode; - var _staticPlaceholder; - var _dataDeprecated = []; - _mainFileFetcher.get("deprecated").then(function(d2) { - _dataDeprecated = d2; - }).catch(function() { - }); - if (_isMulti && field.key && /[^:]$/.test(field.key)) { - field.key += ":"; - } - function snake(s2) { - return s2.replace(/\s+/g, "_"); - } - function clean2(s2) { - return s2.split(";").map(function(s3) { - return s3.trim(); - }).join(";"); } - function tagValue(dval) { - dval = clean2(dval || ""); - var found = getOptions(true).find(function(o2) { - return o2.key && clean2(o2.value) === dval; - }); - if (found) - return found.key; - if (field.type === "typeCombo" && !dval) { - return "yes"; + function closeEditorTank() { + if (!_tankID || !context.hasEntity(_tankID)) { + return addTank(); } - return restrictTagValueSpelling(dval) || void 0; - } - function restrictTagValueSpelling(dval) { - if (_snake_case) { - dval = snake(dval); + var ids = context.selectedIDs(); + if (context.mode().id !== "select" || !ids.length || ids[0] !== _tankID) { + context.enter(modeSelect(context, [_tankID])); } - if (!field.caseSensitive) { - dval = dval.toLowerCase(); + context.history().checkpoint("hasTank"); + context.on("exit.intro", function() { + continueTo(rightClickTank); + }); + timeout2(function() { + reveal( + ".entity-editor-pane", + helpHtml("intro.buildings.close", { button: { html: icon("#iD-icon-close", "inline") } }) + ); + }, 500); + function continueTo(nextStep) { + context.on("exit.intro", null); + nextStep(); } - return dval; - } - function getLabelId(field2, v2) { - return field2.hasTextForStringId("options.".concat(v2, ".title")) ? "options.".concat(v2, ".title") : "options.".concat(v2); } - function displayValue(tval) { - tval = tval || ""; - var stringsField = field.resolveReference("stringsCrossReference"); - const labelId = getLabelId(stringsField, tval); - if (stringsField.hasTextForStringId(labelId)) { - return stringsField.t(labelId, { default: tval }); - } - if (field.type === "typeCombo" && tval.toLowerCase() === "yes") { - return ""; + function rightClickTank() { + if (!_tankID) + return continueTo(addTank); + context.enter(modeBrowse(context)); + context.history().reset("hasTank"); + context.map().centerEase(tank, 500); + timeout2(function() { + context.on("enter.intro", function(mode) { + if (mode.id !== "select") + return; + var ids = context.selectedIDs(); + if (ids.length !== 1 || ids[0] !== _tankID) + return; + timeout2(function() { + var node = selectMenuItem(context, "circularize").node(); + if (!node) + return; + continueTo(clickCircle); + }, 50); + }); + var rightclickString = helpHtml("intro.buildings." + (context.lastPointerType() === "mouse" ? "rightclick_tank" : "edit_menu_tank_touch")); + revealTank(tank, rightclickString); + context.map().on("move.intro drawn.intro", function() { + revealTank(tank, rightclickString, { duration: 0 }); + }); + context.history().on("change.intro", function() { + continueTo(rightClickTank); + }); + }, 600); + function continueTo(nextStep) { + context.on("enter.intro", null); + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + nextStep(); } - return tval; } - function renderValue(tval) { - tval = tval || ""; - var stringsField = field.resolveReference("stringsCrossReference"); - const labelId = getLabelId(stringsField, tval); - if (stringsField.hasTextForStringId(labelId)) { - return stringsField.t.append(labelId, { default: tval }); - } - if (field.type === "typeCombo" && tval.toLowerCase() === "yes") { - tval = ""; + function clickCircle() { + if (!_tankID) + return chapter.restart(); + var entity = context.hasEntity(_tankID); + if (!entity) + return continueTo(rightClickTank); + var node = selectMenuItem(context, "circularize").node(); + if (!node) { + return continueTo(rightClickTank); } - return (selection2) => selection2.text(tval); - } - function objectDifference(a2, b2) { - return a2.filter(function(d1) { - return !b2.some(function(d2) { - return d1.value === d2.value; - }); + var wasChanged = false; + reveal( + ".edit-menu", + helpHtml("intro.buildings.circle_tank"), + { padding: 50 } + ); + context.on("enter.intro", function(mode) { + if (mode.id === "browse") { + continueTo(rightClickTank); + } else if (mode.id === "move" || mode.id === "rotate") { + continueTo(retryClickCircle); + } + }); + context.map().on("move.intro", function() { + var node2 = selectMenuItem(context, "circularize").node(); + if (!wasChanged && !node2) { + return continueTo(rightClickTank); + } + reveal( + ".edit-menu", + helpHtml("intro.buildings.circle_tank"), + { duration: 0, padding: 50 } + ); }); - } - function initCombo(selection2, attachTo) { - if (!_allowCustomValues) { - selection2.attr("readonly", "readonly"); - } - if (_showTagInfoSuggestions && services.taginfo) { - selection2.call(_combobox.fetcher(setTaginfoValues), attachTo); - setTaginfoValues("", setPlaceholder); - } else { - selection2.call(_combobox, attachTo); - setTimeout(() => setStaticValues(setPlaceholder), 0); + context.history().on("change.intro", function() { + wasChanged = true; + context.history().on("change.intro", null); + timeout2(function() { + if (context.history().undoAnnotation() === _t("operations.circularize.annotation.feature", { n: 1 })) { + continueTo(play); + } else { + continueTo(retryClickCircle); + } + }, 500); + }); + function continueTo(nextStep) { + context.on("enter.intro", null); + context.map().on("move.intro", null); + context.history().on("change.intro", null); + nextStep(); } } - function getOptions(allOptions) { - var stringsField = field.resolveReference("stringsCrossReference"); - if (!(field.options || stringsField.options)) - return []; - let options2; - if (allOptions !== true) { - options2 = field.options || stringsField.options; - } else { - options2 = [].concat(field.options, stringsField.options).filter(Boolean); - } - return options2.map(function(v2) { - const labelId = getLabelId(stringsField, v2); - return { - key: v2, - value: stringsField.t(labelId, { default: v2 }), - title: stringsField.t("options.".concat(v2, ".description"), { default: v2 }), - display: addComboboxIcons(stringsField.t.append(labelId, { default: v2 }), v2), - klass: stringsField.hasTextForStringId(labelId) ? "" : "raw-option" - }; + function retryClickCircle() { + context.enter(modeBrowse(context)); + revealTank(tank, helpHtml("intro.buildings.retry_circle"), { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + continueTo(rightClickTank); + } }); + function continueTo(nextStep) { + nextStep(); + } } - function hasStaticValues() { - return getOptions().length > 0; + function play() { + dispatch14.call("done"); + reveal( + ".ideditor", + helpHtml("intro.buildings.play", { next: _t("intro.startediting.title") }), + { + tooltipBox: ".intro-nav-wrap .chapter-startEditing", + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + reveal(".ideditor"); + } + } + ); } - function setStaticValues(callback, filter2) { - _comboData = getOptions(); - if (filter2 !== void 0) { - _comboData = _comboData.filter(filter2); - } - _comboData = objectDifference(_comboData, _multiData); - _combobox.data(_comboData); - if (callback) - callback(_comboData); + chapter.enter = function() { + addHouse(); + }; + chapter.exit = function() { + timeouts.forEach(window.clearTimeout); + context.on("enter.intro exit.intro", null); + context.map().on("move.intro drawn.intro", null); + context.history().on("change.intro", null); + context.container().select(".inspector-wrap").on("wheel.intro", null); + context.container().select(".preset-search-input").on("keydown.intro keyup.intro", null); + context.container().select(".more-fields .combobox-input").on("click.intro", null); + }; + chapter.restart = function() { + chapter.exit(); + chapter.enter(); + }; + return utilRebind(chapter, dispatch14, "on"); + } + + // modules/ui/intro/start_editing.js + function uiIntroStartEditing(context, reveal) { + var dispatch14 = dispatch_default("done", "startEditing"); + var modalSelection = select_default2(null); + var chapter = { + title: "intro.startediting.title" + }; + function showHelp() { + reveal( + ".map-control.help-control", + helpHtml("intro.startediting.help"), + { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + shortcuts(); + } + } + ); } - function setTaginfoValues(q2, callback) { - var queryFilter = (d2) => d2.value.toLowerCase().includes(q2.toLowerCase()) || d2.key.toLowerCase().includes(q2.toLowerCase()); - if (hasStaticValues()) { - setStaticValues(callback, queryFilter); - } - var stringsField = field.resolveReference("stringsCrossReference"); - var fn = _isMulti ? "multikeys" : "values"; - var query = (_isMulti ? field.key : "") + q2; - var hasCountryPrefix = _isNetwork && _countryCode && _countryCode.indexOf(q2.toLowerCase()) === 0; - if (hasCountryPrefix) { - query = _countryCode + ":"; - } - var params = { - debounce: q2 !== "", - key: field.key, - query - }; - if (_entityIDs.length) { - params.geometry = context.graph().geometry(_entityIDs[0]); - } - services.taginfo[fn](params, function(err, data) { - if (err) - return; - data = data.filter((d2) => field.type !== "typeCombo" || d2.value !== "yes"); - data = data.filter((d2) => { - var value = d2.value; - if (_isMulti) { - value = value.slice(field.key.length); + function shortcuts() { + reveal( + ".map-control.help-control", + helpHtml("intro.startediting.shortcuts"), + { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + showSave(); } - return value === restrictTagValueSpelling(value); - }); - var deprecatedValues = osmEntity.deprecatedTagValuesByKey(_dataDeprecated)[field.key]; - if (deprecatedValues) { - data = data.filter((d2) => !deprecatedValues.includes(d2.value)); } - if (hasCountryPrefix) { - data = data.filter((d2) => d2.value.toLowerCase().indexOf(_countryCode + ":") === 0); + ); + } + function showSave() { + context.container().selectAll(".shaded").remove(); + reveal( + ".top-toolbar button.save", + helpHtml("intro.startediting.save"), + { + buttonText: _t.html("intro.ok"), + buttonCallback: function() { + showStart(); + } } - const additionalOptions = (field.options || stringsField.options || []).filter((v2) => !data.some((dv) => dv.value === (_isMulti ? field.key + v2 : v2))).map((v2) => ({ value: v2 })); - _container.classed("empty-combobox", data.length === 0); - _comboData = data.concat(additionalOptions).map(function(d2) { - var v2 = d2.value; - if (_isMulti) - v2 = v2.replace(field.key, ""); - const labelId = getLabelId(stringsField, v2); - var isLocalizable = stringsField.hasTextForStringId(labelId); - var label = stringsField.t(labelId, { default: v2 }); - return { - key: v2, - value: label, - title: stringsField.t("options.".concat(v2, ".description"), { default: isLocalizable ? v2 : d2.title !== label ? d2.title : "" }), - display: addComboboxIcons(stringsField.t.append(labelId, { default: v2 }), v2), - klass: isLocalizable ? "" : "raw-option" - }; - }); - _comboData = _comboData.filter(queryFilter); - _comboData = objectDifference(_comboData, _multiData); - if (callback) - callback(_comboData, hasStaticValues()); + ); + } + function showStart() { + context.container().selectAll(".shaded").remove(); + modalSelection = uiModal(context.container()); + modalSelection.select(".modal").attr("class", "modal-splash modal"); + modalSelection.selectAll(".close").remove(); + var startbutton = modalSelection.select(".content").attr("class", "fillL").append("button").attr("class", "modal-section huge-modal-button").on("click", function() { + modalSelection.remove(); }); + startbutton.append("svg").attr("class", "illustration").append("use").attr("xlink:href", "#iD-logo-walkthrough"); + startbutton.append("h2").call(_t.append("intro.startediting.start")); + dispatch14.call("startEditing"); } - function addComboboxIcons(disp, value) { - const iconsField = field.resolveReference("iconsCrossReference"); - if (iconsField.icons) { - return function(selection2) { - var span = selection2.insert("span", ":first-child").attr("class", "tag-value-icon"); - if (iconsField.icons[value]) { - span.call(svgIcon("#".concat(iconsField.icons[value]))); + chapter.enter = function() { + showHelp(); + }; + chapter.exit = function() { + modalSelection.remove(); + context.container().selectAll(".shaded").remove(); + }; + return utilRebind(chapter, dispatch14, "on"); + } + + // modules/ui/intro/intro.js + var chapterUi = { + welcome: uiIntroWelcome, + navigation: uiIntroNavigation, + point: uiIntroPoint, + area: uiIntroArea, + line: uiIntroLine, + building: uiIntroBuilding, + startEditing: uiIntroStartEditing + }; + var chapterFlow = [ + "welcome", + "navigation", + "point", + "area", + "line", + "building", + "startEditing" + ]; + function uiIntro(context) { + const INTRO_IMAGERY = "EsriWorldImageryClarity"; + let _introGraph = {}; + let _currChapter; + function intro(selection2) { + _mainFileFetcher.get("intro_graph").then((dataIntroGraph) => { + for (let id2 in dataIntroGraph) { + if (!_introGraph[id2]) { + _introGraph[id2] = osmEntity(localize(dataIntroGraph[id2])); } - disp.call(this, selection2); - }; - } - return disp; + } + selection2.call(startIntro); + }).catch(function() { + }); } - function setPlaceholder(values) { - if (_isMulti || _isSemi) { - _staticPlaceholder = field.placeholder() || _t("inspector.add"); - } else { - var vals = values.map(function(d2) { - return d2.value; - }).filter(function(s2) { - return s2.length < 20; - }); - var placeholders = vals.length > 1 ? vals : values.map(function(d2) { - return d2.key; - }); - _staticPlaceholder = field.placeholder() || placeholders.slice(0, 3).join(", "); - } - if (!/(…|\.\.\.)$/.test(_staticPlaceholder)) { - _staticPlaceholder += "\u2026"; + function startIntro(selection2) { + context.enter(modeBrowse(context)); + let osm = context.connection(); + let history = context.history().toJSON(); + let hash = window.location.hash; + let center = context.map().center(); + let zoom = context.map().zoom(); + let background = context.background().baseLayerSource(); + let overlays = context.background().overlayLayerSources(); + let opacity = context.container().selectAll(".main-map .layer-background").style("opacity"); + let caches = osm && osm.caches(); + let baseEntities = context.history().graph().base().entities; + context.ui().sidebar.expand(); + context.container().selectAll("button.sidebar-toggle").classed("disabled", true); + context.inIntro(true); + if (osm) { + osm.toggle(false).reset(); } - var ph; - if (!_isMulti && !_isSemi && _tags && Array.isArray(_tags[field.key])) { - ph = _t("inspector.multiple_values"); + context.history().reset(); + context.history().merge(Object.values(coreGraph().load(_introGraph).entities)); + context.history().checkpoint("initial"); + let imagery = context.background().findSource(INTRO_IMAGERY); + if (imagery) { + context.background().baseLayerSource(imagery); } else { - ph = _staticPlaceholder; + context.background().bing(); } - _container.selectAll("input").attr("placeholder", ph); - var hideAdd = !_allowCustomValues && !values.length; - _container.selectAll(".chiplist .input-wrap").style("display", hideAdd ? "none" : null); - } - function change() { - var t2 = {}; - var val; - if (_isMulti || _isSemi) { - var vals; - if (_isMulti) { - vals = [tagValue(utilGetSetValue(_input))]; - } else if (_isSemi) { - val = tagValue(utilGetSetValue(_input)) || ""; - val = val.replace(/,/g, ";"); - vals = val.split(";"); + overlays.forEach((d2) => context.background().toggleOverlayLayer(d2)); + let layers = context.layers(); + layers.all().forEach((item) => { + if (typeof item.layer.enabled === "function") { + item.layer.enabled(item.id === "osm"); } - vals = vals.filter(Boolean); - if (!vals.length) - return; - _container.classed("active", false); - utilGetSetValue(_input, ""); - if (_isMulti) { - utilArrayUniq(vals).forEach(function(v2) { - var key = (field.key || "") + v2; - if (_tags) { - var old = _tags[key]; - if (typeof old === "string" && old.toLowerCase() !== "no") - return; - } - key = context.cleanTagKey(key); - field.keys.push(key); - t2[key] = "yes"; - }); - } else if (_isSemi) { - var arr = _multiData.map(function(d2) { - return d2.key; - }); - arr = arr.concat(vals); - t2[field.key] = context.cleanTagValue(utilArrayUniq(arr).filter(Boolean).join(";")); + }); + context.container().selectAll(".main-map .layer-background").style("opacity", 1); + let curtain = uiCurtain(context.container().node()); + selection2.call(curtain); + corePreferences("walkthrough_started", "yes"); + let storedProgress = corePreferences("walkthrough_progress") || ""; + let progress = storedProgress.split(";").filter(Boolean); + let chapters = chapterFlow.map((chapter, i3) => { + let s2 = chapterUi[chapter](context, curtain.reveal).on("done", () => { + buttons.filter((d2) => d2.title === s2.title).classed("finished", true); + if (i3 < chapterFlow.length - 1) { + const next = chapterFlow[i3 + 1]; + context.container().select("button.chapter-".concat(next)).classed("next", true); + } + progress.push(chapter); + corePreferences("walkthrough_progress", utilArrayUniq(progress).join(";")); + }); + return s2; + }); + chapters[chapters.length - 1].on("startEditing", () => { + progress.push("startEditing"); + corePreferences("walkthrough_progress", utilArrayUniq(progress).join(";")); + let incomplete = utilArrayDifference(chapterFlow, progress); + if (!incomplete.length) { + corePreferences("walkthrough_completed", "yes"); } - window.setTimeout(function() { - _input.node().focus(); - }, 10); - } else { - var rawValue = utilGetSetValue(_input); - if (!rawValue && Array.isArray(_tags[field.key])) - return; - val = context.cleanTagValue(tagValue(rawValue)); - t2[field.key] = val || void 0; + curtain.remove(); + navwrap.remove(); + context.container().selectAll(".main-map .layer-background").style("opacity", opacity); + context.container().selectAll("button.sidebar-toggle").classed("disabled", false); + if (osm) { + osm.toggle(true).reset().caches(caches); + } + context.history().reset().merge(Object.values(baseEntities)); + context.background().baseLayerSource(background); + overlays.forEach((d2) => context.background().toggleOverlayLayer(d2)); + if (history) { + context.history().fromJSON(history, false); + } + context.map().centerZoom(center, zoom); + window.location.replace(hash); + context.inIntro(false); + }); + let navwrap = selection2.append("div").attr("class", "intro-nav-wrap fillD"); + navwrap.append("svg").attr("class", "intro-nav-wrap-logo").append("use").attr("xlink:href", "#iD-logo-walkthrough"); + let buttonwrap = navwrap.append("div").attr("class", "joined").selectAll("button.chapter"); + let buttons = buttonwrap.data(chapters).enter().append("button").attr("class", (d2, i3) => "chapter chapter-".concat(chapterFlow[i3])).on("click", enterChapter); + buttons.append("span").html((d2) => _t.html(d2.title)); + buttons.append("span").attr("class", "status").call(svgIcon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward", "inline")); + enterChapter(null, chapters[0]); + function enterChapter(d3_event, newChapter) { + if (_currChapter) { + _currChapter.exit(); + } + context.enter(modeBrowse(context)); + _currChapter = newChapter; + _currChapter.enter(); + buttons.classed("next", false).classed("active", (d2) => d2.title === _currChapter.title); } - dispatch14.call("change", this, t2); } - function removeMultikey(d3_event, d2) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - var t2 = {}; - if (_isMulti) { - t2[d2.key] = void 0; - } else if (_isSemi) { - var arr = _multiData.map(function(md) { - return md.key === d2.key ? null : md.key; - }).filter(Boolean); - arr = utilArrayUniq(arr); - t2[field.key] = arr.length ? arr.join(";") : void 0; - _lengthIndicator.update(t2[field.key]); + return intro; + } + + // modules/ui/issues_info.js + function uiIssuesInfo(context) { + var warningsItem = { + id: "warnings", + count: 0, + iconID: "iD-icon-alert", + descriptionID: "issues.warnings_and_errors" + }; + var resolvedItem = { + id: "resolved", + count: 0, + iconID: "iD-icon-apply", + descriptionID: "issues.user_resolved_issues" + }; + function update(selection2) { + var shownItems = []; + var liveIssues = context.validator().getIssues({ + what: corePreferences("validate-what") || "edited", + where: corePreferences("validate-where") || "all" + }); + if (liveIssues.length) { + warningsItem.count = liveIssues.length; + shownItems.push(warningsItem); } - dispatch14.call("change", this, t2); + if (corePreferences("validate-what") === "all") { + var resolvedIssues = context.validator().getResolvedIssues(); + if (resolvedIssues.length) { + resolvedItem.count = resolvedIssues.length; + shownItems.push(resolvedItem); + } + } + var chips = selection2.selectAll(".chip").data(shownItems, function(d2) { + return d2.id; + }); + chips.exit().remove(); + var enter = chips.enter().append("a").attr("class", function(d2) { + return "chip " + d2.id + "-count"; + }).attr("href", "#").each(function(d2) { + var chipSelection = select_default2(this); + var tooltipBehavior = uiTooltip().placement("top").title(() => _t.append(d2.descriptionID)); + chipSelection.call(tooltipBehavior).on("click", function(d3_event) { + d3_event.preventDefault(); + tooltipBehavior.hide(select_default2(this)); + context.ui().togglePanes(context.container().select(".map-panes .issues-pane")); + }); + chipSelection.call(svgIcon("#" + d2.iconID)); + }); + enter.append("span").attr("class", "count"); + enter.merge(chips).selectAll("span.count").text(function(d2) { + return d2.count.toString(); + }); } - function invertMultikey(d3_event, d2) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - var t2 = {}; - if (_isMulti) { - t2[d2.key] = _tags[d2.key] === "yes" ? "no" : "yes"; + return function(selection2) { + update(selection2); + context.validator().on("validated.infobox", function() { + update(selection2); + }); + }; + } + + // modules/ui/map_in_map.js + function uiMapInMap(context) { + function mapInMap(selection2) { + var backgroundLayer = rendererTileLayer(context); + var overlayLayers = {}; + var projection2 = geoRawMercator(); + var dataLayer = svgData(projection2, context).showLabels(false); + var debugLayer = svgDebug(projection2, context); + var zoom = zoom_default2().scaleExtent([geoZoomToScale(0.5), geoZoomToScale(24)]).on("start", zoomStarted).on("zoom", zoomed).on("end", zoomEnded); + var wrap2 = select_default2(null); + var tiles = select_default2(null); + var viewport = select_default2(null); + var _isTransformed = false; + var _isHidden = true; + var _skipEvents = false; + var _gesture = null; + var _zDiff = 6; + var _dMini; + var _cMini; + var _tStart; + var _tCurr; + var _timeoutID; + function zoomStarted() { + if (_skipEvents) + return; + _tStart = _tCurr = projection2.transform(); + _gesture = null; } - dispatch14.call("change", this, t2); - } - function combo(selection2) { - _container = selection2.selectAll(".form-field-input-wrap").data([0]); - var type2 = _isMulti || _isSemi ? "multicombo" : "combo"; - _container = _container.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + type2).merge(_container); - if (_isMulti || _isSemi) { - _container = _container.selectAll(".chiplist").data([0]); - var listClass = "chiplist"; - if (field.key === "destination" || field.key === "via") { - listClass += " full-line-chips"; + function zoomed(d3_event) { + if (_skipEvents) + return; + var x2 = d3_event.transform.x; + var y2 = d3_event.transform.y; + var k2 = d3_event.transform.k; + var isZooming = k2 !== _tStart.k; + var isPanning = x2 !== _tStart.x || y2 !== _tStart.y; + if (!isZooming && !isPanning) { + return; } - _container = _container.enter().append("ul").attr("class", listClass).on("click", function() { - window.setTimeout(function() { - _input.node().focus(); - }, 10); - }).merge(_container); - _inputWrap = _container.selectAll(".input-wrap").data([0]); - _inputWrap = _inputWrap.enter().append("li").attr("class", "input-wrap").merge(_inputWrap); - var hideAdd = !_allowCustomValues && !_comboData.length; - _inputWrap.style("display", hideAdd ? "none" : null); - _input = _inputWrap.selectAll("input").data([0]); - } else { - _input = _container.selectAll("input").data([0]); - } - _input = _input.enter().append("input").attr("type", "text").attr("id", field.domId).call(utilNoAuto).call(initCombo, _container).merge(_input); - if (_isSemi) { - _inputWrap.call(_lengthIndicator); - } else if (!_isMulti) { - _container.call(_lengthIndicator); + if (!_gesture) { + _gesture = isZooming ? "zoom" : "pan"; + } + var tMini = projection2.transform(); + var tX, tY, scale; + if (_gesture === "zoom") { + scale = k2 / tMini.k; + tX = (_cMini[0] / scale - _cMini[0]) * scale; + tY = (_cMini[1] / scale - _cMini[1]) * scale; + } else { + k2 = tMini.k; + scale = 1; + tX = x2 - tMini.x; + tY = y2 - tMini.y; + } + utilSetTransform(tiles, tX, tY, scale); + utilSetTransform(viewport, 0, 0, scale); + _isTransformed = true; + _tCurr = identity2.translate(x2, y2).scale(k2); + var zMain = geoScaleToZoom(context.projection.scale()); + var zMini = geoScaleToZoom(k2); + _zDiff = zMain - zMini; + queueRedraw(); } - if (_isNetwork) { - var extent = combinedEntityExtent(); - var countryCode = extent && iso1A2Code(extent.center()); - _countryCode = countryCode && countryCode.toLowerCase(); + function zoomEnded() { + if (_skipEvents) + return; + if (_gesture !== "pan") + return; + updateProjection(); + _gesture = null; + context.map().center(projection2.invert(_cMini)); } - _input.on("change", change).on("blur", change).on("input", function() { - let val = utilGetSetValue(_input); - updateIcon(val); - if (_isSemi && _tags[field.key]) { - val += ";" + _tags[field.key]; + function updateProjection() { + var loc = context.map().center(); + var tMain = context.projection.transform(); + var zMain = geoScaleToZoom(tMain.k); + var zMini = Math.max(zMain - _zDiff, 0.5); + var kMini = geoZoomToScale(zMini); + projection2.translate([tMain.x, tMain.y]).scale(kMini); + var point2 = projection2(loc); + var mouse = _gesture === "pan" ? geoVecSubtract([_tCurr.x, _tCurr.y], [_tStart.x, _tStart.y]) : [0, 0]; + var xMini = _cMini[0] - point2[0] + tMain.x + mouse[0]; + var yMini = _cMini[1] - point2[1] + tMain.y + mouse[1]; + projection2.translate([xMini, yMini]).clipExtent([[0, 0], _dMini]); + _tCurr = projection2.transform(); + if (_isTransformed) { + utilSetTransform(tiles, 0, 0); + utilSetTransform(viewport, 0, 0); + _isTransformed = false; } - _lengthIndicator.update(val); - }); - _input.on("keydown.field", function(d3_event) { - switch (d3_event.keyCode) { - case 13: - _input.node().blur(); - d3_event.stopPropagation(); - break; + zoom.scaleExtent([geoZoomToScale(0.5), geoZoomToScale(zMain - 3)]); + _skipEvents = true; + wrap2.call(zoom.transform, _tCurr); + _skipEvents = false; + } + function redraw() { + clearTimeout(_timeoutID); + if (_isHidden) + return; + updateProjection(); + var zMini = geoScaleToZoom(projection2.scale()); + tiles = wrap2.selectAll(".map-in-map-tiles").data([0]); + tiles = tiles.enter().append("div").attr("class", "map-in-map-tiles").merge(tiles); + backgroundLayer.source(context.background().baseLayerSource()).projection(projection2).dimensions(_dMini); + var background = tiles.selectAll(".map-in-map-background").data([0]); + background.enter().append("div").attr("class", "map-in-map-background").merge(background).call(backgroundLayer); + var overlaySources = context.background().overlayLayerSources(); + var activeOverlayLayers = []; + for (var i3 = 0; i3 < overlaySources.length; i3++) { + if (overlaySources[i3].validZoom(zMini)) { + if (!overlayLayers[i3]) + overlayLayers[i3] = rendererTileLayer(context); + activeOverlayLayers.push(overlayLayers[i3].source(overlaySources[i3]).projection(projection2).dimensions(_dMini)); + } } - }); - if (_isMulti || _isSemi) { - _combobox.on("accept", function() { - _input.node().blur(); - _input.node().focus(); + var overlay = tiles.selectAll(".map-in-map-overlay").data([0]); + overlay = overlay.enter().append("div").attr("class", "map-in-map-overlay").merge(overlay); + var overlays = overlay.selectAll("div").data(activeOverlayLayers, function(d2) { + return d2.source().name(); }); - _input.on("focus", function() { - _container.classed("active", true); + overlays.exit().remove(); + overlays = overlays.enter().append("div").merge(overlays).each(function(layer) { + select_default2(this).call(layer); }); + var dataLayers = tiles.selectAll(".map-in-map-data").data([0]); + dataLayers.exit().remove(); + dataLayers = dataLayers.enter().append("svg").attr("class", "map-in-map-data").merge(dataLayers).call(dataLayer).call(debugLayer); + if (_gesture !== "pan") { + var getPath = path_default(projection2); + var bbox2 = { type: "Polygon", coordinates: [context.map().extent().polygon()] }; + viewport = wrap2.selectAll(".map-in-map-viewport").data([0]); + viewport = viewport.enter().append("svg").attr("class", "map-in-map-viewport").merge(viewport); + var path = viewport.selectAll(".map-in-map-bbox").data([bbox2]); + path.enter().append("path").attr("class", "map-in-map-bbox").merge(path).attr("d", getPath).classed("thick", function(d2) { + return getPath.area(d2) < 30; + }); + } } - _combobox.on("cancel", function() { - _input.node().blur(); - }).on("update", function() { - updateIcon(utilGetSetValue(_input)); - }); - } - function updateIcon(value) { - value = tagValue(value); - let container = _container; - if (field.type === "multiCombo" || field.type === "semiCombo") { - container = _container.select(".input-wrap"); + function queueRedraw() { + clearTimeout(_timeoutID); + _timeoutID = setTimeout(function() { + redraw(); + }, 750); } - const iconsField = field.resolveReference("iconsCrossReference"); - if (iconsField.icons) { - container.selectAll(".tag-value-icon").remove(); - if (iconsField.icons[value]) { - container.selectAll(".tag-value-icon").data([value]).enter().insert("div", "input").attr("class", "tag-value-icon").call(svgIcon("#".concat(iconsField.icons[value]))); + function toggle(d3_event) { + if (d3_event) + d3_event.preventDefault(); + _isHidden = !_isHidden; + context.container().select(".minimap-toggle-item").classed("active", !_isHidden).select("input").property("checked", !_isHidden); + if (_isHidden) { + wrap2.style("display", "block").style("opacity", "1").transition().duration(200).style("opacity", "0").on("end", function() { + selection2.selectAll(".map-in-map").style("display", "none"); + }); + } else { + wrap2.style("display", "block").style("opacity", "0").transition().duration(200).style("opacity", "1").on("end", function() { + redraw(); + }); } } + uiMapInMap.toggle = toggle; + wrap2 = selection2.selectAll(".map-in-map").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "map-in-map").style("display", _isHidden ? "none" : "block").call(zoom).on("dblclick.zoom", null).merge(wrap2); + _dMini = [200, 150]; + _cMini = geoVecScale(_dMini, 0.5); + context.map().on("drawn.map-in-map", function(drawn) { + if (drawn.full === true) { + redraw(); + } + }); + redraw(); + context.keybinding().on(_t("background.minimap.key"), toggle); } - combo.tags = function(tags) { - _tags = tags; - var stringsField = field.resolveReference("stringsCrossReference"); - var isMixed = Array.isArray(tags[field.key]); - var showsValue = (value) => !isMixed && value && !(field.type === "typeCombo" && value === "yes"); - var isRawValue = (value) => showsValue(value) && !stringsField.hasTextForStringId("options.".concat(value)) && !stringsField.hasTextForStringId("options.".concat(value, ".title")); - var isKnownValue = (value) => showsValue(value) && !isRawValue(value); - var isReadOnly = !_allowCustomValues; - if (_isMulti || _isSemi) { - _multiData = []; - var maxLength; - if (_isMulti) { - for (var k2 in tags) { - if (field.key && k2.indexOf(field.key) !== 0) - continue; - if (!field.key && field.keys.indexOf(k2) === -1) - continue; - var v2 = tags[k2]; - var suffix = field.key ? k2.slice(field.key.length) : k2; - _multiData.push({ - key: k2, - value: displayValue(suffix), - display: addComboboxIcons(renderValue(suffix), suffix), - state: typeof v2 === "string" ? v2.toLowerCase() : "", - isMixed: Array.isArray(v2) - }); - } - if (field.key) { - field.keys = _multiData.map(function(d2) { - return d2.key; - }); - maxLength = context.maxCharsForTagKey() - utilUnicodeCharsCount(field.key); - } else { - maxLength = context.maxCharsForTagKey(); - } - } else if (_isSemi) { - var allValues = []; - var commonValues; - if (Array.isArray(tags[field.key])) { - tags[field.key].forEach(function(tagVal) { - var thisVals = utilArrayUniq((tagVal || "").split(";")).filter(Boolean); - allValues = allValues.concat(thisVals); - if (!commonValues) { - commonValues = thisVals; - } else { - commonValues = commonValues.filter((value) => thisVals.includes(value)); - } - }); - allValues = utilArrayUniq(allValues).filter(Boolean); - } else { - allValues = utilArrayUniq((tags[field.key] || "").split(";")).filter(Boolean); - commonValues = allValues; - } - _multiData = allValues.map(function(v3) { - return { - key: v3, - value: displayValue(v3), - display: addComboboxIcons(renderValue(v3), v3), - isMixed: !commonValues.includes(v3) - }; - }); - var currLength = utilUnicodeCharsCount(commonValues.join(";")); - maxLength = context.maxCharsForTagValue() - currLength; - if (currLength > 0) { - maxLength -= 1; - } + return mapInMap; + } + + // modules/ui/notice.js + function uiNotice(context) { + return function(selection2) { + var div = selection2.append("div").attr("class", "notice"); + var button = div.append("button").attr("class", "zoom-to notice fillD").on("click", function() { + context.map().zoomEase(context.minEditableZoom()); + }).on("wheel", function(d3_event) { + var e22 = new WheelEvent(d3_event.type, d3_event); + context.surface().node().dispatchEvent(e22); + }); + button.call(svgIcon("#iD-icon-plus", "pre-text")).append("span").attr("class", "label").call(_t.append("zoom_in_edit")); + function disableTooHigh() { + var canEdit = context.map().zoom() >= context.minEditableZoom(); + div.style("display", canEdit ? "none" : "block"); + } + context.map().on("move.notice", debounce_default(disableTooHigh, 500)); + disableTooHigh(); + }; + } + + // modules/ui/photoviewer.js + function uiPhotoviewer(context) { + var dispatch14 = dispatch_default("resize"); + var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; + function photoviewer(selection2) { + selection2.append("button").attr("class", "thumb-hide").attr("title", _t("icons.close")).on("click", function() { + if (services.streetside) { + services.streetside.hideViewer(context); } - maxLength = Math.max(0, maxLength); - var hideAdd = maxLength <= 0 || !_allowCustomValues && !_comboData.length; - _container.selectAll(".chiplist .input-wrap").style("display", hideAdd ? "none" : null); - var allowDragAndDrop = _isSemi && !Array.isArray(tags[field.key]); - var chips = _container.selectAll(".chip").data(_multiData); - chips.exit().remove(); - var enter = chips.enter().insert("li", ".input-wrap").attr("class", "chip"); - enter.append("span"); - enter.append("a"); - chips = chips.merge(enter).order().classed("raw-value", function(d2) { - var k3 = d2.key; - if (_isMulti) - k3 = k3.replace(field.key, ""); - return !stringsField.hasTextForStringId("options." + k3); - }).classed("draggable", allowDragAndDrop).classed("mixed", function(d2) { - return d2.isMixed; - }).attr("title", function(d2) { - if (d2.isMixed) { - return _t("inspector.unshared_value_tooltip"); - } - if (!["yes", "no"].includes(d2.state)) { - return d2.state; - } - return null; - }).classed("negated", (d2) => d2.state === "no"); - if (!_isSemi) { - chips.selectAll("input[type=checkbox]").remove(); - chips.insert("input", "span").attr("type", "checkbox").property("checked", (d2) => d2.state === "yes").property("indeterminate", (d2) => d2.isMixed || !["yes", "no"].includes(d2.state)).on("click", invertMultikey); + if (services.mapillary) { + services.mapillary.hideViewer(context); } - if (allowDragAndDrop) { - registerDragAndDrop(chips); + if (services.kartaview) { + services.kartaview.hideViewer(context); } - chips.select("span").each(function(d2) { - const selection2 = select_default2(this); - if (d2.display) { - selection2.text(""); - d2.display(selection2); - } else { - selection2.text(d2.value); - } - }); - chips.select("a").attr("href", "#").on("click", removeMultikey).attr("class", "remove").text("\xD7"); - updateIcon(""); - } else { - var mixedValues = isMixed && tags[field.key].map(function(val) { - return displayValue(val); - }).filter(Boolean); - utilGetSetValue(_input, !isMixed ? displayValue(tags[field.key]) : "").data([tags[field.key]]).classed("raw-value", isRawValue).classed("known-value", isKnownValue).attr("readonly", isReadOnly ? "readonly" : void 0).attr("title", isMixed ? mixedValues.join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : _staticPlaceholder || "").classed("mixed", isMixed).on("keydown.deleteCapture", function(d3_event) { - if (isReadOnly && isKnownValue(tags[field.key]) && (d3_event.keyCode === utilKeybinding.keyCodes["\u232B"] || d3_event.keyCode === utilKeybinding.keyCodes["\u2326"])) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - var t2 = {}; - t2[field.key] = void 0; - dispatch14.call("change", this, t2); - } - }); - if (!Array.isArray(tags[field.key])) { - updateIcon(tags[field.key]); + if (services.mapilio) { + services.mapilio.hideViewer(context); } - if (!isMixed) { - _lengthIndicator.update(tags[field.key]); + if (services.vegbilder) { + services.vegbilder.hideViewer(context); } + }).append("div").call(svgIcon("#iD-icon-close")); + function preventDefault(d3_event) { + d3_event.preventDefault(); } - const refreshStyles = () => { - _input.data([tagValue(utilGetSetValue(_input))]).classed("raw-value", isRawValue).classed("known-value", isKnownValue); - }; - _input.on("input.refreshStyles", refreshStyles); - _combobox.on("update.refreshStyles", refreshStyles); - refreshStyles(); - }; - function registerDragAndDrop(selection2) { - var dragOrigin, targetIndex; - selection2.call( - drag_default().on("start", function(d3_event) { - dragOrigin = { - x: d3_event.x, - y: d3_event.y - }; - targetIndex = null; - }).on("drag", function(d3_event) { - var x2 = d3_event.x - dragOrigin.x, y2 = d3_event.y - dragOrigin.y; - if (!select_default2(this).classed("dragging") && // don't display drag until dragging beyond a distance threshold - Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2)) <= 5) + selection2.append("button").attr("class", "resize-handle-xy").on("touchstart touchdown touchend", preventDefault).on( + _pointerPrefix + "down", + buildResizeListener(selection2, "resize", dispatch14, { resizeOnX: true, resizeOnY: true }) + ); + selection2.append("button").attr("class", "resize-handle-x").on("touchstart touchdown touchend", preventDefault).on( + _pointerPrefix + "down", + buildResizeListener(selection2, "resize", dispatch14, { resizeOnX: true }) + ); + selection2.append("button").attr("class", "resize-handle-y").on("touchstart touchdown touchend", preventDefault).on( + _pointerPrefix + "down", + buildResizeListener(selection2, "resize", dispatch14, { resizeOnY: true }) + ); + function buildResizeListener(target, eventName, dispatch15, options2) { + var resizeOnX = !!options2.resizeOnX; + var resizeOnY = !!options2.resizeOnY; + var minHeight = options2.minHeight || 240; + var minWidth = options2.minWidth || 320; + var pointerId; + var startX; + var startY; + var startWidth; + var startHeight; + function startResize(d3_event) { + if (pointerId !== (d3_event.pointerId || "mouse")) return; - var index = selection2.nodes().indexOf(this); - select_default2(this).classed("dragging", true); - targetIndex = null; - var targetIndexOffsetTop = null; - var draggedTagWidth = select_default2(this).node().offsetWidth; - if (field.key === "destination" || field.key === "via") { - _container.selectAll(".chip").style("transform", function(d2, index2) { - var node = select_default2(this).node(); - if (index === index2) { - return "translate(" + x2 + "px, " + y2 + "px)"; - } else if (index2 > index && d3_event.y > node.offsetTop) { - if (targetIndex === null || index2 > targetIndex) { - targetIndex = index2; - } - return "translateY(-100%)"; - } else if (index2 < index && d3_event.y < node.offsetTop + node.offsetHeight) { - if (targetIndex === null || index2 < targetIndex) { - targetIndex = index2; - } - return "translateY(100%)"; - } - return null; - }); - } else { - _container.selectAll(".chip").each(function(d2, index2) { - var node = select_default2(this).node(); - if (index !== index2 && d3_event.x < node.offsetLeft + node.offsetWidth + 5 && d3_event.x > node.offsetLeft && d3_event.y < node.offsetTop + node.offsetHeight && d3_event.y > node.offsetTop) { - targetIndex = index2; - targetIndexOffsetTop = node.offsetTop; - } - }).style("transform", function(d2, index2) { - var node = select_default2(this).node(); - if (index === index2) { - return "translate(" + x2 + "px, " + y2 + "px)"; - } - if (node.offsetTop === targetIndexOffsetTop) { - if (index2 < index && index2 >= targetIndex) { - return "translateX(" + draggedTagWidth + "px)"; - } else if (index2 > index && index2 <= targetIndex) { - return "translateX(-" + draggedTagWidth + "px)"; - } - } - return null; - }); + d3_event.preventDefault(); + d3_event.stopPropagation(); + var mapSize = context.map().dimensions(); + if (resizeOnX) { + var maxWidth = mapSize[0]; + var newWidth = clamp3(startWidth + d3_event.clientX - startX, minWidth, maxWidth); + target.style("width", newWidth + "px"); } - }).on("end", function() { - if (!select_default2(this).classed("dragging")) { - return; + if (resizeOnY) { + var maxHeight = mapSize[1] - 90; + var newHeight = clamp3(startHeight + startY - d3_event.clientY, minHeight, maxHeight); + target.style("height", newHeight + "px"); } - var index = selection2.nodes().indexOf(this); - select_default2(this).classed("dragging", false); - _container.selectAll(".chip").style("transform", null); - if (typeof targetIndex === "number") { - var element = _multiData[index]; - _multiData.splice(index, 1); - _multiData.splice(targetIndex, 0, element); - var t2 = {}; - if (_multiData.length) { - t2[field.key] = _multiData.map(function(element2) { - return element2.key; - }).join(";"); - } else { - t2[field.key] = void 0; - } - dispatch14.call("change", this, t2); + dispatch15.call(eventName, target, subtractPadding(utilGetDimensions(target, true), target)); + } + function clamp3(num, min3, max3) { + return Math.max(min3, Math.min(num, max3)); + } + function stopResize(d3_event) { + if (pointerId !== (d3_event.pointerId || "mouse")) + return; + d3_event.preventDefault(); + d3_event.stopPropagation(); + select_default2(window).on("." + eventName, null); + } + return function initResize(d3_event) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + pointerId = d3_event.pointerId || "mouse"; + startX = d3_event.clientX; + startY = d3_event.clientY; + var targetRect = target.node().getBoundingClientRect(); + startWidth = targetRect.width; + startHeight = targetRect.height; + select_default2(window).on(_pointerPrefix + "move." + eventName, startResize, false).on(_pointerPrefix + "up." + eventName, stopResize, false); + if (_pointerPrefix === "pointer") { + select_default2(window).on("pointercancel." + eventName, stopResize, false); } - dragOrigin = void 0; - targetIndex = void 0; - }) - ); + }; + } } - combo.focus = function() { - _input.node().focus(); + photoviewer.onMapResize = function() { + var photoviewer2 = context.container().select(".photoviewer"); + var content = context.container().select(".main-content"); + var mapDimensions = utilGetDimensions(content, true); + var photoDimensions = utilGetDimensions(photoviewer2, true); + if (photoDimensions[0] > mapDimensions[0] || photoDimensions[1] > mapDimensions[1] - 90) { + var setPhotoDimensions = [ + Math.min(photoDimensions[0], mapDimensions[0]), + Math.min(photoDimensions[1], mapDimensions[1] - 90) + ]; + photoviewer2.style("width", setPhotoDimensions[0] + "px").style("height", setPhotoDimensions[1] + "px"); + dispatch14.call("resize", photoviewer2, subtractPadding(setPhotoDimensions, photoviewer2)); + } }; - combo.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return combo; + function subtractPadding(dimensions, selection2) { + return [ + dimensions[0] - parseFloat(selection2.style("padding-left")) - parseFloat(selection2.style("padding-right")), + dimensions[1] - parseFloat(selection2.style("padding-top")) - parseFloat(selection2.style("padding-bottom")) + ]; + } + return utilRebind(photoviewer, dispatch14, "on"); + } + + // modules/ui/restore.js + function uiRestore(context) { + return function(selection2) { + if (!context.history().hasRestorableChanges()) + return; + let modalSelection = uiModal(selection2, true); + modalSelection.select(".modal").attr("class", "modal fillL"); + let introModal = modalSelection.select(".content"); + introModal.append("div").attr("class", "modal-section").append("h3").call(_t.append("restore.heading")); + introModal.append("div").attr("class", "modal-section").append("p").call(_t.append("restore.description")); + let buttonWrap = introModal.append("div").attr("class", "modal-actions"); + let restore = buttonWrap.append("button").attr("class", "restore").on("click", () => { + context.history().restore(); + modalSelection.remove(); + }); + restore.append("svg").attr("class", "logo logo-restore").append("use").attr("xlink:href", "#iD-logo-restore"); + restore.append("div").call(_t.append("restore.restore")); + let reset = buttonWrap.append("button").attr("class", "reset").on("click", () => { + context.history().clearSaved(); + modalSelection.remove(); + }); + reset.append("svg").attr("class", "logo logo-reset").append("use").attr("xlink:href", "#iD-logo-reset"); + reset.append("div").call(_t.append("restore.reset")); + restore.node().focus(); }; - function combinedEntityExtent() { - return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + } + + // modules/ui/scale.js + function uiScale(context) { + var projection2 = context.projection, isImperial = !_mainLocalizer.usesMetric(), maxLength = 180, tickHeight = 8; + function scaleDefs(loc1, loc2) { + var lat = (loc2[1] + loc1[1]) / 2, conversion = isImperial ? 3.28084 : 1, dist = geoLonToMeters(loc2[0] - loc1[0], lat) * conversion, scale = { dist: 0, px: 0, text: "" }, buckets, i3, val, dLon; + if (isImperial) { + buckets = [528e4, 528e3, 52800, 5280, 500, 50, 5, 1]; + } else { + buckets = [5e6, 5e5, 5e4, 5e3, 500, 50, 5, 1]; + } + for (i3 = 0; i3 < buckets.length; i3++) { + val = buckets[i3]; + if (dist >= val) { + scale.dist = Math.floor(dist / val) * val; + break; + } else { + scale.dist = +dist.toFixed(2); + } + } + dLon = geoMetersToLon(scale.dist / conversion, lat); + scale.px = Math.round(projection2([loc1[0] + dLon, loc1[1]])[0]); + scale.text = displayLength(scale.dist / conversion, isImperial); + return scale; } - return utilRebind(combo, dispatch14, "on"); + function update(selection2) { + var dims = context.map().dimensions(), loc1 = projection2.invert([0, dims[1]]), loc2 = projection2.invert([maxLength, dims[1]]), scale = scaleDefs(loc1, loc2); + selection2.select(".scale-path").attr("d", "M0.5,0.5v" + tickHeight + "h" + scale.px + "v-" + tickHeight); + selection2.select(".scale-text").style(_mainLocalizer.textDirection() === "ltr" ? "left" : "right", scale.px + 16 + "px").text(scale.text); + } + return function(selection2) { + function switchUnits() { + isImperial = !isImperial; + selection2.call(update); + } + var scalegroup = selection2.append("svg").attr("class", "scale").on("click", switchUnits).append("g").attr("transform", "translate(10,11)"); + scalegroup.append("path").attr("class", "scale-path"); + selection2.append("div").attr("class", "scale-text"); + selection2.call(update); + context.map().on("move.scale", function() { + update(selection2); + }); + }; } - // modules/ui/fields/input.js - var likelyRawNumberFormat = /^-?(0\.\d*|\d*\.\d{0,2}(\d{4,})?|\d{4,}\.\d{3})$/; - function uiFieldText(field, context) { - var dispatch14 = dispatch_default("change"); - var input = select_default2(null); - var outlinkButton = select_default2(null); - var wrap2 = select_default2(null); - var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()); - var _entityIDs = []; - var _tags; - var _phoneFormats = {}; - const isDirectionField = field.key.split(":").some((keyPart) => keyPart === "direction"); - const formatFloat = _mainLocalizer.floatFormatter(_mainLocalizer.languageCode()); - const parseLocaleFloat = _mainLocalizer.floatParser(_mainLocalizer.languageCode()); - const countDecimalPlaces = _mainLocalizer.decimalPlaceCounter(_mainLocalizer.languageCode()); - if (field.type === "tel") { - _mainFileFetcher.get("phone_formats").then(function(d2) { - _phoneFormats = d2; - updatePhonePlaceholder(); + // modules/ui/shortcuts.js + function uiShortcuts(context) { + var detected = utilDetect(); + var _activeTab = 0; + var _modalSelection; + var _selection = select_default2(null); + var _dataShortcuts; + function shortcutsModal(_modalSelection2) { + _modalSelection2.select(".modal").classed("modal-shortcuts", true); + var content = _modalSelection2.select(".content"); + content.append("div").attr("class", "modal-section header").append("h2").call(_t.append("shortcuts.title")); + _mainFileFetcher.get("shortcuts").then(function(data) { + _dataShortcuts = data; + content.call(render); }).catch(function() { }); } - function calcLocked() { - var isLocked = (field.id === "brand" || field.id === "network" || field.id === "operator" || field.id === "flag") && _entityIDs.length && _entityIDs.some(function(entityID) { - var entity = context.graph().hasEntity(entityID); - if (!entity) - return false; - if (entity.tags.wikidata) - return true; - var preset = _mainPresetIndex.match(entity, context.graph()); - var isSuggestion = preset && preset.suggestion; - var which = field.id; - return isSuggestion && !!entity.tags[which] && !!entity.tags[which + ":wikidata"]; + function render(selection2) { + if (!_dataShortcuts) + return; + var wrapper = selection2.selectAll(".wrapper").data([0]); + var wrapperEnter = wrapper.enter().append("div").attr("class", "wrapper modal-section"); + var tabsBar = wrapperEnter.append("div").attr("class", "tabs-bar"); + var shortcutsList = wrapperEnter.append("div").attr("class", "shortcuts-list"); + wrapper = wrapper.merge(wrapperEnter); + var tabs = tabsBar.selectAll(".tab").data(_dataShortcuts); + var tabsEnter = tabs.enter().append("a").attr("class", "tab").attr("href", "#").on("click", function(d3_event, d2) { + d3_event.preventDefault(); + var i3 = _dataShortcuts.indexOf(d2); + _activeTab = i3; + render(selection2); }); - field.locked(isLocked); - } - function i3(selection2) { - calcLocked(); - var isLocked = field.locked(); - wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - input = wrap2.selectAll("input").data([0]); - input = input.enter().append("input").attr("type", field.type === "identifier" ? "text" : field.type).attr("id", field.domId).classed(field.type, true).call(utilNoAuto).merge(input); - input.classed("disabled", !!isLocked).attr("readonly", isLocked || null).on("input", change(true)).on("blur", change()).on("change", change()); - wrap2.call(_lengthIndicator); - if (field.type === "tel") { - updatePhonePlaceholder(); - } else if (field.type === "number") { - var rtl = _mainLocalizer.textDirection() === "rtl"; - input.attr("type", "text"); - var inc = field.increment; - var buttons = wrap2.selectAll(".increment, .decrement").data(rtl ? [inc, -inc] : [-inc, inc]); - buttons.enter().append("button").attr("class", function(d2) { - var which = d2 > 0 ? "increment" : "decrement"; - return "form-field-button " + which; - }).attr("title", function(d2) { - var which = d2 > 0 ? "increment" : "decrement"; - return _t("inspector.".concat(which)); - }).merge(buttons).on("click", function(d3_event, d2) { - d3_event.preventDefault(); - var isMixed = Array.isArray(_tags[field.key]); - if (isMixed) - return; - var raw_vals = input.node().value || "0"; - var vals = raw_vals.split(";"); - vals = vals.map(function(v2) { - v2 = v2.trim(); - const isRawNumber = likelyRawNumberFormat.test(v2); - var num = isRawNumber ? parseFloat(v2) : parseLocaleFloat(v2); - if (isDirectionField) { - const compassDir = cardinal[v2.toLowerCase()]; - if (compassDir !== void 0) { - num = compassDir; - } - } - if (!isFinite(num)) - return v2; - num = parseFloat(num); - if (!isFinite(num)) - return v2; - num += d2; - if (isDirectionField) { - num = (num % 360 + 360) % 360; - } - return formatFloat(clamped(num), isRawNumber ? v2.includes(".") ? v2.split(".")[1].length : 0 : countDecimalPlaces(v2)); + tabsEnter.append("span").html(function(d2) { + return _t.html(d2.text); + }); + wrapper.selectAll(".tab").classed("active", function(d2, i3) { + return i3 === _activeTab; + }); + var shortcuts = shortcutsList.selectAll(".shortcut-tab").data(_dataShortcuts); + var shortcutsEnter = shortcuts.enter().append("div").attr("class", function(d2) { + return "shortcut-tab shortcut-tab-" + d2.tab; + }); + var columnsEnter = shortcutsEnter.selectAll(".shortcut-column").data(function(d2) { + return d2.columns; + }).enter().append("table").attr("class", "shortcut-column"); + var rowsEnter = columnsEnter.selectAll(".shortcut-row").data(function(d2) { + return d2.rows; + }).enter().append("tr").attr("class", "shortcut-row"); + var sectionRows = rowsEnter.filter(function(d2) { + return !d2.shortcuts; + }); + sectionRows.append("td"); + sectionRows.append("td").attr("class", "shortcut-section").append("h3").html(function(d2) { + return _t.html(d2.text); + }); + var shortcutRows = rowsEnter.filter(function(d2) { + return d2.shortcuts; + }); + var shortcutKeys = shortcutRows.append("td").attr("class", "shortcut-keys"); + var modifierKeys = shortcutKeys.filter(function(d2) { + return d2.modifiers; + }); + modifierKeys.selectAll("kbd.modifier").data(function(d2) { + if (detected.os === "win" && d2.text === "shortcuts.editing.commands.redo") { + return ["\u2318"]; + } else if (detected.os !== "mac" && d2.text === "shortcuts.browsing.display_options.fullscreen") { + return []; + } else { + return d2.modifiers; + } + }).enter().each(function() { + var selection3 = select_default2(this); + selection3.append("kbd").attr("class", "modifier").text(function(d2) { + return uiCmd.display(d2); + }); + selection3.append("span").text("+"); + }); + shortcutKeys.selectAll("kbd.shortcut").data(function(d2) { + var arr = d2.shortcuts; + if (detected.os === "win" && d2.text === "shortcuts.editing.commands.redo") { + arr = ["Y"]; + } else if (detected.os !== "mac" && d2.text === "shortcuts.browsing.display_options.fullscreen") { + arr = ["F11"]; + } + arr = arr.map(function(s2) { + return uiCmd.display(s2.indexOf(".") !== -1 ? _t(s2) : s2); + }); + return utilArrayUniq(arr).map(function(s2) { + return { + shortcut: s2, + separator: d2.separator, + suffix: d2.suffix + }; + }); + }).enter().each(function(d2, i3, nodes) { + var selection3 = select_default2(this); + var click = d2.shortcut.toLowerCase().match(/(.*).click/); + if (click && click[1]) { + selection3.call(svgIcon("#iD-walkthrough-mouse-" + click[1], "operation")); + } else if (d2.shortcut.toLowerCase() === "long-press") { + selection3.call(svgIcon("#iD-walkthrough-longpress", "longpress operation")); + } else if (d2.shortcut.toLowerCase() === "tap") { + selection3.call(svgIcon("#iD-walkthrough-tap", "tap operation")); + } else { + selection3.append("kbd").attr("class", "shortcut").text(function(d4) { + return d4.shortcut; }); - input.node().value = vals.join(";"); - change()(); + } + if (i3 < nodes.length - 1) { + selection3.append("span").html(d2.separator || "\xA0" + _t.html("shortcuts.or") + "\xA0"); + } else if (i3 === nodes.length - 1 && d2.suffix) { + selection3.append("span").text(d2.suffix); + } + }); + shortcutKeys.filter(function(d2) { + return d2.gesture; + }).each(function() { + var selection3 = select_default2(this); + selection3.append("span").text("+"); + selection3.append("span").attr("class", "gesture").html(function(d2) { + return _t.html(d2.gesture); }); - } else if (field.type === "identifier" && field.urlFormat && field.pattern) { - input.attr("type", "text"); - outlinkButton = wrap2.selectAll(".foreign-id-permalink").data([0]); - outlinkButton.enter().append("button").call(svgIcon("#iD-icon-out-link")).attr("class", "form-field-button foreign-id-permalink").attr("title", function() { - var domainResults = /^https?:\/\/(.{1,}?)\//.exec(field.urlFormat); - if (domainResults.length >= 2 && domainResults[1]) { - var domain2 = domainResults[1]; - return _t("icons.view_on", { domain: domain2 }); - } - return ""; - }).on("click", function(d3_event) { - d3_event.preventDefault(); - var value = validIdentifierValueForLink(); - if (value) { - var url = field.urlFormat.replace(/{value}/, encodeURIComponent(value)); - window.open(url, "_blank"); + }); + shortcutRows.append("td").attr("class", "shortcut-desc").html(function(d2) { + return d2.text ? _t.html(d2.text) : "\xA0"; + }); + wrapper.selectAll(".shortcut-tab").style("display", function(d2, i3) { + return i3 === _activeTab ? "flex" : "none"; + }); + } + return function(selection2, show) { + _selection = selection2; + if (show) { + _modalSelection = uiModal(selection2); + _modalSelection.call(shortcutsModal); + } else { + context.keybinding().on([_t("shortcuts.toggle.key"), "?"], function() { + if (context.container().selectAll(".modal-shortcuts").size()) { + if (_modalSelection) { + _modalSelection.close(); + _modalSelection = null; + } + } else { + _modalSelection = uiModal(_selection); + _modalSelection.call(shortcutsModal); } - }).classed("disabled", () => !validIdentifierValueForLink()).merge(outlinkButton); - } else if (field.type === "url") { - input.attr("type", "text"); - outlinkButton = wrap2.selectAll(".foreign-id-permalink").data([0]); - outlinkButton.enter().append("button").call(svgIcon("#iD-icon-out-link")).attr("class", "form-field-button foreign-id-permalink").attr("title", () => _t("icons.visit_website")).on("click", function(d3_event) { - d3_event.preventDefault(); - const value = validIdentifierValueForLink(); - if (value) - window.open(value, "_blank"); - }).merge(outlinkButton); - } else if (field.type === "colour") { - input.attr("type", "text"); - updateColourPreview(); - } else if (field.type === "date") { - input.attr("type", "text"); - updateDateField(); + }); } - } - function updateColourPreview() { - function isColourValid(colour2) { - if (!colour2.match(/^(#([0-9a-fA-F]{3}){1,2}|\w+)$/)) { - return false; - } else if (!CSS.supports("color", colour2) || ["unset", "inherit", "initial", "revert"].includes(colour2)) { - return false; + }; + } + + // modules/ui/data_header.js + function uiDataHeader() { + var _datum; + function dataHeader(selection2) { + var header = selection2.selectAll(".data-header").data( + _datum ? [_datum] : [], + function(d2) { + return d2.__featurehash__; } - return true; - } - wrap2.selectAll(".colour-preview").remove(); - const colour = utilGetSetValue(input); - if (!isColourValid(colour) && colour !== "") { - wrap2.selectAll("input.colour-selector").remove(); - wrap2.selectAll(".form-field-button").remove(); - return; - } - var colourSelector = wrap2.selectAll(".colour-selector").data([0]); - colourSelector.enter().append("input").attr("type", "color").attr("class", "colour-selector").on("input", debounce_default(function(d3_event) { - d3_event.preventDefault(); - var colour2 = this.value; - if (!isColourValid(colour2)) - return; - utilGetSetValue(input, this.value); - change()(); - updateColourPreview(); - }, 100)); - wrap2.selectAll("input.colour-selector").attr("value", colour); - var chooserButton = wrap2.selectAll(".colour-preview").data([colour]); - chooserButton = chooserButton.enter().append("div").attr("class", "form-field-button colour-preview").append("div").style("background-color", (d2) => d2).attr("class", "colour-box"); - if (colour === "") { - chooserButton = chooserButton.call(svgIcon("#iD-icon-edit")); - } - chooserButton.on("click", () => wrap2.select(".colour-selector").node().showPicker()); + ); + header.exit().remove(); + var headerEnter = header.enter().append("div").attr("class", "data-header"); + var iconEnter = headerEnter.append("div").attr("class", "data-header-icon"); + iconEnter.append("div").attr("class", "preset-icon-28").call(svgIcon("#iD-icon-data", "note-fill")); + headerEnter.append("div").attr("class", "data-header-label").call(_t.append("map_data.layers.custom.title")); } - function updateDateField() { - function isDateValid(date2) { - return date2.match(/^[0-9]{4}(-[0-9]{2}(-[0-9]{2})?)?$/); - } - const date = utilGetSetValue(input); - const now3 = /* @__PURE__ */ new Date(); - const today = new Date(now3.getTime() - now3.getTimezoneOffset() * 6e4).toISOString().split("T")[0]; - if ((field.key === "check_date" || field.key === "survey:date") && date !== today) { - wrap2.selectAll(".date-set-today").data([0]).enter().append("button").attr("class", "form-field-button date-set-today").call(svgIcon("#fas-rotate")).call(uiTooltip().title(() => _t.append("inspector.set_today"))).on("click", () => { - utilGetSetValue(input, today); - change()(); - updateDateField(); + dataHeader.datum = function(val) { + if (!arguments.length) + return _datum; + _datum = val; + return this; + }; + return dataHeader; + } + + // modules/ui/combobox.js + var _comboHideTimerID; + function uiCombobox(context, klass) { + var dispatch14 = dispatch_default("accept", "cancel", "update"); + var container = context.container(); + var _suggestions = []; + var _data = []; + var _fetched = {}; + var _selected = null; + var _canAutocomplete = true; + var _caseSensitive = false; + var _cancelFetch = false; + var _minItems = 2; + var _tDown = 0; + var _mouseEnterHandler, _mouseLeaveHandler; + var _fetcher = function(val, cb) { + cb(_data.filter(function(d2) { + var terms = d2.terms || []; + terms.push(d2.value); + if (d2.key) { + terms.push(d2.key); + } + return terms.some(function(term) { + return term.toString().toLowerCase().indexOf(val.toLowerCase()) !== -1; }); - } else { - wrap2.selectAll(".date-set-today").remove(); - } - if (!isDateValid(date) && date !== "") { - wrap2.selectAll("input.date-selector").remove(); - wrap2.selectAll(".date-calendar").remove(); + })); + }; + var combobox = function(input, attachTo) { + if (!input || input.empty()) return; - } - if (utilDetect().browser !== "Safari") { - var dateSelector = wrap2.selectAll(".date-selector").data([0]); - dateSelector.enter().append("input").attr("type", "date").attr("class", "date-selector").on("input", debounce_default(function(d3_event) { + input.classed("combobox-input", true).on("focus.combo-input", focus).on("blur.combo-input", blur).on("keydown.combo-input", keydown).on("keyup.combo-input", keyup).on("input.combo-input", change).on("mousedown.combo-input", mousedown).each(function() { + var parent = this.parentNode; + var sibling = this.nextSibling; + select_default2(parent).selectAll(".combobox-caret").filter(function(d2) { + return d2 === input.node(); + }).data([input.node()]).enter().insert("div", function() { + return sibling; + }).attr("class", "combobox-caret").on("mousedown.combo-caret", function(d3_event) { d3_event.preventDefault(); - var date2 = this.value; - if (!isDateValid(date2)) - return; - utilGetSetValue(input, this.value); - change()(); - updateDateField(); - }, 100)); - wrap2.selectAll("input.date-selector").attr("value", date); - var calendarButton = wrap2.selectAll(".date-calendar").data([date]); - calendarButton = calendarButton.enter().append("button").attr("class", "form-field-button date-calendar").call(svgIcon("#fas-calendar-days")); - calendarButton.on("click", () => wrap2.select(".date-selector").node().showPicker()); - } - } - function updatePhonePlaceholder() { - if (input.empty() || !Object.keys(_phoneFormats).length) - return; - var extent = combinedEntityExtent(); - var countryCode = extent && iso1A2Code(extent.center()); - var format2 = countryCode && _phoneFormats[countryCode.toLowerCase()]; - if (format2) - input.attr("placeholder", format2); - } - function validIdentifierValueForLink() { - var _a; - const value = utilGetSetValue(input).trim(); - if (field.type === "url" && value) { - try { - return new URL(value).href; - } catch (e3) { - return null; + input.node().focus(); + mousedown(d3_event); + }).on("mouseup.combo-caret", function(d3_event) { + d3_event.preventDefault(); + mouseup(d3_event); + }); + }); + function mousedown(d3_event) { + if (d3_event.button !== 0) + return; + if (input.classed("disabled")) + return; + _tDown = +/* @__PURE__ */ new Date(); + var start2 = input.property("selectionStart"); + var end = input.property("selectionEnd"); + if (start2 !== end) { + var val = utilGetSetValue(input); + input.node().setSelectionRange(val.length, val.length); + return; } + input.on("mouseup.combo-input", mouseup); } - if (field.type === "identifier" && field.pattern) { - return value && ((_a = value.match(new RegExp(field.pattern))) == null ? void 0 : _a[0]); + function mouseup(d3_event) { + input.on("mouseup.combo-input", null); + if (d3_event.button !== 0) + return; + if (input.classed("disabled")) + return; + if (input.node() !== document.activeElement) + return; + var start2 = input.property("selectionStart"); + var end = input.property("selectionEnd"); + if (start2 !== end) + return; + var combo = container.selectAll(".combobox"); + if (combo.empty() || combo.datum() !== input.node()) { + var tOrig = _tDown; + window.setTimeout(function() { + if (tOrig !== _tDown) + return; + fetchComboData("", function() { + show(); + render(); + }); + }, 250); + } else { + hide(); + } } - return null; - } - function clamped(num) { - if (field.minValue !== void 0) { - num = Math.max(num, field.minValue); + function focus() { + fetchComboData(""); } - if (field.maxValue !== void 0) { - num = Math.min(num, field.maxValue); + function blur() { + _comboHideTimerID = window.setTimeout(hide, 75); } - return num; - } - function getVals(tags) { - if (field.keys) { - const multiSelection = context.selectedIDs(); - tags = multiSelection.length > 1 ? context.selectedIDs().map((id2) => context.graph().entity(id2)).map((entity) => entity.tags) : [tags]; - return tags.map((tags2) => new Set(field.keys.reduce((acc, key) => acc.concat(tags2[key]), []).filter(Boolean))).map((vals) => vals.size === 0 ? /* @__PURE__ */ new Set([void 0]) : vals).reduce((a2, b2) => /* @__PURE__ */ new Set([...a2, ...b2])); - } else { - return new Set([].concat(tags[field.key])); + function show() { + hide(); + container.insert("div", ":first-child").datum(input.node()).attr("class", "combobox" + (klass ? " combobox-" + klass : "")).style("position", "absolute").style("display", "block").style("left", "0px").on("mousedown.combo-container", function(d3_event) { + d3_event.preventDefault(); + }); + container.on("scroll.combo-scroll", render, true); } - } - function change(onInput) { - return function() { - var t2 = {}; - var val = utilGetSetValue(input); - if (!onInput) - val = context.cleanTagValue(val); - if (!val && getVals(_tags).size > 1) - return; - var displayVal = val; - if (field.type === "number" && val) { - var numbers2 = val.split(";"); - numbers2 = numbers2.map(function(v2) { - if (likelyRawNumberFormat.test(v2)) { - return v2; - } - var num = parseLocaleFloat(v2); - const fractionDigits = countDecimalPlaces(v2); - return isFinite(num) ? clamped(num).toFixed(fractionDigits) : v2; - }); - val = numbers2.join(";"); + function hide() { + if (_comboHideTimerID) { + window.clearTimeout(_comboHideTimerID); + _comboHideTimerID = void 0; } - if (!onInput) - utilGetSetValue(input, displayVal); - t2[field.key] = val || void 0; - if (field.keys) { - dispatch14.call("change", this, (tags) => { - if (field.keys.some((key) => tags[key])) { - field.keys.filter((key) => tags[key]).forEach((key) => { - tags[key] = val || void 0; - }); - } else { - tags[field.key] = val || void 0; + container.selectAll(".combobox").remove(); + container.on("scroll.combo-scroll", null); + } + function keydown(d3_event) { + var shown = !container.selectAll(".combobox").empty(); + var tagName = input.node() ? input.node().tagName.toLowerCase() : ""; + switch (d3_event.keyCode) { + case 8: + case 46: + d3_event.stopPropagation(); + _selected = null; + render(); + input.on("input.combo-input", function() { + var start2 = input.property("selectionStart"); + input.node().setSelectionRange(start2, start2); + input.on("input.combo-input", change); + change(false); + }); + break; + case 9: + accept(d3_event); + break; + case 13: + d3_event.preventDefault(); + d3_event.stopPropagation(); + accept(d3_event); + break; + case 38: + if (tagName === "textarea" && !shown) + return; + d3_event.preventDefault(); + if (tagName === "input" && !shown) { + show(); } - return tags; - }, onInput); - } else { - dispatch14.call("change", this, t2, onInput); + nav(-1); + break; + case 40: + if (tagName === "textarea" && !shown) + return; + d3_event.preventDefault(); + if (tagName === "input" && !shown) { + show(); + } + nav(1); + break; } - }; - } - i3.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return i3; - }; - i3.tags = function(tags) { - var _a; - _tags = tags; - const vals = getVals(tags); - const isMixed = vals.size > 1; - var val = vals.size === 1 ? (_a = [...vals][0]) != null ? _a : "" : ""; - var shouldUpdate; - if (field.type === "number" && val) { - var numbers2 = val.split(";"); - var oriNumbers = utilGetSetValue(input).split(";"); - if (numbers2.length !== oriNumbers.length) - shouldUpdate = true; - numbers2 = numbers2.map(function(v2) { - v2 = v2.trim(); - var num = Number(v2); - if (!isFinite(num) || v2 === "") - return v2; - const fractionDigits = v2.includes(".") ? v2.split(".")[1].length : 0; - return formatFloat(num, fractionDigits); - }); - val = numbers2.join(";"); - shouldUpdate = (inputValue, setValue) => { - const inputNums = inputValue.split(";").map( - (setVal) => likelyRawNumberFormat.test(setVal) ? parseFloat(setVal) : parseLocaleFloat(setVal) - ); - const setNums = setValue.split(";").map(parseLocaleFloat); - return !isEqual_default(inputNums, setNums); - }; } - utilGetSetValue(input, val, shouldUpdate).attr("title", isMixed ? [...vals].join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder() || _t("inspector.unknown")).classed("mixed", isMixed); - if (field.type === "number") { - const buttons = wrap2.selectAll(".increment, .decrement"); - if (isMixed) { - buttons.attr("disabled", "disabled").classed("disabled", true); - } else { - var raw_vals = tags[field.key] || "0"; - const canIncDec = raw_vals.split(";").some((val2) => isFinite(Number(val2)) || isDirectionField && cardinal[val2.trim().toLowerCase()]); - buttons.attr("disabled", canIncDec ? null : "disabled").classed("disabled", !canIncDec); + function keyup(d3_event) { + switch (d3_event.keyCode) { + case 27: + cancel(); + break; } } - if (field.type === "tel") - updatePhonePlaceholder(); - if (field.type === "colour") - updateColourPreview(); - if (field.type === "date") - updateDateField(); - if (outlinkButton && !outlinkButton.empty()) { - var disabled = !validIdentifierValueForLink(); - outlinkButton.classed("disabled", disabled); - } - if (!isMixed) { - _lengthIndicator.update(tags[field.key]); - } - }; - i3.focus = function() { - var node = input.node(); - if (node) - node.focus(); - }; - function combinedEntityExtent() { - return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); - } - return utilRebind(i3, dispatch14, "on"); - } - - // modules/ui/fields/access.js - function uiFieldAccess(field, context) { - var dispatch14 = dispatch_default("change"); - var items = select_default2(null); - var _tags; - function access(selection2) { - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - var list = wrap2.selectAll("ul").data([0]); - list = list.enter().append("ul").attr("class", "rows").merge(list); - items = list.selectAll("li").data(field.keys); - var enter = items.enter().append("li").attr("class", function(d2) { - return "labeled-input preset-access-" + d2; - }); - enter.append("span").attr("class", "label preset-label-access").attr("for", function(d2) { - return "preset-input-access-" + d2; - }).html(function(d2) { - return field.t.html("types." + d2); - }); - enter.append("div").attr("class", "preset-input-access-wrap").append("input").attr("type", "text").attr("class", function(d2) { - return "preset-input-access preset-input-access-" + d2; - }).call(utilNoAuto).each(function(d2) { - select_default2(this).call( - uiCombobox(context, "access-" + d2).data(access.options(d2)) - ); - }); - items = items.merge(enter); - wrap2.selectAll(".preset-input-access").on("change", change).on("blur", change); - } - function change(d3_event, d2) { - var tag = {}; - var value = context.cleanTagValue(utilGetSetValue(select_default2(this))); - if (!value && typeof _tags[d2] !== "string") - return; - tag[d2] = value || void 0; - dispatch14.call("change", this, tag); - } - access.options = function(type2) { - var options2 = [ - "yes", - "no", - "designated", - "permissive", - "destination", - "customers", - "private", - "permit", - "unknown" - ]; - if (type2 === "access") { - options2 = options2.filter((v2) => v2 !== "yes" && v2 !== "designated"); + function change(doAutoComplete) { + if (doAutoComplete === void 0) + doAutoComplete = true; + fetchComboData(value(), function(skipAutosuggest) { + _selected = null; + var val = input.property("value"); + if (_suggestions.length) { + if (doAutoComplete && !skipAutosuggest && input.property("selectionEnd") === val.length) { + _selected = tryAutocomplete(); + } + if (!_selected) { + _selected = val; + } + } + if (val.length) { + var combo = container.selectAll(".combobox"); + if (combo.empty()) { + show(); + } + } else { + hide(); + } + render(); + }); } - if (type2 === "bicycle") { - options2.splice(options2.length - 4, 0, "dismount"); + function nav(dir) { + if (_suggestions.length) { + var index = -1; + for (var i3 = 0; i3 < _suggestions.length; i3++) { + if (_selected && _suggestions[i3].value === _selected) { + index = i3; + break; + } + } + index = Math.max(Math.min(index + dir, _suggestions.length - 1), 0); + _selected = _suggestions[index].value; + utilGetSetValue(input, _selected); + dispatch14.call("update"); + } + render(); + ensureVisible(); } - var stringsField = field.resolveReference("stringsCrossReference"); - return options2.map(function(option) { - return { - title: stringsField.t("options." + option + ".description"), - value: option - }; - }); - }; - const placeholdersByTag = { - highway: { - footway: { - foot: "designated", - motor_vehicle: "no" - }, - steps: { - foot: "yes", - motor_vehicle: "no", - bicycle: "no", - horse: "no" - }, - pedestrian: { - foot: "yes", - motor_vehicle: "no" - }, - cycleway: { - motor_vehicle: "no", - bicycle: "designated" - }, - bridleway: { - motor_vehicle: "no", - horse: "designated" - }, - path: { - foot: "yes", - motor_vehicle: "no", - bicycle: "yes", - horse: "yes" - }, - motorway: { - foot: "no", - motor_vehicle: "yes", - bicycle: "no", - horse: "no" - }, - trunk: { - motor_vehicle: "yes" - }, - primary: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - secondary: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - tertiary: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - residential: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - unclassified: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - service: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - motorway_link: { - foot: "no", - motor_vehicle: "yes", - bicycle: "no", - horse: "no" - }, - trunk_link: { - motor_vehicle: "yes" - }, - primary_link: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - secondary_link: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - tertiary_link: { - foot: "yes", - motor_vehicle: "yes", - bicycle: "yes", - horse: "yes" - }, - construction: { - access: "no" + function ensureVisible() { + var combo = container.selectAll(".combobox"); + if (combo.empty()) + return; + var containerRect = container.node().getBoundingClientRect(); + var comboRect = combo.node().getBoundingClientRect(); + if (comboRect.bottom > containerRect.bottom) { + var node = attachTo ? attachTo.node() : input.node(); + node.scrollIntoView({ behavior: "instant", block: "center" }); + render(); } - }, - barrier: { - bollard: { - access: "no", - bicycle: "yes", - foot: "yes" - }, - bus_trap: { - motor_vehicle: "no", - psv: "yes", - foot: "yes", - bicycle: "yes" - }, - city_wall: { - access: "no" - }, - coupure: { - access: "yes" - }, - cycle_barrier: { - motor_vehicle: "no" - }, - ditch: { - access: "no" - }, - entrance: { - access: "yes" - }, - fence: { - access: "no" - }, - hedge: { - access: "no" - }, - jersey_barrier: { - access: "no" - }, - motorcycle_barrier: { - motor_vehicle: "no" - }, - rail_guard: { - access: "no" + var selected = combo.selectAll(".combobox-option.selected").node(); + if (selected) { + selected.scrollIntoView({ behavior: "smooth", block: "nearest" }); } } - }; - access.tags = function(tags) { - _tags = tags; - utilGetSetValue(items.selectAll(".preset-input-access"), function(d2) { - return typeof tags[d2] === "string" ? tags[d2] : ""; - }).classed("mixed", function(d2) { - return tags[d2] && Array.isArray(tags[d2]); - }).attr("title", function(d2) { - return tags[d2] && Array.isArray(tags[d2]) && tags[d2].filter(Boolean).join("\n"); - }).attr("placeholder", function(d2) { - if (tags[d2] && Array.isArray(tags[d2])) { - return _t("inspector.multiple_values"); + function value() { + var value2 = input.property("value"); + var start2 = input.property("selectionStart"); + var end = input.property("selectionEnd"); + if (start2 && end) { + value2 = value2.substring(0, start2); } - if (d2 === "bicycle" || d2 === "motor_vehicle") { - if (tags.vehicle && typeof tags.vehicle === "string") { - return tags.vehicle; + return value2; + } + function fetchComboData(v2, cb) { + _cancelFetch = false; + _fetcher.call(input, v2, function(results, skipAutosuggest) { + if (_cancelFetch) + return; + _suggestions = results; + results.forEach(function(d2) { + _fetched[d2.value] = d2; + }); + if (cb) { + cb(skipAutosuggest); + } + }); + } + function tryAutocomplete() { + if (!_canAutocomplete) + return; + var val = _caseSensitive ? value() : value().toLowerCase(); + if (!val) + return; + if (isFinite(val)) + return; + const suggestionValues = []; + _suggestions.forEach((s2) => { + suggestionValues.push(s2.value); + if (s2.key && s2.key !== s2.value) { + suggestionValues.push(s2.key); + } + }); + var bestIndex = -1; + for (var i3 = 0; i3 < suggestionValues.length; i3++) { + var suggestion = suggestionValues[i3]; + var compare2 = _caseSensitive ? suggestion : suggestion.toLowerCase(); + if (compare2 === val) { + bestIndex = i3; + break; + } else if (bestIndex === -1 && compare2.indexOf(val) === 0) { + bestIndex = i3; } } - if (tags.access && typeof tags.access === "string") { - return tags.access; + if (bestIndex !== -1) { + var bestVal = suggestionValues[bestIndex]; + input.property("value", bestVal); + input.node().setSelectionRange(val.length, bestVal.length); + dispatch14.call("update"); + return bestVal; } - function getPlaceholdersByTag(key, placeholdersByKey) { - if (typeof tags[key] === "string") { - if (placeholdersByKey[tags[key]] && placeholdersByKey[tags[key]][d2]) { - return placeholdersByKey[tags[key]][d2]; - } - } else { - var impliedAccesses = tags[key].filter(Boolean).map(function(val) { - return placeholdersByKey[val] && placeholdersByKey[val][d2]; - }).filter(Boolean); - if (impliedAccesses.length === tags[key].length && new Set(impliedAccesses).size === 1) { - return impliedAccesses[0]; - } - } + } + function render() { + if (_suggestions.length < _minItems || document.activeElement !== input.node()) { + hide(); + return; } - for (const key in placeholdersByTag) { - if (tags[key]) { - const impliedAccess = getPlaceholdersByTag(key, placeholdersByTag[key]); - if (impliedAccess) { - return impliedAccess; - } + var shown = !container.selectAll(".combobox").empty(); + if (!shown) + return; + var combo = container.selectAll(".combobox"); + var options2 = combo.selectAll(".combobox-option").data(_suggestions, function(d2) { + return d2.value; + }); + options2.exit().remove(); + options2.enter().append("a").attr("class", function(d2) { + return "combobox-option " + (d2.klass || ""); + }).attr("title", function(d2) { + return d2.title; + }).each(function(d2) { + if (d2.display) { + d2.display(select_default2(this)); + } else { + select_default2(this).text(d2.value); } + }).on("mouseenter", _mouseEnterHandler).on("mouseleave", _mouseLeaveHandler).merge(options2).classed("selected", function(d2) { + return d2.value === _selected || d2.key === _selected; + }).on("click.combo-option", accept).order(); + var node = attachTo ? attachTo.node() : input.node(); + var containerRect = container.node().getBoundingClientRect(); + var rect = node.getBoundingClientRect(); + combo.style("left", rect.left + 5 - containerRect.left + "px").style("width", rect.width - 10 + "px").style("top", rect.height + rect.top - containerRect.top + "px"); + } + function accept(d3_event, d2) { + _cancelFetch = true; + var thiz = input.node(); + if (d2) { + utilGetSetValue(input, d2.value); + utilTriggerEvent(input, "change"); } - if (d2 === "access" && !tags.barrier) { - return "yes"; - } - return field.placeholder(); - }); + var val = utilGetSetValue(input); + thiz.setSelectionRange(val.length, val.length); + d2 = _fetched[val]; + dispatch14.call("accept", thiz, d2, val); + hide(); + } + function cancel() { + _cancelFetch = true; + var thiz = input.node(); + var val = utilGetSetValue(input); + var start2 = input.property("selectionStart"); + var end = input.property("selectionEnd"); + val = val.slice(0, start2) + val.slice(end); + utilGetSetValue(input, val); + thiz.setSelectionRange(val.length, val.length); + dispatch14.call("cancel", thiz); + hide(); + } }; - access.focus = function() { - items.selectAll(".preset-input-access").node().focus(); + combobox.canAutocomplete = function(val) { + if (!arguments.length) + return _canAutocomplete; + _canAutocomplete = val; + return combobox; }; - return utilRebind(access, dispatch14, "on"); + combobox.caseSensitive = function(val) { + if (!arguments.length) + return _caseSensitive; + _caseSensitive = val; + return combobox; + }; + combobox.data = function(val) { + if (!arguments.length) + return _data; + _data = val; + return combobox; + }; + combobox.fetcher = function(val) { + if (!arguments.length) + return _fetcher; + _fetcher = val; + return combobox; + }; + combobox.minItems = function(val) { + if (!arguments.length) + return _minItems; + _minItems = val; + return combobox; + }; + combobox.itemsMouseEnter = function(val) { + if (!arguments.length) + return _mouseEnterHandler; + _mouseEnterHandler = val; + return combobox; + }; + combobox.itemsMouseLeave = function(val) { + if (!arguments.length) + return _mouseLeaveHandler; + _mouseLeaveHandler = val; + return combobox; + }; + return utilRebind(combobox, dispatch14, "on"); } + uiCombobox.off = function(input, context) { + input.on("focus.combo-input", null).on("blur.combo-input", null).on("keydown.combo-input", null).on("keyup.combo-input", null).on("input.combo-input", null).on("mousedown.combo-input", null).on("mouseup.combo-input", null); + context.container().on("scroll.combo-scroll", null); + }; - // modules/ui/fields/address.js - function uiFieldAddress(field, context) { - var dispatch14 = dispatch_default("change"); - var _selection = select_default2(null); - var _wrap = select_default2(null); - var addrField = _mainPresetIndex.field("address"); - var _entityIDs = []; - var _tags; - var _countryCode; - var _addressFormats = [{ - format: [ - ["housenumber", "street"], - ["city", "postcode"] - ] - }]; - _mainFileFetcher.get("address_formats").then(function(d2) { - _addressFormats = d2; - if (!_selection.empty()) { - _selection.call(address); + // modules/ui/disclosure.js + function uiDisclosure(context, key, expandedDefault) { + var dispatch14 = dispatch_default("toggled"); + var _expanded; + var _label = utilFunctor(""); + var _updatePreference = true; + var _content = function() { + }; + var disclosure = function(selection2) { + if (_expanded === void 0 || _expanded === null) { + var preference = corePreferences("disclosure." + key + ".expanded"); + _expanded = preference === null ? !!expandedDefault : preference === "true"; } - }).catch(function() { - }); - function getNear(isAddressable, type2, searchRadius, resultProp) { - var extent = combinedEntityExtent(); - var l2 = extent.center(); - var box = geoExtent(l2).padByMeters(searchRadius); - var features = context.history().intersects(box).filter(isAddressable).map((d2) => { - let dist = geoSphericalDistance(d2.extent(context.graph()).center(), l2); - if (d2.geometry(context.graph()) === "line") { - var loc = context.projection([ - (extent[0][0] + extent[1][0]) / 2, - (extent[0][1] + extent[1][1]) / 2 - ]); - var choice = geoChooseEdge(context.graph().childNodes(d2), loc, context.projection); - dist = geoSphericalDistance(choice.loc, l2); - } - const value = resultProp && d2.tags[resultProp] ? d2.tags[resultProp] : d2.tags.name; - let title = value; - if (type2 === "street") { - title = "".concat(addrField.t("placeholders.street"), ": ").concat(title); - } else if (type2 === "place") { - title = "".concat(addrField.t("placeholders.place"), ": ").concat(title); - } - return { - title, - value, - dist, - type: type2, - klass: "address-".concat(type2) - }; - }).sort(function(a2, b2) { - return a2.dist - b2.dist; - }); - return utilArrayUniqBy(features, "value"); - } - function getNearStreets() { - function isAddressable(d2) { - return d2.tags.highway && d2.tags.name && d2.type === "way"; + var hideToggle = selection2.selectAll(".hide-toggle-" + key).data([0]); + var hideToggleEnter = hideToggle.enter().append("h3").append("a").attr("role", "button").attr("href", "#").attr("class", "hide-toggle hide-toggle-" + key).call(svgIcon("", "pre-text", "hide-toggle-icon")); + hideToggleEnter.append("span").attr("class", "hide-toggle-text"); + hideToggle = hideToggleEnter.merge(hideToggle); + hideToggle.on("click", toggle).attr("title", _t("icons.".concat(_expanded ? "collapse" : "expand"))).attr("aria-expanded", _expanded).classed("expanded", _expanded); + const label = _label(); + const labelSelection = hideToggle.selectAll(".hide-toggle-text"); + if (typeof label !== "function") { + labelSelection.text(_label()); + } else { + labelSelection.text("").call(label); } - return getNear(isAddressable, "street", 200); - } - function getNearPlaces() { - function isAddressable(d2) { - if (d2.tags.name) { - if (d2.tags.place) - return true; - if (d2.tags.boundary === "administrative" && d2.tags.admin_level > 8) - return true; - } - return false; + hideToggle.selectAll(".hide-toggle-icon").attr( + "xlink:href", + _expanded ? "#iD-icon-down" : _mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward" + ); + var wrap2 = selection2.selectAll(".disclosure-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "disclosure-wrap disclosure-wrap-" + key).merge(wrap2).classed("hide", !_expanded); + if (_expanded) { + wrap2.call(_content); } - return getNear(isAddressable, "place", 200); - } - function getNearCities() { - function isAddressable(d2) { - if (d2.tags.name) { - if (d2.tags.boundary === "administrative" && d2.tags.admin_level === "8") - return true; - if (d2.tags.border_type === "city") - return true; - if (d2.tags.place === "city" || d2.tags.place === "town" || d2.tags.place === "village") - return true; + function toggle(d3_event) { + d3_event.preventDefault(); + _expanded = !_expanded; + if (_updatePreference) { + corePreferences("disclosure." + key + ".expanded", _expanded); } - if (d2.tags["".concat(field.key, ":city")]) - return true; - return false; - } - return getNear(isAddressable, "city", 200, "".concat(field.key, ":city")); - } - function getNearPostcodes() { - return [...new Set([].concat(getNearValues("postcode")).concat(getNear((d2) => d2.tags.postal_code, "postcode", 200, "postal_code")))]; - } - function getNearValues(key) { - const tagKey = "".concat(field.key, ":").concat(key); - function hasTag(d2) { - return _entityIDs.indexOf(d2.id) === -1 && d2.tags[tagKey]; - } - return getNear(hasTag, key, 200, tagKey); - } - function updateForCountryCode() { - if (!_countryCode) - return; - var addressFormat; - for (var i3 = 0; i3 < _addressFormats.length; i3++) { - var format2 = _addressFormats[i3]; - if (!format2.countryCodes) { - addressFormat = format2; - } else if (format2.countryCodes.indexOf(_countryCode) !== -1) { - addressFormat = format2; - break; + hideToggle.classed("expanded", _expanded).attr("aria-expanded", _expanded).attr("title", _t("icons.".concat(_expanded ? "collapse" : "expand"))); + hideToggle.selectAll(".hide-toggle-icon").attr( + "xlink:href", + _expanded ? "#iD-icon-down" : _mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward" + ); + wrap2.call(uiToggle(_expanded)); + if (_expanded) { + wrap2.call(_content); } + dispatch14.call("toggled", this, _expanded); } - var dropdowns = addressFormat.dropdowns || [ - "city", - "county", - "country", - "district", - "hamlet", - "neighbourhood", - "place", - "postcode", - "province", - "quarter", - "state", - "street", - "street+place", - "subdistrict", - "suburb" - ]; - var widths = addressFormat.widths || { - housenumber: 1 / 5, - unit: 1 / 5, - street: 1 / 2, - place: 1 / 2, - city: 2 / 3, - state: 1 / 4, - postcode: 1 / 3 - }; - function row(r2) { - var total = r2.reduce(function(sum, key) { - return sum + (widths[key] || 0.5); - }, 0); - return r2.map(function(key) { - return { - id: key, - width: (widths[key] || 0.5) / total - }; - }); - } - var rows = _wrap.selectAll(".addr-row").data(addressFormat.format, function(d2) { - return d2.toString(); - }); - rows.exit().remove(); - rows.enter().append("div").attr("class", "addr-row").selectAll("input").data(row).enter().append("input").property("type", "text").call(updatePlaceholder).attr("class", function(d2) { - return "addr-" + d2.id; - }).call(utilNoAuto).each(addDropdown).style("width", function(d2) { - return d2.width * 100 + "%"; - }); - function addDropdown(d2) { - if (dropdowns.indexOf(d2.id) === -1) + }; + disclosure.label = function(val) { + if (!arguments.length) + return _label; + _label = utilFunctor(val); + return disclosure; + }; + disclosure.expanded = function(val) { + if (!arguments.length) + return _expanded; + _expanded = val; + return disclosure; + }; + disclosure.updatePreference = function(val) { + if (!arguments.length) + return _updatePreference; + _updatePreference = val; + return disclosure; + }; + disclosure.content = function(val) { + if (!arguments.length) + return _content; + _content = val; + return disclosure; + }; + return utilRebind(disclosure, dispatch14, "on"); + } + + // modules/ui/section.js + function uiSection(id2, context) { + var _classes = utilFunctor(""); + var _shouldDisplay; + var _content; + var _disclosure; + var _label; + var _expandedByDefault = utilFunctor(true); + var _disclosureContent; + var _disclosureExpanded; + var _containerSelection = select_default2(null); + var section = { + id: id2 + }; + section.classes = function(val) { + if (!arguments.length) + return _classes; + _classes = utilFunctor(val); + return section; + }; + section.label = function(val) { + if (!arguments.length) + return _label; + _label = utilFunctor(val); + return section; + }; + section.expandedByDefault = function(val) { + if (!arguments.length) + return _expandedByDefault; + _expandedByDefault = utilFunctor(val); + return section; + }; + section.shouldDisplay = function(val) { + if (!arguments.length) + return _shouldDisplay; + _shouldDisplay = utilFunctor(val); + return section; + }; + section.content = function(val) { + if (!arguments.length) + return _content; + _content = val; + return section; + }; + section.disclosureContent = function(val) { + if (!arguments.length) + return _disclosureContent; + _disclosureContent = val; + return section; + }; + section.disclosureExpanded = function(val) { + if (!arguments.length) + return _disclosureExpanded; + _disclosureExpanded = val; + return section; + }; + section.render = function(selection2) { + _containerSelection = selection2.selectAll(".section-" + id2).data([0]); + var sectionEnter = _containerSelection.enter().append("div").attr("class", "section section-" + id2 + " " + (_classes && _classes() || "")); + _containerSelection = sectionEnter.merge(_containerSelection); + _containerSelection.call(renderContent); + }; + section.reRender = function() { + _containerSelection.call(renderContent); + }; + section.selection = function() { + return _containerSelection; + }; + section.disclosure = function() { + return _disclosure; + }; + function renderContent(selection2) { + if (_shouldDisplay) { + var shouldDisplay = _shouldDisplay(); + selection2.classed("hide", !shouldDisplay); + if (!shouldDisplay) { + selection2.html(""); return; - var nearValues; - switch (d2.id) { - case "street": - nearValues = getNearStreets; - break; - case "place": - nearValues = getNearPlaces; - break; - case "street+place": - nearValues = () => [].concat(getNearStreets()).concat(getNearPlaces()); - d2.isAutoStreetPlace = true; - d2.id = _tags["".concat(field.key, ":place")] ? "place" : "street"; - break; - case "city": - nearValues = getNearCities; - break; - case "postcode": - nearValues = getNearPostcodes; - break; - default: - nearValues = getNearValues; } - select_default2(this).call( - uiCombobox(context, "address-".concat(d2.isAutoStreetPlace ? "street-place" : d2.id)).minItems(1).caseSensitive(true).fetcher(function(typedValue, callback) { - typedValue = typedValue.toLowerCase(); - callback(nearValues(d2.id).filter((v2) => v2.value.toLowerCase().indexOf(typedValue) !== -1)); - }).on("accept", function(selected) { - if (d2.isAutoStreetPlace) { - d2.id = selected ? selected.type : "street"; - } - }) - ); } - _wrap.selectAll("input").on("blur", change()).on("change", change()); - _wrap.selectAll("input:not(.combobox-input)").on("input", change(true)); - if (_tags) - updateTags(_tags); - } - function address(selection2) { - _selection = selection2; - _wrap = selection2.selectAll(".form-field-input-wrap").data([0]); - _wrap = _wrap.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(_wrap); - var extent = combinedEntityExtent(); - if (extent) { - var countryCode; - if (context.inIntro()) { - countryCode = _t("intro.graph.countrycode"); - } else { - var center = extent.center(); - countryCode = iso1A2Code(center); + if (_disclosureContent) { + if (!_disclosure) { + _disclosure = uiDisclosure(context, id2.replace(/-/g, "_"), _expandedByDefault()).label(_label || "").content(_disclosureContent); } - if (countryCode) { - _countryCode = countryCode.toLowerCase(); - updateForCountryCode(); + if (_disclosureExpanded !== void 0) { + _disclosure.expanded(_disclosureExpanded); + _disclosureExpanded = void 0; } + selection2.call(_disclosure); + return; + } + if (_content) { + selection2.call(_content); } } - function change(onInput) { - return function() { - setTimeout(() => { - var tags = {}; - _wrap.selectAll("input").each(function(subfield) { - var key = field.key + ":" + subfield.id; - var value = this.value; - if (!onInput) - value = context.cleanTagValue(value); - if (Array.isArray(_tags[key]) && !value) - return; - if (subfield.isAutoStreetPlace) { - if (subfield.id === "street") { - tags["".concat(field.key, ":place")] = void 0; - } else if (subfield.id === "place") { - tags["".concat(field.key, ":street")] = void 0; - } - } - tags[key] = value || void 0; - }); - Object.keys(tags).filter((k2) => tags[k2]).forEach((k2) => _tags[k2] = tags[k2]); - dispatch14.call("change", this, tags, onInput); - }, 0); - }; + return section; + } + + // modules/ui/tag_reference.js + function uiTagReference(what) { + var wikibase = what.qid ? services.wikidata : services.osmWikibase; + var tagReference = {}; + var _button = select_default2(null); + var _body = select_default2(null); + var _loaded; + var _showing; + function load() { + if (!wikibase) + return; + _button.classed("tag-reference-loading", true); + wikibase.getDocs(what, gotDocs); } - function updatePlaceholder(inputSelection) { - return inputSelection.attr("placeholder", function(subfield) { - if (_tags && Array.isArray(_tags[field.key + ":" + subfield.id])) { - return _t("inspector.multiple_values"); - } - if (subfield.isAutoStreetPlace) { - return "".concat(getLocalPlaceholder("street"), " / ").concat(getLocalPlaceholder("place")); + function gotDocs(err, docs) { + _body.html(""); + if (!docs || !docs.title) { + _body.append("p").attr("class", "tag-reference-description").call(_t.append("inspector.no_documentation_key")); + done(); + return; + } + if (docs.imageURL) { + _body.append("img").attr("class", "tag-reference-wiki-image").attr("alt", docs.description).attr("src", docs.imageURL).on("load", function() { + done(); + }).on("error", function() { + select_default2(this).remove(); + done(); + }); + } else { + done(); + } + var tagReferenceDescription = _body.append("p").attr("class", "tag-reference-description").append("span"); + if (docs.description) { + tagReferenceDescription = tagReferenceDescription.attr("class", "localized-text").attr("lang", docs.descriptionLocaleCode || "und").text(docs.description); + } else { + tagReferenceDescription = tagReferenceDescription.call(_t.append("inspector.no_documentation_key")); + } + tagReferenceDescription.append("a").attr("class", "tag-reference-edit").attr("target", "_blank").attr("title", _t("inspector.edit_reference")).attr("href", docs.editURL).call(svgIcon("#iD-icon-edit", "inline")); + if (docs.wiki) { + _body.append("a").attr("class", "tag-reference-link").attr("target", "_blank").attr("href", docs.wiki.url).call(svgIcon("#iD-icon-out-link", "inline")).append("span").call(_t.append(docs.wiki.text)); + } + if (what.key === "comment") { + _body.append("a").attr("class", "tag-reference-comment-link").attr("target", "_blank").call(svgIcon("#iD-icon-out-link", "inline")).attr("href", _t("commit.about_changeset_comments_link")).append("span").call(_t.append("commit.about_changeset_comments")); + } + } + function done() { + _loaded = true; + _button.classed("tag-reference-loading", false); + _body.classed("expanded", true).transition().duration(200).style("max-height", "200px").style("opacity", "1"); + _showing = true; + _button.selectAll("svg.icon use").each(function() { + var iconUse = select_default2(this); + if (iconUse.attr("href") === "#iD-icon-info") { + iconUse.attr("href", "#iD-icon-info-filled"); } - return getLocalPlaceholder(subfield.id); }); } - function getLocalPlaceholder(key) { - if (_countryCode) { - var localkey = key + "!" + _countryCode; - var tkey = addrField.hasTextForStringId("placeholders." + localkey) ? localkey : key; - return addrField.t("placeholders." + tkey); - } + function hide() { + _body.transition().duration(200).style("max-height", "0px").style("opacity", "0").on("end", function() { + _body.classed("expanded", false); + }); + _showing = false; + _button.selectAll("svg.icon use").each(function() { + var iconUse = select_default2(this); + if (iconUse.attr("href") === "#iD-icon-info-filled") { + iconUse.attr("href", "#iD-icon-info"); + } + }); } - function updateTags(tags) { - utilGetSetValue(_wrap.selectAll("input"), (subfield) => { - var val; - if (subfield.isAutoStreetPlace) { - const streetKey = "".concat(field.key, ":street"); - const placeKey = "".concat(field.key, ":place"); - if (tags[streetKey] !== void 0 || tags[placeKey] === void 0) { - val = tags[streetKey]; - subfield.id = "street"; - } else { - val = tags[placeKey]; - subfield.id = "place"; - } + tagReference.button = function(selection2, klass, iconName) { + _button = selection2.selectAll(".tag-reference-button").data([0]); + _button = _button.enter().append("button").attr("class", "tag-reference-button " + (klass || "")).attr("title", _t("icons.information")).call(svgIcon("#iD-icon-" + (iconName || "inspect"))).merge(_button); + _button.on("click", function(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + this.blur(); + if (_showing) { + hide(); + } else if (_loaded) { + done(); } else { - val = tags["".concat(field.key, ":").concat(subfield.id)]; + load(); } - return typeof val === "string" ? val : ""; - }).attr("title", function(subfield) { - var val = tags[field.key + ":" + subfield.id]; - return val && Array.isArray(val) ? val.filter(Boolean).join("\n") : void 0; - }).classed("mixed", function(subfield) { - return Array.isArray(tags[field.key + ":" + subfield.id]); - }).call(updatePlaceholder); - } - function combinedEntityExtent() { - return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); - } - address.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return address; + }); }; - address.tags = function(tags) { - _tags = tags; - updateTags(tags); + tagReference.body = function(selection2) { + var itemID = what.qid || what.key + "-" + (what.value || ""); + _body = selection2.selectAll(".tag-reference-body").data([itemID], function(d2) { + return d2; + }); + _body.exit().remove(); + _body = _body.enter().append("div").attr("class", "tag-reference-body").style("max-height", "0").style("opacity", "0").merge(_body); + if (_showing === false) { + hide(); + } }; - address.focus = function() { - var node = _wrap.selectAll("input").node(); - if (node) - node.focus(); + tagReference.showing = function(val) { + if (!arguments.length) + return _showing; + _showing = val; + return tagReference; }; - return utilRebind(address, dispatch14, "on"); + return tagReference; } - // modules/ui/fields/directional_combo.js - function uiFieldDirectionalCombo(field, context) { - var dispatch14 = dispatch_default("change"); - var items = select_default2(null); - var wrap2 = select_default2(null); - var _tags; - var _combos = {}; - if (field.type === "cycleway") { - field = __spreadProps(__spreadValues({}, field), { - key: field.keys[0], - keys: field.keys.slice(1) - }); + // modules/ui/field_help.js + function uiFieldHelp(context, fieldName) { + var fieldHelp = {}; + var _inspector = select_default2(null); + var _wrap = select_default2(null); + var _body = select_default2(null); + var fieldHelpKeys = { + restrictions: [ + ["about", [ + "about", + "from_via_to", + "maxdist", + "maxvia" + ]], + ["inspecting", [ + "about", + "from_shadow", + "allow_shadow", + "restrict_shadow", + "only_shadow", + "restricted", + "only" + ]], + ["modifying", [ + "about", + "indicators", + "allow_turn", + "restrict_turn", + "only_turn" + ]], + ["tips", [ + "simple", + "simple_example", + "indirect", + "indirect_example", + "indirect_noedit" + ]] + ] + }; + var fieldHelpHeadings = {}; + var replacements = { + distField: { html: _t.html("restriction.controls.distance") }, + viaField: { html: _t.html("restriction.controls.via") }, + fromShadow: { html: icon("#iD-turn-shadow", "inline shadow from") }, + allowShadow: { html: icon("#iD-turn-shadow", "inline shadow allow") }, + restrictShadow: { html: icon("#iD-turn-shadow", "inline shadow restrict") }, + onlyShadow: { html: icon("#iD-turn-shadow", "inline shadow only") }, + allowTurn: { html: icon("#iD-turn-yes", "inline turn") }, + restrictTurn: { html: icon("#iD-turn-no", "inline turn") }, + onlyTurn: { html: icon("#iD-turn-only", "inline turn") } + }; + var docs = fieldHelpKeys[fieldName].map(function(key) { + var helpkey = "help.field." + fieldName + "." + key[0]; + var text = key[1].reduce(function(all, part) { + var subkey = helpkey + "." + part; + var depth = fieldHelpHeadings[subkey]; + var hhh = depth ? Array(depth + 1).join("#") + " " : ""; + return all + hhh + _t.html(subkey, replacements) + "\n\n"; + }, ""); + return { + key: helpkey, + title: _t.html(helpkey + ".title"), + html: marked(text.trim()) + }; + }); + function show() { + updatePosition(); + _body.classed("hide", false).style("opacity", "0").transition().duration(200).style("opacity", "1"); } - function directionalCombo(selection2) { - function stripcolon(s2) { - return s2.replace(":", ""); - } - wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - var div = wrap2.selectAll("ul").data([0]); - div = div.enter().append("ul").attr("class", "rows").merge(div); - items = div.selectAll("li").data(field.keys); - var enter = items.enter().append("li").attr("class", function(d2) { - return "labeled-input preset-directionalcombo-" + stripcolon(d2); + function hide() { + _body.classed("hide", true).transition().duration(200).style("opacity", "0").on("end", function() { + _body.classed("hide", true); }); - enter.append("span").attr("class", "label preset-label-directionalcombo").attr("for", function(d2) { - return "preset-input-directionalcombo-" + stripcolon(d2); - }).html(function(d2) { - return field.t.html("types." + d2); + } + function clickHelp(index) { + var d2 = docs[index]; + var tkeys = fieldHelpKeys[fieldName][index][1]; + _body.selectAll(".field-help-nav-item").classed("active", function(d4, i3) { + return i3 === index; }); - enter.append("div").attr("class", "preset-input-directionalcombo-wrap form-field-input-wrap").each(function(key) { - const subField = __spreadProps(__spreadValues({}, field), { - type: "combo", - key - }); - const combo = uiFieldCombo(subField, context); - combo.on("change", (t2) => change(key, t2[key])); - _combos[key] = combo; - select_default2(this).call(combo); + var content = _body.selectAll(".field-help-content").html(d2.html); + content.selectAll("p").attr("class", function(d4, i3) { + return tkeys[i3]; }); - items = items.merge(enter); - wrap2.selectAll(".preset-input-directionalcombo").on("change", change).on("blur", change); + if (d2.key === "help.field.restrictions.inspecting") { + content.insert("img", "p.from_shadow").attr("class", "field-help-image cf").attr("src", context.imagePath("tr_inspect.gif")); + } else if (d2.key === "help.field.restrictions.modifying") { + content.insert("img", "p.allow_turn").attr("class", "field-help-image cf").attr("src", context.imagePath("tr_modify.gif")); + } } - function change(key, newValue) { - const commonKey = field.key; - const otherKey = key === field.keys[0] ? field.keys[1] : field.keys[0]; - dispatch14.call("change", this, (tags) => { - const otherValue = tags[otherKey] || tags[commonKey]; - if (newValue === otherValue) { - tags[commonKey] = newValue; - delete tags[key]; - delete tags[otherKey]; + fieldHelp.button = function(selection2) { + if (_body.empty()) + return; + var button = selection2.selectAll(".field-help-button").data([0]); + button.enter().append("button").attr("class", "field-help-button").call(svgIcon("#iD-icon-help")).merge(button).on("click", function(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + if (_body.classed("hide")) { + show(); } else { - tags[key] = newValue; - delete tags[commonKey]; - tags[otherKey] = otherValue; + hide(); } - return tags; }); - } - directionalCombo.tags = function(tags) { - _tags = tags; - const commonKey = field.key; - for (let key in _combos) { - const uniqueValues = [...new Set([].concat(_tags[commonKey]).concat(_tags[key]).filter(Boolean))]; - _combos[key].tags({ [key]: uniqueValues.length > 1 ? uniqueValues : uniqueValues[0] }); - } }; - directionalCombo.focus = function() { - var node = wrap2.selectAll("input").node(); - if (node) - node.focus(); + function updatePosition() { + var wrap2 = _wrap.node(); + var inspector = _inspector.node(); + var wRect = wrap2.getBoundingClientRect(); + var iRect = inspector.getBoundingClientRect(); + _body.style("top", wRect.top + inspector.scrollTop - iRect.top + "px"); + } + fieldHelp.body = function(selection2) { + _wrap = selection2.selectAll(".form-field-input-wrap"); + if (_wrap.empty()) + return; + _inspector = context.container().select(".sidebar .entity-editor-pane .inspector-body"); + if (_inspector.empty()) + return; + _body = _inspector.selectAll(".field-help-body").data([0]); + var enter = _body.enter().append("div").attr("class", "field-help-body hide"); + var titleEnter = enter.append("div").attr("class", "field-help-title cf"); + titleEnter.append("h2").attr("class", _mainLocalizer.textDirection() === "rtl" ? "fr" : "fl").call(_t.append("help.field." + fieldName + ".title")); + titleEnter.append("button").attr("class", "fr close").attr("title", _t("icons.close")).on("click", function(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + hide(); + }).call(svgIcon("#iD-icon-close")); + var navEnter = enter.append("div").attr("class", "field-help-nav cf"); + var titles = docs.map(function(d2) { + return d2.title; + }); + navEnter.selectAll(".field-help-nav-item").data(titles).enter().append("div").attr("class", "field-help-nav-item").html(function(d2) { + return d2; + }).on("click", function(d3_event, d2) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + clickHelp(titles.indexOf(d2)); + }); + enter.append("div").attr("class", "field-help-content"); + _body = _body.merge(enter); + clickHelp(0); }; - return utilRebind(directionalCombo, dispatch14, "on"); + return fieldHelp; } - // modules/ui/fields/lanes.js - function uiFieldLanes(field, context) { + // modules/ui/fields/check.js + function uiFieldCheck(field, context) { var dispatch14 = dispatch_default("change"); - var LANE_WIDTH = 40; - var LANE_HEIGHT = 200; + var options2 = field.options; + var values = []; + var texts = []; + var _tags; + var input = select_default2(null); + var text = select_default2(null); + var label = select_default2(null); + var reverser = select_default2(null); + var _impliedYes; var _entityIDs = []; - function lanes(selection2) { - var lanesData = context.entity(_entityIDs[0]).lanes(); - if (!context.container().select(".inspector-wrap.inspector-hidden").empty() || !selection2.node().parentNode) { - selection2.call(lanes.off); - return; + var _value; + var stringsField = field.resolveReference("stringsCrossReference"); + if (!options2 && stringsField.options) { + options2 = stringsField.options; + } + if (options2) { + for (var i3 in options2) { + var v2 = options2[i3]; + values.push(v2 === "undefined" ? void 0 : v2); + texts.push(stringsField.t.html("options." + v2, { "default": v2 })); + } + } else { + values = [void 0, "yes"]; + texts = [_t.html("inspector.unknown"), _t.html("inspector.check.yes")]; + if (field.type !== "defaultCheck") { + values.push("no"); + texts.push(_t.html("inspector.check.no")); } - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - var surface = wrap2.selectAll(".surface").data([0]); - var d2 = utilGetDimensions(wrap2); - var freeSpace = d2[0] - lanesData.lanes.length * LANE_WIDTH * 1.5 + LANE_WIDTH * 0.5; - surface = surface.enter().append("svg").attr("width", d2[0]).attr("height", 300).attr("class", "surface").merge(surface); - var lanesSelection = surface.selectAll(".lanes").data([0]); - lanesSelection = lanesSelection.enter().append("g").attr("class", "lanes").merge(lanesSelection); - lanesSelection.attr("transform", function() { - return "translate(" + freeSpace / 2 + ", 0)"; - }); - var lane = lanesSelection.selectAll(".lane").data(lanesData.lanes); - lane.exit().remove(); - var enter = lane.enter().append("g").attr("class", "lane"); - enter.append("g").append("rect").attr("y", 50).attr("width", LANE_WIDTH).attr("height", LANE_HEIGHT); - enter.append("g").attr("class", "forward").append("text").attr("y", 40).attr("x", 14).text("\u25B2"); - enter.append("g").attr("class", "bothways").append("text").attr("y", 40).attr("x", 14).text("\u25B2\u25BC"); - enter.append("g").attr("class", "backward").append("text").attr("y", 40).attr("x", 14).text("\u25BC"); - lane = lane.merge(enter); - lane.attr("transform", function(d4) { - return "translate(" + LANE_WIDTH * d4.index * 1.5 + ", 0)"; - }); - lane.select(".forward").style("visibility", function(d4) { - return d4.direction === "forward" ? "visible" : "hidden"; - }); - lane.select(".bothways").style("visibility", function(d4) { - return d4.direction === "bothways" ? "visible" : "hidden"; - }); - lane.select(".backward").style("visibility", function(d4) { - return d4.direction === "backward" ? "visible" : "hidden"; - }); } - lanes.entityIDs = function(val) { + function checkImpliedYes() { + _impliedYes = field.id === "oneway_yes"; + if (field.id === "oneway") { + var entity = context.entity(_entityIDs[0]); + for (var key in entity.tags) { + if (key in osmOneWayTags && entity.tags[key] in osmOneWayTags[key]) { + _impliedYes = true; + texts[0] = _t.html("_tagging.presets.fields.oneway_yes.options.undefined"); + break; + } + } + } + } + function reverserHidden() { + if (!context.container().select("div.inspector-hover").empty()) + return true; + return !(_value === "yes" || _impliedYes && !_value); + } + function reverserSetText(selection2) { + var entity = _entityIDs.length && context.hasEntity(_entityIDs[0]); + if (reverserHidden() || !entity) + return selection2; + var first = entity.first(); + var last = entity.isClosed() ? entity.nodes[entity.nodes.length - 2] : entity.last(); + var pseudoDirection = first < last; + var icon2 = pseudoDirection ? "#iD-icon-forward" : "#iD-icon-backward"; + selection2.selectAll(".reverser-span").html("").call(_t.append("inspector.check.reverser")).call(svgIcon(icon2, "inline")); + return selection2; + } + var check = function(selection2) { + checkImpliedYes(); + label = selection2.selectAll(".form-field-input-wrap").data([0]); + var enter = label.enter().append("label").attr("class", "form-field-input-wrap form-field-input-check"); + enter.append("input").property("indeterminate", field.type !== "defaultCheck").attr("type", "checkbox").attr("id", field.domId); + enter.append("span").html(texts[0]).attr("class", "value"); + if (field.type === "onewayCheck") { + enter.append("button").attr("class", "reverser" + (reverserHidden() ? " hide" : "")).append("span").attr("class", "reverser-span"); + } + label = label.merge(enter); + input = label.selectAll("input"); + text = label.selectAll("span.value"); + input.on("click", function(d3_event) { + d3_event.stopPropagation(); + var t2 = {}; + if (Array.isArray(_tags[field.key])) { + if (values.indexOf("yes") !== -1) { + t2[field.key] = "yes"; + } else { + t2[field.key] = values[0]; + } + } else { + t2[field.key] = values[(values.indexOf(_value) + 1) % values.length]; + } + if (t2[field.key] === "reversible" || t2[field.key] === "alternating") { + t2[field.key] = values[0]; + } + dispatch14.call("change", this, t2); + }); + if (field.type === "onewayCheck") { + reverser = label.selectAll(".reverser"); + reverser.call(reverserSetText).on("click", function(d3_event) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + context.perform( + function(graph) { + for (var i4 in _entityIDs) { + graph = actionReverse(_entityIDs[i4])(graph); + } + return graph; + }, + _t("operations.reverse.annotation.line", { n: 1 }) + ); + context.validator().validate(); + select_default2(this).call(reverserSetText); + }); + } + }; + check.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; _entityIDs = val; + return check; }; - lanes.tags = function() { + check.tags = function(tags) { + _tags = tags; + function isChecked(val) { + return val !== "no" && val !== "" && val !== void 0 && val !== null; + } + function textFor(val) { + if (val === "") + val = void 0; + var index = values.indexOf(val); + return index !== -1 ? texts[index] : '"' + val + '"'; + } + checkImpliedYes(); + var isMixed = Array.isArray(tags[field.key]); + _value = !isMixed && tags[field.key] && tags[field.key].toLowerCase(); + if (field.type === "onewayCheck" && (_value === "1" || _value === "-1")) { + _value = "yes"; + } + input.property("indeterminate", isMixed || field.type !== "defaultCheck" && !_value).property("checked", isChecked(_value)); + text.html(isMixed ? _t.html("inspector.multiple_values") : textFor(_value)).classed("mixed", isMixed); + label.classed("set", !!_value); + if (field.type === "onewayCheck") { + reverser.classed("hide", reverserHidden()).call(reverserSetText); + } }; - lanes.focus = function() { + check.focus = function() { + input.node().focus(); }; - lanes.off = function() { + return utilRebind(check, dispatch14, "on"); + } + + // modules/ui/length_indicator.js + function uiLengthIndicator(maxChars) { + var _wrap = select_default2(null); + var _tooltip = uiPopover("tooltip max-length-warning").placement("bottom").hasArrow(true).content(() => (selection2) => { + selection2.text(""); + selection2.call(svgIcon("#iD-icon-alert", "inline")); + selection2.call(_t.append("inspector.max_length_reached", { maxChars })); + }); + var _silent = false; + var lengthIndicator = function(selection2) { + _wrap = selection2.selectAll("span.length-indicator-wrap").data([0]); + _wrap = _wrap.enter().append("span").merge(_wrap).classed("length-indicator-wrap", true); + selection2.call(_tooltip); }; - return utilRebind(lanes, dispatch14, "on"); + lengthIndicator.update = function(val) { + const strLen = utilUnicodeCharsCount(utilCleanOsmString(val, Number.POSITIVE_INFINITY)); + let indicator = _wrap.selectAll("span.length-indicator").data([strLen]); + indicator.enter().append("span").merge(indicator).classed("length-indicator", true).classed("limit-reached", (d2) => d2 > maxChars).style("border-right-width", (d2) => "".concat(Math.abs(maxChars - d2) * 2, "px")).style("margin-right", (d2) => d2 > maxChars ? "".concat((maxChars - d2) * 2, "px") : 0).style("opacity", (d2) => d2 > maxChars * 0.8 ? Math.min(1, (d2 / maxChars - 0.8) / (1 - 0.8)) : 0).style("pointer-events", (d2) => d2 > maxChars * 0.8 ? null : "none"); + if (_silent) + return; + if (strLen > maxChars) { + _tooltip.show(); + } else { + _tooltip.hide(); + } + }; + lengthIndicator.silent = function(val) { + if (!arguments.length) + return _silent; + _silent = val; + return lengthIndicator; + }; + return lengthIndicator; } - uiFieldLanes.supportsMultiselection = false; - // modules/ui/fields/localized.js - var _languagesArray = []; - function uiFieldLocalized(field, context) { - var dispatch14 = dispatch_default("change", "input"); - var wikipedia = services.wikipedia; - var input = select_default2(null); - var localizedInputs = select_default2(null); + // modules/ui/fields/combo.js + function uiFieldCombo(field, context) { + var dispatch14 = dispatch_default("change"); + var _isMulti = field.type === "multiCombo" || field.type === "manyCombo"; + var _isNetwork = field.type === "networkCombo"; + var _isSemi = field.type === "semiCombo"; + var _showTagInfoSuggestions = field.type !== "manyCombo" && field.autoSuggestions !== false; + var _allowCustomValues = field.type !== "manyCombo" && field.customValues !== false; + var _snake_case = field.snake_case || field.snake_case === void 0; + var _combobox = uiCombobox(context, "combo-" + field.safeid).caseSensitive(field.caseSensitive).minItems(1); + var _container = select_default2(null); + var _inputWrap = select_default2(null); + var _input = select_default2(null); var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()); - var _countryCode; + var _comboData = []; + var _multiData = []; + var _entityIDs = []; var _tags; - _mainFileFetcher.get("languages").then(loadLanguagesArray).catch(function() { - }); - var _territoryLanguages = {}; - _mainFileFetcher.get("territory_languages").then(function(d2) { - _territoryLanguages = d2; + var _countryCode; + var _staticPlaceholder; + var _dataDeprecated = []; + _mainFileFetcher.get("deprecated").then(function(d2) { + _dataDeprecated = d2; }).catch(function() { }); - var langCombo = uiCombobox(context, "localized-lang").fetcher(fetchLanguages).minItems(0); - var _selection = select_default2(null); - var _multilingual = []; - var _buttonTip = uiTooltip().title(() => _t.append("translate.translate")).placement("left"); - var _wikiTitles; - var _entityIDs = []; - function loadLanguagesArray(dataLanguages) { - if (_languagesArray.length !== 0) - return; - var replacements = { - sr: "sr-Cyrl", - // in OSM, `sr` implies Cyrillic - "sr-Cyrl": false - // `sr-Cyrl` isn't used in OSM - }; - for (var code in dataLanguages) { - if (replacements[code] === false) - continue; - var metaCode = code; - if (replacements[code]) - metaCode = replacements[code]; - _languagesArray.push({ - localName: _mainLocalizer.languageName(metaCode, { localOnly: true }), - nativeName: dataLanguages[metaCode].nativeName, - code, - label: _mainLocalizer.languageName(metaCode) - }); - } + if (_isMulti && field.key && /[^:]$/.test(field.key)) { + field.key += ":"; } - function calcLocked() { - var isLocked = field.id === "name" && _entityIDs.length && _entityIDs.some(function(entityID) { - var entity = context.graph().hasEntity(entityID); - if (!entity) - return false; - if (entity.tags.wikidata) - return true; - if (entity.tags["name:etymology:wikidata"]) - return true; - var preset = _mainPresetIndex.match(entity, context.graph()); - if (preset) { - var isSuggestion = preset.suggestion; - var fields = preset.fields(entity.extent(context.graph()).center()); - var showsBrandField = fields.some(function(d2) { - return d2.id === "brand"; - }); - var showsOperatorField = fields.some(function(d2) { - return d2.id === "operator"; - }); - var setsName = preset.addTags.name; - var setsBrandWikidata = preset.addTags["brand:wikidata"]; - var setsOperatorWikidata = preset.addTags["operator:wikidata"]; - return isSuggestion && setsName && (setsBrandWikidata && !showsBrandField || setsOperatorWikidata && !showsOperatorField); - } - return false; - }); - field.locked(isLocked); + function snake(s2) { + return s2.replace(/\s+/g, "_"); } - function calcMultilingual(tags) { - var existingLangsOrdered = _multilingual.map(function(item2) { - return item2.lang; + function clean2(s2) { + return s2.split(";").map(function(s3) { + return s3.trim(); + }).join(";"); + } + function tagValue(dval) { + dval = clean2(dval || ""); + var found = getOptions(true).find(function(o2) { + return o2.key && clean2(o2.value) === dval; }); - var existingLangs = new Set(existingLangsOrdered.filter(Boolean)); - for (var k2 in tags) { - var m2 = k2.match(/^(.*):([a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-[A-Z]{2})?)$/); - if (m2 && m2[1] === field.key && m2[2]) { - var item = { lang: m2[2], value: tags[k2] }; - if (existingLangs.has(item.lang)) { - _multilingual[existingLangsOrdered.indexOf(item.lang)].value = item.value; - existingLangs.delete(item.lang); - } else { - _multilingual.push(item); - } - } + if (found) + return found.key; + if (field.type === "typeCombo" && !dval) { + return "yes"; } - _multilingual.forEach(function(item2) { - if (item2.lang && existingLangs.has(item2.lang)) { - item2.value = ""; - } - }); + return restrictTagValueSpelling(dval) || void 0; } - function localized(selection2) { - _selection = selection2; - calcLocked(); - var isLocked = field.locked(); - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - input = wrap2.selectAll(".localized-main").data([0]); - input = input.enter().append("input").attr("type", "text").attr("id", field.domId).attr("class", "localized-main").call(utilNoAuto).merge(input); - input.classed("disabled", !!isLocked).attr("readonly", isLocked || null).on("input", change(true)).on("blur", change()).on("change", change()); - wrap2.call(_lengthIndicator); - var translateButton = wrap2.selectAll(".localized-add").data([0]); - translateButton = translateButton.enter().append("button").attr("class", "localized-add form-field-button").attr("aria-label", _t("icons.plus")).call(svgIcon("#iD-icon-plus")).merge(translateButton); - translateButton.classed("disabled", !!isLocked).call(isLocked ? _buttonTip.destroy : _buttonTip).on("click", addNew); - if (_tags && !_multilingual.length) { - calcMultilingual(_tags); + function restrictTagValueSpelling(dval) { + if (_snake_case) { + dval = snake(dval); } - localizedInputs = selection2.selectAll(".localized-multilingual").data([0]); - localizedInputs = localizedInputs.enter().append("div").attr("class", "localized-multilingual").merge(localizedInputs); - localizedInputs.call(renderMultilingual); - localizedInputs.selectAll("button, input").classed("disabled", !!isLocked).attr("readonly", isLocked || null); - selection2.selectAll(".combobox-caret").classed("nope", true); - function addNew(d3_event) { - d3_event.preventDefault(); - if (field.locked()) - return; - var defaultLang = _mainLocalizer.languageCode().toLowerCase(); - var langExists = _multilingual.find(function(datum2) { - return datum2.lang === defaultLang; - }); - var isLangEn = defaultLang.indexOf("en") > -1; - if (isLangEn || langExists) { - defaultLang = ""; - langExists = _multilingual.find(function(datum2) { - return datum2.lang === defaultLang; - }); - } - if (!langExists) { - _multilingual.unshift({ lang: defaultLang, value: "" }); - localizedInputs.call(renderMultilingual); - } + if (!field.caseSensitive) { + dval = dval.toLowerCase(); } - function change(onInput) { - return function(d3_event) { - if (field.locked()) { - d3_event.preventDefault(); - return; - } - var val = utilGetSetValue(select_default2(this)); - if (!onInput) - val = context.cleanTagValue(val); - if (!val && Array.isArray(_tags[field.key])) - return; - var t2 = {}; - t2[field.key] = val || void 0; - dispatch14.call("change", this, t2, onInput); - }; + return dval; + } + function getLabelId(field2, v2) { + return field2.hasTextForStringId("options.".concat(v2, ".title")) ? "options.".concat(v2, ".title") : "options.".concat(v2); + } + function displayValue(tval) { + tval = tval || ""; + var stringsField = field.resolveReference("stringsCrossReference"); + const labelId = getLabelId(stringsField, tval); + if (stringsField.hasTextForStringId(labelId)) { + return stringsField.t(labelId, { default: tval }); + } + if (field.type === "typeCombo" && tval.toLowerCase() === "yes") { + return ""; } + return tval; } - function key(lang) { - return field.key + ":" + lang; + function renderValue(tval) { + tval = tval || ""; + var stringsField = field.resolveReference("stringsCrossReference"); + const labelId = getLabelId(stringsField, tval); + if (stringsField.hasTextForStringId(labelId)) { + return stringsField.t.append(labelId, { default: tval }); + } + if (field.type === "typeCombo" && tval.toLowerCase() === "yes") { + tval = ""; + } + return (selection2) => selection2.text(tval); } - function changeLang(d3_event, d2) { - var tags = {}; - var lang = utilGetSetValue(select_default2(this)).toLowerCase(); - var language = _languagesArray.find(function(d4) { - return d4.label.toLowerCase() === lang || d4.localName && d4.localName.toLowerCase() === lang || d4.nativeName && d4.nativeName.toLowerCase() === lang; + function objectDifference(a2, b2) { + return a2.filter(function(d1) { + return !b2.some(function(d2) { + return d1.value === d2.value; + }); }); - if (language) - lang = language.code; - if (d2.lang && d2.lang !== lang) { - tags[key(d2.lang)] = void 0; + } + function initCombo(selection2, attachTo) { + if (!_allowCustomValues) { + selection2.attr("readonly", "readonly"); } - var newKey = lang && context.cleanTagKey(key(lang)); - var value = utilGetSetValue(select_default2(this.parentNode).selectAll(".localized-value")); - if (newKey && value) { - tags[newKey] = value; - } else if (newKey && _wikiTitles && _wikiTitles[d2.lang]) { - tags[newKey] = _wikiTitles[d2.lang]; + if (_showTagInfoSuggestions && services.taginfo) { + selection2.call(_combobox.fetcher(setTaginfoValues), attachTo); + setTaginfoValues("", setPlaceholder); + } else { + selection2.call(_combobox, attachTo); + setTimeout(() => setStaticValues(setPlaceholder), 0); } - d2.lang = lang; - dispatch14.call("change", this, tags); } - function changeValue(d3_event, d2) { - if (!d2.lang) - return; - var value = context.cleanTagValue(utilGetSetValue(select_default2(this))) || void 0; - if (!value && Array.isArray(d2.value)) - return; - var t2 = {}; - t2[key(d2.lang)] = value; - d2.value = value; - dispatch14.call("change", this, t2); + function getOptions(allOptions) { + var stringsField = field.resolveReference("stringsCrossReference"); + if (!(field.options || stringsField.options)) + return []; + let options2; + if (allOptions !== true) { + options2 = field.options || stringsField.options; + } else { + options2 = [].concat(field.options, stringsField.options).filter(Boolean); + } + return options2.map(function(v2) { + const labelId = getLabelId(stringsField, v2); + return { + key: v2, + value: stringsField.t(labelId, { default: v2 }), + title: stringsField.t("options.".concat(v2, ".description"), { default: v2 }), + display: addComboboxIcons(stringsField.t.append(labelId, { default: v2 }), v2), + klass: stringsField.hasTextForStringId(labelId) ? "" : "raw-option" + }; + }); } - function fetchLanguages(value, cb) { - var v2 = value.toLowerCase(); - var langCodes = [_mainLocalizer.localeCode(), _mainLocalizer.languageCode()]; - if (_countryCode && _territoryLanguages[_countryCode]) { - langCodes = langCodes.concat(_territoryLanguages[_countryCode]); + function hasStaticValues() { + return getOptions().length > 0; + } + function setStaticValues(callback, filter2) { + _comboData = getOptions(); + if (filter2 !== void 0) { + _comboData = _comboData.filter(filter2); } - var langItems = []; - langCodes.forEach(function(code) { - var langItem = _languagesArray.find(function(item) { - return item.code === code; + _comboData = objectDifference(_comboData, _multiData); + _combobox.data(_comboData); + if (callback) + callback(_comboData); + } + function setTaginfoValues(q2, callback) { + var queryFilter = (d2) => d2.value.toLowerCase().includes(q2.toLowerCase()) || d2.key.toLowerCase().includes(q2.toLowerCase()); + if (hasStaticValues()) { + setStaticValues(callback, queryFilter); + } + var stringsField = field.resolveReference("stringsCrossReference"); + var fn = _isMulti ? "multikeys" : "values"; + var query = (_isMulti ? field.key : "") + q2; + var hasCountryPrefix = _isNetwork && _countryCode && _countryCode.indexOf(q2.toLowerCase()) === 0; + if (hasCountryPrefix) { + query = _countryCode + ":"; + } + var params = { + debounce: q2 !== "", + key: field.key, + query + }; + if (_entityIDs.length) { + params.geometry = context.graph().geometry(_entityIDs[0]); + } + services.taginfo[fn](params, function(err, data) { + if (err) + return; + data = data.filter((d2) => field.type !== "typeCombo" || d2.value !== "yes"); + data = data.filter((d2) => { + var value = d2.value; + if (_isMulti) { + value = value.slice(field.key.length); + } + return value === restrictTagValueSpelling(value); }); - if (langItem) - langItems.push(langItem); + var deprecatedValues = osmEntity.deprecatedTagValuesByKey(_dataDeprecated)[field.key]; + if (deprecatedValues) { + data = data.filter((d2) => !deprecatedValues.includes(d2.value)); + } + if (hasCountryPrefix) { + data = data.filter((d2) => d2.value.toLowerCase().indexOf(_countryCode + ":") === 0); + } + const additionalOptions = (field.options || stringsField.options || []).filter((v2) => !data.some((dv) => dv.value === (_isMulti ? field.key + v2 : v2))).map((v2) => ({ value: v2 })); + _container.classed("empty-combobox", data.length === 0); + _comboData = data.concat(additionalOptions).map(function(d2) { + var v2 = d2.value; + if (_isMulti) + v2 = v2.replace(field.key, ""); + const labelId = getLabelId(stringsField, v2); + var isLocalizable = stringsField.hasTextForStringId(labelId); + var label = stringsField.t(labelId, { default: v2 }); + return { + key: v2, + value: label, + title: stringsField.t("options.".concat(v2, ".description"), { default: isLocalizable ? v2 : d2.title !== label ? d2.title : "" }), + display: addComboboxIcons(stringsField.t.append(labelId, { default: v2 }), v2), + klass: isLocalizable ? "" : "raw-option" + }; + }); + _comboData = _comboData.filter(queryFilter); + _comboData = objectDifference(_comboData, _multiData); + if (callback) + callback(_comboData, hasStaticValues()); }); - langItems = utilArrayUniq(langItems.concat(_languagesArray)); - cb(langItems.filter(function(d2) { - return d2.label.toLowerCase().indexOf(v2) >= 0 || d2.localName && d2.localName.toLowerCase().indexOf(v2) >= 0 || d2.nativeName && d2.nativeName.toLowerCase().indexOf(v2) >= 0 || d2.code.toLowerCase().indexOf(v2) >= 0; - }).map(function(d2) { - return { value: d2.label }; - })); } - function renderMultilingual(selection2) { - var entries = selection2.selectAll("div.entry").data(_multilingual, function(d2) { - return d2.lang; - }); - entries.exit().style("top", "0").style("max-height", "240px").transition().duration(200).style("opacity", "0").style("max-height", "0px").remove(); - var entriesEnter = entries.enter().append("div").attr("class", "entry").each(function(_2, index) { - var wrap2 = select_default2(this); - var domId = utilUniqueDomId(index); - var label = wrap2.append("label").attr("class", "field-label").attr("for", domId); - var text2 = label.append("span").attr("class", "label-text"); - text2.append("span").attr("class", "label-textvalue").call(_t.append("translate.localized_translation_label")); - text2.append("span").attr("class", "label-textannotation"); - label.append("button").attr("class", "remove-icon-multilingual").attr("title", _t("icons.remove")).on("click", function(d3_event, d2) { - if (field.locked()) - return; - d3_event.preventDefault(); - _multilingual.splice(_multilingual.indexOf(d2), 1); - var langKey = d2.lang && key(d2.lang); - if (langKey && langKey in _tags) { - delete _tags[langKey]; - var t2 = {}; - t2[langKey] = void 0; - dispatch14.call("change", this, t2); - return; + function addComboboxIcons(disp, value) { + const iconsField = field.resolveReference("iconsCrossReference"); + if (iconsField.icons) { + return function(selection2) { + var span = selection2.insert("span", ":first-child").attr("class", "tag-value-icon"); + if (iconsField.icons[value]) { + span.call(svgIcon("#".concat(iconsField.icons[value]))); } - renderMultilingual(selection2); - }).call(svgIcon("#iD-operation-delete")); - wrap2.append("input").attr("class", "localized-lang").attr("id", domId).attr("type", "text").attr("placeholder", _t("translate.localized_translation_language")).on("blur", changeLang).on("change", changeLang).call(langCombo); - wrap2.append("input").attr("type", "text").attr("class", "localized-value").on("blur", changeValue).on("change", changeValue); - }); - entriesEnter.style("margin-top", "0px").style("max-height", "0px").style("opacity", "0").transition().duration(200).style("margin-top", "10px").style("max-height", "240px").style("opacity", "1").on("end", function() { - select_default2(this).style("max-height", "").style("overflow", "visible"); - }); - entries = entries.merge(entriesEnter); - entries.order(); - entries.classed("present", true); - utilGetSetValue(entries.select(".localized-lang"), function(d2) { - var langItem = _languagesArray.find(function(item) { - return item.code === d2.lang; + disp.call(this, selection2); + }; + } + return disp; + } + function setPlaceholder(values) { + if (_isMulti || _isSemi) { + _staticPlaceholder = field.placeholder() || _t("inspector.add"); + } else { + var vals = values.map(function(d2) { + return d2.value; + }).filter(function(s2) { + return s2.length < 20; }); - if (langItem) - return langItem.label; - return d2.lang; - }); - utilGetSetValue(entries.select(".localized-value"), function(d2) { - return typeof d2.value === "string" ? d2.value : ""; - }).attr("title", function(d2) { - return Array.isArray(d2.value) ? d2.value.filter(Boolean).join("\n") : null; - }).attr("placeholder", function(d2) { - return Array.isArray(d2.value) ? _t("inspector.multiple_values") : _t("translate.localized_translation_name"); - }).classed("mixed", function(d2) { - return Array.isArray(d2.value); - }); + var placeholders = vals.length > 1 ? vals : values.map(function(d2) { + return d2.key; + }); + _staticPlaceholder = field.placeholder() || placeholders.slice(0, 3).join(", "); + } + if (!/(…|\.\.\.)$/.test(_staticPlaceholder)) { + _staticPlaceholder += "\u2026"; + } + var ph; + if (!_isMulti && !_isSemi && _tags && Array.isArray(_tags[field.key])) { + ph = _t("inspector.multiple_values"); + } else { + ph = _staticPlaceholder; + } + _container.selectAll("input").attr("placeholder", ph); + var hideAdd = !_allowCustomValues && !values.length; + _container.selectAll(".chiplist .input-wrap").style("display", hideAdd ? "none" : null); } - localized.tags = function(tags) { - _tags = tags; - if (typeof tags.wikipedia === "string" && !_wikiTitles) { - _wikiTitles = {}; - var wm = tags.wikipedia.match(/([^:]+):(.+)/); - if (wm && wm[0] && wm[1]) { - wikipedia.translations(wm[1], wm[2], function(err, d2) { - if (err || !d2) - return; - _wikiTitles = d2; + function change() { + var t2 = {}; + var val; + if (_isMulti || _isSemi) { + var vals; + if (_isMulti) { + vals = [tagValue(utilGetSetValue(_input))]; + } else if (_isSemi) { + val = tagValue(utilGetSetValue(_input)) || ""; + val = val.replace(/,/g, ";"); + vals = val.split(";"); + } + vals = vals.filter(Boolean); + if (!vals.length) + return; + _container.classed("active", false); + utilGetSetValue(_input, ""); + if (_isMulti) { + utilArrayUniq(vals).forEach(function(v2) { + var key = (field.key || "") + v2; + if (_tags) { + var old = _tags[key]; + if (typeof old === "string" && old.toLowerCase() !== "no") + return; + } + key = context.cleanTagKey(key); + field.keys.push(key); + t2[key] = "yes"; + }); + } else if (_isSemi) { + var arr = _multiData.map(function(d2) { + return d2.key; }); + arr = arr.concat(vals); + t2[field.key] = context.cleanTagValue(utilArrayUniq(arr).filter(Boolean).join(";")); } + window.setTimeout(function() { + _input.node().focus(); + }, 10); + } else { + var rawValue = utilGetSetValue(_input); + if (!rawValue && Array.isArray(_tags[field.key])) + return; + val = context.cleanTagValue(tagValue(rawValue)); + t2[field.key] = val || void 0; } - var isMixed = Array.isArray(tags[field.key]); - utilGetSetValue(input, typeof tags[field.key] === "string" ? tags[field.key] : "").attr("title", isMixed ? tags[field.key].filter(Boolean).join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder()).classed("mixed", isMixed); - calcMultilingual(tags); - _selection.call(localized); - if (!isMixed) { - _lengthIndicator.update(tags[field.key]); + dispatch14.call("change", this, t2); + } + function removeMultikey(d3_event, d2) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + var t2 = {}; + if (_isMulti) { + t2[d2.key] = void 0; + } else if (_isSemi) { + var arr = _multiData.map(function(md) { + return md.key === d2.key ? null : md.key; + }).filter(Boolean); + arr = utilArrayUniq(arr); + t2[field.key] = arr.length ? arr.join(";") : void 0; + _lengthIndicator.update(t2[field.key]); } - }; - localized.focus = function() { - input.node().focus(); - }; - localized.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - _multilingual = []; - loadCountryCode(); - return localized; - }; - function loadCountryCode() { - var extent = combinedEntityExtent(); - var countryCode = extent && iso1A2Code(extent.center()); - _countryCode = countryCode && countryCode.toLowerCase(); + dispatch14.call("change", this, t2); } - function combinedEntityExtent() { - return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + function invertMultikey(d3_event, d2) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + var t2 = {}; + if (_isMulti) { + t2[d2.key] = _tags[d2.key] === "yes" ? "no" : "yes"; + } + dispatch14.call("change", this, t2); } - return utilRebind(localized, dispatch14, "on"); - } - - // modules/ui/fields/roadheight.js - function uiFieldRoadheight(field, context) { - var dispatch14 = dispatch_default("change"); - var primaryUnitInput = select_default2(null); - var primaryInput = select_default2(null); - var secondaryInput = select_default2(null); - var secondaryUnitInput = select_default2(null); - var _entityIDs = []; - var _tags; - var _isImperial; - var formatFloat = _mainLocalizer.floatFormatter(_mainLocalizer.languageCode()); - var parseLocaleFloat = _mainLocalizer.floatParser(_mainLocalizer.languageCode()); - var primaryUnits = [ - { - value: "m", - title: _t("inspector.roadheight.meter") - }, - { - value: "ft", - title: _t("inspector.roadheight.foot") + function combo(selection2) { + _container = selection2.selectAll(".form-field-input-wrap").data([0]); + var type2 = _isMulti || _isSemi ? "multicombo" : "combo"; + _container = _container.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + type2).merge(_container); + if (_isMulti || _isSemi) { + _container = _container.selectAll(".chiplist").data([0]); + var listClass = "chiplist"; + if (field.key === "destination" || field.key === "via") { + listClass += " full-line-chips"; + } + _container = _container.enter().append("ul").attr("class", listClass).on("click", function() { + window.setTimeout(function() { + _input.node().focus(); + }, 10); + }).merge(_container); + _inputWrap = _container.selectAll(".input-wrap").data([0]); + _inputWrap = _inputWrap.enter().append("li").attr("class", "input-wrap").merge(_inputWrap); + var hideAdd = !_allowCustomValues && !_comboData.length; + _inputWrap.style("display", hideAdd ? "none" : null); + _input = _inputWrap.selectAll("input").data([0]); + } else { + _input = _container.selectAll("input").data([0]); } - ]; - var unitCombo = uiCombobox(context, "roadheight-unit").data(primaryUnits); - function roadheight(selection2) { - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - primaryInput = wrap2.selectAll("input.roadheight-number").data([0]); - primaryInput = primaryInput.enter().append("input").attr("type", "text").attr("class", "roadheight-number").attr("id", field.domId).call(utilNoAuto).merge(primaryInput); - primaryInput.on("change", change).on("blur", change); - var loc = combinedEntityExtent().center(); - _isImperial = roadHeightUnit(loc) === "ft"; - primaryUnitInput = wrap2.selectAll("input.roadheight-unit").data([0]); - primaryUnitInput = primaryUnitInput.enter().append("input").attr("type", "text").attr("class", "roadheight-unit").call(unitCombo).merge(primaryUnitInput); - primaryUnitInput.on("blur", changeUnits).on("change", changeUnits); - secondaryInput = wrap2.selectAll("input.roadheight-secondary-number").data([0]); - secondaryInput = secondaryInput.enter().append("input").attr("type", "text").attr("class", "roadheight-secondary-number").call(utilNoAuto).merge(secondaryInput); - secondaryInput.on("change", change).on("blur", change); - secondaryUnitInput = wrap2.selectAll("input.roadheight-secondary-unit").data([0]); - secondaryUnitInput = secondaryUnitInput.enter().append("input").attr("type", "text").call(utilNoAuto).classed("disabled", true).classed("roadheight-secondary-unit", true).attr("readonly", "readonly").merge(secondaryUnitInput); - function changeUnits() { - var primaryUnit = utilGetSetValue(primaryUnitInput); - if (primaryUnit === "m") { - _isImperial = false; - } else if (primaryUnit === "ft") { - _isImperial = true; + _input = _input.enter().append("input").attr("type", "text").attr("id", field.domId).call(utilNoAuto).call(initCombo, _container).merge(_input); + if (_isSemi) { + _inputWrap.call(_lengthIndicator); + } else if (!_isMulti) { + _container.call(_lengthIndicator); + } + if (_isNetwork) { + var extent = combinedEntityExtent(); + var countryCode = extent && iso1A2Code(extent.center()); + _countryCode = countryCode && countryCode.toLowerCase(); + } + _input.on("change", change).on("blur", change).on("input", function() { + let val = utilGetSetValue(_input); + updateIcon(val); + if (_isSemi && _tags[field.key]) { + val += ";" + _tags[field.key]; } - utilGetSetValue(primaryUnitInput, _isImperial ? "ft" : "m"); - setUnitSuggestions(); - change(); + _lengthIndicator.update(val); + }); + _input.on("keydown.field", function(d3_event) { + switch (d3_event.keyCode) { + case 13: + _input.node().blur(); + d3_event.stopPropagation(); + break; + } + }); + if (_isMulti || _isSemi) { + _combobox.on("accept", function() { + _input.node().blur(); + _input.node().focus(); + }); + _input.on("focus", function() { + _container.classed("active", true); + }); } + _combobox.on("cancel", function() { + _input.node().blur(); + }).on("update", function() { + updateIcon(utilGetSetValue(_input)); + }); } - function setUnitSuggestions() { - utilGetSetValue(primaryUnitInput, _isImperial ? "ft" : "m"); - } - function change() { - var tag = {}; - var primaryValue = utilGetSetValue(primaryInput).trim(); - var secondaryValue = utilGetSetValue(secondaryInput).trim(); - if (!primaryValue && !secondaryValue && Array.isArray(_tags[field.key])) - return; - if (!primaryValue && !secondaryValue) { - tag[field.key] = void 0; - } else { - var rawPrimaryValue = likelyRawNumberFormat.test(primaryValue) ? parseFloat(primaryValue) : parseLocaleFloat(primaryValue); - if (isNaN(rawPrimaryValue)) - rawPrimaryValue = primaryValue; - var rawSecondaryValue = likelyRawNumberFormat.test(secondaryValue) ? parseFloat(secondaryValue) : parseLocaleFloat(secondaryValue); - if (isNaN(rawSecondaryValue)) - rawSecondaryValue = secondaryValue; - if (isNaN(rawPrimaryValue) || isNaN(rawSecondaryValue) || !_isImperial) { - tag[field.key] = context.cleanTagValue(rawPrimaryValue); - } else { - if (rawPrimaryValue !== "") { - rawPrimaryValue = rawPrimaryValue + "'"; - } - if (rawSecondaryValue !== "") { - rawSecondaryValue = rawSecondaryValue + '"'; - } - tag[field.key] = context.cleanTagValue(rawPrimaryValue + rawSecondaryValue); + function updateIcon(value) { + value = tagValue(value); + let container = _container; + if (field.type === "multiCombo" || field.type === "semiCombo") { + container = _container.select(".input-wrap"); + } + const iconsField = field.resolveReference("iconsCrossReference"); + if (iconsField.icons) { + container.selectAll(".tag-value-icon").remove(); + if (iconsField.icons[value]) { + container.selectAll(".tag-value-icon").data([value]).enter().insert("div", "input").attr("class", "tag-value-icon").call(svgIcon("#".concat(iconsField.icons[value]))); } } - dispatch14.call("change", this, tag); } - roadheight.tags = function(tags) { + combo.tags = function(tags) { _tags = tags; - var primaryValue = tags[field.key]; - var secondaryValue; - var isMixed = Array.isArray(primaryValue); - if (!isMixed) { - if (primaryValue && (primaryValue.indexOf("'") >= 0 || primaryValue.indexOf('"') >= 0)) { - secondaryValue = primaryValue.match(/(-?[\d.]+)"/); - if (secondaryValue !== null) { - secondaryValue = formatFloat(parseFloat(secondaryValue[1])); + var stringsField = field.resolveReference("stringsCrossReference"); + var isMixed = Array.isArray(tags[field.key]); + var showsValue = (value) => !isMixed && value && !(field.type === "typeCombo" && value === "yes"); + var isRawValue = (value) => showsValue(value) && !stringsField.hasTextForStringId("options.".concat(value)) && !stringsField.hasTextForStringId("options.".concat(value, ".title")); + var isKnownValue = (value) => showsValue(value) && !isRawValue(value); + var isReadOnly = !_allowCustomValues; + if (_isMulti || _isSemi) { + _multiData = []; + var maxLength; + if (_isMulti) { + for (var k2 in tags) { + if (field.key && k2.indexOf(field.key) !== 0) + continue; + if (!field.key && field.keys.indexOf(k2) === -1) + continue; + var v2 = tags[k2]; + var suffix = field.key ? k2.slice(field.key.length) : k2; + _multiData.push({ + key: k2, + value: displayValue(suffix), + display: addComboboxIcons(renderValue(suffix), suffix), + state: typeof v2 === "string" ? v2.toLowerCase() : "", + isMixed: Array.isArray(v2) + }); } - primaryValue = primaryValue.match(/(-?[\d.]+)'/); - if (primaryValue !== null) { - primaryValue = formatFloat(parseFloat(primaryValue[1])); + if (field.key) { + field.keys = _multiData.map(function(d2) { + return d2.key; + }); + maxLength = context.maxCharsForTagKey() - utilUnicodeCharsCount(field.key); + } else { + maxLength = context.maxCharsForTagKey(); } - _isImperial = true; - } else if (primaryValue) { - var rawValue = primaryValue; - primaryValue = parseFloat(rawValue); - if (isNaN(primaryValue)) { - primaryValue = rawValue; + } else if (_isSemi) { + var allValues = []; + var commonValues; + if (Array.isArray(tags[field.key])) { + tags[field.key].forEach(function(tagVal) { + var thisVals = utilArrayUniq((tagVal || "").split(";")).filter(Boolean); + allValues = allValues.concat(thisVals); + if (!commonValues) { + commonValues = thisVals; + } else { + commonValues = commonValues.filter((value) => thisVals.includes(value)); + } + }); + allValues = utilArrayUniq(allValues).filter(Boolean); } else { - primaryValue = formatFloat(primaryValue); + allValues = utilArrayUniq((tags[field.key] || "").split(";")).filter(Boolean); + commonValues = allValues; + } + _multiData = allValues.map(function(v3) { + return { + key: v3, + value: displayValue(v3), + display: addComboboxIcons(renderValue(v3), v3), + isMixed: !commonValues.includes(v3) + }; + }); + var currLength = utilUnicodeCharsCount(commonValues.join(";")); + maxLength = context.maxCharsForTagValue() - currLength; + if (currLength > 0) { + maxLength -= 1; } - _isImperial = false; } - } - setUnitSuggestions(); - var inchesPlaceholder = formatFloat(0); - utilGetSetValue(primaryInput, typeof primaryValue === "string" ? primaryValue : "").attr("title", isMixed ? primaryValue.filter(Boolean).join("\n") : null).attr("placeholder", isMixed ? _t("inspector.multiple_values") : _t("inspector.unknown")).classed("mixed", isMixed); - utilGetSetValue(secondaryInput, typeof secondaryValue === "string" ? secondaryValue : "").attr("placeholder", isMixed ? _t("inspector.multiple_values") : _isImperial ? inchesPlaceholder : null).classed("mixed", isMixed).classed("disabled", !_isImperial).attr("readonly", _isImperial ? null : "readonly"); - secondaryUnitInput.attr("value", _isImperial ? _t("inspector.roadheight.inch") : null); - }; - roadheight.focus = function() { - primaryInput.node().focus(); - }; - roadheight.entityIDs = function(val) { - _entityIDs = val; - }; - function combinedEntityExtent() { - return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); - } - return utilRebind(roadheight, dispatch14, "on"); - } - - // modules/ui/fields/roadspeed.js - function uiFieldRoadspeed(field, context) { - var dispatch14 = dispatch_default("change"); - var unitInput = select_default2(null); - var input = select_default2(null); - var _entityIDs = []; - var _tags; - var _isImperial; - var formatFloat = _mainLocalizer.floatFormatter(_mainLocalizer.languageCode()); - var parseLocaleFloat = _mainLocalizer.floatParser(_mainLocalizer.languageCode()); - var speedCombo = uiCombobox(context, "roadspeed"); - var unitCombo = uiCombobox(context, "roadspeed-unit").data(["km/h", "mph"].map(comboValues)); - var metricValues = [20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; - var imperialValues = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80]; - function roadspeed(selection2) { - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - input = wrap2.selectAll("input.roadspeed-number").data([0]); - input = input.enter().append("input").attr("type", "text").attr("class", "roadspeed-number").attr("id", field.domId).call(utilNoAuto).call(speedCombo).merge(input); - input.on("change", change).on("blur", change); - var loc = combinedEntityExtent().center(); - _isImperial = roadSpeedUnit(loc) === "mph"; - unitInput = wrap2.selectAll("input.roadspeed-unit").data([0]); - unitInput = unitInput.enter().append("input").attr("type", "text").attr("class", "roadspeed-unit").attr("aria-label", _t("inspector.speed_unit")).call(unitCombo).merge(unitInput); - unitInput.on("blur", changeUnits).on("change", changeUnits); - function changeUnits() { - var unit2 = utilGetSetValue(unitInput); - if (unit2 === "km/h") { - _isImperial = false; - } else if (unit2 === "mph") { - _isImperial = true; + maxLength = Math.max(0, maxLength); + var hideAdd = maxLength <= 0 || !_allowCustomValues && !_comboData.length; + _container.selectAll(".chiplist .input-wrap").style("display", hideAdd ? "none" : null); + var allowDragAndDrop = _isSemi && !Array.isArray(tags[field.key]); + var chips = _container.selectAll(".chip").data(_multiData); + chips.exit().remove(); + var enter = chips.enter().insert("li", ".input-wrap").attr("class", "chip"); + enter.append("span"); + const field_buttons = enter.append("div").attr("class", "field_buttons"); + field_buttons.append("a").attr("class", "remove"); + chips = chips.merge(enter).order().classed("raw-value", function(d2) { + var k3 = d2.key; + if (_isMulti) + k3 = k3.replace(field.key, ""); + return !stringsField.hasTextForStringId("options." + k3); + }).classed("draggable", allowDragAndDrop).classed("mixed", function(d2) { + return d2.isMixed; + }).attr("title", function(d2) { + if (d2.isMixed) { + return _t("inspector.unshared_value_tooltip"); + } + if (!["yes", "no"].includes(d2.state)) { + return d2.state; + } + return null; + }).classed("negated", (d2) => d2.state === "no"); + if (!_isSemi) { + chips.selectAll("input[type=checkbox]").remove(); + chips.insert("input", "span").attr("type", "checkbox").property("checked", (d2) => d2.state === "yes").property("indeterminate", (d2) => d2.isMixed || !["yes", "no"].includes(d2.state)).on("click", invertMultikey); } - utilGetSetValue(unitInput, _isImperial ? "mph" : "km/h"); - setUnitSuggestions(); - change(); - } - } - function setUnitSuggestions() { - speedCombo.data((_isImperial ? imperialValues : metricValues).map(comboValues)); - utilGetSetValue(unitInput, _isImperial ? "mph" : "km/h"); - } - function comboValues(d2) { - return { - value: formatFloat(d2), - title: formatFloat(d2) - }; - } - function change() { - var tag = {}; - var value = utilGetSetValue(input).trim(); - if (!value && Array.isArray(_tags[field.key])) - return; - if (!value) { - tag[field.key] = void 0; + if (allowDragAndDrop) { + registerDragAndDrop(chips); + } + chips.each(function(d2) { + const selection2 = select_default2(this); + const text_span = selection2.select("span"); + const field_buttons2 = selection2.select(".field_buttons"); + const clean_value = d2.value.trim(); + text_span.text(""); + if (clean_value.startsWith("https://")) { + text_span.text(clean_value); + field_buttons2.select("button").remove(); + field_buttons2.append("button").call(svgIcon("#iD-icon-out-link")).attr("class", "form-field-button foreign-id-permalink").attr("title", () => _t("icons.visit_website")).attr("aria-label", () => _t("icons.visit_website")).on("click", function(d3_event) { + d3_event.preventDefault(); + window.open(clean_value, "_blank"); + }); + return; + } + if (d2.display) { + d2.display(text_span); + return; + } + text_span.text(d2.value); + }); + chips.select("a.remove").attr("href", "#").on("click", removeMultikey).attr("class", "remove").text("\xD7"); + updateIcon(""); } else { - var rawValue = likelyRawNumberFormat.test(value) ? parseFloat(value) : parseLocaleFloat(value); - if (isNaN(rawValue)) - rawValue = value; - if (isNaN(rawValue) || !_isImperial) { - tag[field.key] = context.cleanTagValue(rawValue); - } else { - tag[field.key] = context.cleanTagValue(rawValue + " mph"); + var mixedValues = isMixed && tags[field.key].map(function(val) { + return displayValue(val); + }).filter(Boolean); + utilGetSetValue(_input, !isMixed ? displayValue(tags[field.key]) : "").data([tags[field.key]]).classed("raw-value", isRawValue).classed("known-value", isKnownValue).attr("readonly", isReadOnly ? "readonly" : void 0).attr("title", isMixed ? mixedValues.join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : _staticPlaceholder || "").classed("mixed", isMixed).on("keydown.deleteCapture", function(d3_event) { + if (isReadOnly && isKnownValue(tags[field.key]) && (d3_event.keyCode === utilKeybinding.keyCodes["\u232B"] || d3_event.keyCode === utilKeybinding.keyCodes["\u2326"])) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + var t2 = {}; + t2[field.key] = void 0; + dispatch14.call("change", this, t2); + } + }); + if (!Array.isArray(tags[field.key])) { + updateIcon(tags[field.key]); + } + if (!isMixed) { + _lengthIndicator.update(tags[field.key]); } } - dispatch14.call("change", this, tag); + const refreshStyles = () => { + _input.data([tagValue(utilGetSetValue(_input))]).classed("raw-value", isRawValue).classed("known-value", isKnownValue); + }; + _input.on("input.refreshStyles", refreshStyles); + _combobox.on("update.refreshStyles", refreshStyles); + refreshStyles(); + }; + function registerDragAndDrop(selection2) { + var dragOrigin, targetIndex; + selection2.call( + drag_default().on("start", function(d3_event) { + dragOrigin = { + x: d3_event.x, + y: d3_event.y + }; + targetIndex = null; + }).on("drag", function(d3_event) { + var x2 = d3_event.x - dragOrigin.x, y2 = d3_event.y - dragOrigin.y; + if (!select_default2(this).classed("dragging") && // don't display drag until dragging beyond a distance threshold + Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2)) <= 5) + return; + var index = selection2.nodes().indexOf(this); + select_default2(this).classed("dragging", true); + targetIndex = null; + var targetIndexOffsetTop = null; + var draggedTagWidth = select_default2(this).node().offsetWidth; + if (field.key === "destination" || field.key === "via") { + _container.selectAll(".chip").style("transform", function(d2, index2) { + var node = select_default2(this).node(); + if (index === index2) { + return "translate(" + x2 + "px, " + y2 + "px)"; + } else if (index2 > index && d3_event.y > node.offsetTop) { + if (targetIndex === null || index2 > targetIndex) { + targetIndex = index2; + } + return "translateY(-100%)"; + } else if (index2 < index && d3_event.y < node.offsetTop + node.offsetHeight) { + if (targetIndex === null || index2 < targetIndex) { + targetIndex = index2; + } + return "translateY(100%)"; + } + return null; + }); + } else { + _container.selectAll(".chip").each(function(d2, index2) { + var node = select_default2(this).node(); + if (index !== index2 && d3_event.x < node.offsetLeft + node.offsetWidth + 5 && d3_event.x > node.offsetLeft && d3_event.y < node.offsetTop + node.offsetHeight && d3_event.y > node.offsetTop) { + targetIndex = index2; + targetIndexOffsetTop = node.offsetTop; + } + }).style("transform", function(d2, index2) { + var node = select_default2(this).node(); + if (index === index2) { + return "translate(" + x2 + "px, " + y2 + "px)"; + } + if (node.offsetTop === targetIndexOffsetTop) { + if (index2 < index && index2 >= targetIndex) { + return "translateX(" + draggedTagWidth + "px)"; + } else if (index2 > index && index2 <= targetIndex) { + return "translateX(-" + draggedTagWidth + "px)"; + } + } + return null; + }); + } + }).on("end", function() { + if (!select_default2(this).classed("dragging")) { + return; + } + var index = selection2.nodes().indexOf(this); + select_default2(this).classed("dragging", false); + _container.selectAll(".chip").style("transform", null); + if (typeof targetIndex === "number") { + var element = _multiData[index]; + _multiData.splice(index, 1); + _multiData.splice(targetIndex, 0, element); + var t2 = {}; + if (_multiData.length) { + t2[field.key] = _multiData.map(function(element2) { + return element2.key; + }).join(";"); + } else { + t2[field.key] = void 0; + } + dispatch14.call("change", this, t2); + } + dragOrigin = void 0; + targetIndex = void 0; + }) + ); } - roadspeed.tags = function(tags) { - _tags = tags; - var rawValue = tags[field.key]; - var value = rawValue; - var isMixed = Array.isArray(value); - if (!isMixed) { - if (rawValue && rawValue.indexOf("mph") >= 0) { - _isImperial = true; - } else if (rawValue) { - _isImperial = false; - } - value = parseInt(value, 10); - if (isNaN(value)) { - value = rawValue; - } else { - value = formatFloat(value); - } - } - setUnitSuggestions(); - utilGetSetValue(input, typeof value === "string" ? value : "").attr("title", isMixed ? value.filter(Boolean).join("\n") : null).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder()).classed("mixed", isMixed); - }; - roadspeed.focus = function() { - input.node().focus(); + combo.focus = function() { + _input.node().focus(); }; - roadspeed.entityIDs = function(val) { + combo.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; _entityIDs = val; + return combo; }; function combinedEntityExtent() { return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); } - return utilRebind(roadspeed, dispatch14, "on"); + return utilRebind(combo, dispatch14, "on"); } - // modules/ui/fields/radio.js - function uiFieldRadio(field, context) { + // modules/ui/fields/input.js + var likelyRawNumberFormat = /^-?(0\.\d*|\d*\.\d{0,2}(\d{4,})?|\d{4,}\.\d{3})$/; + function uiFieldText(field, context) { var dispatch14 = dispatch_default("change"); - var placeholder = select_default2(null); + var input = select_default2(null); + var outlinkButton = select_default2(null); var wrap2 = select_default2(null); - var labels = select_default2(null); - var radios = select_default2(null); - var radioData = (field.options || field.keys).slice(); - var typeField; - var layerField; - var _oldType = {}; + var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()); var _entityIDs = []; - function selectedKey() { - var node = wrap2.selectAll(".form-field-input-radio label.active input"); - return !node.empty() && node.datum(); + var _tags; + var _phoneFormats = {}; + const isDirectionField = field.key.split(":").some((keyPart) => keyPart === "direction"); + const formatFloat = _mainLocalizer.floatFormatter(_mainLocalizer.languageCode()); + const parseLocaleFloat = _mainLocalizer.floatParser(_mainLocalizer.languageCode()); + const countDecimalPlaces = _mainLocalizer.decimalPlaceCounter(_mainLocalizer.languageCode()); + if (field.type === "tel") { + _mainFileFetcher.get("phone_formats").then(function(d2) { + _phoneFormats = d2; + updatePhonePlaceholder(); + }).catch(function() { + }); } - function radio(selection2) { - selection2.classed("preset-radio", true); - wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - var enter = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-radio"); - enter.append("span").attr("class", "placeholder"); - wrap2 = wrap2.merge(enter); - placeholder = wrap2.selectAll(".placeholder"); - labels = wrap2.selectAll("label").data(radioData); - enter = labels.enter().append("label"); - var stringsField = field.resolveReference("stringsCrossReference"); - enter.append("input").attr("type", "radio").attr("name", field.id).attr("value", function(d2) { - return stringsField.t("options." + d2, { "default": d2 }); - }).attr("checked", false); - enter.append("span").each(function(d2) { - stringsField.t.append("options." + d2, { "default": d2 })(select_default2(this)); + function calcLocked() { + var isLocked = (field.id === "brand" || field.id === "network" || field.id === "operator" || field.id === "flag") && _entityIDs.length && _entityIDs.some(function(entityID) { + var entity = context.graph().hasEntity(entityID); + if (!entity) + return false; + if (entity.tags.wikidata) + return true; + var preset = _mainPresetIndex.match(entity, context.graph()); + var isSuggestion = preset && preset.suggestion; + var which = field.id; + return isSuggestion && !!entity.tags[which] && !!entity.tags[which + ":wikidata"]; }); - labels = labels.merge(enter); - radios = labels.selectAll("input").on("change", changeRadio); + field.locked(isLocked); } - function structureExtras(selection2, tags) { - var selected = selectedKey() || tags.layer !== void 0; - var type2 = _mainPresetIndex.field(selected); - var layer = _mainPresetIndex.field("layer"); - var showLayer = selected === "bridge" || selected === "tunnel" || tags.layer !== void 0; - var extrasWrap = selection2.selectAll(".structure-extras-wrap").data(selected ? [0] : []); - extrasWrap.exit().remove(); - extrasWrap = extrasWrap.enter().append("div").attr("class", "structure-extras-wrap").merge(extrasWrap); - var list = extrasWrap.selectAll("ul").data([0]); - list = list.enter().append("ul").attr("class", "rows").merge(list); - if (type2) { - if (!typeField || typeField.id !== selected) { - typeField = uiField(context, type2, _entityIDs, { wrap: false }).on("change", changeType); - } - typeField.tags(tags); - } else { - typeField = null; + function i3(selection2) { + calcLocked(); + var isLocked = field.locked(); + wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + input = wrap2.selectAll("input").data([0]); + input = input.enter().append("input").attr("type", field.type === "identifier" ? "text" : field.type).attr("id", field.domId).classed(field.type, true).call(utilNoAuto).merge(input); + input.classed("disabled", !!isLocked).attr("readonly", isLocked || null).on("input", change(true)).on("blur", change()).on("change", change()); + wrap2.call(_lengthIndicator); + if (field.type === "tel") { + updatePhonePlaceholder(); + } else if (field.type === "number") { + var rtl = _mainLocalizer.textDirection() === "rtl"; + input.attr("type", "text"); + var inc = field.increment; + var buttons = wrap2.selectAll(".increment, .decrement").data(rtl ? [inc, -inc] : [-inc, inc]); + buttons.enter().append("button").attr("class", function(d2) { + var which = d2 > 0 ? "increment" : "decrement"; + return "form-field-button " + which; + }).attr("title", function(d2) { + var which = d2 > 0 ? "increment" : "decrement"; + return _t("inspector.".concat(which)); + }).merge(buttons).on("click", function(d3_event, d2) { + d3_event.preventDefault(); + var isMixed = Array.isArray(_tags[field.key]); + if (isMixed) + return; + var raw_vals = input.node().value || "0"; + var vals = raw_vals.split(";"); + vals = vals.map(function(v2) { + v2 = v2.trim(); + const isRawNumber = likelyRawNumberFormat.test(v2); + var num = isRawNumber ? parseFloat(v2) : parseLocaleFloat(v2); + if (isDirectionField) { + const compassDir = cardinal[v2.toLowerCase()]; + if (compassDir !== void 0) { + num = compassDir; + } + } + if (!isFinite(num)) + return v2; + num = parseFloat(num); + if (!isFinite(num)) + return v2; + num += d2; + if (isDirectionField) { + num = (num % 360 + 360) % 360; + } + return formatFloat(clamped(num), isRawNumber ? v2.includes(".") ? v2.split(".")[1].length : 0 : countDecimalPlaces(v2)); + }); + input.node().value = vals.join(";"); + change()(); + }); + } else if (field.type === "identifier" && field.urlFormat && field.pattern) { + input.attr("type", "text"); + outlinkButton = wrap2.selectAll(".foreign-id-permalink").data([0]); + outlinkButton = outlinkButton.enter().append("button").call(svgIcon("#iD-icon-out-link")).attr("class", "form-field-button foreign-id-permalink").attr("title", function() { + var domainResults = /^https?:\/\/(.{1,}?)\//.exec(field.urlFormat); + if (domainResults.length >= 2 && domainResults[1]) { + var domain = domainResults[1]; + return _t("icons.view_on", { domain }); + } + return ""; + }).merge(outlinkButton); + outlinkButton.on("click", function(d3_event) { + d3_event.preventDefault(); + var value = validIdentifierValueForLink(); + if (value) { + var url = field.urlFormat.replace(/{value}/, encodeURIComponent(value)); + window.open(url, "_blank"); + } + }).classed("disabled", () => !validIdentifierValueForLink()).merge(outlinkButton); + } else if (field.type === "url") { + input.attr("type", "text"); + outlinkButton = wrap2.selectAll(".foreign-id-permalink").data([0]); + outlinkButton.enter().append("button").call(svgIcon("#iD-icon-out-link")).attr("class", "form-field-button foreign-id-permalink").attr("title", () => _t("icons.visit_website")).on("click", function(d3_event) { + d3_event.preventDefault(); + const value = validIdentifierValueForLink(); + if (value) + window.open(value, "_blank"); + }).merge(outlinkButton); + } else if (field.type === "colour") { + input.attr("type", "text"); + updateColourPreview(); + } else if (field.type === "date") { + input.attr("type", "text"); + updateDateField(); } - var typeItem = list.selectAll(".structure-type-item").data(typeField ? [typeField] : [], function(d2) { - return d2.id; - }); - typeItem.exit().remove(); - var typeEnter = typeItem.enter().insert("li", ":first-child").attr("class", "labeled-input structure-type-item"); - typeEnter.append("span").attr("class", "label structure-label-type").attr("for", "preset-input-" + selected).call(_t.append("inspector.radio.structure.type")); - typeEnter.append("div").attr("class", "structure-input-type-wrap"); - typeItem = typeItem.merge(typeEnter); - if (typeField) { - typeItem.selectAll(".structure-input-type-wrap").call(typeField.render); + } + function updateColourPreview() { + wrap2.selectAll(".colour-preview").remove(); + const colour = utilGetSetValue(input); + if (!isColourValid(colour) && colour !== "") { + wrap2.selectAll("input.colour-selector").remove(); + wrap2.selectAll(".form-field-button").remove(); + return; } - if (layer && showLayer) { - if (!layerField) { - layerField = uiField(context, layer, _entityIDs, { wrap: false }).on("change", changeLayer); - } - layerField.tags(tags); - field.keys = utilArrayUnion(field.keys, ["layer"]); - } else { - layerField = null; - field.keys = field.keys.filter(function(k2) { - return k2 !== "layer"; + var colourSelector = wrap2.selectAll(".colour-selector").data([0]); + colourSelector.enter().append("input").attr("type", "color").attr("class", "colour-selector").on("input", debounce_default(function(d3_event) { + d3_event.preventDefault(); + var colour2 = this.value; + if (!isColourValid(colour2)) + return; + utilGetSetValue(input, this.value); + change()(); + updateColourPreview(); + }, 100)); + wrap2.selectAll("input.colour-selector").attr("value", colour); + var chooserButton = wrap2.selectAll(".colour-preview").data([colour]); + chooserButton = chooserButton.enter().append("div").attr("class", "form-field-button colour-preview").append("div").style("background-color", (d2) => d2).attr("class", "colour-box"); + if (colour === "") { + chooserButton = chooserButton.call(svgIcon("#iD-icon-edit")); + } + chooserButton.on("click", () => wrap2.select(".colour-selector").node().showPicker()); + } + function updateDateField() { + function isDateValid(date2) { + return date2.match(/^[0-9]{4}(-[0-9]{2}(-[0-9]{2})?)?$/); + } + const date = utilGetSetValue(input); + const now3 = /* @__PURE__ */ new Date(); + const today = new Date(now3.getTime() - now3.getTimezoneOffset() * 6e4).toISOString().split("T")[0]; + if ((field.key === "check_date" || field.key === "survey:date") && date !== today) { + wrap2.selectAll(".date-set-today").data([0]).enter().append("button").attr("class", "form-field-button date-set-today").call(svgIcon("#fas-rotate")).call(uiTooltip().title(() => _t.append("inspector.set_today"))).on("click", () => { + utilGetSetValue(input, today); + change()(); + updateDateField(); }); + } else { + wrap2.selectAll(".date-set-today").remove(); } - var layerItem = list.selectAll(".structure-layer-item").data(layerField ? [layerField] : []); - layerItem.exit().remove(); - var layerEnter = layerItem.enter().append("li").attr("class", "labeled-input structure-layer-item"); - layerEnter.append("span").attr("class", "label structure-label-layer").attr("for", "preset-input-layer").call(_t.append("inspector.radio.structure.layer")); - layerEnter.append("div").attr("class", "structure-input-layer-wrap"); - layerItem = layerItem.merge(layerEnter); - if (layerField) { - layerItem.selectAll(".structure-input-layer-wrap").call(layerField.render); + if (!isDateValid(date) && date !== "") { + wrap2.selectAll("input.date-selector").remove(); + wrap2.selectAll(".date-calendar").remove(); + return; + } + if (utilDetect().browser !== "Safari") { + var dateSelector = wrap2.selectAll(".date-selector").data([0]); + dateSelector.enter().append("input").attr("type", "date").attr("class", "date-selector").on("input", debounce_default(function(d3_event) { + d3_event.preventDefault(); + var date2 = this.value; + if (!isDateValid(date2)) + return; + utilGetSetValue(input, this.value); + change()(); + updateDateField(); + }, 100)); + wrap2.selectAll("input.date-selector").attr("value", date); + var calendarButton = wrap2.selectAll(".date-calendar").data([date]); + calendarButton = calendarButton.enter().append("button").attr("class", "form-field-button date-calendar").call(svgIcon("#fas-calendar-days")); + calendarButton.on("click", () => wrap2.select(".date-selector").node().showPicker()); } } - function changeType(t2, onInput) { - var key = selectedKey(); - if (!key) + function updatePhonePlaceholder() { + if (input.empty() || !Object.keys(_phoneFormats).length) return; - var val = t2[key]; - if (val !== "no") { - _oldType[key] = val; - } - if (field.type === "structureRadio") { - if (val === "no" || key !== "bridge" && key !== "tunnel" || key === "tunnel" && val === "building_passage") { - t2.layer = void 0; - } - if (t2.layer === void 0) { - if (key === "bridge" && val !== "no") { - t2.layer = "1"; - } - if (key === "tunnel" && val !== "no" && val !== "building_passage") { - t2.layer = "-1"; - } + var extent = combinedEntityExtent(); + var countryCode = extent && iso1A2Code(extent.center()); + var format2 = countryCode && _phoneFormats[countryCode.toLowerCase()]; + if (format2) + input.attr("placeholder", format2); + } + function validIdentifierValueForLink() { + var _a2; + const value = utilGetSetValue(input).trim(); + if (field.type === "url" && value) { + try { + return new URL(value).href; + } catch (e3) { + return null; } } - dispatch14.call("change", this, t2, onInput); + if (field.type === "identifier" && field.pattern) { + return value && ((_a2 = value.match(new RegExp(field.pattern))) == null ? void 0 : _a2[0]); + } + return null; } - function changeLayer(t2, onInput) { - if (t2.layer === "0") { - t2.layer = void 0; + function clamped(num) { + if (field.minValue !== void 0) { + num = Math.max(num, field.minValue); } - dispatch14.call("change", this, t2, onInput); + if (field.maxValue !== void 0) { + num = Math.min(num, field.maxValue); + } + return num; } - function changeRadio() { - var t2 = {}; - var activeKey; - if (field.key) { - t2[field.key] = void 0; + function getVals(tags) { + if (field.keys) { + const multiSelection = context.selectedIDs(); + tags = multiSelection.length > 1 ? context.selectedIDs().map((id2) => context.graph().entity(id2)).map((entity) => entity.tags) : [tags]; + return tags.map((tags2) => new Set(field.keys.reduce((acc, key) => acc.concat(tags2[key]), []).filter(Boolean))).map((vals) => vals.size === 0 ? /* @__PURE__ */ new Set([void 0]) : vals).reduce((a2, b2) => /* @__PURE__ */ new Set([...a2, ...b2])); + } else { + return new Set([].concat(tags[field.key])); } - radios.each(function(d2) { - var active = select_default2(this).property("checked"); - if (active) - activeKey = d2; - if (field.key) { - if (active) - t2[field.key] = d2; - } else { - var val = _oldType[activeKey] || "yes"; - t2[d2] = active ? val : void 0; + } + function change(onInput) { + return function() { + var t2 = {}; + var val = utilGetSetValue(input); + if (!onInput) + val = context.cleanTagValue(val); + if (!val && getVals(_tags).size > 1) + return; + var displayVal = val; + if (field.type === "number" && val) { + var numbers2 = val.split(";"); + numbers2 = numbers2.map(function(v2) { + if (likelyRawNumberFormat.test(v2)) { + return v2; + } + var num = parseLocaleFloat(v2); + const fractionDigits = countDecimalPlaces(v2); + return isFinite(num) ? clamped(num).toFixed(fractionDigits) : v2; + }); + val = numbers2.join(";"); } - }); - if (field.type === "structureRadio") { - if (activeKey === "bridge") { - t2.layer = "1"; - } else if (activeKey === "tunnel" && t2.tunnel !== "building_passage") { - t2.layer = "-1"; + if (!onInput) + utilGetSetValue(input, displayVal); + t2[field.key] = val || void 0; + if (field.keys) { + dispatch14.call("change", this, (tags) => { + if (field.keys.some((key) => tags[key])) { + field.keys.filter((key) => tags[key]).forEach((key) => { + tags[key] = val || void 0; + }); + } else { + tags[field.key] = val || void 0; + } + return tags; + }, onInput); } else { - t2.layer = void 0; + dispatch14.call("change", this, t2, onInput); } - } - dispatch14.call("change", this, t2); + }; } - radio.tags = function(tags) { - function isOptionChecked(d2) { - if (field.key) { - return tags[field.key] === d2; - } - return !!(typeof tags[d2] === "string" && tags[d2].toLowerCase() !== "no"); + i3.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + _entityIDs = val; + return i3; + }; + i3.tags = function(tags) { + var _a2; + _tags = tags; + const vals = getVals(tags); + const isMixed = vals.size > 1; + var val = vals.size === 1 ? (_a2 = [...vals][0]) != null ? _a2 : "" : ""; + var shouldUpdate; + if (field.type === "number" && val) { + var numbers2 = val.split(";"); + var oriNumbers = utilGetSetValue(input).split(";"); + if (numbers2.length !== oriNumbers.length) + shouldUpdate = true; + numbers2 = numbers2.map(function(v2) { + v2 = v2.trim(); + var num = Number(v2); + if (!isFinite(num) || v2 === "") + return v2; + const fractionDigits = v2.includes(".") ? v2.split(".")[1].length : 0; + return formatFloat(num, fractionDigits); + }); + val = numbers2.join(";"); + shouldUpdate = (inputValue, setValue) => { + const inputNums = inputValue.split(";").map( + (setVal) => likelyRawNumberFormat.test(setVal) ? parseFloat(setVal) : parseLocaleFloat(setVal) + ); + const setNums = setValue.split(";").map(parseLocaleFloat); + return !isEqual_default(inputNums, setNums); + }; } - function isMixed(d2) { - if (field.key) { - return Array.isArray(tags[field.key]) && tags[field.key].includes(d2); + utilGetSetValue(input, val, shouldUpdate).attr("title", isMixed ? [...vals].join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder() || _t("inspector.unknown")).classed("mixed", isMixed); + if (field.type === "number") { + const buttons = wrap2.selectAll(".increment, .decrement"); + if (isMixed) { + buttons.attr("disabled", "disabled").classed("disabled", true); + } else { + var raw_vals = tags[field.key] || "0"; + const canIncDec = raw_vals.split(";").some((val2) => isFinite(Number(val2)) || isDirectionField && cardinal[val2.trim().toLowerCase()]); + buttons.attr("disabled", canIncDec ? null : "disabled").classed("disabled", !canIncDec); } - return Array.isArray(tags[d2]); } - radios.property("checked", function(d2) { - return isOptionChecked(d2) && (field.key || field.options.filter(isOptionChecked).length === 1); - }); - labels.classed("active", function(d2) { - if (field.key) { - return Array.isArray(tags[field.key]) && tags[field.key].includes(d2) || tags[field.key] === d2; - } - return Array.isArray(tags[d2]) && tags[d2].some((v2) => typeof v2 === "string" && v2.toLowerCase() !== "no") || !!(typeof tags[d2] === "string" && tags[d2].toLowerCase() !== "no"); - }).classed("mixed", isMixed).attr("title", function(d2) { - return isMixed(d2) ? _t("inspector.unshared_value_tooltip") : null; - }); - var selection2 = radios.filter(function() { - return this.checked; - }); - if (selection2.empty()) { - placeholder.text(""); - placeholder.call(_t.append("inspector.none")); - } else { - placeholder.text(selection2.attr("value")); - _oldType[selection2.datum()] = tags[selection2.datum()]; + if (field.type === "tel") + updatePhonePlaceholder(); + if (field.type === "colour") + updateColourPreview(); + if (field.type === "date") + updateDateField(); + if (outlinkButton && !outlinkButton.empty()) { + var disabled = !validIdentifierValueForLink(); + outlinkButton.classed("disabled", disabled); } - if (field.type === "structureRadio") { - if (!!tags.waterway && !_oldType.tunnel) { - _oldType.tunnel = "culvert"; - } - wrap2.call(structureExtras, tags); + if (!isMixed) { + _lengthIndicator.update(tags[field.key]); } }; - radio.focus = function() { - radios.node().focus(); - }; - radio.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - _oldType = {}; - return radio; - }; - radio.isAllowed = function() { - return _entityIDs.length === 1; + i3.focus = function() { + var node = input.node(); + if (node) + node.focus(); }; - return utilRebind(radio, dispatch14, "on"); + function combinedEntityExtent() { + return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + } + return utilRebind(i3, dispatch14, "on"); } - // modules/ui/fields/restrictions.js - function uiFieldRestrictions(field, context) { + // modules/ui/fields/access.js + function uiFieldAccess(field, context) { var dispatch14 = dispatch_default("change"); - var breathe = behaviorBreathe(context); - corePreferences("turn-restriction-via-way", null); - var storedViaWay = corePreferences("turn-restriction-via-way0"); - var storedDistance = corePreferences("turn-restriction-distance"); - var _maxViaWay = storedViaWay !== null ? +storedViaWay : 0; - var _maxDistance = storedDistance ? +storedDistance : 30; - var _initialized3 = false; - var _parent = select_default2(null); - var _container = select_default2(null); - var _oldTurns; - var _graph; - var _vertexID; - var _intersection; - var _fromWayID; - var _lastXPos; - function restrictions(selection2) { - _parent = selection2; - if (_vertexID && (context.graph() !== _graph || !_intersection)) { - _graph = context.graph(); - _intersection = osmIntersection(_graph, _vertexID, _maxDistance); - } - var isOK = _intersection && _intersection.vertices.length && // has vertices - _intersection.vertices.filter(function(vertex) { - return vertex.id === _vertexID; - }).length && _intersection.ways.length > 2 && // has more than 2 ways - _intersection.ways.filter(function(way) { - return way.__to; - }).length > 1; - select_default2(selection2.node().parentNode).classed("hide", !isOK); - if (!isOK || !context.container().select(".inspector-wrap.inspector-hidden").empty() || !selection2.node().parentNode || !selection2.node().parentNode.parentNode) { - selection2.call(restrictions.off); - return; - } + var items = select_default2(null); + var _tags; + function access(selection2) { var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - var container = wrap2.selectAll(".restriction-container").data([0]); - var containerEnter = container.enter().append("div").attr("class", "restriction-container"); - containerEnter.append("div").attr("class", "restriction-help"); - _container = containerEnter.merge(container).call(renderViewer); - var controls = wrap2.selectAll(".restriction-controls").data([0]); - controls.enter().append("div").attr("class", "restriction-controls-container").append("div").attr("class", "restriction-controls").merge(controls).call(renderControls); - } - function renderControls(selection2) { - var distControl = selection2.selectAll(".restriction-distance").data([0]); - distControl.exit().remove(); - var distControlEnter = distControl.enter().append("div").attr("class", "restriction-control restriction-distance"); - distControlEnter.append("span").attr("class", "restriction-control-label restriction-distance-label").call(_t.append("restriction.controls.distance", { suffix: ":" })); - distControlEnter.append("input").attr("class", "restriction-distance-input").attr("type", "range").attr("min", "20").attr("max", "50").attr("step", "5"); - distControlEnter.append("span").attr("class", "restriction-distance-text"); - selection2.selectAll(".restriction-distance-input").property("value", _maxDistance).on("input", function() { - var val = select_default2(this).property("value"); - _maxDistance = +val; - _intersection = null; - _container.selectAll(".layer-osm .layer-turns *").remove(); - corePreferences("turn-restriction-distance", _maxDistance); - _parent.call(restrictions); + var list2 = wrap2.selectAll("ul").data([0]); + list2 = list2.enter().append("ul").attr("class", "rows").merge(list2); + items = list2.selectAll("li").data(field.keys); + var enter = items.enter().append("li").attr("class", function(d2) { + return "labeled-input preset-access-" + d2; }); - selection2.selectAll(".restriction-distance-text").call(displayMaxDistance(_maxDistance)); - var viaControl = selection2.selectAll(".restriction-via-way").data([0]); - viaControl.exit().remove(); - var viaControlEnter = viaControl.enter().append("div").attr("class", "restriction-control restriction-via-way"); - viaControlEnter.append("span").attr("class", "restriction-control-label restriction-via-way-label").call(_t.append("restriction.controls.via", { suffix: ":" })); - viaControlEnter.append("input").attr("class", "restriction-via-way-input").attr("type", "range").attr("min", "0").attr("max", "2").attr("step", "1"); - viaControlEnter.append("span").attr("class", "restriction-via-way-text"); - selection2.selectAll(".restriction-via-way-input").property("value", _maxViaWay).on("input", function() { - var val = select_default2(this).property("value"); - _maxViaWay = +val; - _container.selectAll(".layer-osm .layer-turns *").remove(); - corePreferences("turn-restriction-via-way0", _maxViaWay); - _parent.call(restrictions); + enter.append("div").attr("class", "label preset-label-access").attr("for", function(d2) { + return "preset-input-access-" + d2; + }).html(function(d2) { + return field.t.html("types." + d2); }); - selection2.selectAll(".restriction-via-way-text").call(displayMaxVia(_maxViaWay)); + enter.append("div").attr("class", "preset-input-access-wrap").append("input").attr("type", "text").attr("class", function(d2) { + return "preset-input-access preset-input-access-" + d2; + }).call(utilNoAuto).each(function(d2) { + select_default2(this).call( + uiCombobox(context, "access-" + d2).data(access.options(d2)) + ); + }); + items = items.merge(enter); + wrap2.selectAll(".preset-input-access").on("change", change).on("blur", change); } - function renderViewer(selection2) { - if (!_intersection) + function change(d3_event, d2) { + var tag2 = {}; + var value = context.cleanTagValue(utilGetSetValue(select_default2(this))); + if (!value && typeof _tags[d2] !== "string") return; - var vgraph = _intersection.graph; - var filter2 = utilFunctor(true); - var projection2 = geoRawMercator(); - var sdims = utilGetDimensions(context.container().select(".sidebar")); - var d2 = [sdims[0] - 50, 370]; - var c2 = geoVecScale(d2, 0.5); - var z2 = 22; - projection2.scale(geoZoomToScale(z2)); - var extent = geoExtent(); - for (var i3 = 0; i3 < _intersection.vertices.length; i3++) { - extent._extend(_intersection.vertices[i3].extent()); - } - var padTop = 35; - if (_intersection.vertices.length > 1) { - var hPadding = Math.min(160, Math.max(110, d2[0] * 0.4)); - var vPadding = 160; - var tl = projection2([extent[0][0], extent[1][1]]); - var br = projection2([extent[1][0], extent[0][1]]); - var hFactor = (br[0] - tl[0]) / (d2[0] - hPadding); - var vFactor = (br[1] - tl[1]) / (d2[1] - vPadding - padTop); - var hZoomDiff = Math.log(Math.abs(hFactor)) / Math.LN2; - var vZoomDiff = Math.log(Math.abs(vFactor)) / Math.LN2; - z2 = z2 - Math.max(hZoomDiff, vZoomDiff); - projection2.scale(geoZoomToScale(z2)); - } - var extentCenter = projection2(extent.center()); - extentCenter[1] = extentCenter[1] - padTop / 2; - projection2.translate(geoVecSubtract(c2, extentCenter)).clipExtent([[0, 0], d2]); - var drawLayers = svgLayers(projection2, context).only(["osm", "touch"]).dimensions(d2); - var drawVertices = svgVertices(projection2, context); - var drawLines = svgLines(projection2, context); - var drawTurns = svgTurns(projection2, context); - var firstTime = selection2.selectAll(".surface").empty(); - selection2.call(drawLayers); - var surface = selection2.selectAll(".surface").classed("tr", true); - if (firstTime) { - _initialized3 = true; - surface.call(breathe); - } - if (_fromWayID && !vgraph.hasEntity(_fromWayID)) { - _fromWayID = null; - _oldTurns = null; - } - surface.call(utilSetDimensions, d2).call(drawVertices, vgraph, _intersection.vertices, filter2, extent, z2).call(drawLines, vgraph, _intersection.ways, filter2).call(drawTurns, vgraph, _intersection.turns(_fromWayID, _maxViaWay)); - surface.on("click.restrictions", click).on("mouseover.restrictions", mouseover); - surface.selectAll(".selected").classed("selected", false); - surface.selectAll(".related").classed("related", false); - var way; - if (_fromWayID) { - way = vgraph.entity(_fromWayID); - surface.selectAll("." + _fromWayID).classed("selected", true).classed("related", true); - } - document.addEventListener("resizeWindow", function() { - utilSetDimensions(_container, null); - redraw(1); - }, false); - updateHints(null); - function click(d3_event) { - surface.call(breathe.off).call(breathe); - var datum2 = d3_event.target.__data__; - var entity = datum2 && datum2.properties && datum2.properties.entity; - if (entity) { - datum2 = entity; - } - if (datum2 instanceof osmWay && (datum2.__from || datum2.__via)) { - _fromWayID = datum2.id; - _oldTurns = null; - redraw(); - } else if (datum2 instanceof osmTurn) { - var actions, extraActions, turns, i4; - var restrictionType = osmInferRestriction(vgraph, datum2, projection2); - if (datum2.restrictionID && !datum2.direct) { - return; - } else if (datum2.restrictionID && !datum2.only) { - var seen = {}; - var datumOnly = JSON.parse(JSON.stringify(datum2)); - datumOnly.only = true; - restrictionType = restrictionType.replace(/^no/, "only"); - turns = _intersection.turns(_fromWayID, 2); - extraActions = []; - _oldTurns = []; - for (i4 = 0; i4 < turns.length; i4++) { - var turn = turns[i4]; - if (seen[turn.restrictionID]) - continue; - if (turn.direct && turn.path[1] === datum2.path[1]) { - seen[turns[i4].restrictionID] = true; - turn.restrictionType = osmInferRestriction(vgraph, turn, projection2); - _oldTurns.push(turn); - extraActions.push(actionUnrestrictTurn(turn)); - } - } - actions = _intersection.actions.concat(extraActions, [ - actionRestrictTurn(datumOnly, restrictionType), - _t("operations.restriction.annotation.create") - ]); - } else if (datum2.restrictionID) { - turns = _oldTurns || []; - extraActions = []; - for (i4 = 0; i4 < turns.length; i4++) { - if (turns[i4].key !== datum2.key) { - extraActions.push(actionRestrictTurn(turns[i4], turns[i4].restrictionType)); - } - } - _oldTurns = null; - actions = _intersection.actions.concat(extraActions, [ - actionUnrestrictTurn(datum2), - _t("operations.restriction.annotation.delete") - ]); - } else { - actions = _intersection.actions.concat([ - actionRestrictTurn(datum2, restrictionType), - _t("operations.restriction.annotation.create") - ]); - } - context.perform.apply(context, actions); - var s2 = surface.selectAll("." + datum2.key); - datum2 = s2.empty() ? null : s2.datum(); - updateHints(datum2); - } else { - _fromWayID = null; - _oldTurns = null; - redraw(); - } + tag2[d2] = value || void 0; + dispatch14.call("change", this, tag2); + } + access.options = function(type2) { + var options2 = [ + "yes", + "no", + "designated", + "permissive", + "destination", + "customers", + "private", + "permit", + "unknown" + ]; + if (type2 === "access") { + options2 = options2.filter((v2) => v2 !== "yes" && v2 !== "designated"); } - function mouseover(d3_event) { - var datum2 = d3_event.target.__data__; - updateHints(datum2); + if (type2 === "bicycle") { + options2.splice(options2.length - 4, 0, "dismount"); } - _lastXPos = _lastXPos || sdims[0]; - function redraw(minChange) { - var xPos = -1; - if (minChange) { - xPos = utilGetDimensions(context.container().select(".sidebar"))[0]; - } - if (!minChange || minChange && Math.abs(xPos - _lastXPos) >= minChange) { - if (context.hasEntity(_vertexID)) { - _lastXPos = xPos; - _container.call(renderViewer); - } + var stringsField = field.resolveReference("stringsCrossReference"); + return options2.map(function(option) { + return { + title: stringsField.t("options." + option + ".description"), + value: option + }; + }); + }; + const placeholdersByTag = { + highway: { + footway: { + foot: "designated", + motor_vehicle: "no" + }, + steps: { + foot: "yes", + motor_vehicle: "no", + bicycle: "no", + horse: "no" + }, + pedestrian: { + foot: "yes", + motor_vehicle: "no" + }, + cycleway: { + motor_vehicle: "no", + bicycle: "designated" + }, + bridleway: { + motor_vehicle: "no", + horse: "designated" + }, + path: { + foot: "yes", + motor_vehicle: "no", + bicycle: "yes", + horse: "yes" + }, + motorway: { + foot: "no", + motor_vehicle: "yes", + bicycle: "no", + horse: "no" + }, + trunk: { + motor_vehicle: "yes" + }, + primary: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + secondary: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + tertiary: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + residential: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + unclassified: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + service: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + motorway_link: { + foot: "no", + motor_vehicle: "yes", + bicycle: "no", + horse: "no" + }, + trunk_link: { + motor_vehicle: "yes" + }, + primary_link: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + secondary_link: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + tertiary_link: { + foot: "yes", + motor_vehicle: "yes", + bicycle: "yes", + horse: "yes" + }, + construction: { + access: "no" + }, + busway: { + access: "no", + bus: "designated", + emergency: "yes" } - } - function highlightPathsFrom(wayID) { - surface.selectAll(".related").classed("related", false).classed("allow", false).classed("restrict", false).classed("only", false); - surface.selectAll("." + wayID).classed("related", true); - if (wayID) { - var turns = _intersection.turns(wayID, _maxViaWay); - for (var i4 = 0; i4 < turns.length; i4++) { - var turn = turns[i4]; - var ids = [turn.to.way]; - var klass = turn.no ? "restrict" : turn.only ? "only" : "allow"; - if (turn.only || turns.length === 1) { - if (turn.via.ways) { - ids = ids.concat(turn.via.ways); - } - } else if (turn.to.way === wayID) { - continue; - } - surface.selectAll(utilEntitySelector(ids)).classed("related", true).classed("allow", klass === "allow").classed("restrict", klass === "restrict").classed("only", klass === "only"); - } + }, + barrier: { + bollard: { + access: "no", + bicycle: "yes", + foot: "yes" + }, + bus_trap: { + motor_vehicle: "no", + psv: "yes", + foot: "yes", + bicycle: "yes" + }, + city_wall: { + access: "no" + }, + coupure: { + access: "yes" + }, + cycle_barrier: { + motor_vehicle: "no" + }, + ditch: { + access: "no" + }, + entrance: { + access: "yes" + }, + fence: { + access: "no" + }, + hedge: { + access: "no" + }, + jersey_barrier: { + access: "no" + }, + motorcycle_barrier: { + motor_vehicle: "no" + }, + rail_guard: { + access: "no" } } - function updateHints(datum2) { - var help = _container.selectAll(".restriction-help").html(""); - var placeholders = {}; - ["from", "via", "to"].forEach(function(k2) { - placeholders[k2] = { html: '' + _t("restriction.help." + k2) + "" }; - }); - var entity = datum2 && datum2.properties && datum2.properties.entity; - if (entity) { - datum2 = entity; - } - if (_fromWayID) { - way = vgraph.entity(_fromWayID); - surface.selectAll("." + _fromWayID).classed("selected", true).classed("related", true); - } - if (datum2 instanceof osmWay && datum2.__from) { - way = datum2; - highlightPathsFrom(_fromWayID ? null : way.id); - surface.selectAll("." + way.id).classed("related", true); - var clickSelect = !_fromWayID || _fromWayID !== way.id; - help.append("div").html(_t.html("restriction.help." + (clickSelect ? "select_from_name" : "from_name"), { - from: placeholders.from, - fromName: displayName(way.id, vgraph) - })); - } else if (datum2 instanceof osmTurn) { - var restrictionType = osmInferRestriction(vgraph, datum2, projection2); - var turnType = restrictionType.replace(/^(only|no)\_/, ""); - var indirect = datum2.direct === false ? _t.html("restriction.help.indirect") : ""; - var klass, turnText, nextText; - if (datum2.no) { - klass = "restrict"; - turnText = _t.html("restriction.help.turn.no_" + turnType, { indirect: { html: indirect } }); - nextText = _t.html("restriction.help.turn.only_" + turnType, { indirect: "" }); - } else if (datum2.only) { - klass = "only"; - turnText = _t.html("restriction.help.turn.only_" + turnType, { indirect: { html: indirect } }); - nextText = _t.html("restriction.help.turn.allowed_" + turnType, { indirect: "" }); - } else { - klass = "allow"; - turnText = _t.html("restriction.help.turn.allowed_" + turnType, { indirect: { html: indirect } }); - nextText = _t.html("restriction.help.turn.no_" + turnType, { indirect: "" }); - } - help.append("div").attr("class", "qualifier " + klass).html(turnText); - help.append("div").html(_t.html("restriction.help.from_name_to_name", { - from: placeholders.from, - fromName: displayName(datum2.from.way, vgraph), - to: placeholders.to, - toName: displayName(datum2.to.way, vgraph) - })); - if (datum2.via.ways && datum2.via.ways.length) { - var names = []; - for (var i4 = 0; i4 < datum2.via.ways.length; i4++) { - var prev = names[names.length - 1]; - var curr = displayName(datum2.via.ways[i4], vgraph); - if (!prev || curr !== prev) { - names.push(curr); - } - } - help.append("div").html(_t.html("restriction.help.via_names", { - via: placeholders.via, - viaNames: names.join(", ") - })); - } - if (!indirect) { - help.append("div").html(_t.html("restriction.help.toggle", { turn: { html: nextText.trim() } })); + }; + access.tags = function(tags) { + _tags = tags; + utilGetSetValue(items.selectAll(".preset-input-access"), function(d2) { + return typeof tags[d2] === "string" ? tags[d2] : ""; + }).classed("mixed", function(d2) { + return tags[d2] && Array.isArray(tags[d2]); + }).attr("title", function(d2) { + return tags[d2] && Array.isArray(tags[d2]) && tags[d2].filter(Boolean).join("\n"); + }).attr("placeholder", function(d2) { + if (tags[d2] && Array.isArray(tags[d2])) { + return _t("inspector.multiple_values"); + } + if (d2 === "bicycle" || d2 === "motor_vehicle") { + if (tags.vehicle && typeof tags.vehicle === "string") { + return tags.vehicle; } - highlightPathsFrom(null); - var alongIDs = datum2.path.slice(); - surface.selectAll(utilEntitySelector(alongIDs)).classed("related", true).classed("allow", klass === "allow").classed("restrict", klass === "restrict").classed("only", klass === "only"); - } else { - highlightPathsFrom(null); - if (_fromWayID) { - help.append("div").html(_t.html("restriction.help.from_name", { - from: placeholders.from, - fromName: displayName(_fromWayID, vgraph) - })); + } + if (tags.access && typeof tags.access === "string") { + return tags.access; + } + function getPlaceholdersByTag(key, placeholdersByKey) { + if (typeof tags[key] === "string") { + if (placeholdersByKey[tags[key]] && placeholdersByKey[tags[key]][d2]) { + return placeholdersByKey[tags[key]][d2]; + } } else { - help.append("div").html(_t.html("restriction.help.select_from", { - from: placeholders.from - })); + var impliedAccesses = tags[key].filter(Boolean).map(function(val) { + return placeholdersByKey[val] && placeholdersByKey[val][d2]; + }).filter(Boolean); + if (impliedAccesses.length === tags[key].length && new Set(impliedAccesses).size === 1) { + return impliedAccesses[0]; + } } } - } - } - function displayMaxDistance(maxDist) { - return (selection2) => { - var isImperial = !_mainLocalizer.usesMetric(); - var opts; - if (isImperial) { - var distToFeet = { - // imprecise conversion for prettier display - 20: 70, - 25: 85, - 30: 100, - 35: 115, - 40: 130, - 45: 145, - 50: 160 - }[maxDist]; - opts = { distance: _t("units.feet", { quantity: distToFeet }) }; - } else { - opts = { distance: _t("units.meters", { quantity: maxDist }) }; + for (const key in placeholdersByTag) { + if (tags[key]) { + const impliedAccess = getPlaceholdersByTag(key, placeholdersByTag[key]); + if (impliedAccess) { + return impliedAccess; + } + } } - return selection2.html("").call(_t.append("restriction.controls.distance_up_to", opts)); - }; - } - function displayMaxVia(maxVia) { - return (selection2) => { - selection2 = selection2.html(""); - return maxVia === 0 ? selection2.call(_t.append("restriction.controls.via_node_only")) : maxVia === 1 ? selection2.call(_t.append("restriction.controls.via_up_to_one")) : selection2.call(_t.append("restriction.controls.via_up_to_two")); - }; - } - function displayName(entityID, graph) { - var entity = graph.entity(entityID); - var name = utilDisplayName(entity) || ""; - var matched = _mainPresetIndex.match(entity, graph); - var type2 = matched && matched.name() || utilDisplayType(entity.id); - return name || type2; - } - restrictions.entityIDs = function(val) { - _intersection = null; - _fromWayID = null; - _oldTurns = null; - _vertexID = val[0]; - }; - restrictions.tags = function() { - }; - restrictions.focus = function() { - }; - restrictions.off = function(selection2) { - if (!_initialized3) - return; - selection2.selectAll(".surface").call(breathe.off).on("click.restrictions", null).on("mouseover.restrictions", null); - select_default2(window).on("resize.restrictions", null); - }; - return utilRebind(restrictions, dispatch14, "on"); - } - uiFieldRestrictions.supportsMultiselection = false; - - // modules/ui/fields/textarea.js - function uiFieldTextarea(field, context) { - var dispatch14 = dispatch_default("change"); - var input = select_default2(null); - var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()).silent(field.usage === "changeset" && field.key === "comment"); - var _tags; - function textarea(selection2) { - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).style("position", "relative").merge(wrap2); - input = wrap2.selectAll("textarea").data([0]); - input = input.enter().append("textarea").attr("id", field.domId).call(utilNoAuto).on("input", change(true)).on("blur", change()).on("change", change()).merge(input); - wrap2.call(_lengthIndicator); - function change(onInput) { - return function() { - var val = utilGetSetValue(input); - if (!onInput) - val = context.cleanTagValue(val); - if (!val && Array.isArray(_tags[field.key])) - return; - var t2 = {}; - t2[field.key] = val || void 0; - dispatch14.call("change", this, t2, onInput); - }; - } - } - textarea.tags = function(tags) { - _tags = tags; - var isMixed = Array.isArray(tags[field.key]); - utilGetSetValue(input, !isMixed && tags[field.key] ? tags[field.key] : "").attr("title", isMixed ? tags[field.key].filter(Boolean).join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder() || _t("inspector.unknown")).classed("mixed", isMixed); - if (!isMixed) { - _lengthIndicator.update(tags[field.key]); - } + if (d2 === "access" && !tags.barrier) { + return "yes"; + } + return field.placeholder(); + }); }; - textarea.focus = function() { - input.node().focus(); + access.focus = function() { + items.selectAll(".preset-input-access").node().focus(); }; - return utilRebind(textarea, dispatch14, "on"); + return utilRebind(access, dispatch14, "on"); } - // modules/ui/fields/wikidata.js - function uiFieldWikidata(field, context) { - var wikidata = services.wikidata; + // modules/ui/fields/address.js + function uiFieldAddress(field, context) { var dispatch14 = dispatch_default("change"); var _selection = select_default2(null); - var _searchInput = select_default2(null); - var _qid = null; - var _wikidataEntity = null; - var _wikiURL = ""; + var _wrap = select_default2(null); + var addrField = _mainPresetIndex.field("address"); var _entityIDs = []; - var _wikipediaKey = field.keys && field.keys.find(function(key) { - return key.includes("wikipedia"); + var _tags; + var _countryCode; + var _addressFormats = [{ + format: [ + ["housenumber", "street"], + ["city", "postcode"] + ] + }]; + _mainFileFetcher.get("address_formats").then(function(d2) { + _addressFormats = d2; + if (!_selection.empty()) { + _selection.call(address); + } + }).catch(function() { }); - var _hintKey = field.key === "wikidata" ? "name" : field.key.split(":")[0]; - var combobox = uiCombobox(context, "combo-" + field.safeid).caseSensitive(true).minItems(1); - function wiki(selection2) { - _selection = selection2; - var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); - var list = wrap2.selectAll("ul").data([0]); - list = list.enter().append("ul").attr("class", "rows").merge(list); - var searchRow = list.selectAll("li.wikidata-search").data([0]); - var searchRowEnter = searchRow.enter().append("li").attr("class", "wikidata-search"); - searchRowEnter.append("input").attr("type", "text").attr("id", field.domId).style("flex", "1").call(utilNoAuto).on("focus", function() { - var node = select_default2(this).node(); - node.setSelectionRange(0, node.value.length); - }).on("blur", function() { - setLabelForEntity(); - }).call(combobox.fetcher(fetchWikidataItems)); - combobox.on("accept", function(d2) { - if (d2) { - _qid = d2.id; - change(); + function getNear(isAddressable, type2, searchRadius, resultProp) { + var extent = combinedEntityExtent(); + var l2 = extent.center(); + var box = geoExtent(l2).padByMeters(searchRadius); + var features = context.history().intersects(box).filter(isAddressable).map((d2) => { + let dist = geoSphericalDistance(d2.extent(context.graph()).center(), l2); + if (d2.geometry(context.graph()) === "line") { + var loc = context.projection([ + (extent[0][0] + extent[1][0]) / 2, + (extent[0][1] + extent[1][1]) / 2 + ]); + var choice = geoChooseEdge(context.graph().childNodes(d2), loc, context.projection); + dist = geoSphericalDistance(choice.loc, l2); } - }).on("cancel", function() { - setLabelForEntity(); - }); - searchRowEnter.append("button").attr("class", "form-field-button wiki-link").attr("title", _t("icons.view_on", { domain: "wikidata.org" })).call(svgIcon("#iD-icon-out-link")).on("click", function(d3_event) { - d3_event.preventDefault(); - if (_wikiURL) - window.open(_wikiURL, "_blank"); - }); - searchRow = searchRow.merge(searchRowEnter); - _searchInput = searchRow.select("input"); - var wikidataProperties = ["description", "identifier"]; - var items = list.selectAll("li.labeled-input").data(wikidataProperties); - var enter = items.enter().append("li").attr("class", function(d2) { - return "labeled-input preset-wikidata-" + d2; - }); - enter.append("span").attr("class", "label").html(function(d2) { - return _t.html("wikidata." + d2); - }); - enter.append("input").attr("type", "text").call(utilNoAuto).classed("disabled", "true").attr("readonly", "true"); - enter.append("button").attr("class", "form-field-button").attr("title", _t("icons.copy")).call(svgIcon("#iD-operation-copy")).on("click", function(d3_event) { - d3_event.preventDefault(); - select_default2(this.parentNode).select("input").node().select(); - document.execCommand("copy"); + const value = resultProp && d2.tags[resultProp] ? d2.tags[resultProp] : d2.tags.name; + let title = value; + if (type2 === "street") { + title = "".concat(addrField.t("placeholders.street"), ": ").concat(title); + } else if (type2 === "place") { + title = "".concat(addrField.t("placeholders.place"), ": ").concat(title); + } + return { + title, + value, + dist, + type: type2, + klass: "address-".concat(type2) + }; + }).sort(function(a2, b2) { + return a2.dist - b2.dist; }); + return utilArrayUniqBy(features, "value"); } - function fetchWikidataItems(q2, callback) { - if (!q2 && _hintKey) { - for (var i3 in _entityIDs) { - var entity = context.hasEntity(_entityIDs[i3]); - if (entity.tags[_hintKey]) { - q2 = entity.tags[_hintKey]; - break; - } + function getNearStreets() { + function isAddressable(d2) { + return d2.tags.highway && d2.tags.name && d2.type === "way"; + } + return getNear(isAddressable, "street", 200); + } + function getNearPlaces() { + function isAddressable(d2) { + if (d2.tags.name) { + if (d2.tags.place) + return true; + if (d2.tags.boundary === "administrative" && d2.tags.admin_level > 8) + return true; } + return false; } - wikidata.itemsForSearchQuery(q2, function(err, data) { - if (err) { - if (err !== "No query") - console.error(err); - return; + return getNear(isAddressable, "place", 200); + } + function getNearCities() { + function isAddressable(d2) { + if (d2.tags.name) { + if (d2.tags.boundary === "administrative" && d2.tags.admin_level === "8") + return true; + if (d2.tags.border_type === "city") + return true; + if (d2.tags.place === "city" || d2.tags.place === "town" || d2.tags.place === "village") + return true; } - var result = data.map(function(item) { + if (d2.tags["".concat(field.key, ":city")]) + return true; + return false; + } + return getNear(isAddressable, "city", 200, "".concat(field.key, ":city")); + } + function getNearPostcodes() { + return [...new Set([].concat(getNearValues("postcode")).concat(getNear((d2) => d2.tags.postal_code, "postcode", 200, "postal_code")))]; + } + function getNearValues(key) { + const tagKey = "".concat(field.key, ":").concat(key); + function hasTag(d2) { + return _entityIDs.indexOf(d2.id) === -1 && d2.tags[tagKey]; + } + return getNear(hasTag, key, 200, tagKey); + } + function updateForCountryCode() { + if (!_countryCode) + return; + var addressFormat; + for (var i3 = 0; i3 < _addressFormats.length; i3++) { + var format2 = _addressFormats[i3]; + if (!format2.countryCodes) { + addressFormat = format2; + } else if (format2.countryCodes.indexOf(_countryCode) !== -1) { + addressFormat = format2; + break; + } + } + var dropdowns = addressFormat.dropdowns || [ + "city", + "county", + "country", + "district", + "hamlet", + "neighbourhood", + "place", + "postcode", + "province", + "quarter", + "state", + "street", + "street+place", + "subdistrict", + "suburb" + ]; + var widths = addressFormat.widths || { + housenumber: 1 / 5, + unit: 1 / 5, + street: 1 / 2, + place: 1 / 2, + city: 2 / 3, + state: 1 / 4, + postcode: 1 / 3 + }; + function row(r2) { + var total = r2.reduce(function(sum, key) { + return sum + (widths[key] || 0.5); + }, 0); + return r2.map(function(key) { return { - id: item.id, - value: item.display.label.value + " (" + item.id + ")", - display: (selection2) => selection2.append("span").attr("class", "localized-text").attr("lang", item.display.label.language).text(item.display.label.value), - title: item.display.description && item.display.description.value, - terms: item.aliases + id: key, + width: (widths[key] || 0.5) / total }; }); - if (callback) - callback(result); + } + var rows = _wrap.selectAll(".addr-row").data(addressFormat.format, function(d2) { + return d2.toString(); }); - } - function change() { - var syncTags = {}; - syncTags[field.key] = _qid; - dispatch14.call("change", this, syncTags); - var initGraph = context.graph(); - var initEntityIDs = _entityIDs; - wikidata.entityByQID(_qid, function(err, entity) { - if (err) - return; - if (context.graph() !== initGraph) - return; - if (!entity.sitelinks) + rows.exit().remove(); + rows.enter().append("div").attr("class", "addr-row").selectAll("input").data(row).enter().append("input").property("type", "text").call(updatePlaceholder).attr("class", function(d2) { + return "addr-" + d2.id; + }).call(utilNoAuto).each(addDropdown).style("width", function(d2) { + return d2.width * 100 + "%"; + }); + function addDropdown(d2) { + if (dropdowns.indexOf(d2.id) === -1) return; - var langs = wikidata.languagesToQuery(); - ["labels", "descriptions"].forEach(function(key) { - if (!entity[key]) - return; - var valueLangs = Object.keys(entity[key]); - if (valueLangs.length === 0) - return; - var valueLang = valueLangs[0]; - if (langs.indexOf(valueLang) === -1) { - langs.push(valueLang); - } - }); - var newWikipediaValue; - if (_wikipediaKey) { - var foundPreferred; - for (var i3 in langs) { - var lang = langs[i3]; - var siteID = lang.replace("-", "_") + "wiki"; - if (entity.sitelinks[siteID]) { - foundPreferred = true; - newWikipediaValue = lang + ":" + entity.sitelinks[siteID].title; - break; - } - } - if (!foundPreferred) { - var wikiSiteKeys = Object.keys(entity.sitelinks).filter(function(site) { - return site.endsWith("wiki"); - }); - if (wikiSiteKeys.length === 0) { - newWikipediaValue = null; - } else { - var wikiLang = wikiSiteKeys[0].slice(0, -4).replace("_", "-"); - var wikiTitle = entity.sitelinks[wikiSiteKeys[0]].title; - newWikipediaValue = wikiLang + ":" + wikiTitle; + var nearValues; + switch (d2.id) { + case "street": + nearValues = getNearStreets; + break; + case "place": + nearValues = getNearPlaces; + break; + case "street+place": + nearValues = () => [].concat(getNearStreets()).concat(getNearPlaces()); + d2.isAutoStreetPlace = true; + d2.id = _tags["".concat(field.key, ":place")] ? "place" : "street"; + break; + case "city": + nearValues = getNearCities; + break; + case "postcode": + nearValues = getNearPostcodes; + break; + default: + nearValues = getNearValues; + } + select_default2(this).call( + uiCombobox(context, "address-".concat(d2.isAutoStreetPlace ? "street-place" : d2.id)).minItems(1).caseSensitive(true).fetcher(function(typedValue, callback) { + typedValue = typedValue.toLowerCase(); + callback(nearValues(d2.id).filter((v2) => v2.value.toLowerCase().indexOf(typedValue) !== -1)); + }).on("accept", function(selected) { + if (d2.isAutoStreetPlace) { + d2.id = selected ? selected.type : "street"; } - } + }) + ); + } + _wrap.selectAll("input").on("blur", change()).on("change", change()); + _wrap.selectAll("input:not(.combobox-input)").on("input", change(true)); + if (_tags) + updateTags(_tags); + } + function address(selection2) { + _selection = selection2; + _wrap = selection2.selectAll(".form-field-input-wrap").data([0]); + _wrap = _wrap.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(_wrap); + var extent = combinedEntityExtent(); + if (extent) { + var countryCode; + if (context.inIntro()) { + countryCode = _t("intro.graph.countrycode"); + } else { + var center = extent.center(); + countryCode = iso1A2Code(center); } - if (newWikipediaValue) { - newWikipediaValue = context.cleanTagValue(newWikipediaValue); + if (countryCode) { + _countryCode = countryCode.toLowerCase(); + updateForCountryCode(); } - if (typeof newWikipediaValue === "undefined") - return; - var actions = initEntityIDs.map(function(entityID) { - var entity2 = context.hasEntity(entityID); - if (!entity2) - return null; - var currTags = Object.assign({}, entity2.tags); - if (newWikipediaValue === null) { - if (!currTags[_wikipediaKey]) - return null; - delete currTags[_wikipediaKey]; - } else { - currTags[_wikipediaKey] = newWikipediaValue; - } - return actionChangeTags(entityID, currTags); - }).filter(Boolean); - if (!actions.length) - return; - context.overwrite( - function actionUpdateWikipediaTags(graph) { - actions.forEach(function(action) { - graph = action(graph); - }); - return graph; - }, - context.history().undoAnnotation() - ); - }); + } + } + function change(onInput) { + return function() { + setTimeout(() => { + var tags = {}; + _wrap.selectAll("input").each(function(subfield) { + var key = field.key + ":" + subfield.id; + var value = this.value; + if (!onInput) + value = context.cleanTagValue(value); + if (Array.isArray(_tags[key]) && !value) + return; + if (subfield.isAutoStreetPlace) { + if (subfield.id === "street") { + tags["".concat(field.key, ":place")] = void 0; + } else if (subfield.id === "place") { + tags["".concat(field.key, ":street")] = void 0; + } + } + tags[key] = value || void 0; + }); + Object.keys(tags).filter((k2) => tags[k2]).forEach((k2) => _tags[k2] = tags[k2]); + dispatch14.call("change", this, tags, onInput); + }, 0); + }; } - function setLabelForEntity() { - var label = ""; - if (_wikidataEntity) { - label = entityPropertyForDisplay(_wikidataEntity, "labels"); - if (label.length === 0) { - label = _wikidataEntity.id.toString(); + function updatePlaceholder(inputSelection) { + return inputSelection.attr("placeholder", function(subfield) { + if (_tags && Array.isArray(_tags[field.key + ":" + subfield.id])) { + return _t("inspector.multiple_values"); } - } - utilGetSetValue(_searchInput, label); - } - wiki.tags = function(tags) { - var isMixed = Array.isArray(tags[field.key]); - _searchInput.attr("title", isMixed ? tags[field.key].filter(Boolean).join("\n") : null).attr("placeholder", isMixed ? _t("inspector.multiple_values") : "").classed("mixed", isMixed); - _qid = typeof tags[field.key] === "string" && tags[field.key] || ""; - if (!/^Q[0-9]*$/.test(_qid)) { - unrecognized(); - return; - } - _wikiURL = "https://wikidata.org/wiki/" + _qid; - wikidata.entityByQID(_qid, function(err, entity) { - if (err) { - unrecognized(); - return; + if (subfield.isAutoStreetPlace) { + return "".concat(getLocalPlaceholder("street"), " / ").concat(getLocalPlaceholder("place")); } - _wikidataEntity = entity; - setLabelForEntity(); - var description = entityPropertyForDisplay(entity, "descriptions"); - _selection.select("button.wiki-link").classed("disabled", false); - _selection.select(".preset-wikidata-description").style("display", function() { - return description.length > 0 ? "flex" : "none"; - }).select("input").attr("value", description); - _selection.select(".preset-wikidata-identifier").style("display", function() { - return entity.id ? "flex" : "none"; - }).select("input").attr("value", entity.id); + return getLocalPlaceholder(subfield.id); }); - function unrecognized() { - _wikidataEntity = null; - setLabelForEntity(); - _selection.select(".preset-wikidata-description").style("display", "none"); - _selection.select(".preset-wikidata-identifier").style("display", "none"); - _selection.select("button.wiki-link").classed("disabled", true); - if (_qid && _qid !== "") { - _wikiURL = "https://wikidata.org/wiki/Special:Search?search=" + _qid; + } + function getLocalPlaceholder(key) { + if (_countryCode) { + var localkey = key + "!" + _countryCode; + var tkey = addrField.hasTextForStringId("placeholders." + localkey) ? localkey : key; + return addrField.t("placeholders." + tkey); + } + } + function updateTags(tags) { + utilGetSetValue(_wrap.selectAll("input"), (subfield) => { + var val; + if (subfield.isAutoStreetPlace) { + const streetKey = "".concat(field.key, ":street"); + const placeKey = "".concat(field.key, ":place"); + if (tags[streetKey] !== void 0 || tags[placeKey] === void 0) { + val = tags[streetKey]; + subfield.id = "street"; + } else { + val = tags[placeKey]; + subfield.id = "place"; + } } else { - _wikiURL = ""; + val = tags["".concat(field.key, ":").concat(subfield.id)]; } - } - }; - function entityPropertyForDisplay(wikidataEntity, propKey) { - if (!wikidataEntity[propKey]) - return ""; - var propObj = wikidataEntity[propKey]; - var langKeys = Object.keys(propObj); - if (langKeys.length === 0) - return ""; - var langs = wikidata.languagesToQuery(); - for (var i3 in langs) { - var lang = langs[i3]; - var valueObj = propObj[lang]; - if (valueObj && valueObj.value && valueObj.value.length > 0) - return valueObj.value; - } - return propObj[langKeys[0]].value; + return typeof val === "string" ? val : ""; + }).attr("title", function(subfield) { + var val = tags[field.key + ":" + subfield.id]; + return val && Array.isArray(val) ? val.filter(Boolean).join("\n") : void 0; + }).classed("mixed", function(subfield) { + return Array.isArray(tags[field.key + ":" + subfield.id]); + }).call(updatePlaceholder); } - wiki.entityIDs = function(val) { + function combinedEntityExtent() { + return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + } + address.entityIDs = function(val) { if (!arguments.length) return _entityIDs; _entityIDs = val; - return wiki; + return address; }; - wiki.focus = function() { - _searchInput.node().focus(); + address.tags = function(tags) { + _tags = tags; + updateTags(tags); }; - return utilRebind(wiki, dispatch14, "on"); + address.focus = function() { + var node = _wrap.selectAll("input").node(); + if (node) + node.focus(); + }; + return utilRebind(address, dispatch14, "on"); } - // modules/ui/fields/wikipedia.js - function uiFieldWikipedia(field, context) { - const dispatch14 = dispatch_default("change"); - const wikipedia = services.wikipedia; - const wikidata = services.wikidata; - let _langInput = select_default2(null); - let _titleInput = select_default2(null); - let _wikiURL = ""; - let _entityIDs; - let _tags; - let _dataWikipedia = []; - _mainFileFetcher.get("wmf_sitematrix").then((d2) => { - _dataWikipedia = d2; - if (_tags) - updateForTags(_tags); - }).catch(() => { - }); - const langCombo = uiCombobox(context, "wikipedia-lang").fetcher((value, callback) => { - const v2 = value.toLowerCase(); - callback( - _dataWikipedia.filter((d2) => { - return d2[0].toLowerCase().indexOf(v2) >= 0 || d2[1].toLowerCase().indexOf(v2) >= 0 || d2[2].toLowerCase().indexOf(v2) >= 0; - }).map((d2) => ({ value: d2[1] })) - ); - }); - const titleCombo = uiCombobox(context, "wikipedia-title").fetcher((value, callback) => { - if (!value) { - value = ""; - for (let i3 in _entityIDs) { - let entity = context.hasEntity(_entityIDs[i3]); - if (entity.tags.name) { - value = entity.tags.name; - break; - } - } + // modules/ui/fields/directional_combo.js + function uiFieldDirectionalCombo(field, context) { + var dispatch14 = dispatch_default("change"); + var items = select_default2(null); + var wrap2 = select_default2(null); + var _tags; + var _combos = {}; + if (field.type === "cycleway") { + field = { + ...field, + key: field.keys[0], + keys: field.keys.slice(1) + }; + } + function directionalCombo(selection2) { + function stripcolon(s2) { + return s2.replace(":", ""); } - const searchfn = value.length > 7 ? wikipedia.search : wikipedia.suggestions; - searchfn(language()[2], value, (query, data) => { - callback(data.map((d2) => ({ value: d2 }))); + wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + var div = wrap2.selectAll("ul").data([0]); + div = div.enter().append("ul").attr("class", "rows rows-table").merge(div); + items = div.selectAll("li").data(field.keys); + var enter = items.enter().append("li").attr("class", function(d2) { + return "labeled-input preset-directionalcombo-" + stripcolon(d2); }); - }); - function wiki(selection2) { - let wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); - wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-".concat(field.type)).merge(wrap2); - let langContainer = wrap2.selectAll(".wiki-lang-container").data([0]); - langContainer = langContainer.enter().append("div").attr("class", "wiki-lang-container").merge(langContainer); - _langInput = langContainer.selectAll("input.wiki-lang").data([0]); - _langInput = _langInput.enter().append("input").attr("type", "text").attr("class", "wiki-lang").attr("placeholder", _t("translate.localized_translation_language")).call(utilNoAuto).call(langCombo).merge(_langInput); - _langInput.on("blur", changeLang).on("change", changeLang); - let titleContainer = wrap2.selectAll(".wiki-title-container").data([0]); - titleContainer = titleContainer.enter().append("div").attr("class", "wiki-title-container").merge(titleContainer); - _titleInput = titleContainer.selectAll("input.wiki-title").data([0]); - _titleInput = _titleInput.enter().append("input").attr("type", "text").attr("class", "wiki-title").attr("id", field.domId).call(utilNoAuto).call(titleCombo).merge(_titleInput); - _titleInput.on("blur", function() { - change(true); - }).on("change", function() { - change(false); + enter.append("div").attr("class", "label preset-label-directionalcombo").attr("for", function(d2) { + return "preset-input-directionalcombo-" + stripcolon(d2); + }).html(function(d2) { + return field.t.html("types." + d2); }); - let link2 = titleContainer.selectAll(".wiki-link").data([0]); - link2 = link2.enter().append("button").attr("class", "form-field-button wiki-link").attr("title", _t("icons.view_on", { domain: "wikipedia.org" })).call(svgIcon("#iD-icon-out-link")).merge(link2); - link2.on("click", (d3_event) => { - d3_event.preventDefault(); - if (_wikiURL) - window.open(_wikiURL, "_blank"); + enter.append("div").attr("class", "preset-input-directionalcombo-wrap form-field-input-wrap").each(function(key) { + const subField = { + ...field, + type: "combo", + key + }; + const combo = uiFieldCombo(subField, context); + combo.on("change", (t2) => change(key, t2[key])); + _combos[key] = combo; + select_default2(this).call(combo); }); + items = items.merge(enter); + wrap2.selectAll(".preset-input-directionalcombo").on("change", change).on("blur", change); } - function defaultLanguageInfo(skipEnglishFallback) { - const langCode = _mainLocalizer.languageCode().toLowerCase(); - for (let i3 in _dataWikipedia) { - let d2 = _dataWikipedia[i3]; - if (d2[2] === langCode) - return d2; - } - return skipEnglishFallback ? ["", "", ""] : ["English", "English", "en"]; - } - function language(skipEnglishFallback) { - const value = utilGetSetValue(_langInput).toLowerCase(); - for (let i3 in _dataWikipedia) { - let d2 = _dataWikipedia[i3]; - if (d2[0].toLowerCase() === value || d2[1].toLowerCase() === value || d2[2] === value) - return d2; - } - return defaultLanguageInfo(skipEnglishFallback); - } - function changeLang() { - utilGetSetValue(_langInput, language()[1]); - change(true); - } - function change(skipWikidata) { - let value = utilGetSetValue(_titleInput); - const m2 = value.match(/https?:\/\/([-a-z]+)\.wikipedia\.org\/(?:wiki|\1-[-a-z]+)\/([^#]+)(?:#(.+))?/); - const langInfo = m2 && _dataWikipedia.find((d2) => m2[1] === d2[2]); - let syncTags = {}; - if (langInfo) { - const nativeLangName = langInfo[1]; - value = decodeURIComponent(m2[2]).replace(/_/g, " "); - if (m2[3]) { - let anchor; - anchor = decodeURIComponent(m2[3]); - value += "#" + anchor.replace(/_/g, " "); + function change(key, newValue) { + const commonKey = field.key; + const otherKey = key === field.keys[0] ? field.keys[1] : field.keys[0]; + dispatch14.call("change", this, (tags) => { + const otherValue = tags[otherKey] || tags[commonKey]; + if (newValue === otherValue) { + tags[commonKey] = newValue; + delete tags[key]; + delete tags[otherKey]; + } else { + tags[key] = newValue; + delete tags[commonKey]; + tags[otherKey] = otherValue; } - value = value.slice(0, 1).toUpperCase() + value.slice(1); - utilGetSetValue(_langInput, nativeLangName); - utilGetSetValue(_titleInput, value); - } - if (value) { - syncTags.wikipedia = context.cleanTagValue(language()[2] + ":" + value); - } else { - syncTags.wikipedia = void 0; - } - dispatch14.call("change", this, syncTags); - if (skipWikidata || !value || !language()[2]) - return; - const initGraph = context.graph(); - const initEntityIDs = _entityIDs; - wikidata.itemsByTitle(language()[2], value, (err, data) => { - if (err || !data || !Object.keys(data).length) - return; - if (context.graph() !== initGraph) - return; - const qids = Object.keys(data); - const value2 = qids && qids.find((id2) => id2.match(/^Q\d+$/)); - let actions = initEntityIDs.map((entityID) => { - let entity = context.entity(entityID).tags; - let currTags = Object.assign({}, entity); - if (currTags.wikidata !== value2) { - currTags.wikidata = value2; - return actionChangeTags(entityID, currTags); - } - return null; - }).filter(Boolean); - if (!actions.length) - return; - context.overwrite( - function actionUpdateWikidataTags(graph) { - actions.forEach(function(action) { - graph = action(graph); - }); - return graph; - }, - context.history().undoAnnotation() - ); + return tags; }); } - wiki.tags = (tags) => { + directionalCombo.tags = function(tags) { _tags = tags; - updateForTags(tags); + const commonKey = field.key; + for (let key in _combos) { + const uniqueValues = [...new Set([].concat(_tags[commonKey]).concat(_tags[key]).filter(Boolean))]; + _combos[key].tags({ [key]: uniqueValues.length > 1 ? uniqueValues : uniqueValues[0] }); + } }; - function updateForTags(tags) { - const value = typeof tags[field.key] === "string" ? tags[field.key] : ""; - const m2 = value.match(/([^:]+):([^#]+)(?:#(.+))?/); - const tagLang = m2 && m2[1]; - const tagArticleTitle = m2 && m2[2]; - let anchor = m2 && m2[3]; - const tagLangInfo = tagLang && _dataWikipedia.find((d2) => tagLang === d2[2]); - if (tagLangInfo) { - const nativeLangName = tagLangInfo[1]; - utilGetSetValue(_langInput, nativeLangName); - utilGetSetValue(_titleInput, tagArticleTitle + (anchor ? "#" + anchor : "")); - if (anchor) { - try { - anchor = encodeURIComponent(anchor.replace(/ /g, "_")).replace(/%/g, "."); - } catch (e3) { - anchor = anchor.replace(/ /g, "_"); - } - } - _wikiURL = "https://" + tagLang + ".wikipedia.org/wiki/" + tagArticleTitle.replace(/ /g, "_") + (anchor ? "#" + anchor : ""); - } else { - utilGetSetValue(_titleInput, value); - if (value && value !== "") { - utilGetSetValue(_langInput, ""); - const defaultLangInfo = defaultLanguageInfo(); - _wikiURL = "https://".concat(defaultLangInfo[2], ".wikipedia.org/w/index.php?fulltext=1&search=").concat(value); - } else { - const shownOrDefaultLangInfo = language( - true - /* skipEnglishFallback */ - ); - utilGetSetValue(_langInput, shownOrDefaultLangInfo[1]); - _wikiURL = ""; - } + directionalCombo.focus = function() { + var node = wrap2.selectAll("input").node(); + if (node) + node.focus(); + }; + return utilRebind(directionalCombo, dispatch14, "on"); + } + + // modules/ui/fields/lanes.js + function uiFieldLanes(field, context) { + var dispatch14 = dispatch_default("change"); + var LANE_WIDTH = 40; + var LANE_HEIGHT = 200; + var _entityIDs = []; + function lanes(selection2) { + var lanesData = context.entity(_entityIDs[0]).lanes(); + if (!context.container().select(".inspector-wrap.inspector-hidden").empty() || !selection2.node().parentNode) { + selection2.call(lanes.off); + return; } + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + var surface = wrap2.selectAll(".surface").data([0]); + var d2 = utilGetDimensions(wrap2); + var freeSpace = d2[0] - lanesData.lanes.length * LANE_WIDTH * 1.5 + LANE_WIDTH * 0.5; + surface = surface.enter().append("svg").attr("width", d2[0]).attr("height", 300).attr("class", "surface").merge(surface); + var lanesSelection = surface.selectAll(".lanes").data([0]); + lanesSelection = lanesSelection.enter().append("g").attr("class", "lanes").merge(lanesSelection); + lanesSelection.attr("transform", function() { + return "translate(" + freeSpace / 2 + ", 0)"; + }); + var lane = lanesSelection.selectAll(".lane").data(lanesData.lanes); + lane.exit().remove(); + var enter = lane.enter().append("g").attr("class", "lane"); + enter.append("g").append("rect").attr("y", 50).attr("width", LANE_WIDTH).attr("height", LANE_HEIGHT); + enter.append("g").attr("class", "forward").append("text").attr("y", 40).attr("x", 14).text("\u25B2"); + enter.append("g").attr("class", "bothways").append("text").attr("y", 40).attr("x", 14).text("\u25B2\u25BC"); + enter.append("g").attr("class", "backward").append("text").attr("y", 40).attr("x", 14).text("\u25BC"); + lane = lane.merge(enter); + lane.attr("transform", function(d4) { + return "translate(" + LANE_WIDTH * d4.index * 1.5 + ", 0)"; + }); + lane.select(".forward").style("visibility", function(d4) { + return d4.direction === "forward" ? "visible" : "hidden"; + }); + lane.select(".bothways").style("visibility", function(d4) { + return d4.direction === "bothways" ? "visible" : "hidden"; + }); + lane.select(".backward").style("visibility", function(d4) { + return d4.direction === "backward" ? "visible" : "hidden"; + }); } - wiki.entityIDs = (val) => { - if (!arguments.length) - return _entityIDs; + lanes.entityIDs = function(val) { _entityIDs = val; - return wiki; }; - wiki.focus = () => { - _titleInput.node().focus(); + lanes.tags = function() { }; - return utilRebind(wiki, dispatch14, "on"); + lanes.focus = function() { + }; + lanes.off = function() { + }; + return utilRebind(lanes, dispatch14, "on"); } - uiFieldWikipedia.supportsMultiselection = false; - - // modules/ui/fields/index.js - var uiFields = { - access: uiFieldAccess, - address: uiFieldAddress, - check: uiFieldCheck, - colour: uiFieldText, - combo: uiFieldCombo, - cycleway: uiFieldDirectionalCombo, - date: uiFieldText, - defaultCheck: uiFieldCheck, - directionalCombo: uiFieldDirectionalCombo, - email: uiFieldText, - identifier: uiFieldText, - lanes: uiFieldLanes, - localized: uiFieldLocalized, - roadheight: uiFieldRoadheight, - roadspeed: uiFieldRoadspeed, - manyCombo: uiFieldCombo, - multiCombo: uiFieldCombo, - networkCombo: uiFieldCombo, - number: uiFieldText, - onewayCheck: uiFieldCheck, - radio: uiFieldRadio, - restrictions: uiFieldRestrictions, - semiCombo: uiFieldCombo, - structureRadio: uiFieldRadio, - tel: uiFieldText, - text: uiFieldText, - textarea: uiFieldTextarea, - typeCombo: uiFieldCombo, - url: uiFieldText, - wikidata: uiFieldWikidata, - wikipedia: uiFieldWikipedia - }; + uiFieldLanes.supportsMultiselection = false; - // modules/ui/field.js - function uiField(context, presetField2, entityIDs, options2) { - options2 = Object.assign({ - show: true, - wrap: true, - remove: true, - revert: true, - info: true - }, options2); - var dispatch14 = dispatch_default("change", "revert"); - var field = Object.assign({}, presetField2); - field.domId = utilUniqueDomId("form-field-" + field.safeid); - var _show = options2.show; - var _state = ""; - var _tags = {}; - var _entityExtent; - if (entityIDs && entityIDs.length) { - _entityExtent = entityIDs.reduce(function(extent, entityID) { - var entity = context.graph().entity(entityID); - return extent.extend(entity.extent(context.graph())); - }, geoExtent()); + // modules/ui/fields/localized.js + var _languagesArray = []; + function uiFieldLocalized(field, context) { + var dispatch14 = dispatch_default("change", "input"); + var wikipedia = services.wikipedia; + var input = select_default2(null); + var localizedInputs = select_default2(null); + var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()); + var _countryCode; + var _tags; + _mainFileFetcher.get("languages").then(loadLanguagesArray).catch(function() { + }); + var _territoryLanguages = {}; + _mainFileFetcher.get("territory_languages").then(function(d2) { + _territoryLanguages = d2; + }).catch(function() { + }); + var langCombo = uiCombobox(context, "localized-lang").fetcher(fetchLanguages).minItems(0); + var _selection = select_default2(null); + var _multilingual = []; + var _buttonTip = uiTooltip().title(() => _t.append("translate.translate")).placement("left"); + var _wikiTitles; + var _entityIDs = []; + function loadLanguagesArray(dataLanguages) { + if (_languagesArray.length !== 0) + return; + var replacements = { + sr: "sr-Cyrl", + // in OSM, `sr` implies Cyrillic + "sr-Cyrl": false + // `sr-Cyrl` isn't used in OSM + }; + for (var code in dataLanguages) { + if (replacements[code] === false) + continue; + var metaCode = code; + if (replacements[code]) + metaCode = replacements[code]; + _languagesArray.push({ + localName: _mainLocalizer.languageName(metaCode, { localOnly: true }), + nativeName: dataLanguages[metaCode].nativeName, + code, + label: _mainLocalizer.languageName(metaCode) + }); + } } - var _locked = false; - var _lockedTip = uiTooltip().title(() => _t.append("inspector.lock.suggestion", { label: field.title })).placement("bottom"); - if (_show && !field.impl) { - createField(); + function calcLocked() { + var isLocked = field.id === "name" && _entityIDs.length && _entityIDs.some(function(entityID) { + var entity = context.graph().hasEntity(entityID); + if (!entity) + return false; + if (entity.tags.wikidata) + return true; + if (entity.tags["name:etymology:wikidata"]) + return true; + var preset = _mainPresetIndex.match(entity, context.graph()); + if (preset) { + var isSuggestion = preset.suggestion; + var fields = preset.fields(entity.extent(context.graph()).center()); + var showsBrandField = fields.some(function(d2) { + return d2.id === "brand"; + }); + var showsOperatorField = fields.some(function(d2) { + return d2.id === "operator"; + }); + var setsName = preset.addTags.name; + var setsBrandWikidata = preset.addTags["brand:wikidata"]; + var setsOperatorWikidata = preset.addTags["operator:wikidata"]; + return isSuggestion && setsName && (setsBrandWikidata && !showsBrandField || setsOperatorWikidata && !showsOperatorField); + } + return false; + }); + field.locked(isLocked); } - function createField() { - field.impl = uiFields[field.type](field, context).on("change", function(t2, onInput) { - dispatch14.call("change", field, t2, onInput); + function calcMultilingual(tags) { + var existingLangsOrdered = _multilingual.map(function(item2) { + return item2.lang; }); - if (entityIDs) { - field.entityIDs = entityIDs; - if (field.impl.entityIDs) { - field.impl.entityIDs(entityIDs); + var existingLangs = new Set(existingLangsOrdered.filter(Boolean)); + for (var k2 in tags) { + var m2 = k2.match(/^(.*):([a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-[A-Z]{2})?)$/); + if (m2 && m2[1] === field.key && m2[2]) { + var item = { lang: m2[2], value: tags[k2] }; + if (existingLangs.has(item.lang)) { + _multilingual[existingLangsOrdered.indexOf(item.lang)].value = item.value; + existingLangs.delete(item.lang); + } else { + _multilingual.push(item); + } } } + _multilingual.forEach(function(item2) { + if (item2.lang && existingLangs.has(item2.lang)) { + item2.value = ""; + } + }); } - function allKeys() { - let keys2 = field.keys || [field.key]; - if (field.type === "directionalCombo" && field.key) { - keys2 = keys2.concat(field.key); + function localized(selection2) { + _selection = selection2; + calcLocked(); + var isLocked = field.locked(); + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + input = wrap2.selectAll(".localized-main").data([0]); + input = input.enter().append("input").attr("type", "text").attr("id", field.domId).attr("class", "localized-main").call(utilNoAuto).merge(input); + input.classed("disabled", !!isLocked).attr("readonly", isLocked || null).on("input", change(true)).on("blur", change()).on("change", change()); + wrap2.call(_lengthIndicator); + var translateButton = wrap2.selectAll(".localized-add").data([0]); + translateButton = translateButton.enter().append("button").attr("class", "localized-add form-field-button").attr("aria-label", _t("icons.plus")).call(svgIcon("#iD-icon-plus")).merge(translateButton); + translateButton.classed("disabled", !!isLocked).call(isLocked ? _buttonTip.destroy : _buttonTip).on("click", addNew); + if (_tags && !_multilingual.length) { + calcMultilingual(_tags); } - return keys2; - } - function isModified() { - if (!entityIDs || !entityIDs.length) - return false; - return entityIDs.some(function(entityID) { - var original = context.graph().base().entities[entityID]; - var latest = context.graph().entity(entityID); - return allKeys().some(function(key) { - return original ? latest.tags[key] !== original.tags[key] : latest.tags[key]; + localizedInputs = selection2.selectAll(".localized-multilingual").data([0]); + localizedInputs = localizedInputs.enter().append("div").attr("class", "localized-multilingual").merge(localizedInputs); + localizedInputs.call(renderMultilingual); + localizedInputs.selectAll("button, input").classed("disabled", !!isLocked).attr("readonly", isLocked || null); + selection2.selectAll(".combobox-caret").classed("nope", true); + function addNew(d3_event) { + d3_event.preventDefault(); + if (field.locked()) + return; + var defaultLang = _mainLocalizer.languageCode().toLowerCase(); + var langExists = _multilingual.find(function(datum2) { + return datum2.lang === defaultLang; }); - }); - } - function tagsContainFieldKey() { - return allKeys().some(function(key) { - if (field.type === "multiCombo") { - for (var tagKey in _tags) { - if (tagKey.indexOf(key) === 0) { - return true; - } - } - return false; + var isLangEn = defaultLang.indexOf("en") > -1; + if (isLangEn || langExists) { + defaultLang = ""; + langExists = _multilingual.find(function(datum2) { + return datum2.lang === defaultLang; + }); } - return _tags[key] !== void 0; + if (!langExists) { + _multilingual.unshift({ lang: defaultLang, value: "" }); + localizedInputs.call(renderMultilingual); + } + } + function change(onInput) { + return function(d3_event) { + if (field.locked()) { + d3_event.preventDefault(); + return; + } + var val = utilGetSetValue(select_default2(this)); + if (!onInput) + val = context.cleanTagValue(val); + if (!val && Array.isArray(_tags[field.key])) + return; + var t2 = {}; + t2[field.key] = val || void 0; + dispatch14.call("change", this, t2, onInput); + }; + } + } + function key(lang) { + return field.key + ":" + lang; + } + function changeLang(d3_event, d2) { + var tags = {}; + var lang = utilGetSetValue(select_default2(this)).toLowerCase(); + var language = _languagesArray.find(function(d4) { + return d4.label.toLowerCase() === lang || d4.localName && d4.localName.toLowerCase() === lang || d4.nativeName && d4.nativeName.toLowerCase() === lang; }); + if (language) + lang = language.code; + if (d2.lang && d2.lang !== lang) { + tags[key(d2.lang)] = void 0; + } + var newKey = lang && context.cleanTagKey(key(lang)); + var value = utilGetSetValue(select_default2(this.parentNode).selectAll(".localized-value")); + if (newKey && value) { + tags[newKey] = value; + } else if (newKey && _wikiTitles && _wikiTitles[d2.lang]) { + tags[newKey] = _wikiTitles[d2.lang]; + } + d2.lang = lang; + dispatch14.call("change", this, tags); } - function revert(d3_event, d2) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - if (!entityIDs || _locked) + function changeValue(d3_event, d2) { + if (!d2.lang) return; - dispatch14.call("revert", d2, allKeys()); - } - function remove2(d3_event, d2) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - if (_locked) + var value = context.cleanTagValue(utilGetSetValue(select_default2(this))) || void 0; + if (!value && Array.isArray(d2.value)) return; var t2 = {}; - allKeys().forEach(function(key) { - t2[key] = void 0; - }); - dispatch14.call("change", d2, t2); + t2[key(d2.lang)] = value; + d2.value = value; + dispatch14.call("change", this, t2); } - field.render = function(selection2) { - var container = selection2.selectAll(".form-field").data([field]); - var enter = container.enter().append("div").attr("class", function(d2) { - return "form-field form-field-" + d2.safeid; - }).classed("nowrap", !options2.wrap); - if (options2.wrap) { - var labelEnter = enter.append("label").attr("class", "field-label").attr("for", function(d2) { - return d2.domId; - }); - var textEnter = labelEnter.append("span").attr("class", "label-text"); - textEnter.append("span").attr("class", "label-textvalue").each(function(d2) { - d2.label()(select_default2(this)); - }); - textEnter.append("span").attr("class", "label-textannotation"); - if (options2.remove) { - labelEnter.append("button").attr("class", "remove-icon").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")); - } - if (options2.revert) { - labelEnter.append("button").attr("class", "modified-icon").attr("title", _t("icons.undo")).call(svgIcon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-redo" : "#iD-icon-undo")); - } + function fetchLanguages(value, cb) { + var v2 = value.toLowerCase(); + var langCodes = [_mainLocalizer.localeCode(), _mainLocalizer.languageCode()]; + if (_countryCode && _territoryLanguages[_countryCode]) { + langCodes = langCodes.concat(_territoryLanguages[_countryCode]); } - container = container.merge(enter); - container.select(".field-label > .remove-icon").on("click", remove2); - container.select(".field-label > .modified-icon").on("click", revert); - container.each(function(d2) { - var selection3 = select_default2(this); - if (!d2.impl) { - createField(); - } - var reference, help; - if (options2.wrap && field.type === "restrictions") { - help = uiFieldHelp(context, "restrictions"); - } - if (options2.wrap && options2.info) { - var referenceKey = d2.key || ""; - if (d2.type === "multiCombo") { - referenceKey = referenceKey.replace(/:$/, ""); - } - var referenceOptions = d2.reference || { - key: referenceKey, - value: _tags[referenceKey] - }; - reference = uiTagReference(referenceOptions, context); - if (_state === "hover") { - reference.showing(false); + var langItems = []; + langCodes.forEach(function(code) { + var langItem = _languagesArray.find(function(item) { + return item.code === code; + }); + if (langItem) + langItems.push(langItem); + }); + langItems = utilArrayUniq(langItems.concat(_languagesArray)); + cb(langItems.filter(function(d2) { + return d2.label.toLowerCase().indexOf(v2) >= 0 || d2.localName && d2.localName.toLowerCase().indexOf(v2) >= 0 || d2.nativeName && d2.nativeName.toLowerCase().indexOf(v2) >= 0 || d2.code.toLowerCase().indexOf(v2) >= 0; + }).map(function(d2) { + return { value: d2.label }; + })); + } + function renderMultilingual(selection2) { + var entries = selection2.selectAll("div.entry").data(_multilingual, function(d2) { + return d2.lang; + }); + entries.exit().style("top", "0").style("max-height", "240px").transition().duration(200).style("opacity", "0").style("max-height", "0px").remove(); + var entriesEnter = entries.enter().append("div").attr("class", "entry").each(function(_2, index) { + var wrap2 = select_default2(this); + var domId = utilUniqueDomId(index); + var label = wrap2.append("label").attr("class", "field-label").attr("for", domId); + var text = label.append("span").attr("class", "label-text"); + text.append("span").attr("class", "label-textvalue").call(_t.append("translate.localized_translation_label")); + text.append("span").attr("class", "label-textannotation"); + label.append("button").attr("class", "remove-icon-multilingual").attr("title", _t("icons.remove")).on("click", function(d3_event, d2) { + if (field.locked()) + return; + d3_event.preventDefault(); + _multilingual.splice(_multilingual.indexOf(d2), 1); + var langKey = d2.lang && key(d2.lang); + if (langKey && langKey in _tags) { + delete _tags[langKey]; + var t2 = {}; + t2[langKey] = void 0; + dispatch14.call("change", this, t2); + return; } - } - selection3.call(d2.impl); - if (help) { - selection3.call(help.body).select(".field-label").call(help.button); - } - if (reference) { - selection3.call(reference.body).select(".field-label").call(reference.button); - } - d2.impl.tags(_tags); + renderMultilingual(selection2); + }).call(svgIcon("#iD-operation-delete")); + wrap2.append("input").attr("class", "localized-lang").attr("id", domId).attr("type", "text").attr("placeholder", _t("translate.localized_translation_language")).on("blur", changeLang).on("change", changeLang).call(langCombo); + wrap2.append("input").attr("type", "text").attr("class", "localized-value").on("blur", changeValue).on("change", changeValue); }); - container.classed("locked", _locked).classed("modified", isModified()).classed("present", tagsContainFieldKey()); - var annotation = container.selectAll(".field-label .label-textannotation"); - var icon2 = annotation.selectAll(".icon").data(_locked ? [0] : []); - icon2.exit().remove(); - icon2.enter().append("svg").attr("class", "icon").append("use").attr("xlink:href", "#fas-lock"); - container.call(_locked ? _lockedTip : _lockedTip.destroy); - }; - field.state = function(val) { - if (!arguments.length) - return _state; - _state = val; - return field; - }; - field.tags = function(val) { - if (!arguments.length) - return _tags; - _tags = val; - if (tagsContainFieldKey() && !_show) { - _show = true; - if (!field.impl) { - createField(); + entriesEnter.style("margin-top", "0px").style("max-height", "0px").style("opacity", "0").transition().duration(200).style("margin-top", "10px").style("max-height", "240px").style("opacity", "1").on("end", function() { + select_default2(this).style("max-height", "").style("overflow", "visible"); + }); + entries = entries.merge(entriesEnter); + entries.order(); + entries.classed("present", true); + utilGetSetValue(entries.select(".localized-lang"), function(d2) { + var langItem = _languagesArray.find(function(item) { + return item.code === d2.lang; + }); + if (langItem) + return langItem.label; + return d2.lang; + }); + utilGetSetValue(entries.select(".localized-value"), function(d2) { + return typeof d2.value === "string" ? d2.value : ""; + }).attr("title", function(d2) { + return Array.isArray(d2.value) ? d2.value.filter(Boolean).join("\n") : null; + }).attr("placeholder", function(d2) { + return Array.isArray(d2.value) ? _t("inspector.multiple_values") : _t("translate.localized_translation_name"); + }).classed("mixed", function(d2) { + return Array.isArray(d2.value); + }); + } + localized.tags = function(tags) { + _tags = tags; + if (typeof tags.wikipedia === "string" && !_wikiTitles) { + _wikiTitles = {}; + var wm = tags.wikipedia.match(/([^:]+):(.+)/); + if (wm && wm[0] && wm[1]) { + wikipedia.translations(wm[1], wm[2], function(err, d2) { + if (err || !d2) + return; + _wikiTitles = d2; + }); } } - return field; + var isMixed = Array.isArray(tags[field.key]); + utilGetSetValue(input, typeof tags[field.key] === "string" ? tags[field.key] : "").attr("title", isMixed ? tags[field.key].filter(Boolean).join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder()).classed("mixed", isMixed); + calcMultilingual(tags); + _selection.call(localized); + if (!isMixed) { + _lengthIndicator.update(tags[field.key]); + } }; - field.locked = function(val) { + localized.focus = function() { + input.node().focus(); + }; + localized.entityIDs = function(val) { if (!arguments.length) - return _locked; - _locked = val; - return field; + return _entityIDs; + _entityIDs = val; + _multilingual = []; + loadCountryCode(); + return localized; }; - field.show = function() { - _show = true; - if (!field.impl) { - createField(); + function loadCountryCode() { + var extent = combinedEntityExtent(); + var countryCode = extent && iso1A2Code(extent.center()); + _countryCode = countryCode && countryCode.toLowerCase(); + } + function combinedEntityExtent() { + return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + } + return utilRebind(localized, dispatch14, "on"); + } + + // modules/ui/fields/roadheight.js + function uiFieldRoadheight(field, context) { + var dispatch14 = dispatch_default("change"); + var primaryUnitInput = select_default2(null); + var primaryInput = select_default2(null); + var secondaryInput = select_default2(null); + var secondaryUnitInput = select_default2(null); + var _entityIDs = []; + var _tags; + var _isImperial; + var formatFloat = _mainLocalizer.floatFormatter(_mainLocalizer.languageCode()); + var parseLocaleFloat = _mainLocalizer.floatParser(_mainLocalizer.languageCode()); + var primaryUnits = [ + { + value: "m", + title: _t("inspector.roadheight.meter") + }, + { + value: "ft", + title: _t("inspector.roadheight.foot") } - if (field.default && field.key && _tags[field.key] !== field.default) { - var t2 = {}; - t2[field.key] = field.default; - dispatch14.call("change", this, t2); + ]; + var unitCombo = uiCombobox(context, "roadheight-unit").data(primaryUnits); + function roadheight(selection2) { + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + primaryInput = wrap2.selectAll("input.roadheight-number").data([0]); + primaryInput = primaryInput.enter().append("input").attr("type", "text").attr("class", "roadheight-number").attr("id", field.domId).call(utilNoAuto).merge(primaryInput); + primaryInput.on("change", change).on("blur", change); + var loc = combinedEntityExtent().center(); + _isImperial = roadHeightUnit(loc) === "ft"; + primaryUnitInput = wrap2.selectAll("input.roadheight-unit").data([0]); + primaryUnitInput = primaryUnitInput.enter().append("input").attr("type", "text").attr("class", "roadheight-unit").call(unitCombo).merge(primaryUnitInput); + primaryUnitInput.on("blur", changeUnits).on("change", changeUnits); + secondaryInput = wrap2.selectAll("input.roadheight-secondary-number").data([0]); + secondaryInput = secondaryInput.enter().append("input").attr("type", "text").attr("class", "roadheight-secondary-number").call(utilNoAuto).merge(secondaryInput); + secondaryInput.on("change", change).on("blur", change); + secondaryUnitInput = wrap2.selectAll("input.roadheight-secondary-unit").data([0]); + secondaryUnitInput = secondaryUnitInput.enter().append("input").attr("type", "text").call(utilNoAuto).classed("disabled", true).classed("roadheight-secondary-unit", true).attr("readonly", "readonly").merge(secondaryUnitInput); + function changeUnits() { + var primaryUnit = utilGetSetValue(primaryUnitInput); + if (primaryUnit === "m") { + _isImperial = false; + } else if (primaryUnit === "ft") { + _isImperial = true; + } + utilGetSetValue(primaryUnitInput, _isImperial ? "ft" : "m"); + setUnitSuggestions(); + change(); } - }; - field.isShown = function() { - return _show; - }; - field.isAllowed = function() { - if (entityIDs && entityIDs.length > 1 && uiFields[field.type].supportsMultiselection === false) - return false; - if (field.geometry && !entityIDs.every(function(entityID) { - return field.matchGeometry(context.graph().geometry(entityID)); - })) - return false; - if (entityIDs && _entityExtent && field.locationSetID) { - var validHere = _sharedLocationManager.locationSetsAt(_entityExtent.center()); - if (!validHere[field.locationSetID]) - return false; + } + function setUnitSuggestions() { + utilGetSetValue(primaryUnitInput, _isImperial ? "ft" : "m"); + } + function change() { + var tag2 = {}; + var primaryValue = utilGetSetValue(primaryInput).trim(); + var secondaryValue = utilGetSetValue(secondaryInput).trim(); + if (!primaryValue && !secondaryValue && Array.isArray(_tags[field.key])) + return; + if (!primaryValue && !secondaryValue) { + tag2[field.key] = void 0; + } else { + var rawPrimaryValue = likelyRawNumberFormat.test(primaryValue) ? parseFloat(primaryValue) : parseLocaleFloat(primaryValue); + if (isNaN(rawPrimaryValue)) + rawPrimaryValue = primaryValue; + var rawSecondaryValue = likelyRawNumberFormat.test(secondaryValue) ? parseFloat(secondaryValue) : parseLocaleFloat(secondaryValue); + if (isNaN(rawSecondaryValue)) + rawSecondaryValue = secondaryValue; + if (isNaN(rawPrimaryValue) || isNaN(rawSecondaryValue) || !_isImperial) { + tag2[field.key] = context.cleanTagValue(rawPrimaryValue); + } else { + if (rawPrimaryValue !== "") { + rawPrimaryValue = rawPrimaryValue + "'"; + } + if (rawSecondaryValue !== "") { + rawSecondaryValue = rawSecondaryValue + '"'; + } + tag2[field.key] = context.cleanTagValue(rawPrimaryValue + rawSecondaryValue); + } } - var prerequisiteTag = field.prerequisiteTag; - if (entityIDs && !tagsContainFieldKey() && // ignore tagging prerequisites if a value is already present - prerequisiteTag) { - if (!entityIDs.every(function(entityID) { - var entity = context.graph().entity(entityID); - if (prerequisiteTag.key) { - var value = entity.tags[prerequisiteTag.key]; - if (!value) - return false; - if (prerequisiteTag.valueNot) { - return prerequisiteTag.valueNot !== value; - } - if (prerequisiteTag.value) { - return prerequisiteTag.value === value; - } - } else if (prerequisiteTag.keyNot) { - if (entity.tags[prerequisiteTag.keyNot]) - return false; + dispatch14.call("change", this, tag2); + } + roadheight.tags = function(tags) { + _tags = tags; + var primaryValue = tags[field.key]; + var secondaryValue; + var isMixed = Array.isArray(primaryValue); + if (!isMixed) { + if (primaryValue && (primaryValue.indexOf("'") >= 0 || primaryValue.indexOf('"') >= 0)) { + secondaryValue = primaryValue.match(/(-?[\d.]+)"/); + if (secondaryValue !== null) { + secondaryValue = formatFloat(parseFloat(secondaryValue[1])); } - return true; - })) - return false; + primaryValue = primaryValue.match(/(-?[\d.]+)'/); + if (primaryValue !== null) { + primaryValue = formatFloat(parseFloat(primaryValue[1])); + } + _isImperial = true; + } else if (primaryValue) { + var rawValue = primaryValue; + primaryValue = parseFloat(rawValue); + if (isNaN(primaryValue)) { + primaryValue = rawValue; + } else { + primaryValue = formatFloat(primaryValue); + } + _isImperial = false; + } } - return true; + setUnitSuggestions(); + var inchesPlaceholder = formatFloat(0); + utilGetSetValue(primaryInput, typeof primaryValue === "string" ? primaryValue : "").attr("title", isMixed ? primaryValue.filter(Boolean).join("\n") : null).attr("placeholder", isMixed ? _t("inspector.multiple_values") : _t("inspector.unknown")).classed("mixed", isMixed); + utilGetSetValue(secondaryInput, typeof secondaryValue === "string" ? secondaryValue : "").attr("placeholder", isMixed ? _t("inspector.multiple_values") : _isImperial ? inchesPlaceholder : null).classed("mixed", isMixed).classed("disabled", !_isImperial).attr("readonly", _isImperial ? null : "readonly"); + secondaryUnitInput.attr("value", _isImperial ? _t("inspector.roadheight.inch") : null); }; - field.focus = function() { - if (field.impl) { - field.impl.focus(); - } + roadheight.focus = function() { + primaryInput.node().focus(); }; - return utilRebind(field, dispatch14, "on"); + roadheight.entityIDs = function(val) { + _entityIDs = val; + }; + function combinedEntityExtent() { + return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + } + return utilRebind(roadheight, dispatch14, "on"); } - // modules/ui/form_fields.js - function uiFormFields(context) { - var moreCombo = uiCombobox(context, "more-fields").minItems(1); - var _fieldsArr = []; - var _lastPlaceholder = ""; - var _state = ""; - var _klass = ""; - function formFields(selection2) { - var allowedFields = _fieldsArr.filter(function(field) { - return field.isAllowed(); - }); - var shown = allowedFields.filter(function(field) { - return field.isShown(); - }); - var notShown = allowedFields.filter(function(field) { - return !field.isShown(); - }); - var container = selection2.selectAll(".form-fields-container").data([0]); - container = container.enter().append("div").attr("class", "form-fields-container " + (_klass || "")).merge(container); - var fields = container.selectAll(".wrap-form-field").data(shown, function(d2) { - return d2.id + (d2.entityIDs ? d2.entityIDs.join() : ""); - }); - fields.exit().remove(); - var enter = fields.enter().append("div").attr("class", function(d2) { - return "wrap-form-field wrap-form-field-" + d2.safeid; - }); - fields = fields.merge(enter); - fields.order().each(function(d2) { - select_default2(this).call(d2.render); - }); - var titles = []; - var moreFields = notShown.map(function(field) { - var title = field.title(); - titles.push(title); - var terms = field.terms(); - if (field.key) - terms.push(field.key); - if (field.keys) - terms = terms.concat(field.keys); - return { - display: field.label(), - value: title, - title, - field, - terms - }; - }); - var placeholder = titles.slice(0, 3).join(", ") + (titles.length > 3 ? "\u2026" : ""); - var more = selection2.selectAll(".more-fields").data(_state === "hover" || moreFields.length === 0 ? [] : [0]); - more.exit().remove(); - var moreEnter = more.enter().append("div").attr("class", "more-fields").append("label"); - moreEnter.append("span").call(_t.append("inspector.add_fields")); - more = moreEnter.merge(more); - var input = more.selectAll(".value").data([0]); - input.exit().remove(); - input = input.enter().append("input").attr("class", "value").attr("type", "text").attr("placeholder", placeholder).call(utilNoAuto).merge(input); - input.call(utilGetSetValue, "").call( - moreCombo.data(moreFields).on("accept", function(d2) { - if (!d2) - return; - var field = d2.field; - field.show(); - selection2.call(formFields); - field.focus(); - }) - ); - if (_lastPlaceholder !== placeholder) { - input.attr("placeholder", placeholder); - _lastPlaceholder = placeholder; + // modules/ui/fields/roadspeed.js + function uiFieldRoadspeed(field, context) { + var dispatch14 = dispatch_default("change"); + var unitInput = select_default2(null); + var input = select_default2(null); + var _entityIDs = []; + var _tags; + var _isImperial; + var formatFloat = _mainLocalizer.floatFormatter(_mainLocalizer.languageCode()); + var parseLocaleFloat = _mainLocalizer.floatParser(_mainLocalizer.languageCode()); + var speedCombo = uiCombobox(context, "roadspeed"); + var unitCombo = uiCombobox(context, "roadspeed-unit").data(["km/h", "mph"].map(comboValues)); + var metricValues = [20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; + var imperialValues = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80]; + function roadspeed(selection2) { + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + input = wrap2.selectAll("input.roadspeed-number").data([0]); + input = input.enter().append("input").attr("type", "text").attr("class", "roadspeed-number").attr("id", field.domId).call(utilNoAuto).call(speedCombo).merge(input); + input.on("change", change).on("blur", change); + var loc = combinedEntityExtent().center(); + _isImperial = roadSpeedUnit(loc) === "mph"; + unitInput = wrap2.selectAll("input.roadspeed-unit").data([0]); + unitInput = unitInput.enter().append("input").attr("type", "text").attr("class", "roadspeed-unit").attr("aria-label", _t("inspector.speed_unit")).call(unitCombo).merge(unitInput); + unitInput.on("blur", changeUnits).on("change", changeUnits); + function changeUnits() { + var unit2 = utilGetSetValue(unitInput); + if (unit2 === "km/h") { + _isImperial = false; + } else if (unit2 === "mph") { + _isImperial = true; + } + utilGetSetValue(unitInput, _isImperial ? "mph" : "km/h"); + setUnitSuggestions(); + change(); } } - formFields.fieldsArr = function(val) { - if (!arguments.length) - return _fieldsArr; - _fieldsArr = val || []; - return formFields; + function setUnitSuggestions() { + speedCombo.data((_isImperial ? imperialValues : metricValues).map(comboValues)); + utilGetSetValue(unitInput, _isImperial ? "mph" : "km/h"); + } + function comboValues(d2) { + return { + value: formatFloat(d2), + title: formatFloat(d2) + }; + } + function change() { + var tag2 = {}; + var value = utilGetSetValue(input).trim(); + if (!value && Array.isArray(_tags[field.key])) + return; + if (!value) { + tag2[field.key] = void 0; + } else { + var rawValue = likelyRawNumberFormat.test(value) ? parseFloat(value) : parseLocaleFloat(value); + if (isNaN(rawValue)) + rawValue = value; + if (isNaN(rawValue) || !_isImperial) { + tag2[field.key] = context.cleanTagValue(rawValue); + } else { + tag2[field.key] = context.cleanTagValue(rawValue + " mph"); + } + } + dispatch14.call("change", this, tag2); + } + roadspeed.tags = function(tags) { + _tags = tags; + var rawValue = tags[field.key]; + var value = rawValue; + var isMixed = Array.isArray(value); + if (!isMixed) { + if (rawValue && rawValue.indexOf("mph") >= 0) { + _isImperial = true; + } else if (rawValue) { + _isImperial = false; + } + value = parseInt(value, 10); + if (isNaN(value)) { + value = rawValue; + } else { + value = formatFloat(value); + } + } + setUnitSuggestions(); + utilGetSetValue(input, typeof value === "string" ? value : "").attr("title", isMixed ? value.filter(Boolean).join("\n") : null).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder()).classed("mixed", isMixed); }; - formFields.state = function(val) { - if (!arguments.length) - return _state; - _state = val; - return formFields; + roadspeed.focus = function() { + input.node().focus(); }; - formFields.klass = function(val) { - if (!arguments.length) - return _klass; - _klass = val; - return formFields; + roadspeed.entityIDs = function(val) { + _entityIDs = val; }; - return formFields; + function combinedEntityExtent() { + return _entityIDs && _entityIDs.length && utilTotalExtent(_entityIDs, context.graph()); + } + return utilRebind(roadspeed, dispatch14, "on"); } - // modules/ui/changeset_editor.js - function uiChangesetEditor(context) { + // modules/ui/fields/radio.js + function uiFieldRadio(field, context) { var dispatch14 = dispatch_default("change"); - var formFields = uiFormFields(context); - var commentCombo = uiCombobox(context, "comment").caseSensitive(true); - var _fieldsArr; - var _tags; - var _changesetID; - function changesetEditor(selection2) { - render(selection2); + var placeholder = select_default2(null); + var wrap2 = select_default2(null); + var labels = select_default2(null); + var radios = select_default2(null); + var radioData = (field.options || field.keys).slice(); + var typeField; + var layerField; + var _oldType = {}; + var _entityIDs = []; + function selectedKey() { + var node = wrap2.selectAll(".form-field-input-radio label.active input"); + return !node.empty() && node.datum(); } - function render(selection2) { - var initial = false; - if (!_fieldsArr) { - initial = true; - var presets = _mainPresetIndex; - _fieldsArr = [ - uiField(context, presets.field("comment"), null, { show: true, revert: false }), - uiField(context, presets.field("source"), null, { show: true, revert: false }), - uiField(context, presets.field("hashtags"), null, { show: false, revert: false }) - ]; - _fieldsArr.forEach(function(field) { - field.on("change", function(t2, onInput) { - dispatch14.call("change", field, void 0, t2, onInput); - }); - }); + function radio(selection2) { + selection2.classed("preset-radio", true); + wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + var enter = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-radio"); + enter.append("span").attr("class", "placeholder"); + wrap2 = wrap2.merge(enter); + placeholder = wrap2.selectAll(".placeholder"); + labels = wrap2.selectAll("label").data(radioData); + enter = labels.enter().append("label"); + var stringsField = field.resolveReference("stringsCrossReference"); + enter.append("input").attr("type", "radio").attr("name", field.id).attr("value", function(d2) { + return stringsField.t("options." + d2, { "default": d2 }); + }).attr("checked", false); + enter.append("span").each(function(d2) { + stringsField.t.append("options." + d2, { "default": d2 })(select_default2(this)); + }); + labels = labels.merge(enter); + radios = labels.selectAll("input").on("change", changeRadio); + } + function structureExtras(selection2, tags) { + var selected = selectedKey() || tags.layer !== void 0; + var type2 = _mainPresetIndex.field(selected); + var layer = _mainPresetIndex.field("layer"); + var showLayer = selected === "bridge" || selected === "tunnel" || tags.layer !== void 0; + var extrasWrap = selection2.selectAll(".structure-extras-wrap").data(selected ? [0] : []); + extrasWrap.exit().remove(); + extrasWrap = extrasWrap.enter().append("div").attr("class", "structure-extras-wrap").merge(extrasWrap); + var list2 = extrasWrap.selectAll("ul").data([0]); + list2 = list2.enter().append("ul").attr("class", "rows").merge(list2); + if (type2) { + if (!typeField || typeField.id !== selected) { + typeField = uiField(context, type2, _entityIDs, { wrap: false }).on("change", changeType); + } + typeField.tags(tags); + } else { + typeField = null; } - _fieldsArr.forEach(function(field) { - field.tags(_tags); + var typeItem = list2.selectAll(".structure-type-item").data(typeField ? [typeField] : [], function(d2) { + return d2.id; }); - selection2.call(formFields.fieldsArr(_fieldsArr)); - if (initial) { - var commentField = selection2.select(".form-field-comment textarea"); - var commentNode = commentField.node(); - if (commentNode) { - commentNode.focus(); - commentNode.select(); + typeItem.exit().remove(); + var typeEnter = typeItem.enter().insert("li", ":first-child").attr("class", "labeled-input structure-type-item"); + typeEnter.append("div").attr("class", "label structure-label-type").attr("for", "preset-input-" + selected).call(_t.append("inspector.radio.structure.type")); + typeEnter.append("div").attr("class", "structure-input-type-wrap"); + typeItem = typeItem.merge(typeEnter); + if (typeField) { + typeItem.selectAll(".structure-input-type-wrap").call(typeField.render); + } + if (layer && showLayer) { + if (!layerField) { + layerField = uiField(context, layer, _entityIDs, { wrap: false }).on("change", changeLayer); } - utilTriggerEvent(commentField, "blur"); - var osm = context.connection(); - if (osm) { - osm.userChangesets(function(err, changesets) { - if (err) - return; - var comments = changesets.map(function(changeset) { - var comment = changeset.tags.comment; - return comment ? { title: comment, value: comment } : null; - }).filter(Boolean); - commentField.call( - commentCombo.data(utilArrayUniqBy(comments, "title")) - ); - }); + layerField.tags(tags); + field.keys = utilArrayUnion(field.keys, ["layer"]); + } else { + layerField = null; + field.keys = field.keys.filter(function(k2) { + return k2 !== "layer"; + }); + } + var layerItem = list2.selectAll(".structure-layer-item").data(layerField ? [layerField] : []); + layerItem.exit().remove(); + var layerEnter = layerItem.enter().append("li").attr("class", "labeled-input structure-layer-item"); + layerEnter.append("div").attr("class", "label structure-label-layer").attr("for", "preset-input-layer").call(_t.append("inspector.radio.structure.layer")); + layerEnter.append("div").attr("class", "structure-input-layer-wrap"); + layerItem = layerItem.merge(layerEnter); + if (layerField) { + layerItem.selectAll(".structure-input-layer-wrap").call(layerField.render); + } + } + function changeType(t2, onInput) { + var key = selectedKey(); + if (!key) + return; + var val = t2[key]; + if (val !== "no") { + _oldType[key] = val; + } + if (field.type === "structureRadio") { + if (val === "no" || key !== "bridge" && key !== "tunnel" || key === "tunnel" && val === "building_passage") { + t2.layer = void 0; + } + if (t2.layer === void 0) { + if (key === "bridge" && val !== "no") { + t2.layer = "1"; + } + if (key === "tunnel" && val !== "no" && val !== "building_passage") { + t2.layer = "-1"; + } } } - const warnings = []; - if (_tags.comment.match(/google/i)) { - warnings.push({ - id: 'contains "google"', - msg: _t.append("commit.google_warning"), - link: _t("commit.google_warning_link") - }); + dispatch14.call("change", this, t2, onInput); + } + function changeLayer(t2, onInput) { + if (t2.layer === "0") { + t2.layer = void 0; } - const maxChars = context.maxCharsForTagValue(); - const strLen = utilUnicodeCharsCount(utilCleanOsmString(_tags.comment, Number.POSITIVE_INFINITY)); - if (strLen > maxChars || false) { - warnings.push({ - id: "message too long", - msg: _t.append("commit.changeset_comment_length_warning", { maxChars }) - }); + dispatch14.call("change", this, t2, onInput); + } + function changeRadio() { + var t2 = {}; + var activeKey; + if (field.key) { + t2[field.key] = void 0; } - var commentWarning = selection2.select(".form-field-comment").selectAll(".comment-warning").data(warnings, (d2) => d2.id); - commentWarning.exit().transition().duration(200).style("opacity", 0).remove(); - var commentEnter = commentWarning.enter().insert("div", ".comment-warning").attr("class", "comment-warning field-warning").style("opacity", 0); - commentEnter.call(svgIcon("#iD-icon-alert", "inline")).append("span"); - commentEnter.transition().duration(200).style("opacity", 1); - commentWarning.merge(commentEnter).selectAll("div > span").text("").each(function(d2) { - let selection3 = select_default2(this); - if (d2.link) { - selection3 = selection3.append("a").attr("target", "_blank").attr("href", d2.link); + radios.each(function(d2) { + var active = select_default2(this).property("checked"); + if (active) + activeKey = d2; + if (field.key) { + if (active) + t2[field.key] = d2; + } else { + var val = _oldType[activeKey] || "yes"; + t2[d2] = active ? val : void 0; } - selection3.call(d2.msg); }); + if (field.type === "structureRadio") { + if (activeKey === "bridge") { + t2.layer = "1"; + } else if (activeKey === "tunnel" && t2.tunnel !== "building_passage") { + t2.layer = "-1"; + } else { + t2.layer = void 0; + } + } + dispatch14.call("change", this, t2); } - changesetEditor.tags = function(_2) { - if (!arguments.length) - return _tags; - _tags = _2; - return changesetEditor; + radio.tags = function(tags) { + function isOptionChecked(d2) { + if (field.key) { + return tags[field.key] === d2; + } + return !!(typeof tags[d2] === "string" && tags[d2].toLowerCase() !== "no"); + } + function isMixed(d2) { + if (field.key) { + return Array.isArray(tags[field.key]) && tags[field.key].includes(d2); + } + return Array.isArray(tags[d2]); + } + radios.property("checked", function(d2) { + return isOptionChecked(d2) && (field.key || field.options.filter(isOptionChecked).length === 1); + }); + labels.classed("active", function(d2) { + if (field.key) { + return Array.isArray(tags[field.key]) && tags[field.key].includes(d2) || tags[field.key] === d2; + } + return Array.isArray(tags[d2]) && tags[d2].some((v2) => typeof v2 === "string" && v2.toLowerCase() !== "no") || !!(typeof tags[d2] === "string" && tags[d2].toLowerCase() !== "no"); + }).classed("mixed", isMixed).attr("title", function(d2) { + return isMixed(d2) ? _t("inspector.unshared_value_tooltip") : null; + }); + var selection2 = radios.filter(function() { + return this.checked; + }); + if (selection2.empty()) { + placeholder.text(""); + placeholder.call(_t.append("inspector.none")); + } else { + placeholder.text(selection2.attr("value")); + _oldType[selection2.datum()] = tags[selection2.datum()]; + } + if (field.type === "structureRadio") { + if (!!tags.waterway && !_oldType.tunnel) { + _oldType.tunnel = "culvert"; + } + wrap2.call(structureExtras, tags); + } }; - changesetEditor.changesetID = function(_2) { + radio.focus = function() { + radios.node().focus(); + }; + radio.entityIDs = function(val) { if (!arguments.length) - return _changesetID; - if (_changesetID === _2) - return changesetEditor; - _changesetID = _2; - _fieldsArr = null; - return changesetEditor; + return _entityIDs; + _entityIDs = val; + _oldType = {}; + return radio; }; - return utilRebind(changesetEditor, dispatch14, "on"); + radio.isAllowed = function() { + return _entityIDs.length === 1; + }; + return utilRebind(radio, dispatch14, "on"); } - // modules/ui/commit.js - var import_fast_deep_equal9 = __toESM(require_fast_deep_equal()); - - // modules/util/jxon.js - var JXON = new function() { - var sValueProp = "keyValue", sAttributesProp = "keyAttributes", sAttrPref = "@", aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i; - function parseText(sValue) { - if (rIsNull.test(sValue)) { - return null; + // modules/ui/fields/restrictions.js + function uiFieldRestrictions(field, context) { + var dispatch14 = dispatch_default("change"); + var breathe = behaviorBreathe(context); + corePreferences("turn-restriction-via-way", null); + var storedViaWay = corePreferences("turn-restriction-via-way0"); + var storedDistance = corePreferences("turn-restriction-distance"); + var _maxViaWay = storedViaWay !== null ? +storedViaWay : 0; + var _maxDistance = storedDistance ? +storedDistance : 30; + var _initialized3 = false; + var _parent = select_default2(null); + var _container = select_default2(null); + var _oldTurns; + var _graph; + var _vertexID; + var _intersection; + var _fromWayID; + var _lastXPos; + function restrictions(selection2) { + _parent = selection2; + if (_vertexID && (context.graph() !== _graph || !_intersection)) { + _graph = context.graph(); + _intersection = osmIntersection(_graph, _vertexID, _maxDistance); } - if (rIsBool.test(sValue)) { - return sValue.toLowerCase() === "true"; + var isOK = _intersection && _intersection.vertices.length && // has vertices + _intersection.vertices.filter(function(vertex) { + return vertex.id === _vertexID; + }).length && _intersection.ways.length > 2; + select_default2(selection2.node().parentNode).classed("hide", !isOK); + if (!isOK || !context.container().select(".inspector-wrap.inspector-hidden").empty() || !selection2.node().parentNode || !selection2.node().parentNode.parentNode) { + selection2.call(restrictions.off); + return; + } + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + var container = wrap2.selectAll(".restriction-container").data([0]); + var containerEnter = container.enter().append("div").attr("class", "restriction-container"); + containerEnter.append("div").attr("class", "restriction-help"); + _container = containerEnter.merge(container).call(renderViewer); + var controls = wrap2.selectAll(".restriction-controls").data([0]); + controls.enter().append("div").attr("class", "restriction-controls-container").append("div").attr("class", "restriction-controls").merge(controls).call(renderControls); + } + function renderControls(selection2) { + var distControl = selection2.selectAll(".restriction-distance").data([0]); + distControl.exit().remove(); + var distControlEnter = distControl.enter().append("div").attr("class", "restriction-control restriction-distance"); + distControlEnter.append("span").attr("class", "restriction-control-label restriction-distance-label").call(_t.append("restriction.controls.distance", { suffix: ":" })); + distControlEnter.append("input").attr("class", "restriction-distance-input").attr("type", "range").attr("min", "20").attr("max", "50").attr("step", "5"); + distControlEnter.append("span").attr("class", "restriction-distance-text"); + selection2.selectAll(".restriction-distance-input").property("value", _maxDistance).on("input", function() { + var val = select_default2(this).property("value"); + _maxDistance = +val; + _intersection = null; + _container.selectAll(".layer-osm .layer-turns *").remove(); + corePreferences("turn-restriction-distance", _maxDistance); + _parent.call(restrictions); + }); + selection2.selectAll(".restriction-distance-text").call(displayMaxDistance(_maxDistance)); + var viaControl = selection2.selectAll(".restriction-via-way").data([0]); + viaControl.exit().remove(); + var viaControlEnter = viaControl.enter().append("div").attr("class", "restriction-control restriction-via-way"); + viaControlEnter.append("span").attr("class", "restriction-control-label restriction-via-way-label").call(_t.append("restriction.controls.via", { suffix: ":" })); + viaControlEnter.append("input").attr("class", "restriction-via-way-input").attr("type", "range").attr("min", "0").attr("max", "2").attr("step", "1"); + viaControlEnter.append("span").attr("class", "restriction-via-way-text"); + selection2.selectAll(".restriction-via-way-input").property("value", _maxViaWay).on("input", function() { + var val = select_default2(this).property("value"); + _maxViaWay = +val; + _container.selectAll(".layer-osm .layer-turns *").remove(); + corePreferences("turn-restriction-via-way0", _maxViaWay); + _parent.call(restrictions); + }); + selection2.selectAll(".restriction-via-way-text").call(displayMaxVia(_maxViaWay)); + } + function renderViewer(selection2) { + if (!_intersection) + return; + var vgraph = _intersection.graph; + var filter2 = utilFunctor(true); + var projection2 = geoRawMercator(); + var sdims = utilGetDimensions(context.container().select(".sidebar")); + var d2 = [sdims[0] - 50, 370]; + var c2 = geoVecScale(d2, 0.5); + var z2 = 22; + projection2.scale(geoZoomToScale(z2)); + var extent = geoExtent(); + for (var i3 = 0; i3 < _intersection.vertices.length; i3++) { + extent._extend(_intersection.vertices[i3].extent()); } - if (isFinite(sValue)) { - return parseFloat(sValue); + var padTop = 35; + if (_intersection.vertices.length > 1) { + var hPadding = Math.min(160, Math.max(110, d2[0] * 0.4)); + var vPadding = 160; + var tl = projection2([extent[0][0], extent[1][1]]); + var br2 = projection2([extent[1][0], extent[0][1]]); + var hFactor = (br2[0] - tl[0]) / (d2[0] - hPadding); + var vFactor = (br2[1] - tl[1]) / (d2[1] - vPadding - padTop); + var hZoomDiff = Math.log(Math.abs(hFactor)) / Math.LN2; + var vZoomDiff = Math.log(Math.abs(vFactor)) / Math.LN2; + z2 = z2 - Math.max(hZoomDiff, vZoomDiff); + projection2.scale(geoZoomToScale(z2)); } - if (isFinite(Date.parse(sValue))) { - return new Date(sValue); + var extentCenter = projection2(extent.center()); + extentCenter[1] = extentCenter[1] - padTop / 2; + projection2.translate(geoVecSubtract(c2, extentCenter)).clipExtent([[0, 0], d2]); + var drawLayers = svgLayers(projection2, context).only(["osm", "touch"]).dimensions(d2); + var drawVertices = svgVertices(projection2, context); + var drawLines = svgLines(projection2, context); + var drawTurns = svgTurns(projection2, context); + var firstTime = selection2.selectAll(".surface").empty(); + selection2.call(drawLayers); + var surface = selection2.selectAll(".surface").classed("tr", true); + if (firstTime) { + _initialized3 = true; + surface.call(breathe); } - return sValue; - } - function EmptyTree() { - } - EmptyTree.prototype.toString = function() { - return "null"; - }; - EmptyTree.prototype.valueOf = function() { - return null; - }; - function objectify(vValue) { - return vValue === null ? new EmptyTree() : vValue instanceof Object ? vValue : new vValue.constructor(vValue); - } - function createObjTree(oParentNode, nVerb, bFreeze, bNesteAttr) { - var nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(), bAttributes = oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2); - var sProp, vContent, nLength = 0, sCollectedTxt = "", vResult = bHighVerb ? {} : ( - /* put here the default value for empty nodes: */ - true - ); - if (bChildren) { - for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) { - oNode = oParentNode.childNodes.item(nItem); - if (oNode.nodeType === 4) { - sCollectedTxt += oNode.nodeValue; - } else if (oNode.nodeType === 3) { - sCollectedTxt += oNode.nodeValue.trim(); - } else if (oNode.nodeType === 1 && !oNode.prefix) { - aCache.push(oNode); - } - } + if (_fromWayID && !vgraph.hasEntity(_fromWayID)) { + _fromWayID = null; + _oldTurns = null; } - var nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt); - if (!bHighVerb && (bChildren || bAttributes)) { - vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; + surface.call(utilSetDimensions, d2).call(drawVertices, vgraph, _intersection.vertices, filter2, extent, z2).call(drawLines, vgraph, _intersection.ways, filter2).call(drawTurns, vgraph, _intersection.turns(_fromWayID, _maxViaWay)); + surface.on("click.restrictions", click).on("mouseover.restrictions", mouseover); + surface.selectAll(".selected").classed("selected", false); + surface.selectAll(".related").classed("related", false); + var way; + if (_fromWayID) { + way = vgraph.entity(_fromWayID); + surface.selectAll("." + _fromWayID).classed("selected", true).classed("related", true); } - for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) { - sProp = aCache[nElId].nodeName.toLowerCase(); - vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr); - if (vResult.hasOwnProperty(sProp)) { - if (vResult[sProp].constructor !== Array) { - vResult[sProp] = [vResult[sProp]]; + document.addEventListener("resizeWindow", function() { + utilSetDimensions(_container, null); + redraw(1); + }, false); + updateHints(null); + function click(d3_event) { + surface.call(breathe.off).call(breathe); + var datum2 = d3_event.target.__data__; + var entity = datum2 && datum2.properties && datum2.properties.entity; + if (entity) { + datum2 = entity; + } + if (datum2 instanceof osmWay && (datum2.__from || datum2.__via)) { + _fromWayID = datum2.id; + _oldTurns = null; + redraw(); + } else if (datum2 instanceof osmTurn) { + var actions, extraActions, turns, i4; + var restrictionType = osmInferRestriction(vgraph, datum2, projection2); + if (datum2.restrictionID && !datum2.direct) { + return; + } else if (datum2.restrictionID && !datum2.only) { + var seen = {}; + var datumOnly = JSON.parse(JSON.stringify(datum2)); + datumOnly.only = true; + restrictionType = restrictionType.replace(/^no/, "only"); + turns = _intersection.turns(_fromWayID, 2); + extraActions = []; + _oldTurns = []; + for (i4 = 0; i4 < turns.length; i4++) { + var turn = turns[i4]; + if (seen[turn.restrictionID]) + continue; + if (turn.direct && turn.path[1] === datum2.path[1]) { + seen[turns[i4].restrictionID] = true; + turn.restrictionType = osmInferRestriction(vgraph, turn, projection2); + _oldTurns.push(turn); + extraActions.push(actionUnrestrictTurn(turn)); + } + } + actions = _intersection.actions.concat(extraActions, [ + actionRestrictTurn(datumOnly, restrictionType), + _t("operations.restriction.annotation.create") + ]); + } else if (datum2.restrictionID) { + turns = _oldTurns || []; + extraActions = []; + for (i4 = 0; i4 < turns.length; i4++) { + if (turns[i4].key !== datum2.key) { + extraActions.push(actionRestrictTurn(turns[i4], turns[i4].restrictionType)); + } + } + _oldTurns = null; + actions = _intersection.actions.concat(extraActions, [ + actionUnrestrictTurn(datum2), + _t("operations.restriction.annotation.delete") + ]); + } else { + actions = _intersection.actions.concat([ + actionRestrictTurn(datum2, restrictionType), + _t("operations.restriction.annotation.create") + ]); } - vResult[sProp].push(vContent); + context.perform.apply(context, actions); + var s2 = surface.selectAll("." + datum2.key); + datum2 = s2.empty() ? null : s2.datum(); + updateHints(datum2); } else { - vResult[sProp] = vContent; - nLength++; + _fromWayID = null; + _oldTurns = null; + redraw(); } } - if (bAttributes) { - var nAttrLen = oParentNode.attributes.length, sAPrefix = bNesteAttr ? "" : sAttrPref, oAttrParent = bNesteAttr ? {} : vResult; - for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) { - oAttrib = oParentNode.attributes.item(nAttrib); - oAttrParent[sAPrefix + oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim()); + function mouseover(d3_event) { + var datum2 = d3_event.target.__data__; + updateHints(datum2); + } + _lastXPos = _lastXPos || sdims[0]; + function redraw(minChange) { + var xPos = -1; + if (minChange) { + xPos = utilGetDimensions(context.container().select(".sidebar"))[0]; } - if (bNesteAttr) { - if (bFreeze) { - Object.freeze(oAttrParent); + if (!minChange || minChange && Math.abs(xPos - _lastXPos) >= minChange) { + if (context.hasEntity(_vertexID)) { + _lastXPos = xPos; + _container.call(renderViewer); } - vResult[sAttributesProp] = oAttrParent; - nLength -= nAttrLen - 1; } } - if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) { - vResult[sValueProp] = vBuiltVal; - } else if (!bHighVerb && nLength === 0 && sCollectedTxt) { - vResult = vBuiltVal; - } - if (bFreeze && (bHighVerb || nLength > 0)) { - Object.freeze(vResult); - } - aCache.length = nLevelStart; - return vResult; - } - function loadObjTree(oXMLDoc, oParentEl, oParentObj) { - var vValue, oChild; - if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) { - oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); - } else if (oParentObj.constructor === Date) { - oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString())); + function highlightPathsFrom(wayID) { + surface.selectAll(".related").classed("related", false).classed("allow", false).classed("restrict", false).classed("only", false); + surface.selectAll("." + wayID).classed("related", true); + if (wayID) { + var turns = _intersection.turns(wayID, _maxViaWay); + for (var i4 = 0; i4 < turns.length; i4++) { + var turn = turns[i4]; + var ids = [turn.to.way]; + var klass = turn.no ? "restrict" : turn.only ? "only" : "allow"; + if (turn.only || turns.length === 1) { + if (turn.via.ways) { + ids = ids.concat(turn.via.ways); + } + } else if (turn.to.way === wayID) { + continue; + } + surface.selectAll(utilEntitySelector(ids)).classed("related", true).classed("allow", klass === "allow").classed("restrict", klass === "restrict").classed("only", klass === "only"); + } + } } - for (var sName in oParentObj) { - vValue = oParentObj[sName]; - if (isFinite(sName) || vValue instanceof Function) { - continue; + function updateHints(datum2) { + var help = _container.selectAll(".restriction-help").html(""); + var placeholders = {}; + ["from", "via", "to"].forEach(function(k2) { + placeholders[k2] = { html: '' + _t("restriction.help." + k2) + "" }; + }); + var entity = datum2 && datum2.properties && datum2.properties.entity; + if (entity) { + datum2 = entity; } - if (sName === sValueProp) { - if (vValue !== null && vValue !== true) { - oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); + if (_fromWayID) { + way = vgraph.entity(_fromWayID); + surface.selectAll("." + _fromWayID).classed("selected", true).classed("related", true); + } + if (datum2 instanceof osmWay && datum2.__from) { + way = datum2; + highlightPathsFrom(_fromWayID ? null : way.id); + surface.selectAll("." + way.id).classed("related", true); + var clickSelect = !_fromWayID || _fromWayID !== way.id; + help.append("div").html(_t.html("restriction.help." + (clickSelect ? "select_from_name" : "from_name"), { + from: placeholders.from, + fromName: displayName(way.id, vgraph) + })); + } else if (datum2 instanceof osmTurn) { + var restrictionType = osmInferRestriction(vgraph, datum2, projection2); + var turnType = restrictionType.replace(/^(only|no)\_/, ""); + var indirect = datum2.direct === false ? _t.html("restriction.help.indirect") : ""; + var klass, turnText, nextText; + if (datum2.no) { + klass = "restrict"; + turnText = _t.html("restriction.help.turn.no_" + turnType, { indirect: { html: indirect } }); + nextText = _t.html("restriction.help.turn.only_" + turnType, { indirect: "" }); + } else if (datum2.only) { + klass = "only"; + turnText = _t.html("restriction.help.turn.only_" + turnType, { indirect: { html: indirect } }); + nextText = _t.html("restriction.help.turn.allowed_" + turnType, { indirect: "" }); + } else { + klass = "allow"; + turnText = _t.html("restriction.help.turn.allowed_" + turnType, { indirect: { html: indirect } }); + nextText = _t.html("restriction.help.turn.no_" + turnType, { indirect: "" }); } - } else if (sName === sAttributesProp) { - for (var sAttrib in vValue) { - oParentEl.setAttribute(sAttrib, vValue[sAttrib]); + help.append("div").attr("class", "qualifier " + klass).html(turnText); + help.append("div").html(_t.html("restriction.help.from_name_to_name", { + from: placeholders.from, + fromName: displayName(datum2.from.way, vgraph), + to: placeholders.to, + toName: displayName(datum2.to.way, vgraph) + })); + if (datum2.via.ways && datum2.via.ways.length) { + var names = []; + for (var i4 = 0; i4 < datum2.via.ways.length; i4++) { + var prev = names[names.length - 1]; + var curr = displayName(datum2.via.ways[i4], vgraph); + if (!prev || curr !== prev) { + names.push(curr); + } + } + help.append("div").html(_t.html("restriction.help.via_names", { + via: placeholders.via, + viaNames: names.join(", ") + })); } - } else if (sName.charAt(0) === sAttrPref) { - oParentEl.setAttribute(sName.slice(1), vValue); - } else if (vValue.constructor === Array) { - for (var nItem = 0; nItem < vValue.length; nItem++) { - oChild = oXMLDoc.createElement(sName); - loadObjTree(oXMLDoc, oChild, vValue[nItem]); - oParentEl.appendChild(oChild); + if (!indirect) { + help.append("div").html(_t.html("restriction.help.toggle", { turn: { html: nextText.trim() } })); } + highlightPathsFrom(null); + var alongIDs = datum2.path.slice(); + surface.selectAll(utilEntitySelector(alongIDs)).classed("related", true).classed("allow", klass === "allow").classed("restrict", klass === "restrict").classed("only", klass === "only"); } else { - oChild = oXMLDoc.createElement(sName); - if (vValue instanceof Object) { - loadObjTree(oXMLDoc, oChild, vValue); - } else if (vValue !== null && vValue !== true) { - oChild.appendChild(oXMLDoc.createTextNode(vValue.toString())); + highlightPathsFrom(null); + if (_fromWayID) { + help.append("div").html(_t.html("restriction.help.from_name", { + from: placeholders.from, + fromName: displayName(_fromWayID, vgraph) + })); + } else { + help.append("div").html(_t.html("restriction.help.select_from", { + from: placeholders.from + })); } - oParentEl.appendChild(oChild); } } } - this.build = function(oXMLParent, nVerbosity, bFreeze, bNesteAttributes) { - var _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : ( - /* put here the default verbosity level: */ - 1 - ); - return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3); - }; - this.unbuild = function(oObjTree) { - var oNewDoc = document.implementation.createDocument("", "", null); - loadObjTree(oNewDoc, oNewDoc, oObjTree); - return oNewDoc; - }; - this.stringify = function(oObjTree) { - return new XMLSerializer().serializeToString(JXON.unbuild(oObjTree)); - }; - }(); - - // modules/ui/sections/changes.js - function uiSectionChanges(context) { - var _discardTags = {}; - _mainFileFetcher.get("discarded").then(function(d2) { - _discardTags = d2; - }).catch(function() { - }); - var section = uiSection("changes-list", context).label(function() { - var history = context.history(); - var summary = history.difference().summary(); - return _t.append("inspector.title_count", { title: _t("commit.changes"), count: summary.length }); - }).disclosureContent(renderDisclosureContent); - function renderDisclosureContent(selection2) { - var history = context.history(); - var summary = history.difference().summary(); - var container = selection2.selectAll(".commit-section").data([0]); - var containerEnter = container.enter().append("div").attr("class", "commit-section"); - containerEnter.append("ul").attr("class", "changeset-list"); - container = containerEnter.merge(container); - var items = container.select("ul").selectAll("li").data(summary); - var itemsEnter = items.enter().append("li").attr("class", "change-item"); - var buttons = itemsEnter.append("button").on("mouseover", mouseover).on("mouseout", mouseout).on("click", click); - buttons.each(function(d2) { - select_default2(this).call(svgIcon("#iD-icon-" + d2.entity.geometry(d2.graph), "pre-text " + d2.changeType)); - }); - buttons.append("span").attr("class", "change-type").html(function(d2) { - return _t.html("commit." + d2.changeType) + " "; - }); - buttons.append("strong").attr("class", "entity-type").text(function(d2) { - var matched = _mainPresetIndex.match(d2.entity, d2.graph); - return matched && matched.name() || utilDisplayType(d2.entity.id); - }); - buttons.append("span").attr("class", "entity-name").text(function(d2) { - var name = utilDisplayName(d2.entity) || "", string = ""; - if (name !== "") { - string += ":"; - } - return string += " " + name; - }); - items = itemsEnter.merge(items); - var changeset = new osmChangeset().update({ id: void 0 }); - var changes = history.changes(actionDiscardTags(history.difference(), _discardTags)); - delete changeset.id; - var data = JXON.stringify(changeset.osmChangeJXON(changes)); - var blob = new Blob([data], { type: "text/xml;charset=utf-8;" }); - var fileName = "changes.osc"; - var linkEnter = container.selectAll(".download-changes").data([0]).enter().append("a").attr("class", "download-changes"); - linkEnter.attr("href", window.URL.createObjectURL(blob)).attr("download", fileName); - linkEnter.call(svgIcon("#iD-icon-load", "inline")).append("span").call(_t.append("commit.download_changes")); - function mouseover(d2) { - if (d2.entity) { - context.surface().selectAll( - utilEntityOrMemberSelector([d2.entity.id], context.graph()) - ).classed("hover", true); - } - } - function mouseout() { - context.surface().selectAll(".hover").classed("hover", false); - } - function click(d3_event, change) { - if (change.changeType !== "deleted") { - var entity = change.entity; - context.map().zoomToEase(entity); - context.surface().selectAll(utilEntityOrMemberSelector([entity.id], context.graph())).classed("hover", true); + function displayMaxDistance(maxDist) { + return (selection2) => { + var isImperial = !_mainLocalizer.usesMetric(); + var opts; + if (isImperial) { + var distToFeet = { + // imprecise conversion for prettier display + 20: 70, + 25: 85, + 30: 100, + 35: 115, + 40: 130, + 45: 145, + 50: 160 + }[maxDist]; + opts = { distance: _t("units.feet", { quantity: distToFeet }) }; + } else { + opts = { distance: _t("units.meters", { quantity: maxDist }) }; } - } + return selection2.html("").call(_t.append("restriction.controls.distance_up_to", opts)); + }; } - return section; - } - - // modules/ui/commit_warnings.js - function uiCommitWarnings(context) { - function commitWarnings(selection2) { - var issuesBySeverity = context.validator().getIssuesBySeverity({ what: "edited", where: "all", includeDisabledRules: true }); - for (var severity in issuesBySeverity) { - var issues = issuesBySeverity[severity]; - if (severity !== "error") { - issues = issues.filter(function(issue) { - return issue.type !== "help_request"; - }); - } - var section = severity + "-section"; - var issueItem = severity + "-item"; - var container = selection2.selectAll("." + section).data(issues.length ? [0] : []); - container.exit().remove(); - var containerEnter = container.enter().append("div").attr("class", "modal-section " + section + " fillL2"); - containerEnter.append("h3").call(severity === "warning" ? _t.append("commit.warnings") : _t.append("commit.errors")); - containerEnter.append("ul").attr("class", "changeset-list"); - container = containerEnter.merge(container); - var items = container.select("ul").selectAll("li").data(issues, function(d2) { - return d2.key; - }); - items.exit().remove(); - var itemsEnter = items.enter().append("li").attr("class", issueItem); - var buttons = itemsEnter.append("button").on("mouseover", function(d3_event, d2) { - if (d2.entityIds) { - context.surface().selectAll( - utilEntityOrMemberSelector( - d2.entityIds, - context.graph() - ) - ).classed("hover", true); - } - }).on("mouseout", function() { - context.surface().selectAll(".hover").classed("hover", false); - }).on("click", function(d3_event, d2) { - context.validator().focusIssue(d2); - }); - buttons.call(svgIcon("#iD-icon-alert", "pre-text")); - buttons.append("strong").attr("class", "issue-message"); - buttons.filter(function(d2) { - return d2.tooltip; - }).call( - uiTooltip().title(function(d2) { - return d2.tooltip; - }).placement("top") - ); - items = itemsEnter.merge(items); - items.selectAll(".issue-message").text("").each(function(d2) { - return d2.message(context)(select_default2(this)); - }); + function displayMaxVia(maxVia) { + return (selection2) => { + selection2 = selection2.html(""); + return maxVia === 0 ? selection2.call(_t.append("restriction.controls.via_node_only")) : maxVia === 1 ? selection2.call(_t.append("restriction.controls.via_up_to_one")) : selection2.call(_t.append("restriction.controls.via_up_to_two")); + }; + } + function displayName(entityID, graph) { + var entity = graph.entity(entityID); + var name = utilDisplayName(entity) || ""; + var matched = _mainPresetIndex.match(entity, graph); + var type2 = matched && matched.name() || utilDisplayType(entity.id); + return name || type2; + } + restrictions.entityIDs = function(val) { + _intersection = null; + _fromWayID = null; + _oldTurns = null; + _vertexID = val[0]; + }; + restrictions.tags = function() { + }; + restrictions.focus = function() { + }; + restrictions.off = function(selection2) { + if (!_initialized3) + return; + selection2.selectAll(".surface").call(breathe.off).on("click.restrictions", null).on("mouseover.restrictions", null); + select_default2(window).on("resize.restrictions", null); + }; + return utilRebind(restrictions, dispatch14, "on"); + } + uiFieldRestrictions.supportsMultiselection = false; + + // modules/ui/fields/textarea.js + function uiFieldTextarea(field, context) { + var dispatch14 = dispatch_default("change"); + var input = select_default2(null); + var _lengthIndicator = uiLengthIndicator(context.maxCharsForTagValue()).silent(field.usage === "changeset" && field.key === "comment"); + var _tags; + function textarea(selection2) { + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).style("position", "relative").merge(wrap2); + input = wrap2.selectAll("textarea").data([0]); + input = input.enter().append("textarea").attr("id", field.domId).call(utilNoAuto).on("input", change(true)).on("blur", change()).on("change", change()).merge(input); + wrap2.call(_lengthIndicator); + function change(onInput) { + return function() { + var val = utilGetSetValue(input); + if (!onInput) + val = context.cleanTagValue(val); + if (!val && Array.isArray(_tags[field.key])) + return; + var t2 = {}; + t2[field.key] = val || void 0; + dispatch14.call("change", this, t2, onInput); + }; } } - return commitWarnings; + textarea.tags = function(tags) { + _tags = tags; + var isMixed = Array.isArray(tags[field.key]); + utilGetSetValue(input, !isMixed && tags[field.key] ? tags[field.key] : "").attr("title", isMixed ? tags[field.key].filter(Boolean).join("\n") : void 0).attr("placeholder", isMixed ? _t("inspector.multiple_values") : field.placeholder() || _t("inspector.unknown")).classed("mixed", isMixed); + if (!isMixed) { + _lengthIndicator.update(tags[field.key]); + } + }; + textarea.focus = function() { + input.node().focus(); + }; + return utilRebind(textarea, dispatch14, "on"); } - // modules/ui/commit.js - var readOnlyTags = [ - /^changesets_count$/, - /^created_by$/, - /^ideditor:/, - /^imagery_used$/, - /^host$/, - /^locale$/, - /^warnings:/, - /^resolved:/, - /^closed:note$/, - /^closed:keepright$/, - /^closed:improveosm:/, - /^closed:osmose:/ - ]; - var hashtagRegex = /(#[^\u2000-\u206F\u2E00-\u2E7F\s\\'!"#$%()*,.\/:;<=>?@\[\]^`{|}~]+)/g; - function uiCommit(context) { - var dispatch14 = dispatch_default("cancel"); - var _userDetails2; - var _selection; - var changesetEditor = uiChangesetEditor(context).on("change", changeTags); - var rawTagEditor = uiSectionRawTagEditor("changeset-tag-editor", context).on("change", changeTags).readOnlyTags(readOnlyTags); - var commitChanges = uiSectionChanges(context); - var commitWarnings = uiCommitWarnings(context); - function commit(selection2) { + // modules/ui/fields/wikidata.js + function uiFieldWikidata(field, context) { + var wikidata = services.wikidata; + var dispatch14 = dispatch_default("change"); + var _selection = select_default2(null); + var _searchInput = select_default2(null); + var _qid = null; + var _wikidataEntity = null; + var _wikiURL = ""; + var _entityIDs = []; + var _wikipediaKey = field.keys && field.keys.find(function(key) { + return key.includes("wikipedia"); + }); + var _hintKey = field.key === "wikidata" ? "name" : field.key.split(":")[0]; + var combobox = uiCombobox(context, "combo-" + field.safeid).caseSensitive(true).minItems(1); + function wiki(selection2) { _selection = selection2; - if (!context.changeset) - initChangeset(); - loadDerivedChangesetTags(); - selection2.call(render); - } - function initChangeset() { - var commentDate = +corePreferences("commentDate") || 0; - var currDate = Date.now(); - var cutoff = 2 * 86400 * 1e3; - if (commentDate > currDate || currDate - commentDate > cutoff) { - corePreferences("comment", null); - corePreferences("hashtags", null); - corePreferences("source", null); - } - if (context.defaultChangesetComment()) { - corePreferences("comment", context.defaultChangesetComment()); - corePreferences("commentDate", Date.now()); - } - if (context.defaultChangesetSource()) { - corePreferences("source", context.defaultChangesetSource()); - corePreferences("commentDate", Date.now()); - } - if (context.defaultChangesetHashtags()) { - corePreferences("hashtags", context.defaultChangesetHashtags()); - corePreferences("commentDate", Date.now()); - } - var detected = utilDetect(); - var tags = { - comment: corePreferences("comment") || "", - created_by: context.cleanTagValue("iD " + context.version), - host: context.cleanTagValue(detected.host), - locale: context.cleanTagValue(_mainLocalizer.localeCode()) - }; - findHashtags(tags, true); - var hashtags = corePreferences("hashtags"); - if (hashtags) { - tags.hashtags = hashtags; - } - var source = corePreferences("source"); - if (source) { - tags.source = source; - } - var photoOverlaysUsed = context.history().photoOverlaysUsed(); - if (photoOverlaysUsed.length) { - var sources = (tags.source || "").split(";"); - if (sources.indexOf("streetlevel imagery") === -1) { - sources.push("streetlevel imagery"); + var wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-" + field.type).merge(wrap2); + var list2 = wrap2.selectAll("ul").data([0]); + list2 = list2.enter().append("ul").attr("class", "rows").merge(list2); + var searchRow = list2.selectAll("li.wikidata-search").data([0]); + var searchRowEnter = searchRow.enter().append("li").attr("class", "wikidata-search"); + searchRowEnter.append("input").attr("type", "text").attr("id", field.domId).style("flex", "1").call(utilNoAuto).on("focus", function() { + var node = select_default2(this).node(); + node.setSelectionRange(0, node.value.length); + }).on("blur", function() { + setLabelForEntity(); + }).call(combobox.fetcher(fetchWikidataItems)); + combobox.on("accept", function(d2) { + if (d2) { + _qid = d2.id; + change(); } - photoOverlaysUsed.forEach(function(photoOverlay) { - if (sources.indexOf(photoOverlay) === -1) { - sources.push(photoOverlay); - } - }); - tags.source = context.cleanTagValue(sources.join(";")); - } - context.changeset = new osmChangeset({ tags }); + }).on("cancel", function() { + setLabelForEntity(); + }); + searchRowEnter.append("button").attr("class", "form-field-button wiki-link").attr("title", _t("icons.view_on", { domain: "wikidata.org" })).call(svgIcon("#iD-icon-out-link")).on("click", function(d3_event) { + d3_event.preventDefault(); + if (_wikiURL) + window.open(_wikiURL, "_blank"); + }); + searchRow = searchRow.merge(searchRowEnter); + _searchInput = searchRow.select("input"); + var wikidataProperties = ["description", "identifier"]; + var items = list2.selectAll("li.labeled-input").data(wikidataProperties); + var enter = items.enter().append("li").attr("class", function(d2) { + return "labeled-input preset-wikidata-" + d2; + }); + enter.append("span").attr("class", "label").html(function(d2) { + return _t.html("wikidata." + d2); + }); + enter.append("input").attr("type", "text").call(utilNoAuto).classed("disabled", "true").attr("readonly", "true"); + enter.append("button").attr("class", "form-field-button").attr("title", _t("icons.copy")).call(svgIcon("#iD-operation-copy")).on("click", function(d3_event) { + d3_event.preventDefault(); + select_default2(this.parentNode).select("input").node().select(); + document.execCommand("copy"); + }); } - function loadDerivedChangesetTags() { - var osm = context.connection(); - if (!osm) - return; - var tags = Object.assign({}, context.changeset.tags); - var imageryUsed = context.cleanTagValue(context.history().imageryUsed().join(";")); - tags.imagery_used = imageryUsed || "None"; - var osmClosed = osm.getClosedIDs(); - var itemType; - if (osmClosed.length) { - tags["closed:note"] = context.cleanTagValue(osmClosed.join(";")); - } - if (services.keepRight) { - var krClosed = services.keepRight.getClosedIDs(); - if (krClosed.length) { - tags["closed:keepright"] = context.cleanTagValue(krClosed.join(";")); + function fetchWikidataItems(q2, callback) { + if (!q2 && _hintKey) { + for (var i3 in _entityIDs) { + var entity = context.hasEntity(_entityIDs[i3]); + if (entity.tags[_hintKey]) { + q2 = entity.tags[_hintKey]; + break; + } } } - if (services.improveOSM) { - var iOsmClosed = services.improveOSM.getClosedCounts(); - for (itemType in iOsmClosed) { - tags["closed:improveosm:" + itemType] = context.cleanTagValue(iOsmClosed[itemType].toString()); + wikidata.itemsForSearchQuery(q2, function(err, data) { + if (err) { + if (err !== "No query") + console.error(err); + return; } - } - if (services.osmose) { - var osmoseClosed = services.osmose.getClosedCounts(); - for (itemType in osmoseClosed) { - tags["closed:osmose:" + itemType] = context.cleanTagValue(osmoseClosed[itemType].toString()); + var result = data.map(function(item) { + return { + id: item.id, + value: item.display.label.value + " (" + item.id + ")", + display: (selection2) => selection2.append("span").attr("class", "localized-text").attr("lang", item.display.label.language).text(item.display.label.value), + title: item.display.description && item.display.description.value, + terms: item.aliases + }; + }); + if (callback) + callback(result); + }); + } + function change() { + var syncTags = {}; + syncTags[field.key] = _qid; + dispatch14.call("change", this, syncTags); + var initGraph = context.graph(); + var initEntityIDs = _entityIDs; + wikidata.entityByQID(_qid, function(err, entity) { + if (err) + return; + if (context.graph() !== initGraph) + return; + if (!entity.sitelinks) + return; + var langs = wikidata.languagesToQuery(); + ["labels", "descriptions"].forEach(function(key) { + if (!entity[key]) + return; + var valueLangs = Object.keys(entity[key]); + if (valueLangs.length === 0) + return; + var valueLang = valueLangs[0]; + if (langs.indexOf(valueLang) === -1) { + langs.push(valueLang); + } + }); + var newWikipediaValue; + if (_wikipediaKey) { + var foundPreferred; + for (var i3 in langs) { + var lang = langs[i3]; + var siteID = lang.replace("-", "_") + "wiki"; + if (entity.sitelinks[siteID]) { + foundPreferred = true; + newWikipediaValue = lang + ":" + entity.sitelinks[siteID].title; + break; + } + } + if (!foundPreferred) { + var wikiSiteKeys = Object.keys(entity.sitelinks).filter(function(site) { + return site.endsWith("wiki"); + }); + if (wikiSiteKeys.length === 0) { + newWikipediaValue = null; + } else { + var wikiLang = wikiSiteKeys[0].slice(0, -4).replace("_", "-"); + var wikiTitle = entity.sitelinks[wikiSiteKeys[0]].title; + newWikipediaValue = wikiLang + ":" + wikiTitle; + } + } } - } - for (var key in tags) { - if (key.match(/(^warnings:)|(^resolved:)/)) { - delete tags[key]; + if (newWikipediaValue) { + newWikipediaValue = context.cleanTagValue(newWikipediaValue); } - } - function addIssueCounts(issues, prefix) { - var issuesByType = utilArrayGroupBy(issues, "type"); - for (var issueType in issuesByType) { - var issuesOfType = issuesByType[issueType]; - if (issuesOfType[0].subtype) { - var issuesBySubtype = utilArrayGroupBy(issuesOfType, "subtype"); - for (var issueSubtype in issuesBySubtype) { - var issuesOfSubtype = issuesBySubtype[issueSubtype]; - tags[prefix + ":" + issueType + ":" + issueSubtype] = context.cleanTagValue(issuesOfSubtype.length.toString()); - } + if (typeof newWikipediaValue === "undefined") + return; + var actions = initEntityIDs.map(function(entityID) { + var entity2 = context.hasEntity(entityID); + if (!entity2) + return null; + var currTags = Object.assign({}, entity2.tags); + if (newWikipediaValue === null) { + if (!currTags[_wikipediaKey]) + return null; + delete currTags[_wikipediaKey]; } else { - tags[prefix + ":" + issueType] = context.cleanTagValue(issuesOfType.length.toString()); + currTags[_wikipediaKey] = newWikipediaValue; } + return actionChangeTags(entityID, currTags); + }).filter(Boolean); + if (!actions.length) + return; + context.overwrite( + function actionUpdateWikipediaTags(graph) { + actions.forEach(function(action) { + graph = action(graph); + }); + return graph; + }, + context.history().undoAnnotation() + ); + }); + } + function setLabelForEntity() { + var label = ""; + if (_wikidataEntity) { + label = entityPropertyForDisplay(_wikidataEntity, "labels"); + if (label.length === 0) { + label = _wikidataEntity.id.toString(); } } - var warnings = context.validator().getIssuesBySeverity({ what: "edited", where: "all", includeIgnored: true, includeDisabledRules: true }).warning.filter(function(issue) { - return issue.type !== "help_request"; - }); - addIssueCounts(warnings, "warnings"); - var resolvedIssues = context.validator().getResolvedIssues(); - addIssueCounts(resolvedIssues, "resolved"); - context.changeset = context.changeset.update({ tags }); + utilGetSetValue(_searchInput, label); } - function render(selection2) { - var osm = context.connection(); - if (!osm) + wiki.tags = function(tags) { + var isMixed = Array.isArray(tags[field.key]); + _searchInput.attr("title", isMixed ? tags[field.key].filter(Boolean).join("\n") : null).attr("placeholder", isMixed ? _t("inspector.multiple_values") : "").classed("mixed", isMixed); + _qid = typeof tags[field.key] === "string" && tags[field.key] || ""; + if (!/^Q[0-9]*$/.test(_qid)) { + unrecognized(); return; - var header = selection2.selectAll(".header").data([0]); - var headerTitle = header.enter().append("div").attr("class", "header fillL"); - headerTitle.append("div").append("h2").call(_t.append("commit.title")); - headerTitle.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function() { - dispatch14.call("cancel", this); - }).call(svgIcon("#iD-icon-close")); - var body = selection2.selectAll(".body").data([0]); - body = body.enter().append("div").attr("class", "body").merge(body); - var changesetSection = body.selectAll(".changeset-editor").data([0]); - changesetSection = changesetSection.enter().append("div").attr("class", "modal-section changeset-editor").merge(changesetSection); - changesetSection.call( - changesetEditor.changesetID(context.changeset.id).tags(context.changeset.tags) - ); - body.call(commitWarnings); - var saveSection = body.selectAll(".save-section").data([0]); - saveSection = saveSection.enter().append("div").attr("class", "modal-section save-section fillL").merge(saveSection); - var prose = saveSection.selectAll(".commit-info").data([0]); - if (prose.enter().size()) { - _userDetails2 = null; } - prose = prose.enter().append("p").attr("class", "commit-info").call(_t.append("commit.upload_explanation")).merge(prose); - osm.userDetails(function(err, user) { - if (err) - return; - if (_userDetails2 === user) + _wikiURL = "https://wikidata.org/wiki/" + _qid; + wikidata.entityByQID(_qid, function(err, entity) { + if (err) { + unrecognized(); return; - _userDetails2 = user; - var userLink = select_default2(document.createElement("div")); - if (user.image_url) { - userLink.append("img").attr("src", user.image_url).attr("class", "icon pre-text user-icon"); } - userLink.append("a").attr("class", "user-info").text(user.display_name).attr("href", osm.userURL(user.display_name)).attr("target", "_blank"); - prose.html(_t.html("commit.upload_explanation_with_user", { user: { html: userLink.html() } })); + _wikidataEntity = entity; + setLabelForEntity(); + var description = entityPropertyForDisplay(entity, "descriptions"); + _selection.select("button.wiki-link").classed("disabled", false); + _selection.select(".preset-wikidata-description").style("display", function() { + return description.length > 0 ? "flex" : "none"; + }).select("input").attr("value", description); + _selection.select(".preset-wikidata-identifier").style("display", function() { + return entity.id ? "flex" : "none"; + }).select("input").attr("value", entity.id); }); - var requestReview = saveSection.selectAll(".request-review").data([0]); - var requestReviewEnter = requestReview.enter().append("div").attr("class", "request-review"); - var requestReviewDomId = utilUniqueDomId("commit-input-request-review"); - var labelEnter = requestReviewEnter.append("label").attr("for", requestReviewDomId); - if (!labelEnter.empty()) { - labelEnter.call(uiTooltip().title(() => _t.append("commit.request_review_info")).placement("top")); + function unrecognized() { + _wikidataEntity = null; + setLabelForEntity(); + _selection.select(".preset-wikidata-description").style("display", "none"); + _selection.select(".preset-wikidata-identifier").style("display", "none"); + _selection.select("button.wiki-link").classed("disabled", true); + if (_qid && _qid !== "") { + _wikiURL = "https://wikidata.org/wiki/Special:Search?search=" + _qid; + } else { + _wikiURL = ""; + } } - labelEnter.append("input").attr("type", "checkbox").attr("id", requestReviewDomId); - labelEnter.append("span").call(_t.append("commit.request_review")); - requestReview = requestReview.merge(requestReviewEnter); - var requestReviewInput = requestReview.selectAll("input").property("checked", isReviewRequested(context.changeset.tags)).on("change", toggleRequestReview); - var buttonSection = saveSection.selectAll(".buttons").data([0]); - var buttonEnter = buttonSection.enter().append("div").attr("class", "buttons fillL"); - buttonEnter.append("button").attr("class", "secondary-action button cancel-button").append("span").attr("class", "label").call(_t.append("commit.cancel")); - var uploadButton = buttonEnter.append("button").attr("class", "action button save-button"); - uploadButton.append("span").attr("class", "label").call(_t.append("commit.save")); - var uploadBlockerTooltipText = getUploadBlockerMessage(); - buttonSection = buttonSection.merge(buttonEnter); - buttonSection.selectAll(".cancel-button").on("click.cancel", function() { - dispatch14.call("cancel", this); - }); - buttonSection.selectAll(".save-button").classed("disabled", uploadBlockerTooltipText !== null).on("click.save", function() { - if (!select_default2(this).classed("disabled")) { - this.blur(); - for (var key in context.changeset.tags) { - if (!key) - delete context.changeset.tags[key]; + }; + function entityPropertyForDisplay(wikidataEntity, propKey) { + if (!wikidataEntity[propKey]) + return ""; + var propObj = wikidataEntity[propKey]; + var langKeys = Object.keys(propObj); + if (langKeys.length === 0) + return ""; + var langs = wikidata.languagesToQuery(); + for (var i3 in langs) { + var lang = langs[i3]; + var valueObj = propObj[lang]; + if (valueObj && valueObj.value && valueObj.value.length > 0) + return valueObj.value; + } + return propObj[langKeys[0]].value; + } + wiki.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + _entityIDs = val; + return wiki; + }; + wiki.focus = function() { + _searchInput.node().focus(); + }; + return utilRebind(wiki, dispatch14, "on"); + } + + // modules/ui/fields/wikipedia.js + function uiFieldWikipedia(field, context) { + const dispatch14 = dispatch_default("change"); + const wikipedia = services.wikipedia; + const wikidata = services.wikidata; + let _langInput = select_default2(null); + let _titleInput = select_default2(null); + let _wikiURL = ""; + let _entityIDs; + let _tags; + let _dataWikipedia = []; + _mainFileFetcher.get("wmf_sitematrix").then((d2) => { + _dataWikipedia = d2; + if (_tags) + updateForTags(_tags); + }).catch(() => { + }); + const langCombo = uiCombobox(context, "wikipedia-lang").fetcher((value, callback) => { + const v2 = value.toLowerCase(); + callback( + _dataWikipedia.filter((d2) => { + return d2[0].toLowerCase().indexOf(v2) >= 0 || d2[1].toLowerCase().indexOf(v2) >= 0 || d2[2].toLowerCase().indexOf(v2) >= 0; + }).map((d2) => ({ value: d2[1] })) + ); + }); + const titleCombo = uiCombobox(context, "wikipedia-title").fetcher((value, callback) => { + if (!value) { + value = ""; + for (let i3 in _entityIDs) { + let entity = context.hasEntity(_entityIDs[i3]); + if (entity.tags.name) { + value = entity.tags.name; + break; } - context.uploader().save(context.changeset); } + } + const searchfn = value.length > 7 ? wikipedia.search : wikipedia.suggestions; + searchfn(language()[2], value, (query, data) => { + callback(data.map((d2) => ({ value: d2 }))); + }); + }); + function wiki(selection2) { + let wrap2 = selection2.selectAll(".form-field-input-wrap").data([0]); + wrap2 = wrap2.enter().append("div").attr("class", "form-field-input-wrap form-field-input-".concat(field.type)).merge(wrap2); + let langContainer = wrap2.selectAll(".wiki-lang-container").data([0]); + langContainer = langContainer.enter().append("div").attr("class", "wiki-lang-container").merge(langContainer); + _langInput = langContainer.selectAll("input.wiki-lang").data([0]); + _langInput = _langInput.enter().append("input").attr("type", "text").attr("class", "wiki-lang").attr("placeholder", _t("translate.localized_translation_language")).call(utilNoAuto).call(langCombo).merge(_langInput); + _langInput.on("blur", changeLang).on("change", changeLang); + let titleContainer = wrap2.selectAll(".wiki-title-container").data([0]); + titleContainer = titleContainer.enter().append("div").attr("class", "wiki-title-container").merge(titleContainer); + _titleInput = titleContainer.selectAll("input.wiki-title").data([0]); + _titleInput = _titleInput.enter().append("input").attr("type", "text").attr("class", "wiki-title").attr("id", field.domId).call(utilNoAuto).call(titleCombo).merge(_titleInput); + _titleInput.on("blur", function() { + change(true); + }).on("change", function() { + change(false); }); - uiTooltip().destroyAny(buttonSection.selectAll(".save-button")); - if (uploadBlockerTooltipText) { - buttonSection.selectAll(".save-button").call(uiTooltip().title(() => uploadBlockerTooltipText).placement("top")); + let link3 = titleContainer.selectAll(".wiki-link").data([0]); + link3 = link3.enter().append("button").attr("class", "form-field-button wiki-link").attr("title", _t("icons.view_on", { domain: "wikipedia.org" })).call(svgIcon("#iD-icon-out-link")).merge(link3); + link3.on("click", (d3_event) => { + d3_event.preventDefault(); + if (_wikiURL) + window.open(_wikiURL, "_blank"); + }); + } + function defaultLanguageInfo(skipEnglishFallback) { + const langCode = _mainLocalizer.languageCode().toLowerCase(); + for (let i3 in _dataWikipedia) { + let d2 = _dataWikipedia[i3]; + if (d2[2] === langCode) + return d2; } - var tagSection = body.selectAll(".tag-section.raw-tag-editor").data([0]); - tagSection = tagSection.enter().append("div").attr("class", "modal-section tag-section raw-tag-editor").merge(tagSection); - tagSection.call( - rawTagEditor.tags(Object.assign({}, context.changeset.tags)).render - ); - var changesSection = body.selectAll(".commit-changes-section").data([0]); - changesSection = changesSection.enter().append("div").attr("class", "modal-section commit-changes-section").merge(changesSection); - changesSection.call(commitChanges.render); - function toggleRequestReview() { - var rr = requestReviewInput.property("checked"); - updateChangeset({ review_requested: rr ? "yes" : void 0 }); - tagSection.call( - rawTagEditor.tags(Object.assign({}, context.changeset.tags)).render - ); + return skipEnglishFallback ? ["", "", ""] : ["English", "English", "en"]; + } + function language(skipEnglishFallback) { + const value = utilGetSetValue(_langInput).toLowerCase(); + for (let i3 in _dataWikipedia) { + let d2 = _dataWikipedia[i3]; + if (d2[0].toLowerCase() === value || d2[1].toLowerCase() === value || d2[2] === value) + return d2; } + return defaultLanguageInfo(skipEnglishFallback); } - function getUploadBlockerMessage() { - var errors = context.validator().getIssuesBySeverity({ what: "edited", where: "all" }).error; - if (errors.length) { - return _t.append("commit.outstanding_errors_message", { count: errors.length }); - } else { - var hasChangesetComment = context.changeset && context.changeset.tags.comment && context.changeset.tags.comment.trim().length; - if (!hasChangesetComment) { - return _t.append("commit.comment_needed_message"); + function changeLang() { + utilGetSetValue(_langInput, language()[1]); + change(true); + } + function change(skipWikidata) { + let value = utilGetSetValue(_titleInput); + const m2 = value.match(/https?:\/\/([-a-z]+)\.wikipedia\.org\/(?:wiki|\1-[-a-z]+)\/([^#]+)(?:#(.+))?/); + const langInfo = m2 && _dataWikipedia.find((d2) => m2[1] === d2[2]); + let syncTags = {}; + if (langInfo) { + const nativeLangName = langInfo[1]; + value = decodeURIComponent(m2[2]).replace(/_/g, " "); + if (m2[3]) { + let anchor; + anchor = decodeURIComponent(m2[3]); + value += "#" + anchor.replace(/_/g, " "); } + value = value.slice(0, 1).toUpperCase() + value.slice(1); + utilGetSetValue(_langInput, nativeLangName); + utilGetSetValue(_titleInput, value); } - return null; + if (value) { + syncTags.wikipedia = context.cleanTagValue(language()[2] + ":" + value); + } else { + syncTags.wikipedia = void 0; + } + dispatch14.call("change", this, syncTags); + if (skipWikidata || !value || !language()[2]) + return; + const initGraph = context.graph(); + const initEntityIDs = _entityIDs; + wikidata.itemsByTitle(language()[2], value, (err, data) => { + if (err || !data || !Object.keys(data).length) + return; + if (context.graph() !== initGraph) + return; + const qids = Object.keys(data); + const value2 = qids && qids.find((id2) => id2.match(/^Q\d+$/)); + let actions = initEntityIDs.map((entityID) => { + let entity = context.entity(entityID).tags; + let currTags = Object.assign({}, entity); + if (currTags.wikidata !== value2) { + currTags.wikidata = value2; + return actionChangeTags(entityID, currTags); + } + return null; + }).filter(Boolean); + if (!actions.length) + return; + context.overwrite( + function actionUpdateWikidataTags(graph) { + actions.forEach(function(action) { + graph = action(graph); + }); + return graph; + }, + context.history().undoAnnotation() + ); + }); } - function changeTags(_2, changed, onInput) { - if (changed.hasOwnProperty("comment")) { - if (changed.comment === void 0) { - changed.comment = ""; + wiki.tags = (tags) => { + _tags = tags; + updateForTags(tags); + }; + function updateForTags(tags) { + const value = typeof tags[field.key] === "string" ? tags[field.key] : ""; + const m2 = value.match(/([^:]+):([^#]+)(?:#(.+))?/); + const tagLang = m2 && m2[1]; + const tagArticleTitle = m2 && m2[2]; + let anchor = m2 && m2[3]; + const tagLangInfo = tagLang && _dataWikipedia.find((d2) => tagLang === d2[2]); + if (tagLangInfo) { + const nativeLangName = tagLangInfo[1]; + utilGetSetValue(_langInput, nativeLangName); + utilGetSetValue(_titleInput, tagArticleTitle + (anchor ? "#" + anchor : "")); + if (anchor) { + try { + anchor = encodeURIComponent(anchor.replace(/ /g, "_")).replace(/%/g, "."); + } catch (e3) { + anchor = anchor.replace(/ /g, "_"); + } } - if (!onInput) { - corePreferences("comment", changed.comment); - corePreferences("commentDate", Date.now()); + _wikiURL = "https://" + tagLang + ".wikipedia.org/wiki/" + tagArticleTitle.replace(/ /g, "_") + (anchor ? "#" + anchor : ""); + } else { + utilGetSetValue(_titleInput, value); + if (value && value !== "") { + utilGetSetValue(_langInput, ""); + const defaultLangInfo = defaultLanguageInfo(); + _wikiURL = "https://".concat(defaultLangInfo[2], ".wikipedia.org/w/index.php?fulltext=1&search=").concat(value); + } else { + const shownOrDefaultLangInfo = language( + true + /* skipEnglishFallback */ + ); + utilGetSetValue(_langInput, shownOrDefaultLangInfo[1]); + _wikiURL = ""; } } - if (changed.hasOwnProperty("source")) { - if (changed.source === void 0) { - corePreferences("source", null); - } else if (!onInput) { - corePreferences("source", changed.source); - corePreferences("commentDate", Date.now()); + } + wiki.entityIDs = (val) => { + if (!arguments.length) + return _entityIDs; + _entityIDs = val; + return wiki; + }; + wiki.focus = () => { + _titleInput.node().focus(); + }; + return utilRebind(wiki, dispatch14, "on"); + } + uiFieldWikipedia.supportsMultiselection = false; + + // modules/ui/fields/index.js + var uiFields = { + access: uiFieldAccess, + address: uiFieldAddress, + check: uiFieldCheck, + colour: uiFieldText, + combo: uiFieldCombo, + cycleway: uiFieldDirectionalCombo, + date: uiFieldText, + defaultCheck: uiFieldCheck, + directionalCombo: uiFieldDirectionalCombo, + email: uiFieldText, + identifier: uiFieldText, + lanes: uiFieldLanes, + localized: uiFieldLocalized, + roadheight: uiFieldRoadheight, + roadspeed: uiFieldRoadspeed, + manyCombo: uiFieldCombo, + multiCombo: uiFieldCombo, + networkCombo: uiFieldCombo, + number: uiFieldText, + onewayCheck: uiFieldCheck, + radio: uiFieldRadio, + restrictions: uiFieldRestrictions, + semiCombo: uiFieldCombo, + structureRadio: uiFieldRadio, + tel: uiFieldText, + text: uiFieldText, + textarea: uiFieldTextarea, + typeCombo: uiFieldCombo, + url: uiFieldText, + wikidata: uiFieldWikidata, + wikipedia: uiFieldWikipedia + }; + + // modules/ui/field.js + function uiField(context, presetField2, entityIDs, options2) { + options2 = Object.assign({ + show: true, + wrap: true, + remove: true, + revert: true, + info: true + }, options2); + var dispatch14 = dispatch_default("change", "revert"); + var field = Object.assign({}, presetField2); + field.domId = utilUniqueDomId("form-field-" + field.safeid); + var _show = options2.show; + var _state = ""; + var _tags = {}; + var _entityExtent; + if (entityIDs && entityIDs.length) { + _entityExtent = entityIDs.reduce(function(extent, entityID) { + var entity = context.graph().entity(entityID); + return extent.extend(entity.extent(context.graph())); + }, geoExtent()); + } + var _locked = false; + var _lockedTip = uiTooltip().title(() => _t.append("inspector.lock.suggestion", { label: field.title })).placement("bottom"); + if (_show && !field.impl) { + createField(); + } + function createField() { + field.impl = uiFields[field.type](field, context).on("change", function(t2, onInput) { + dispatch14.call("change", field, t2, onInput); + }); + if (entityIDs) { + field.entityIDs = entityIDs; + if (field.impl.entityIDs) { + field.impl.entityIDs(entityIDs); } } - updateChangeset(changed, onInput); - if (_selection) { - _selection.call(render); - } } - function findHashtags(tags, commentOnly) { - var detectedHashtags = commentHashtags(); - if (detectedHashtags.length) { - corePreferences("hashtags", null); - } - if (!detectedHashtags.length || !commentOnly) { - detectedHashtags = detectedHashtags.concat(hashtagHashtags()); + function allKeys() { + let keys2 = field.keys || [field.key]; + if (field.type === "directionalCombo" && field.key) { + keys2 = keys2.concat(field.key); } - var allLowerCase = /* @__PURE__ */ new Set(); - return detectedHashtags.filter(function(hashtag) { - var lowerCase = hashtag.toLowerCase(); - if (!allLowerCase.has(lowerCase)) { - allLowerCase.add(lowerCase); - return true; - } + return keys2; + } + function isModified() { + if (!entityIDs || !entityIDs.length) return false; + return entityIDs.some(function(entityID) { + var original = context.graph().base().entities[entityID]; + var latest = context.graph().entity(entityID); + return allKeys().some(function(key) { + return original ? latest.tags[key] !== original.tags[key] : latest.tags[key]; + }); }); - function commentHashtags() { - var matches = (tags.comment || "").replace(/http\S*/g, "").match(hashtagRegex); - return matches || []; - } - function hashtagHashtags() { - var matches = (tags.hashtags || "").split(/[,;\s]+/).map(function(s2) { - if (s2[0] !== "#") { - s2 = "#" + s2; + } + function tagsContainFieldKey() { + return allKeys().some(function(key) { + if (field.type === "multiCombo") { + for (var tagKey in _tags) { + if (tagKey.indexOf(key) === 0) { + return true; + } } - var matched = s2.match(hashtagRegex); - return matched && matched[0]; - }).filter(Boolean); - return matches || []; - } + return false; + } + return _tags[key] !== void 0; + }); } - function isReviewRequested(tags) { - var rr = tags.review_requested; - if (rr === void 0) - return false; - rr = rr.trim().toLowerCase(); - return !(rr === "" || rr === "no"); + function revert(d3_event, d2) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + if (!entityIDs || _locked) + return; + dispatch14.call("revert", d2, allKeys()); } - function updateChangeset(changed, onInput) { - var tags = Object.assign({}, context.changeset.tags); - Object.keys(changed).forEach(function(k2) { - var v2 = changed[k2]; - k2 = context.cleanTagKey(k2); - if (readOnlyTags.indexOf(k2) !== -1) - return; - if (v2 === void 0) { - delete tags[k2]; - } else if (onInput) { - tags[k2] = v2; - } else { - tags[k2] = context.cleanTagValue(v2); - } + function remove2(d3_event, d2) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + if (_locked) + return; + var t2 = {}; + allKeys().forEach(function(key) { + t2[key] = void 0; }); - if (!onInput) { - var commentOnly = changed.hasOwnProperty("comment") && changed.comment !== ""; - var arr = findHashtags(tags, commentOnly); - if (arr.length) { - tags.hashtags = context.cleanTagValue(arr.join(";")); - corePreferences("hashtags", tags.hashtags); - } else { - delete tags.hashtags; - corePreferences("hashtags", null); + dispatch14.call("change", d2, t2); + } + field.render = function(selection2) { + var container = selection2.selectAll(".form-field").data([field]); + var enter = container.enter().append("div").attr("class", function(d2) { + return "form-field form-field-" + d2.safeid; + }).classed("nowrap", !options2.wrap); + if (options2.wrap) { + var labelEnter = enter.append("label").attr("class", "field-label").attr("for", function(d2) { + return d2.domId; + }); + var textEnter = labelEnter.append("span").attr("class", "label-text"); + textEnter.append("span").attr("class", "label-textvalue").each(function(d2) { + d2.label()(select_default2(this)); + }); + textEnter.append("span").attr("class", "label-textannotation"); + if (options2.remove) { + labelEnter.append("button").attr("class", "remove-icon").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")); + } + if (options2.revert) { + labelEnter.append("button").attr("class", "modified-icon").attr("title", _t("icons.undo")).call(svgIcon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-redo" : "#iD-icon-undo")); } } - if (_userDetails2 && _userDetails2.changesets_count !== void 0) { - var changesetsCount = parseInt(_userDetails2.changesets_count, 10) + 1; - tags.changesets_count = String(changesetsCount); - if (changesetsCount <= 100) { - var s2; - s2 = corePreferences("walkthrough_completed"); - if (s2) { - tags["ideditor:walkthrough_completed"] = s2; - } - s2 = corePreferences("walkthrough_progress"); - if (s2) { - tags["ideditor:walkthrough_progress"] = s2; + container = container.merge(enter); + container.select(".field-label > .remove-icon").on("click", remove2); + container.select(".field-label > .modified-icon").on("click", revert); + container.each(function(d2) { + var selection3 = select_default2(this); + if (!d2.impl) { + createField(); + } + var reference, help; + if (options2.wrap && field.type === "restrictions") { + help = uiFieldHelp(context, "restrictions"); + } + if (options2.wrap && options2.info) { + var referenceKey = d2.key || ""; + if (d2.type === "multiCombo") { + referenceKey = referenceKey.replace(/:$/, ""); } - s2 = corePreferences("walkthrough_started"); - if (s2) { - tags["ideditor:walkthrough_started"] = s2; + var referenceOptions = d2.reference || { + key: referenceKey, + value: _tags[referenceKey] + }; + reference = uiTagReference(referenceOptions, context); + if (_state === "hover") { + reference.showing(false); } } - } else { - delete tags.changesets_count; + selection3.call(d2.impl); + if (help) { + selection3.call(help.body).select(".field-label").call(help.button); + } + if (reference) { + selection3.call(reference.body).select(".field-label").call(reference.button); + } + d2.impl.tags(_tags); + }); + container.classed("locked", _locked).classed("modified", isModified()).classed("present", tagsContainFieldKey()); + var annotation = container.selectAll(".field-label .label-textannotation"); + var icon2 = annotation.selectAll(".icon").data(_locked ? [0] : []); + icon2.exit().remove(); + icon2.enter().append("svg").attr("class", "icon").append("use").attr("xlink:href", "#fas-lock"); + container.call(_locked ? _lockedTip : _lockedTip.destroy); + }; + field.state = function(val) { + if (!arguments.length) + return _state; + _state = val; + return field; + }; + field.tags = function(val) { + if (!arguments.length) + return _tags; + _tags = val; + if (tagsContainFieldKey() && !_show) { + _show = true; + if (!field.impl) { + createField(); + } } - if (!(0, import_fast_deep_equal9.default)(context.changeset.tags, tags)) { - context.changeset = context.changeset.update({ tags }); + return field; + }; + field.locked = function(val) { + if (!arguments.length) + return _locked; + _locked = val; + return field; + }; + field.show = function() { + _show = true; + if (!field.impl) { + createField(); + } + if (field.default && field.key && _tags[field.key] !== field.default) { + var t2 = {}; + t2[field.key] = field.default; + dispatch14.call("change", this, t2); } - } - commit.reset = function() { - context.changeset = null; }; - return utilRebind(commit, dispatch14, "on"); - } - - // modules/ui/confirm.js - function uiConfirm(selection2) { - var modalSelection = uiModal(selection2); - modalSelection.select(".modal").classed("modal-alert", true); - var section = modalSelection.select(".content"); - section.append("div").attr("class", "modal-section header"); - section.append("div").attr("class", "modal-section message-text"); - var buttons = section.append("div").attr("class", "modal-section buttons cf"); - modalSelection.okButton = function() { - buttons.append("button").attr("class", "button ok-button action").on("click.confirm", function() { - modalSelection.remove(); - }).call(_t.append("confirm.okay")).node().focus(); - return modalSelection; + field.isShown = function() { + return _show; + }; + field.isAllowed = function() { + if (entityIDs && entityIDs.length > 1 && uiFields[field.type].supportsMultiselection === false) + return false; + if (field.geometry && !entityIDs.every(function(entityID) { + return field.matchGeometry(context.graph().geometry(entityID)); + })) + return false; + if (entityIDs && _entityExtent && field.locationSetID) { + var validHere = _sharedLocationManager.locationSetsAt(_entityExtent.center()); + if (!validHere[field.locationSetID]) + return false; + } + var prerequisiteTag = field.prerequisiteTag; + if (entityIDs && !tagsContainFieldKey() && // ignore tagging prerequisites if a value is already present + prerequisiteTag) { + if (!entityIDs.every(function(entityID) { + var entity = context.graph().entity(entityID); + if (prerequisiteTag.key) { + var value = entity.tags[prerequisiteTag.key]; + if (!value) + return false; + if (prerequisiteTag.valueNot) { + return prerequisiteTag.valueNot !== value; + } + if (prerequisiteTag.value) { + return prerequisiteTag.value === value; + } + } else if (prerequisiteTag.keyNot) { + if (entity.tags[prerequisiteTag.keyNot]) + return false; + } + return true; + })) + return false; + } + return true; + }; + field.focus = function() { + if (field.impl) { + field.impl.focus(); + } }; - return modalSelection; + return utilRebind(field, dispatch14, "on"); } - // modules/ui/conflicts.js - function uiConflicts(context) { - var dispatch14 = dispatch_default("cancel", "save"); - var keybinding = utilKeybinding("conflicts"); - var _origChanges; - var _conflictList; - var _shownConflictIndex; - function keybindingOn() { - select_default2(document).call(keybinding.on("\u238B", cancel, true)); - } - function keybindingOff() { - select_default2(document).call(keybinding.unbind); - } - function tryAgain() { - keybindingOff(); - dispatch14.call("save"); - } - function cancel() { - keybindingOff(); - dispatch14.call("cancel"); - } - function conflicts(selection2) { - keybindingOn(); - var headerEnter = selection2.selectAll(".header").data([0]).enter().append("div").attr("class", "header fillL"); - headerEnter.append("button").attr("class", "fr").attr("title", _t("icons.close")).on("click", cancel).call(svgIcon("#iD-icon-close")); - headerEnter.append("h2").call(_t.append("save.conflict.header")); - var bodyEnter = selection2.selectAll(".body").data([0]).enter().append("div").attr("class", "body fillL"); - var conflictsHelpEnter = bodyEnter.append("div").attr("class", "conflicts-help").call(_t.append("save.conflict.help")); - var changeset = new osmChangeset(); - delete changeset.id; - var data = JXON.stringify(changeset.osmChangeJXON(_origChanges)); - var blob = new Blob([data], { type: "text/xml;charset=utf-8;" }); - var fileName = "changes.osc"; - var linkEnter = conflictsHelpEnter.selectAll(".download-changes").append("a").attr("class", "download-changes"); - linkEnter.attr("href", window.URL.createObjectURL(blob)).attr("download", fileName); - linkEnter.call(svgIcon("#iD-icon-load", "inline")).append("span").call(_t.append("save.conflict.download_changes")); - bodyEnter.append("div").attr("class", "conflict-container fillL3").call(showConflict, 0); - bodyEnter.append("div").attr("class", "conflicts-done").attr("opacity", 0).style("display", "none").call(_t.append("save.conflict.done")); - var buttonsEnter = bodyEnter.append("div").attr("class", "buttons col12 joined conflicts-buttons"); - buttonsEnter.append("button").attr("disabled", _conflictList.length > 1).attr("class", "action conflicts-button col6").call(_t.append("save.title")).on("click.try_again", tryAgain); - buttonsEnter.append("button").attr("class", "secondary-action conflicts-button col6").call(_t.append("confirm.cancel")).on("click.cancel", cancel); - } - function showConflict(selection2, index) { - index = utilWrap(index, _conflictList.length); - _shownConflictIndex = index; - var parent = select_default2(selection2.node().parentNode); - if (index === _conflictList.length - 1) { - window.setTimeout(function() { - parent.select(".conflicts-button").attr("disabled", null); - parent.select(".conflicts-done").transition().attr("opacity", 1).style("display", "block"); - }, 250); - } - var conflict = selection2.selectAll(".conflict").data([_conflictList[index]]); - conflict.exit().remove(); - var conflictEnter = conflict.enter().append("div").attr("class", "conflict"); - conflictEnter.append("h4").attr("class", "conflict-count").call(_t.append("save.conflict.count", { num: index + 1, total: _conflictList.length })); - conflictEnter.append("a").attr("class", "conflict-description").attr("href", "#").text(function(d2) { - return d2.name; - }).on("click", function(d3_event, d2) { - d3_event.preventDefault(); - zoomToEntity(d2.id); - }); - var details = conflictEnter.append("div").attr("class", "conflict-detail-container"); - details.append("ul").attr("class", "conflict-detail-list").selectAll("li").data(function(d2) { - return d2.details || []; - }).enter().append("li").attr("class", "conflict-detail-item").html(function(d2) { - return d2; + // modules/ui/form_fields.js + function uiFormFields(context) { + var moreCombo = uiCombobox(context, "more-fields").minItems(1); + var _fieldsArr = []; + var _lastPlaceholder = ""; + var _state = ""; + var _klass = ""; + function formFields(selection2) { + var allowedFields = _fieldsArr.filter(function(field) { + return field.isAllowed(); }); - details.append("div").attr("class", "conflict-choices").call(addChoices); - details.append("div").attr("class", "conflict-nav-buttons joined cf").selectAll("button").data(["previous", "next"]).enter().append("button").attr("class", "conflict-nav-button action col6").attr("disabled", function(d2, i3) { - return i3 === 0 && index === 0 || i3 === 1 && index === _conflictList.length - 1 || null; - }).on("click", function(d3_event, d2) { - d3_event.preventDefault(); - var container = parent.selectAll(".conflict-container"); - var sign2 = d2 === "previous" ? -1 : 1; - container.selectAll(".conflict").remove(); - container.call(showConflict, index + sign2); - }).each(function(d2) { - _t.append("save.conflict." + d2)(select_default2(this)); + var shown = allowedFields.filter(function(field) { + return field.isShown(); }); - } - function addChoices(selection2) { - var choices = selection2.append("ul").attr("class", "layer-list").selectAll("li").data(function(d2) { - return d2.choices || []; + var notShown = allowedFields.filter(function(field) { + return !field.isShown(); }); - var choicesEnter = choices.enter().append("li").attr("class", "layer"); - var labelEnter = choicesEnter.append("label"); - labelEnter.append("input").attr("type", "radio").attr("name", function(d2) { - return d2.id; - }).on("change", function(d3_event, d2) { - var ul = this.parentNode.parentNode.parentNode; - ul.__data__.chosen = d2.id; - choose(d3_event, ul, d2); + var container = selection2.selectAll(".form-fields-container").data([0]); + container = container.enter().append("div").attr("class", "form-fields-container " + (_klass || "")).merge(container); + var fields = container.selectAll(".wrap-form-field").data(shown, function(d2) { + return d2.id + (d2.entityIDs ? d2.entityIDs.join() : ""); }); - labelEnter.append("span").text(function(d2) { - return d2.text; + fields.exit().remove(); + var enter = fields.enter().append("div").attr("class", function(d2) { + return "wrap-form-field wrap-form-field-" + d2.safeid; }); - choicesEnter.merge(choices).each(function(d2) { - var ul = this.parentNode; - if (ul.__data__.chosen === d2.id) { - choose(null, ul, d2); - } + fields = fields.merge(enter); + fields.order().each(function(d2) { + select_default2(this).call(d2.render); }); - } - function choose(d3_event, ul, datum2) { - if (d3_event) - d3_event.preventDefault(); - select_default2(ul).selectAll("li").classed("active", function(d2) { - return d2 === datum2; - }).selectAll("input").property("checked", function(d2) { - return d2 === datum2; + var titles = []; + var moreFields = notShown.map(function(field) { + var title = field.title(); + titles.push(title); + var terms = field.terms(); + if (field.key) + terms.push(field.key); + if (field.keys) + terms = terms.concat(field.keys); + return { + display: field.label(), + value: title, + title, + field, + terms + }; }); - var extent = geoExtent(); - var entity; - entity = context.graph().hasEntity(datum2.id); - if (entity) - extent._extend(entity.extent(context.graph())); - datum2.action(); - entity = context.graph().hasEntity(datum2.id); - if (entity) - extent._extend(entity.extent(context.graph())); - zoomToEntity(datum2.id, extent); - } - function zoomToEntity(id2, extent) { - context.surface().selectAll(".hover").classed("hover", false); - var entity = context.graph().hasEntity(id2); - if (entity) { - if (extent) { - context.map().trimmedExtent(extent); - } else { - context.map().zoomToEase(entity); - } - context.surface().selectAll(utilEntityOrMemberSelector([entity.id], context.graph())).classed("hover", true); + var placeholder = titles.slice(0, 3).join(", ") + (titles.length > 3 ? "\u2026" : ""); + var more = selection2.selectAll(".more-fields").data(_state === "hover" || moreFields.length === 0 ? [] : [0]); + more.exit().remove(); + var moreEnter = more.enter().append("div").attr("class", "more-fields").append("label"); + moreEnter.append("span").call(_t.append("inspector.add_fields")); + more = moreEnter.merge(more); + var input = more.selectAll(".value").data([0]); + input.exit().remove(); + input = input.enter().append("input").attr("class", "value").attr("type", "text").attr("placeholder", placeholder).call(utilNoAuto).merge(input); + input.call(utilGetSetValue, "").call( + moreCombo.data(moreFields).on("accept", function(d2) { + if (!d2) + return; + var field = d2.field; + field.show(); + selection2.call(formFields); + field.focus(); + }) + ); + if (_lastPlaceholder !== placeholder) { + input.attr("placeholder", placeholder); + _lastPlaceholder = placeholder; } } - conflicts.conflictList = function(_2) { + formFields.fieldsArr = function(val) { if (!arguments.length) - return _conflictList; - _conflictList = _2; - return conflicts; + return _fieldsArr; + _fieldsArr = val || []; + return formFields; }; - conflicts.origChanges = function(_2) { + formFields.state = function(val) { if (!arguments.length) - return _origChanges; - _origChanges = _2; - return conflicts; + return _state; + _state = val; + return formFields; }; - conflicts.shownEntityIds = function() { - if (_conflictList && typeof _shownConflictIndex === "number") { - return [_conflictList[_shownConflictIndex].id]; - } - return []; + formFields.klass = function(val) { + if (!arguments.length) + return _klass; + _klass = val; + return formFields; }; - return utilRebind(conflicts, dispatch14, "on"); + return formFields; } - // modules/ui/entity_editor.js - var import_fast_deep_equal10 = __toESM(require_fast_deep_equal()); - - // modules/ui/sections/entity_issues.js - function uiSectionEntityIssues(context) { - var preference = corePreferences("entity-issues.reference.expanded"); - var _expanded = preference === null ? true : preference === "true"; - var _entityIDs = []; - var _issues = []; - var _activeIssueID; - var section = uiSection("entity-issues", context).shouldDisplay(function() { - return _issues.length > 0; - }).label(function() { - return _t.append("inspector.title_count", { title: _t("issues.list_title"), count: _issues.length }); - }).disclosureContent(renderDisclosureContent); - context.validator().on("validated.entity_issues", function() { - reloadIssues(); - section.reRender(); - }).on("focusedIssue.entity_issues", function(issue) { - makeActiveIssue(issue.id); - }); - function reloadIssues() { - _issues = context.validator().getSharedEntityIssues(_entityIDs, { includeDisabledRules: true }); - } - function makeActiveIssue(issueID) { - _activeIssueID = issueID; - section.selection().selectAll(".issue-container").classed("active", function(d2) { - return d2.id === _activeIssueID; - }); + // modules/ui/changeset_editor.js + function uiChangesetEditor(context) { + var dispatch14 = dispatch_default("change"); + var formFields = uiFormFields(context); + var commentCombo = uiCombobox(context, "comment").caseSensitive(true); + var _fieldsArr; + var _tags; + var _changesetID; + function changesetEditor(selection2) { + render(selection2); } - function renderDisclosureContent(selection2) { - selection2.classed("grouped-items-area", true); - _activeIssueID = _issues.length > 0 ? _issues[0].id : null; - var containers = selection2.selectAll(".issue-container").data(_issues, function(d2) { - return d2.key; - }); - containers.exit().remove(); - var containersEnter = containers.enter().append("div").attr("class", "issue-container"); - var itemsEnter = containersEnter.append("div").attr("class", function(d2) { - return "issue severity-" + d2.severity; - }).on("mouseover.highlight", function(d3_event, d2) { - var ids = d2.entityIds.filter(function(e3) { - return _entityIDs.indexOf(e3) === -1; - }); - utilHighlightEntities(ids, true, context); - }).on("mouseout.highlight", function(d3_event, d2) { - var ids = d2.entityIds.filter(function(e3) { - return _entityIDs.indexOf(e3) === -1; + function render(selection2) { + var initial = false; + if (!_fieldsArr) { + initial = true; + var presets = _mainPresetIndex; + _fieldsArr = [ + uiField(context, presets.field("comment"), null, { show: true, revert: false }), + uiField(context, presets.field("source"), null, { show: true, revert: false }), + uiField(context, presets.field("hashtags"), null, { show: false, revert: false }) + ]; + _fieldsArr.forEach(function(field) { + field.on("change", function(t2, onInput) { + dispatch14.call("change", field, void 0, t2, onInput); + }); }); - utilHighlightEntities(ids, false, context); + } + _fieldsArr.forEach(function(field) { + field.tags(_tags); }); - var labelsEnter = itemsEnter.append("div").attr("class", "issue-label"); - var textEnter = labelsEnter.append("button").attr("class", "issue-text").on("click", function(d3_event, d2) { - makeActiveIssue(d2.id); - var extent = d2.extent(context.graph()); - if (extent) { - var setZoom = Math.max(context.map().zoom(), 19); - context.map().unobscuredCenterZoomEase(extent.center(), setZoom); + selection2.call(formFields.fieldsArr(_fieldsArr)); + if (initial) { + var commentField = selection2.select(".form-field-comment textarea"); + var commentNode = commentField.node(); + if (commentNode) { + commentNode.focus(); + commentNode.select(); } - }); - textEnter.each(function(d2) { - var iconName = "#iD-icon-" + (d2.severity === "warning" ? "alert" : "error"); - select_default2(this).call(svgIcon(iconName, "issue-icon")); - }); - textEnter.append("span").attr("class", "issue-message"); - var infoButton = labelsEnter.append("button").attr("class", "issue-info-button").attr("title", _t("icons.information")).call(svgIcon("#iD-icon-inspect")); - infoButton.on("click", function(d3_event) { - d3_event.stopPropagation(); - d3_event.preventDefault(); - this.blur(); - var container = select_default2(this.parentNode.parentNode.parentNode); - var info = container.selectAll(".issue-info"); - var isExpanded = info.classed("expanded"); - _expanded = !isExpanded; - corePreferences("entity-issues.reference.expanded", _expanded); - if (isExpanded) { - info.transition().duration(200).style("max-height", "0px").style("opacity", "0").on("end", function() { - info.classed("expanded", false); - }); - } else { - info.classed("expanded", true).transition().duration(200).style("max-height", "200px").style("opacity", "1").on("end", function() { - info.style("max-height", null); + utilTriggerEvent(commentField, "blur"); + var osm = context.connection(); + if (osm) { + osm.userChangesets(function(err, changesets) { + if (err) + return; + var comments = changesets.map(function(changeset) { + var comment = changeset.tags.comment; + return comment ? { title: comment, value: comment } : null; + }).filter(Boolean); + commentField.call( + commentCombo.data(utilArrayUniqBy(comments, "title")) + ); }); } - }); - itemsEnter.append("ul").attr("class", "issue-fix-list"); - containersEnter.append("div").attr("class", "issue-info" + (_expanded ? " expanded" : "")).style("max-height", _expanded ? null : "0").style("opacity", _expanded ? "1" : "0").each(function(d2) { - if (typeof d2.reference === "function") { - select_default2(this).call(d2.reference); - } else { - select_default2(this).call(_t.append("inspector.no_documentation_key")); + } + const warnings = []; + if (_tags.comment.match(/google/i)) { + warnings.push({ + id: 'contains "google"', + msg: _t.append("commit.google_warning"), + link: _t("commit.google_warning_link") + }); + } + const maxChars = context.maxCharsForTagValue(); + const strLen = utilUnicodeCharsCount(utilCleanOsmString(_tags.comment, Number.POSITIVE_INFINITY)); + if (strLen > maxChars || false) { + warnings.push({ + id: "message too long", + msg: _t.append("commit.changeset_comment_length_warning", { maxChars }) + }); + } + var commentWarning = selection2.select(".form-field-comment").selectAll(".comment-warning").data(warnings, (d2) => d2.id); + commentWarning.exit().transition().duration(200).style("opacity", 0).remove(); + var commentEnter = commentWarning.enter().insert("div", ".comment-warning").attr("class", "comment-warning field-warning").style("opacity", 0); + commentEnter.call(svgIcon("#iD-icon-alert", "inline")).append("span"); + commentEnter.transition().duration(200).style("opacity", 1); + commentWarning.merge(commentEnter).selectAll("div > span").text("").each(function(d2) { + let selection3 = select_default2(this); + if (d2.link) { + selection3 = selection3.append("a").attr("target", "_blank").attr("href", d2.link); } + selection3.call(d2.msg); }); - containers = containers.merge(containersEnter).classed("active", function(d2) { - return d2.id === _activeIssueID; - }); - containers.selectAll(".issue-message").text("").each(function(d2) { - return d2.message(context)(select_default2(this)); - }); - var fixLists = containers.selectAll(".issue-fix-list"); - var fixes = fixLists.selectAll(".issue-fix-item").data(function(d2) { - return d2.fixes ? d2.fixes(context) : []; - }, function(fix) { - return fix.id; - }); - fixes.exit().remove(); - var fixesEnter = fixes.enter().append("li").attr("class", "issue-fix-item"); - var buttons = fixesEnter.append("button").on("click", function(d3_event, d2) { - if (select_default2(this).attr("disabled") || !d2.onClick) - return; - if (d2.issue.dateLastRanFix && /* @__PURE__ */ new Date() - d2.issue.dateLastRanFix < 1e3) - return; - d2.issue.dateLastRanFix = /* @__PURE__ */ new Date(); - utilHighlightEntities(d2.issue.entityIds.concat(d2.entityIds), false, context); - new Promise(function(resolve, reject) { - d2.onClick(context, resolve, reject); - if (d2.onClick.length <= 1) { - resolve(); + } + changesetEditor.tags = function(_2) { + if (!arguments.length) + return _tags; + _tags = _2; + return changesetEditor; + }; + changesetEditor.changesetID = function(_2) { + if (!arguments.length) + return _changesetID; + if (_changesetID === _2) + return changesetEditor; + _changesetID = _2; + _fieldsArr = null; + return changesetEditor; + }; + return utilRebind(changesetEditor, dispatch14, "on"); + } + + // modules/ui/commit.js + var import_fast_deep_equal9 = __toESM(require_fast_deep_equal()); + + // modules/util/jxon.js + var JXON = new function() { + var sValueProp = "keyValue", sAttributesProp = "keyAttributes", sAttrPref = "@", aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i; + function parseText(sValue) { + if (rIsNull.test(sValue)) { + return null; + } + if (rIsBool.test(sValue)) { + return sValue.toLowerCase() === "true"; + } + if (isFinite(sValue)) { + return parseFloat(sValue); + } + if (isFinite(Date.parse(sValue))) { + return new Date(sValue); + } + return sValue; + } + function EmptyTree() { + } + EmptyTree.prototype.toString = function() { + return "null"; + }; + EmptyTree.prototype.valueOf = function() { + return null; + }; + function objectify(vValue) { + return vValue === null ? new EmptyTree() : vValue instanceof Object ? vValue : new vValue.constructor(vValue); + } + function createObjTree(oParentNode, nVerb, bFreeze, bNesteAttr) { + var nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(), bAttributes = oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2); + var sProp, vContent, nLength = 0, sCollectedTxt = "", vResult = bHighVerb ? {} : ( + /* put here the default value for empty nodes: */ + true + ); + if (bChildren) { + for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) { + oNode = oParentNode.childNodes.item(nItem); + if (oNode.nodeType === 4) { + sCollectedTxt += oNode.nodeValue; + } else if (oNode.nodeType === 3) { + sCollectedTxt += oNode.nodeValue.trim(); + } else if (oNode.nodeType === 1 && !oNode.prefix) { + aCache.push(oNode); } - }).then(function() { - context.validator().validate(); - }); - }).on("mouseover.highlight", function(d3_event, d2) { - utilHighlightEntities(d2.entityIds, true, context); - }).on("mouseout.highlight", function(d3_event, d2) { - utilHighlightEntities(d2.entityIds, false, context); - }); - buttons.each(function(d2) { - var iconName = d2.icon || "iD-icon-wrench"; - if (iconName.startsWith("maki")) { - iconName += "-15"; } - select_default2(this).call(svgIcon("#" + iconName, "fix-icon")); - }); - buttons.append("span").attr("class", "fix-message").each(function(d2) { - return d2.title(select_default2(this)); - }); - fixesEnter.merge(fixes).selectAll("button").classed("actionable", function(d2) { - return d2.onClick; - }).attr("disabled", function(d2) { - return d2.onClick ? null : "true"; - }).attr("title", function(d2) { - if (d2.disabledReason) { - return d2.disabledReason; + } + var nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt); + if (!bHighVerb && (bChildren || bAttributes)) { + vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; + } + for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) { + sProp = aCache[nElId].nodeName.toLowerCase(); + vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr); + if (vResult.hasOwnProperty(sProp)) { + if (vResult[sProp].constructor !== Array) { + vResult[sProp] = [vResult[sProp]]; + } + vResult[sProp].push(vContent); + } else { + vResult[sProp] = vContent; + nLength++; + } + } + if (bAttributes) { + var nAttrLen = oParentNode.attributes.length, sAPrefix = bNesteAttr ? "" : sAttrPref, oAttrParent = bNesteAttr ? {} : vResult; + for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) { + oAttrib = oParentNode.attributes.item(nAttrib); + oAttrParent[sAPrefix + oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim()); + } + if (bNesteAttr) { + if (bFreeze) { + Object.freeze(oAttrParent); + } + vResult[sAttributesProp] = oAttrParent; + nLength -= nAttrLen - 1; } - return null; - }); - } - section.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - if (!_entityIDs || !val || !utilArrayIdentical(_entityIDs, val)) { - _entityIDs = val; - _activeIssueID = null; - reloadIssues(); } - return section; - }; - return section; - } - - // modules/ui/preset_icon.js - function uiPresetIcon() { - let _preset; - let _geometry; - function presetIcon(selection2) { - selection2.each(render); - } - function getIcon(p2, geom) { - if (p2.isFallback && p2.isFallback()) - return geom === "vertex" ? "" : "iD-icon-" + p2.id; - if (p2.icon) - return p2.icon; - if (geom === "line") - return "iD-other-line"; - if (geom === "vertex") - return "temaki-vertex"; - return "maki-marker-stroked"; - } - function renderPointBorder(container, drawPoint) { - let pointBorder = container.selectAll(".preset-icon-point-border").data(drawPoint ? [0] : []); - pointBorder.exit().remove(); - let pointBorderEnter = pointBorder.enter(); - const w2 = 40; - const h2 = 40; - pointBorderEnter.append("svg").attr("class", "preset-icon-fill preset-icon-point-border").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)).append("path").attr("transform", "translate(11.5, 8)").attr("d", "M 17,8 C 17,13 11,21 8.5,23.5 C 6,21 0,13 0,8 C 0,4 4,-0.5 8.5,-0.5 C 13,-0.5 17,4 17,8 z"); - pointBorder = pointBorderEnter.merge(pointBorder); - } - function renderCategoryBorder(container, category) { - let categoryBorder = container.selectAll(".preset-icon-category-border").data(category ? [0] : []); - categoryBorder.exit().remove(); - let categoryBorderEnter = categoryBorder.enter(); - const d2 = 60; - let svgEnter = categoryBorderEnter.append("svg").attr("class", "preset-icon-fill preset-icon-category-border").attr("width", d2).attr("height", d2).attr("viewBox", "0 0 ".concat(d2, " ").concat(d2)); - svgEnter.append("path").attr("class", "area").attr("d", "M9.5,7.5 L25.5,7.5 L28.5,12.5 L49.5,12.5 C51.709139,12.5 53.5,14.290861 53.5,16.5 L53.5,43.5 C53.5,45.709139 51.709139,47.5 49.5,47.5 L10.5,47.5 C8.290861,47.5 6.5,45.709139 6.5,43.5 L6.5,12.5 L9.5,7.5 Z"); - categoryBorder = categoryBorderEnter.merge(categoryBorder); - if (category) { - categoryBorder.selectAll("path").attr("class", "area ".concat(category.id)); + if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) { + vResult[sValueProp] = vBuiltVal; + } else if (!bHighVerb && nLength === 0 && sCollectedTxt) { + vResult = vBuiltVal; } + if (bFreeze && (bHighVerb || nLength > 0)) { + Object.freeze(vResult); + } + aCache.length = nLevelStart; + return vResult; } - function renderCircleFill(container, drawVertex) { - let vertexFill = container.selectAll(".preset-icon-fill-vertex").data(drawVertex ? [0] : []); - vertexFill.exit().remove(); - let vertexFillEnter = vertexFill.enter(); - const w2 = 60; - const h2 = 60; - const d2 = 40; - vertexFillEnter.append("svg").attr("class", "preset-icon-fill preset-icon-fill-vertex").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)).append("circle").attr("cx", w2 / 2).attr("cy", h2 / 2).attr("r", d2 / 2); - vertexFill = vertexFillEnter.merge(vertexFill); - } - function renderSquareFill(container, drawArea, tagClasses) { - let fill = container.selectAll(".preset-icon-fill-area").data(drawArea ? [0] : []); - fill.exit().remove(); - let fillEnter = fill.enter(); - const d2 = 60; - const w2 = d2; - const h2 = d2; - const l2 = d2 * 2 / 3; - const c1 = (w2 - l2) / 2; - const c2 = c1 + l2; - fillEnter = fillEnter.append("svg").attr("class", "preset-icon-fill preset-icon-fill-area").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)); - ["fill", "stroke"].forEach((klass) => { - fillEnter.append("path").attr("d", "M".concat(c1, " ").concat(c1, " L").concat(c1, " ").concat(c2, " L").concat(c2, " ").concat(c2, " L").concat(c2, " ").concat(c1, " Z")).attr("class", "area ".concat(klass)); - }); - const rVertex = 2.5; - [[c1, c1], [c1, c2], [c2, c2], [c2, c1]].forEach((point2) => { - fillEnter.append("circle").attr("class", "vertex").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", rVertex); - }); - const rMidpoint = 1.25; - [[c1, w2 / 2], [c2, w2 / 2], [h2 / 2, c1], [h2 / 2, c2]].forEach((point2) => { - fillEnter.append("circle").attr("class", "midpoint").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", rMidpoint); - }); - fill = fillEnter.merge(fill); - fill.selectAll("path.stroke").attr("class", "area stroke ".concat(tagClasses)); - fill.selectAll("path.fill").attr("class", "area fill ".concat(tagClasses)); + function loadObjTree(oXMLDoc, oParentEl, oParentObj) { + var vValue, oChild; + if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) { + oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); + } else if (oParentObj.constructor === Date) { + oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString())); + } + for (var sName in oParentObj) { + vValue = oParentObj[sName]; + if (isFinite(sName) || vValue instanceof Function) { + continue; + } + if (sName === sValueProp) { + if (vValue !== null && vValue !== true) { + oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); + } + } else if (sName === sAttributesProp) { + for (var sAttrib in vValue) { + oParentEl.setAttribute(sAttrib, vValue[sAttrib]); + } + } else if (sName.charAt(0) === sAttrPref) { + oParentEl.setAttribute(sName.slice(1), vValue); + } else if (vValue.constructor === Array) { + for (var nItem = 0; nItem < vValue.length; nItem++) { + oChild = oXMLDoc.createElement(sName); + loadObjTree(oXMLDoc, oChild, vValue[nItem]); + oParentEl.appendChild(oChild); + } + } else { + oChild = oXMLDoc.createElement(sName); + if (vValue instanceof Object) { + loadObjTree(oXMLDoc, oChild, vValue); + } else if (vValue !== null && vValue !== true) { + oChild.appendChild(oXMLDoc.createTextNode(vValue.toString())); + } + oParentEl.appendChild(oChild); + } + } } - function renderLine(container, drawLine, tagClasses) { - let line = container.selectAll(".preset-icon-line").data(drawLine ? [0] : []); - line.exit().remove(); - let lineEnter = line.enter(); - const d2 = 60; - const w2 = d2; - const h2 = d2; - const y2 = Math.round(d2 * 0.72); - const l2 = Math.round(d2 * 0.6); - const r2 = 2.5; - const x12 = (w2 - l2) / 2; - const x2 = x12 + l2; - lineEnter = lineEnter.append("svg").attr("class", "preset-icon-line").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)); - ["casing", "stroke"].forEach((klass) => { - lineEnter.append("path").attr("d", "M".concat(x12, " ").concat(y2, " L").concat(x2, " ").concat(y2)).attr("class", "line ".concat(klass)); + this.build = function(oXMLParent, nVerbosity, bFreeze, bNesteAttributes) { + var _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : ( + /* put here the default verbosity level: */ + 1 + ); + return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3); + }; + this.unbuild = function(oObjTree) { + var oNewDoc = document.implementation.createDocument("", "", null); + loadObjTree(oNewDoc, oNewDoc, oObjTree); + return oNewDoc; + }; + this.stringify = function(oObjTree) { + return new XMLSerializer().serializeToString(JXON.unbuild(oObjTree)); + }; + }(); + + // modules/ui/sections/changes.js + function uiSectionChanges(context) { + var _discardTags = {}; + _mainFileFetcher.get("discarded").then(function(d2) { + _discardTags = d2; + }).catch(function() { + }); + var section = uiSection("changes-list", context).label(function() { + var history = context.history(); + var summary = history.difference().summary(); + return _t.append("inspector.title_count", { title: _t("commit.changes"), count: summary.length }); + }).disclosureContent(renderDisclosureContent); + function renderDisclosureContent(selection2) { + var history = context.history(); + var summary = history.difference().summary(); + var container = selection2.selectAll(".commit-section").data([0]); + var containerEnter = container.enter().append("div").attr("class", "commit-section"); + containerEnter.append("ul").attr("class", "changeset-list"); + container = containerEnter.merge(container); + var items = container.select("ul").selectAll("li").data(summary); + var itemsEnter = items.enter().append("li").attr("class", "change-item"); + var buttons = itemsEnter.append("button").on("mouseover", mouseover).on("mouseout", mouseout).on("click", click); + buttons.each(function(d2) { + select_default2(this).call(svgIcon("#iD-icon-" + d2.entity.geometry(d2.graph), "pre-text " + d2.changeType)); }); - [[x12 - 1, y2], [x2 + 1, y2]].forEach((point2) => { - lineEnter.append("circle").attr("class", "vertex").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", r2); + buttons.append("span").attr("class", "change-type").html(function(d2) { + return _t.html("commit." + d2.changeType) + " "; }); - line = lineEnter.merge(line); - line.selectAll("path.stroke").attr("class", "line stroke ".concat(tagClasses)); - line.selectAll("path.casing").attr("class", "line casing ".concat(tagClasses)); - } - function renderRoute(container, drawRoute, p2) { - let route = container.selectAll(".preset-icon-route").data(drawRoute ? [0] : []); - route.exit().remove(); - let routeEnter = route.enter(); - const d2 = 60; - const w2 = d2; - const h2 = d2; - const y12 = Math.round(d2 * 0.8); - const y2 = Math.round(d2 * 0.68); - const l2 = Math.round(d2 * 0.6); - const r2 = 2; - const x12 = (w2 - l2) / 2; - const x2 = x12 + l2 / 3; - const x3 = x2 + l2 / 3; - const x4 = x3 + l2 / 3; - routeEnter = routeEnter.append("svg").attr("class", "preset-icon-route").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)); - ["casing", "stroke"].forEach((klass) => { - routeEnter.append("path").attr("d", "M".concat(x12, " ").concat(y12, " L").concat(x2, " ").concat(y2)).attr("class", "segment0 line ".concat(klass)); - routeEnter.append("path").attr("d", "M".concat(x2, " ").concat(y2, " L").concat(x3, " ").concat(y12)).attr("class", "segment1 line ".concat(klass)); - routeEnter.append("path").attr("d", "M".concat(x3, " ").concat(y12, " L").concat(x4, " ").concat(y2)).attr("class", "segment2 line ".concat(klass)); + buttons.append("strong").attr("class", "entity-type").text(function(d2) { + var matched = _mainPresetIndex.match(d2.entity, d2.graph); + return matched && matched.name() || utilDisplayType(d2.entity.id); }); - [[x12, y12], [x2, y2], [x3, y12], [x4, y2]].forEach((point2) => { - routeEnter.append("circle").attr("class", "vertex").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", r2); + buttons.append("span").attr("class", "entity-name").text(function(d2) { + var name = utilDisplayName(d2.entity) || "", string = ""; + if (name !== "") { + string += ":"; + } + return string += " " + name; }); - route = routeEnter.merge(route); - if (drawRoute) { - let routeType = p2.tags.type === "waterway" ? "waterway" : p2.tags.route; - const segmentPresetIDs = routeSegments[routeType]; - for (let i3 in segmentPresetIDs) { - const segmentPreset = _mainPresetIndex.item(segmentPresetIDs[i3]); - const segmentTagClasses = svgTagClasses().getClassesString(segmentPreset.tags, ""); - route.selectAll("path.stroke.segment".concat(i3)).attr("class", "segment".concat(i3, " line stroke ").concat(segmentTagClasses)); - route.selectAll("path.casing.segment".concat(i3)).attr("class", "segment".concat(i3, " line casing ").concat(segmentTagClasses)); + items = itemsEnter.merge(items); + var changeset = new osmChangeset().update({ id: void 0 }); + var changes = history.changes(actionDiscardTags(history.difference(), _discardTags)); + delete changeset.id; + var data = JXON.stringify(changeset.osmChangeJXON(changes)); + var blob = new Blob([data], { type: "text/xml;charset=utf-8;" }); + var fileName = "changes.osc"; + var linkEnter = container.selectAll(".download-changes").data([0]).enter().append("a").attr("class", "download-changes"); + linkEnter.attr("href", window.URL.createObjectURL(blob)).attr("download", fileName); + linkEnter.call(svgIcon("#iD-icon-load", "inline")).append("span").call(_t.append("commit.download_changes")); + function mouseover(d2) { + if (d2.entity) { + context.surface().selectAll( + utilEntityOrMemberSelector([d2.entity.id], context.graph()) + ).classed("hover", true); } } - } - function renderSvgIcon(container, picon, geom, isFramed, category, tagClasses) { - const isMaki = picon && /^maki-/.test(picon); - const isTemaki = picon && /^temaki-/.test(picon); - const isFa = picon && /^fa[srb]-/.test(picon); - const isR\u00F6ntgen = picon && /^roentgen-/.test(picon); - const isiDIcon = picon && !(isMaki || isTemaki || isFa || isR\u00F6ntgen); - let icon2 = container.selectAll(".preset-icon").data(picon ? [0] : []); - icon2.exit().remove(); - icon2 = icon2.enter().append("div").attr("class", "preset-icon").call(svgIcon("")).merge(icon2); - icon2.attr("class", "preset-icon " + (geom ? geom + "-geom" : "")).classed("category", category).classed("framed", isFramed).classed("preset-icon-iD", isiDIcon); - icon2.selectAll("svg").attr("class", "icon " + picon + " " + (!isiDIcon && geom !== "line" ? "" : tagClasses)); - icon2.selectAll("use").attr("href", "#" + picon); - } - function renderImageIcon(container, imageURL) { - let imageIcon = container.selectAll("img.image-icon").data(imageURL ? [0] : []); - imageIcon.exit().remove(); - imageIcon = imageIcon.enter().append("img").attr("class", "image-icon").on("load", () => container.classed("showing-img", true)).on("error", () => container.classed("showing-img", false)).merge(imageIcon); - imageIcon.attr("src", imageURL); - } - const routeSegments = { - bicycle: ["highway/cycleway", "highway/cycleway", "highway/cycleway"], - bus: ["highway/unclassified", "highway/secondary", "highway/primary"], - trolleybus: ["highway/unclassified", "highway/secondary", "highway/primary"], - detour: ["highway/tertiary", "highway/residential", "highway/unclassified"], - ferry: ["route/ferry", "route/ferry", "route/ferry"], - foot: ["highway/footway", "highway/footway", "highway/footway"], - hiking: ["highway/path", "highway/path", "highway/path"], - horse: ["highway/bridleway", "highway/bridleway", "highway/bridleway"], - light_rail: ["railway/light_rail", "railway/light_rail", "railway/light_rail"], - monorail: ["railway/monorail", "railway/monorail", "railway/monorail"], - mtb: ["highway/path", "highway/track", "highway/bridleway"], - pipeline: ["man_made/pipeline", "man_made/pipeline", "man_made/pipeline"], - piste: ["piste/downhill", "piste/hike", "piste/nordic"], - power: ["power/line", "power/line", "power/line"], - road: ["highway/secondary", "highway/primary", "highway/trunk"], - subway: ["railway/subway", "railway/subway", "railway/subway"], - train: ["railway/rail", "railway/rail", "railway/rail"], - tram: ["railway/tram", "railway/tram", "railway/tram"], - waterway: ["waterway/stream", "waterway/stream", "waterway/stream"] - }; - function render() { - let p2 = _preset.apply(this, arguments); - let geom = _geometry ? _geometry.apply(this, arguments) : null; - if (geom === "relation" && p2.tags && (p2.tags.type === "route" && p2.tags.route && routeSegments[p2.tags.route] || p2.tags.type === "waterway")) { - geom = "route"; + function mouseout() { + context.surface().selectAll(".hover").classed("hover", false); } - const showThirdPartyIcons = corePreferences("preferences.privacy.thirdpartyicons") || "true"; - const isFallback = p2.isFallback && p2.isFallback(); - const imageURL = showThirdPartyIcons === "true" && p2.imageURL; - const picon = getIcon(p2, geom); - const isCategory = !p2.setTags; - const drawPoint = false; - const drawVertex = picon !== null && geom === "vertex"; - const drawLine = picon && geom === "line" && !isFallback && !isCategory; - const drawArea = picon && geom === "area" && !isFallback && !isCategory; - const drawRoute = picon && geom === "route"; - const isFramed = drawVertex || drawArea || drawLine || drawRoute || isCategory; - let tags = !isCategory ? p2.setTags({}, geom) : {}; - for (let k2 in tags) { - if (tags[k2] === "*") { - tags[k2] = "yes"; + function click(d3_event, change) { + if (change.changeType !== "deleted") { + var entity = change.entity; + context.map().zoomToEase(entity); + context.surface().selectAll(utilEntityOrMemberSelector([entity.id], context.graph())).classed("hover", true); } } - let tagClasses = svgTagClasses().getClassesString(tags, ""); - let selection2 = select_default2(this); - let container = selection2.selectAll(".preset-icon-container").data([0]); - container = container.enter().append("div").attr("class", "preset-icon-container").merge(container); - container.classed("showing-img", !!imageURL).classed("fallback", isFallback); - renderCategoryBorder(container, isCategory && p2); - renderPointBorder(container, drawPoint); - renderCircleFill(container, drawVertex); - renderSquareFill(container, drawArea, tagClasses); - renderLine(container, drawLine, tagClasses); - renderRoute(container, drawRoute, p2); - renderSvgIcon(container, picon, geom, isFramed, isCategory, tagClasses); - renderImageIcon(container, imageURL); } - presetIcon.preset = function(val) { - if (!arguments.length) - return _preset; - _preset = utilFunctor(val); - return presetIcon; - }; - presetIcon.geometry = function(val) { - if (!arguments.length) - return _geometry; - _geometry = utilFunctor(val); - return presetIcon; - }; - return presetIcon; + return section; } - // modules/ui/sections/feature_type.js - function uiSectionFeatureType(context) { - var dispatch14 = dispatch_default("choose"); - var _entityIDs = []; - var _presets = []; - var _tagReference; - var section = uiSection("feature-type", context).label(() => _t.append("inspector.feature_type")).disclosureContent(renderDisclosureContent); - function renderDisclosureContent(selection2) { - selection2.classed("preset-list-item", true); - selection2.classed("mixed-types", _presets.length > 1); - var presetButtonWrap = selection2.selectAll(".preset-list-button-wrap").data([0]).enter().append("div").attr("class", "preset-list-button-wrap"); - var presetButton = presetButtonWrap.append("button").attr("class", "preset-list-button preset-reset").call( - uiTooltip().title(() => _t.append("inspector.back_tooltip")).placement("bottom") - ); - presetButton.append("div").attr("class", "preset-icon-container"); - presetButton.append("div").attr("class", "label").append("div").attr("class", "label-inner"); - presetButtonWrap.append("div").attr("class", "accessory-buttons"); - var tagReferenceBodyWrap = selection2.selectAll(".tag-reference-body-wrap").data([0]); - tagReferenceBodyWrap = tagReferenceBodyWrap.enter().append("div").attr("class", "tag-reference-body-wrap").merge(tagReferenceBodyWrap); - if (_tagReference) { - selection2.selectAll(".preset-list-button-wrap .accessory-buttons").style("display", _presets.length === 1 ? null : "none").call(_tagReference.button); - tagReferenceBodyWrap.style("display", _presets.length === 1 ? null : "none").call(_tagReference.body); + // modules/ui/commit_warnings.js + function uiCommitWarnings(context) { + function commitWarnings(selection2) { + var issuesBySeverity = context.validator().getIssuesBySeverity({ what: "edited", where: "all", includeDisabledRules: true }); + for (var severity in issuesBySeverity) { + var issues = issuesBySeverity[severity]; + if (severity !== "error") { + issues = issues.filter(function(issue) { + return issue.type !== "help_request"; + }); + } + var section = severity + "-section"; + var issueItem = severity + "-item"; + var container = selection2.selectAll("." + section).data(issues.length ? [0] : []); + container.exit().remove(); + var containerEnter = container.enter().append("div").attr("class", "modal-section " + section + " fillL2"); + containerEnter.append("h3").call(severity === "warning" ? _t.append("commit.warnings") : _t.append("commit.errors")); + containerEnter.append("ul").attr("class", "changeset-list"); + container = containerEnter.merge(container); + var items = container.select("ul").selectAll("li").data(issues, function(d2) { + return d2.key; + }); + items.exit().remove(); + var itemsEnter = items.enter().append("li").attr("class", issueItem); + var buttons = itemsEnter.append("button").on("mouseover", function(d3_event, d2) { + if (d2.entityIds) { + context.surface().selectAll( + utilEntityOrMemberSelector( + d2.entityIds, + context.graph() + ) + ).classed("hover", true); + } + }).on("mouseout", function() { + context.surface().selectAll(".hover").classed("hover", false); + }).on("click", function(d3_event, d2) { + context.validator().focusIssue(d2); + }); + buttons.call(svgIcon("#iD-icon-alert", "pre-text")); + buttons.append("strong").attr("class", "issue-message"); + buttons.filter(function(d2) { + return d2.tooltip; + }).call( + uiTooltip().title(function(d2) { + return d2.tooltip; + }).placement("top") + ); + items = itemsEnter.merge(items); + items.selectAll(".issue-message").text("").each(function(d2) { + return d2.message(context)(select_default2(this)); + }); + } + } + return commitWarnings; + } + + // modules/ui/commit.js + var readOnlyTags = [ + /^changesets_count$/, + /^created_by$/, + /^ideditor:/, + /^imagery_used$/, + /^host$/, + /^locale$/, + /^warnings:/, + /^resolved:/, + /^closed:note$/, + /^closed:keepright$/, + /^closed:improveosm:/, + /^closed:osmose:/ + ]; + var hashtagRegex = /(#[^\u2000-\u206F\u2E00-\u2E7F\s\\'!"#$%()*,.\/:;<=>?@\[\]^`{|}~]+)/g; + function uiCommit(context) { + var dispatch14 = dispatch_default("cancel"); + var _userDetails2; + var _selection; + var changesetEditor = uiChangesetEditor(context).on("change", changeTags); + var rawTagEditor = uiSectionRawTagEditor("changeset-tag-editor", context).on("change", changeTags).readOnlyTags(readOnlyTags); + var commitChanges = uiSectionChanges(context); + var commitWarnings = uiCommitWarnings(context); + function commit(selection2) { + _selection = selection2; + if (!context.changeset) + initChangeset(); + loadDerivedChangesetTags(); + selection2.call(render); + } + function initChangeset() { + var commentDate = +corePreferences("commentDate") || 0; + var currDate = Date.now(); + var cutoff = 2 * 86400 * 1e3; + if (commentDate > currDate || currDate - commentDate > cutoff) { + corePreferences("comment", null); + corePreferences("hashtags", null); + corePreferences("source", null); + } + if (context.defaultChangesetComment()) { + corePreferences("comment", context.defaultChangesetComment()); + corePreferences("commentDate", Date.now()); + } + if (context.defaultChangesetSource()) { + corePreferences("source", context.defaultChangesetSource()); + corePreferences("commentDate", Date.now()); + } + if (context.defaultChangesetHashtags()) { + corePreferences("hashtags", context.defaultChangesetHashtags()); + corePreferences("commentDate", Date.now()); + } + var detected = utilDetect(); + var tags = { + comment: corePreferences("comment") || "", + created_by: context.cleanTagValue("iD " + context.version), + host: context.cleanTagValue(detected.host), + locale: context.cleanTagValue(_mainLocalizer.localeCode()) + }; + findHashtags(tags, true); + var hashtags = corePreferences("hashtags"); + if (hashtags) { + tags.hashtags = hashtags; + } + var source = corePreferences("source"); + if (source) { + tags.source = source; + } + var photoOverlaysUsed = context.history().photoOverlaysUsed(); + if (photoOverlaysUsed.length) { + var sources = (tags.source || "").split(";"); + if (sources.indexOf("streetlevel imagery") === -1) { + sources.push("streetlevel imagery"); + } + photoOverlaysUsed.forEach(function(photoOverlay) { + if (sources.indexOf(photoOverlay) === -1) { + sources.push(photoOverlay); + } + }); + tags.source = context.cleanTagValue(sources.join(";")); } - selection2.selectAll(".preset-reset").on("click", function() { - dispatch14.call("choose", this, _presets); - }).on("pointerdown pointerup mousedown mouseup", function(d3_event) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - }); - var geometries = entityGeometries(); - selection2.select(".preset-list-item button").call( - uiPresetIcon().geometry(_presets.length === 1 ? geometries.length === 1 && geometries[0] : null).preset(_presets.length === 1 ? _presets[0] : _mainPresetIndex.item("point")) - ); - var names = _presets.length === 1 ? [ - _presets[0].nameLabel(), - _presets[0].subtitleLabel() - ].filter(Boolean) : [_t.append("inspector.multiple_types")]; - var label = selection2.select(".label-inner"); - var nameparts = label.selectAll(".namepart").data(names, (d2) => d2.stringId); - nameparts.exit().remove(); - nameparts.enter().append("div").attr("class", "namepart").text("").each(function(d2) { - d2(select_default2(this)); - }); + context.changeset = new osmChangeset({ tags }); } - section.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return section; - }; - section.presets = function(val) { - if (!arguments.length) - return _presets; - if (!utilArrayIdentical(val, _presets)) { - _presets = val; - if (_presets.length === 1) { - _tagReference = uiTagReference(_presets[0].reference(), context).showing(false); + function loadDerivedChangesetTags() { + var osm = context.connection(); + if (!osm) + return; + var tags = Object.assign({}, context.changeset.tags); + var imageryUsed = context.cleanTagValue(context.history().imageryUsed().join(";")); + tags.imagery_used = imageryUsed || "None"; + var osmClosed = osm.getClosedIDs(); + var itemType; + if (osmClosed.length) { + tags["closed:note"] = context.cleanTagValue(osmClosed.join(";")); + } + if (services.keepRight) { + var krClosed = services.keepRight.getClosedIDs(); + if (krClosed.length) { + tags["closed:keepright"] = context.cleanTagValue(krClosed.join(";")); } } - return section; - }; - function entityGeometries() { - var counts = {}; - for (var i3 in _entityIDs) { - var geometry = context.graph().geometry(_entityIDs[i3]); - if (!counts[geometry]) - counts[geometry] = 0; - counts[geometry] += 1; + if (services.improveOSM) { + var iOsmClosed = services.improveOSM.getClosedCounts(); + for (itemType in iOsmClosed) { + tags["closed:improveosm:" + itemType] = context.cleanTagValue(iOsmClosed[itemType].toString()); + } } - return Object.keys(counts).sort(function(geom1, geom2) { - return counts[geom2] - counts[geom1]; - }); - } - return utilRebind(section, dispatch14, "on"); - } - - // modules/ui/sections/preset_fields.js - function uiSectionPresetFields(context) { - var section = uiSection("preset-fields", context).label(() => _t.append("inspector.fields")).disclosureContent(renderDisclosureContent); - var dispatch14 = dispatch_default("change", "revert"); - var formFields = uiFormFields(context); - var _state; - var _fieldsArr; - var _presets = []; - var _tags; - var _entityIDs; - function renderDisclosureContent(selection2) { - if (!_fieldsArr) { - var graph = context.graph(); - var geometries = Object.keys(_entityIDs.reduce(function(geoms, entityID) { - geoms[graph.entity(entityID).geometry(graph)] = true; - return geoms; - }, {})); - const loc = _entityIDs.reduce(function(extent, entityID) { - var entity = context.graph().entity(entityID); - return extent.extend(entity.extent(context.graph())); - }, geoExtent()).center(); - var presetsManager = _mainPresetIndex; - var allFields = []; - var allMoreFields = []; - var sharedTotalFields; - _presets.forEach(function(preset) { - var fields = preset.fields(loc); - var moreFields = preset.moreFields(loc); - allFields = utilArrayUnion(allFields, fields); - allMoreFields = utilArrayUnion(allMoreFields, moreFields); - if (!sharedTotalFields) { - sharedTotalFields = utilArrayUnion(fields, moreFields); + if (services.osmose) { + var osmoseClosed = services.osmose.getClosedCounts(); + for (itemType in osmoseClosed) { + tags["closed:osmose:" + itemType] = context.cleanTagValue(osmoseClosed[itemType].toString()); + } + } + for (var key in tags) { + if (key.match(/(^warnings:)|(^resolved:)/)) { + delete tags[key]; + } + } + function addIssueCounts(issues, prefix) { + var issuesByType = utilArrayGroupBy(issues, "type"); + for (var issueType in issuesByType) { + var issuesOfType = issuesByType[issueType]; + if (issuesOfType[0].subtype) { + var issuesBySubtype = utilArrayGroupBy(issuesOfType, "subtype"); + for (var issueSubtype in issuesBySubtype) { + var issuesOfSubtype = issuesBySubtype[issueSubtype]; + tags[prefix + ":" + issueType + ":" + issueSubtype] = context.cleanTagValue(issuesOfSubtype.length.toString()); + } } else { - sharedTotalFields = sharedTotalFields.filter(function(field) { - return fields.indexOf(field) !== -1 || moreFields.indexOf(field) !== -1; - }); - } - }); - var sharedFields = allFields.filter(function(field) { - return sharedTotalFields.indexOf(field) !== -1; - }); - var sharedMoreFields = allMoreFields.filter(function(field) { - return sharedTotalFields.indexOf(field) !== -1; - }); - _fieldsArr = []; - sharedFields.forEach(function(field) { - if (field.matchAllGeometry(geometries)) { - _fieldsArr.push( - uiField(context, field, _entityIDs) - ); + tags[prefix + ":" + issueType] = context.cleanTagValue(issuesOfType.length.toString()); } - }); - var singularEntity = _entityIDs.length === 1 && graph.hasEntity(_entityIDs[0]); - if (singularEntity && singularEntity.isHighwayIntersection(graph) && presetsManager.field("restrictions")) { - _fieldsArr.push( - uiField(context, presetsManager.field("restrictions"), _entityIDs) - ); } - var additionalFields = utilArrayUnion(sharedMoreFields, presetsManager.universal()); - additionalFields.sort(function(field1, field2) { - return field1.title().localeCompare(field2.title(), _mainLocalizer.localeCode()); - }); - additionalFields.forEach(function(field) { - if (sharedFields.indexOf(field) === -1 && field.matchAllGeometry(geometries)) { - _fieldsArr.push( - uiField(context, field, _entityIDs, { show: false }) - ); - } - }); - _fieldsArr.forEach(function(field) { - field.on("change", function(t2, onInput) { - dispatch14.call("change", field, _entityIDs, t2, onInput); - }).on("revert", function(keys2) { - dispatch14.call("revert", field, keys2); - }); - }); } - _fieldsArr.forEach(function(field) { - field.state(_state).tags(_tags); + var warnings = context.validator().getIssuesBySeverity({ what: "edited", where: "all", includeIgnored: true, includeDisabledRules: true }).warning.filter(function(issue) { + return issue.type !== "help_request"; }); - selection2.call( - formFields.fieldsArr(_fieldsArr).state(_state).klass("grouped-items-area") - ); + addIssueCounts(warnings, "warnings"); + var resolvedIssues = context.validator().getResolvedIssues(); + addIssueCounts(resolvedIssues, "resolved"); + context.changeset = context.changeset.update({ tags }); } - section.presets = function(val) { - if (!arguments.length) - return _presets; - if (!_presets || !val || !utilArrayIdentical(_presets, val)) { - _presets = val; - _fieldsArr = null; + function render(selection2) { + var osm = context.connection(); + if (!osm) + return; + var header = selection2.selectAll(".header").data([0]); + var headerTitle = header.enter().append("div").attr("class", "header fillL"); + headerTitle.append("div").append("h2").call(_t.append("commit.title")); + headerTitle.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function() { + dispatch14.call("cancel", this); + }).call(svgIcon("#iD-icon-close")); + var body = selection2.selectAll(".body").data([0]); + body = body.enter().append("div").attr("class", "body").merge(body); + var changesetSection = body.selectAll(".changeset-editor").data([0]); + changesetSection = changesetSection.enter().append("div").attr("class", "modal-section changeset-editor").merge(changesetSection); + changesetSection.call( + changesetEditor.changesetID(context.changeset.id).tags(context.changeset.tags) + ); + body.call(commitWarnings); + var saveSection = body.selectAll(".save-section").data([0]); + saveSection = saveSection.enter().append("div").attr("class", "modal-section save-section fillL").merge(saveSection); + var prose = saveSection.selectAll(".commit-info").data([0]); + if (prose.enter().size()) { + _userDetails2 = null; } - return section; - }; - section.state = function(val) { - if (!arguments.length) - return _state; - _state = val; - return section; - }; - section.tags = function(val) { - if (!arguments.length) - return _tags; - _tags = val; - return section; - }; - section.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - if (!val || !_entityIDs || !utilArrayIdentical(_entityIDs, val)) { - _entityIDs = val; - _fieldsArr = null; + prose = prose.enter().append("p").attr("class", "commit-info").call(_t.append("commit.upload_explanation")).merge(prose); + osm.userDetails(function(err, user) { + if (err) + return; + if (_userDetails2 === user) + return; + _userDetails2 = user; + var userLink = select_default2(document.createElement("div")); + if (user.image_url) { + userLink.append("img").attr("src", user.image_url).attr("class", "icon pre-text user-icon"); + } + userLink.append("a").attr("class", "user-info").text(user.display_name).attr("href", osm.userURL(user.display_name)).attr("target", "_blank"); + prose.html(_t.html("commit.upload_explanation_with_user", { user: { html: userLink.html() } })); + }); + var requestReview = saveSection.selectAll(".request-review").data([0]); + var requestReviewEnter = requestReview.enter().append("div").attr("class", "request-review"); + var requestReviewDomId = utilUniqueDomId("commit-input-request-review"); + var labelEnter = requestReviewEnter.append("label").attr("for", requestReviewDomId); + if (!labelEnter.empty()) { + labelEnter.call(uiTooltip().title(() => _t.append("commit.request_review_info")).placement("top")); } - return section; - }; - return utilRebind(section, dispatch14, "on"); - } - - // modules/ui/sections/raw_member_editor.js - function uiSectionRawMemberEditor(context) { - var section = uiSection("raw-member-editor", context).shouldDisplay(function() { - if (!_entityIDs || _entityIDs.length !== 1) - return false; - var entity = context.hasEntity(_entityIDs[0]); - return entity && entity.type === "relation"; - }).label(function() { - var entity = context.hasEntity(_entityIDs[0]); - if (!entity) - return ""; - var gt2 = entity.members.length > _maxMembers ? ">" : ""; - var count = gt2 + entity.members.slice(0, _maxMembers).length; - return _t.append("inspector.title_count", { title: _t("inspector.members"), count }); - }).disclosureContent(renderDisclosureContent); - var taginfo = services.taginfo; - var _entityIDs; - var _maxMembers = 1e3; - function downloadMember(d3_event, d2) { - d3_event.preventDefault(); - select_default2(this.parentNode).classed("tag-reference-loading", true); - context.loadEntity(d2.id, function() { - section.reRender(); + labelEnter.append("input").attr("type", "checkbox").attr("id", requestReviewDomId); + labelEnter.append("span").call(_t.append("commit.request_review")); + requestReview = requestReview.merge(requestReviewEnter); + var requestReviewInput = requestReview.selectAll("input").property("checked", isReviewRequested(context.changeset.tags)).on("change", toggleRequestReview); + var buttonSection = saveSection.selectAll(".buttons").data([0]); + var buttonEnter = buttonSection.enter().append("div").attr("class", "buttons fillL"); + buttonEnter.append("button").attr("class", "secondary-action button cancel-button").append("span").attr("class", "label").call(_t.append("commit.cancel")); + var uploadButton = buttonEnter.append("button").attr("class", "action button save-button"); + uploadButton.append("span").attr("class", "label").call(_t.append("commit.save")); + var uploadBlockerTooltipText = getUploadBlockerMessage(); + buttonSection = buttonSection.merge(buttonEnter); + buttonSection.selectAll(".cancel-button").on("click.cancel", function() { + dispatch14.call("cancel", this); }); - } - function zoomToMember(d3_event, d2) { - d3_event.preventDefault(); - var entity = context.entity(d2.id); - context.map().zoomToEase(entity); - utilHighlightEntities([d2.id], true, context); - } - function selectMember(d3_event, d2) { - d3_event.preventDefault(); - utilHighlightEntities([d2.id], false, context); - var entity = context.entity(d2.id); - var mapExtent = context.map().extent(); - if (!entity.intersects(mapExtent, context.graph())) { - context.map().zoomToEase(entity); + buttonSection.selectAll(".save-button").classed("disabled", uploadBlockerTooltipText !== null).on("click.save", function() { + if (!select_default2(this).classed("disabled")) { + this.blur(); + for (var key in context.changeset.tags) { + if (!key) + delete context.changeset.tags[key]; + } + context.uploader().save(context.changeset); + } + }); + uiTooltip().destroyAny(buttonSection.selectAll(".save-button")); + if (uploadBlockerTooltipText) { + buttonSection.selectAll(".save-button").call(uiTooltip().title(() => uploadBlockerTooltipText).placement("top")); } - context.enter(modeSelect(context, [d2.id])); - } - function changeRole(d3_event, d2) { - var oldRole = d2.role; - var newRole = context.cleanRelationRole(select_default2(this).property("value")); - if (oldRole !== newRole) { - var member = { id: d2.id, type: d2.type, role: newRole }; - context.perform( - actionChangeMember(d2.relation.id, member, d2.index), - _t("operations.change_role.annotation", { - n: 1 - }) + var tagSection = body.selectAll(".tag-section.raw-tag-editor").data([0]); + tagSection = tagSection.enter().append("div").attr("class", "modal-section tag-section raw-tag-editor").merge(tagSection); + tagSection.call( + rawTagEditor.tags(Object.assign({}, context.changeset.tags)).render + ); + var changesSection = body.selectAll(".commit-changes-section").data([0]); + changesSection = changesSection.enter().append("div").attr("class", "modal-section commit-changes-section").merge(changesSection); + changesSection.call(commitChanges.render); + function toggleRequestReview() { + var rr = requestReviewInput.property("checked"); + updateChangeset({ review_requested: rr ? "yes" : void 0 }); + tagSection.call( + rawTagEditor.tags(Object.assign({}, context.changeset.tags)).render ); - context.validator().validate(); } } - function deleteMember(d3_event, d2) { - utilHighlightEntities([d2.id], false, context); - context.perform( - actionDeleteMember(d2.relation.id, d2.index), - _t("operations.delete_member.annotation", { - n: 1 - }) - ); - if (!context.hasEntity(d2.relation.id)) { - context.enter(modeBrowse(context)); + function getUploadBlockerMessage() { + var errors = context.validator().getIssuesBySeverity({ what: "edited", where: "all" }).error; + if (errors.length) { + return _t.append("commit.outstanding_errors_message", { count: errors.length }); } else { - context.validator().validate(); + var hasChangesetComment = context.changeset && context.changeset.tags.comment && context.changeset.tags.comment.trim().length; + if (!hasChangesetComment) { + return _t.append("commit.comment_needed_message"); + } } + return null; } - function renderDisclosureContent(selection2) { - var entityID = _entityIDs[0]; - var memberships = []; - var entity = context.entity(entityID); - entity.members.slice(0, _maxMembers).forEach(function(member, index) { - memberships.push({ - index, - id: member.id, - type: member.type, - role: member.role, - relation: entity, - member: context.hasEntity(member.id), - domId: utilUniqueDomId(entityID + "-member-" + index) - }); - }); - var list = selection2.selectAll(".member-list").data([0]); - list = list.enter().append("ul").attr("class", "member-list").merge(list); - var items = list.selectAll("li").data(memberships, function(d2) { - return osmEntity.key(d2.relation) + "," + d2.index + "," + (d2.member ? osmEntity.key(d2.member) : "incomplete"); - }); - items.exit().each(unbind).remove(); - var itemsEnter = items.enter().append("li").attr("class", "member-row form-field").classed("member-incomplete", function(d2) { - return !d2.member; - }); - itemsEnter.each(function(d2) { - var item = select_default2(this); - var label = item.append("label").attr("class", "field-label").attr("for", d2.domId); - if (d2.member) { - item.on("mouseover", function() { - utilHighlightEntities([d2.id], true, context); - }).on("mouseout", function() { - utilHighlightEntities([d2.id], false, context); - }); - var labelLink = label.append("span").attr("class", "label-text").append("a").attr("href", "#").on("click", selectMember); - labelLink.append("span").attr("class", "member-entity-type").text(function(d4) { - var matched = _mainPresetIndex.match(d4.member, context.graph()); - return matched && matched.name() || utilDisplayType(d4.member.id); - }); - labelLink.append("span").attr("class", "member-entity-name").text(function(d4) { - return utilDisplayName(d4.member); - }); - label.append("button").attr("title", _t("icons.remove")).attr("class", "remove member-delete").call(svgIcon("#iD-operation-delete")); - label.append("button").attr("class", "member-zoom").attr("title", _t("icons.zoom_to")).call(svgIcon("#iD-icon-framed-dot", "monochrome")).on("click", zoomToMember); - } else { - var labelText = label.append("span").attr("class", "label-text"); - labelText.append("span").attr("class", "member-entity-type").call(_t.append("inspector." + d2.type, { id: d2.id })); - labelText.append("span").attr("class", "member-entity-name").call(_t.append("inspector.incomplete", { id: d2.id })); - label.append("button").attr("class", "member-download").attr("title", _t("icons.download")).call(svgIcon("#iD-icon-load")).on("click", downloadMember); + function changeTags(_2, changed, onInput) { + if (changed.hasOwnProperty("comment")) { + if (changed.comment === void 0) { + changed.comment = ""; + } + if (!onInput) { + corePreferences("comment", changed.comment); + corePreferences("commentDate", Date.now()); + } + } + if (changed.hasOwnProperty("source")) { + if (changed.source === void 0) { + corePreferences("source", null); + } else if (!onInput) { + corePreferences("source", changed.source); + corePreferences("commentDate", Date.now()); + } + } + updateChangeset(changed, onInput); + if (_selection) { + _selection.call(render); + } + } + function findHashtags(tags, commentOnly) { + var detectedHashtags = commentHashtags(); + if (detectedHashtags.length) { + corePreferences("hashtags", null); + } + if (!detectedHashtags.length || !commentOnly) { + detectedHashtags = detectedHashtags.concat(hashtagHashtags()); + } + var allLowerCase = /* @__PURE__ */ new Set(); + return detectedHashtags.filter(function(hashtag) { + var lowerCase = hashtag.toLowerCase(); + if (!allLowerCase.has(lowerCase)) { + allLowerCase.add(lowerCase); + return true; } + return false; }); - var wrapEnter = itemsEnter.append("div").attr("class", "form-field-input-wrap form-field-input-member"); - wrapEnter.append("input").attr("class", "member-role").attr("id", function(d2) { - return d2.domId; - }).property("type", "text").attr("placeholder", _t("inspector.role")).call(utilNoAuto); - if (taginfo) { - wrapEnter.each(bindTypeahead); + function commentHashtags() { + var matches = (tags.comment || "").replace(/http\S*/g, "").match(hashtagRegex); + return matches || []; } - items = items.merge(itemsEnter).order(); - items.select("input.member-role").property("value", function(d2) { - return d2.role; - }).on("blur", changeRole).on("change", changeRole); - items.select("button.member-delete").on("click", deleteMember); - var dragOrigin, targetIndex; - items.call( - drag_default().on("start", function(d3_event) { - dragOrigin = { - x: d3_event.x, - y: d3_event.y - }; - targetIndex = null; - }).on("drag", function(d3_event) { - var x2 = d3_event.x - dragOrigin.x, y2 = d3_event.y - dragOrigin.y; - if (!select_default2(this).classed("dragging") && // don't display drag until dragging beyond a distance threshold - Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2)) <= 5) - return; - var index = items.nodes().indexOf(this); - select_default2(this).classed("dragging", true); - targetIndex = null; - selection2.selectAll("li.member-row").style("transform", function(d2, index2) { - var node = select_default2(this).node(); - if (index === index2) { - return "translate(" + x2 + "px, " + y2 + "px)"; - } else if (index2 > index && d3_event.y > node.offsetTop) { - if (targetIndex === null || index2 > targetIndex) { - targetIndex = index2; - } - return "translateY(-100%)"; - } else if (index2 < index && d3_event.y < node.offsetTop + node.offsetHeight) { - if (targetIndex === null || index2 < targetIndex) { - targetIndex = index2; - } - return "translateY(100%)"; - } - return null; - }); - }).on("end", function(d3_event, d2) { - if (!select_default2(this).classed("dragging")) - return; - var index = items.nodes().indexOf(this); - select_default2(this).classed("dragging", false); - selection2.selectAll("li.member-row").style("transform", null); - if (targetIndex !== null) { - context.perform( - actionMoveMember(d2.relation.id, index, targetIndex), - _t("operations.reorder_members.annotation") - ); - context.validator().validate(); + function hashtagHashtags() { + var matches = (tags.hashtags || "").split(/[,;\s]+/).map(function(s2) { + if (s2[0] !== "#") { + s2 = "#" + s2; + } + var matched = s2.match(hashtagRegex); + return matched && matched[0]; + }).filter(Boolean); + return matches || []; + } + } + function isReviewRequested(tags) { + var rr = tags.review_requested; + if (rr === void 0) + return false; + rr = rr.trim().toLowerCase(); + return !(rr === "" || rr === "no"); + } + function updateChangeset(changed, onInput) { + var tags = Object.assign({}, context.changeset.tags); + Object.keys(changed).forEach(function(k2) { + var v2 = changed[k2]; + k2 = context.cleanTagKey(k2); + if (readOnlyTags.indexOf(k2) !== -1) + return; + if (v2 === void 0) { + delete tags[k2]; + } else if (onInput) { + tags[k2] = v2; + } else { + tags[k2] = context.cleanTagValue(v2); + } + }); + if (!onInput) { + var commentOnly = changed.hasOwnProperty("comment") && changed.comment !== ""; + var arr = findHashtags(tags, commentOnly); + if (arr.length) { + tags.hashtags = context.cleanTagValue(arr.join(";")); + corePreferences("hashtags", tags.hashtags); + } else { + delete tags.hashtags; + corePreferences("hashtags", null); + } + } + if (_userDetails2 && _userDetails2.changesets_count !== void 0) { + var changesetsCount = parseInt(_userDetails2.changesets_count, 10) + 1; + tags.changesets_count = String(changesetsCount); + if (changesetsCount <= 100) { + var s2; + s2 = corePreferences("walkthrough_completed"); + if (s2) { + tags["ideditor:walkthrough_completed"] = s2; } - }) - ); - function bindTypeahead(d2) { - var row = select_default2(this); - var role = row.selectAll("input.member-role"); - var origValue = role.property("value"); - function sort(value, data) { - var sameletter = []; - var other = []; - for (var i3 = 0; i3 < data.length; i3++) { - if (data[i3].value.substring(0, value.length) === value) { - sameletter.push(data[i3]); - } else { - other.push(data[i3]); - } + s2 = corePreferences("walkthrough_progress"); + if (s2) { + tags["ideditor:walkthrough_progress"] = s2; + } + s2 = corePreferences("walkthrough_started"); + if (s2) { + tags["ideditor:walkthrough_started"] = s2; } - return sameletter.concat(other); } - role.call( - uiCombobox(context, "member-role").fetcher(function(role2, callback) { - var geometry; - if (d2.member) { - geometry = context.graph().geometry(d2.member.id); - } else if (d2.type === "relation") { - geometry = "relation"; - } else if (d2.type === "way") { - geometry = "line"; - } else { - geometry = "point"; - } - var rtype = entity.tags.type; - taginfo.roles({ - debounce: true, - rtype: rtype || "", - geometry, - query: role2 - }, function(err, data) { - if (!err) - callback(sort(role2, data)); - }); - }).on("cancel", function() { - role.property("value", origValue); - }) - ); + } else { + delete tags.changesets_count; } - function unbind() { - var row = select_default2(this); - row.selectAll("input.member-role").call(uiCombobox.off, context); + if (!(0, import_fast_deep_equal9.default)(context.changeset.tags, tags)) { + context.changeset = context.changeset.update({ tags }); } } - section.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return section; + commit.reset = function() { + context.changeset = null; }; - return section; + return utilRebind(commit, dispatch14, "on"); } - // modules/actions/delete_members.js - function actionDeleteMembers(relationId, memberIndexes) { - return function(graph) { - memberIndexes.sort((a2, b2) => b2 - a2); - for (var i3 in memberIndexes) { - graph = actionDeleteMember(relationId, memberIndexes[i3])(graph); - } - return graph; + // modules/ui/confirm.js + function uiConfirm(selection2) { + var modalSelection = uiModal(selection2); + modalSelection.select(".modal").classed("modal-alert", true); + var section = modalSelection.select(".content"); + section.append("div").attr("class", "modal-section header"); + section.append("div").attr("class", "modal-section message-text"); + var buttons = section.append("div").attr("class", "modal-section buttons cf"); + modalSelection.okButton = function() { + buttons.append("button").attr("class", "button ok-button action").on("click.confirm", function() { + modalSelection.remove(); + }).call(_t.append("confirm.okay")).node().focus(); + return modalSelection; }; + return modalSelection; } - // modules/ui/sections/raw_membership_editor.js - function uiSectionRawMembershipEditor(context) { - var section = uiSection("raw-membership-editor", context).shouldDisplay(function() { - return _entityIDs && _entityIDs.length; - }).label(function() { - var parents = getSharedParentRelations(); - var gt2 = parents.length > _maxMemberships ? ">" : ""; - var count = gt2 + parents.slice(0, _maxMemberships).length; - return _t.append("inspector.title_count", { title: _t("inspector.relations"), count }); - }).disclosureContent(renderDisclosureContent); - var taginfo = services.taginfo; - var nearbyCombo = uiCombobox(context, "parent-relation").minItems(1).fetcher(fetchNearbyRelations).itemsMouseEnter(function(d3_event, d2) { - if (d2.relation) - utilHighlightEntities([d2.relation.id], true, context); - }).itemsMouseLeave(function(d3_event, d2) { - if (d2.relation) - utilHighlightEntities([d2.relation.id], false, context); - }); - var _inChange = false; - var _entityIDs = []; - var _showBlank; - var _maxMemberships = 1e3; - function getSharedParentRelations() { - var parents = []; - for (var i3 = 0; i3 < _entityIDs.length; i3++) { - var entity = context.graph().hasEntity(_entityIDs[i3]); - if (!entity) - continue; - if (i3 === 0) { - parents = context.graph().parentRelations(entity); - } else { - parents = utilArrayIntersection(parents, context.graph().parentRelations(entity)); - } - if (!parents.length) - break; - } - return parents; + // modules/ui/conflicts.js + function uiConflicts(context) { + var dispatch14 = dispatch_default("cancel", "save"); + var keybinding = utilKeybinding("conflicts"); + var _origChanges; + var _conflictList; + var _shownConflictIndex; + function keybindingOn() { + select_default2(document).call(keybinding.on("\u238B", cancel, true)); } - function getMemberships() { - var memberships = []; - var relations = getSharedParentRelations().slice(0, _maxMemberships); - var isMultiselect = _entityIDs.length > 1; - var i3, relation, membership, index, member, indexedMember; - for (i3 = 0; i3 < relations.length; i3++) { - relation = relations[i3]; - membership = { - relation, - members: [], - hash: osmEntity.key(relation) - }; - for (index = 0; index < relation.members.length; index++) { - member = relation.members[index]; - if (_entityIDs.indexOf(member.id) !== -1) { - indexedMember = Object.assign({}, member, { index }); - membership.members.push(indexedMember); - membership.hash += "," + index.toString(); - if (!isMultiselect) { - memberships.push(membership); - membership = { - relation, - members: [], - hash: osmEntity.key(relation) - }; - } - } - } - if (membership.members.length) - memberships.push(membership); + function keybindingOff() { + select_default2(document).call(keybinding.unbind); + } + function tryAgain() { + keybindingOff(); + dispatch14.call("save"); + } + function cancel() { + keybindingOff(); + dispatch14.call("cancel"); + } + function conflicts(selection2) { + keybindingOn(); + var headerEnter = selection2.selectAll(".header").data([0]).enter().append("div").attr("class", "header fillL"); + headerEnter.append("button").attr("class", "fr").attr("title", _t("icons.close")).on("click", cancel).call(svgIcon("#iD-icon-close")); + headerEnter.append("h2").call(_t.append("save.conflict.header")); + var bodyEnter = selection2.selectAll(".body").data([0]).enter().append("div").attr("class", "body fillL"); + var conflictsHelpEnter = bodyEnter.append("div").attr("class", "conflicts-help").call(_t.append("save.conflict.help")); + var changeset = new osmChangeset(); + delete changeset.id; + var data = JXON.stringify(changeset.osmChangeJXON(_origChanges)); + var blob = new Blob([data], { type: "text/xml;charset=utf-8;" }); + var fileName = "changes.osc"; + var linkEnter = conflictsHelpEnter.selectAll(".download-changes").append("a").attr("class", "download-changes"); + linkEnter.attr("href", window.URL.createObjectURL(blob)).attr("download", fileName); + linkEnter.call(svgIcon("#iD-icon-load", "inline")).append("span").call(_t.append("save.conflict.download_changes")); + bodyEnter.append("div").attr("class", "conflict-container fillL3").call(showConflict, 0); + bodyEnter.append("div").attr("class", "conflicts-done").attr("opacity", 0).style("display", "none").call(_t.append("save.conflict.done")); + var buttonsEnter = bodyEnter.append("div").attr("class", "buttons col12 joined conflicts-buttons"); + buttonsEnter.append("button").attr("disabled", _conflictList.length > 1).attr("class", "action conflicts-button col6").call(_t.append("save.title")).on("click.try_again", tryAgain); + buttonsEnter.append("button").attr("class", "secondary-action conflicts-button col6").call(_t.append("confirm.cancel")).on("click.cancel", cancel); + } + function showConflict(selection2, index) { + index = utilWrap(index, _conflictList.length); + _shownConflictIndex = index; + var parent = select_default2(selection2.node().parentNode); + if (index === _conflictList.length - 1) { + window.setTimeout(function() { + parent.select(".conflicts-button").attr("disabled", null); + parent.select(".conflicts-done").transition().attr("opacity", 1).style("display", "block"); + }, 250); } - memberships.forEach(function(membership2) { - membership2.domId = utilUniqueDomId("membership-" + membership2.relation.id); - var roles = []; - membership2.members.forEach(function(member2) { - if (roles.indexOf(member2.role) === -1) - roles.push(member2.role); - }); - membership2.role = roles.length === 1 ? roles[0] : roles; + var conflict = selection2.selectAll(".conflict").data([_conflictList[index]]); + conflict.exit().remove(); + var conflictEnter = conflict.enter().append("div").attr("class", "conflict"); + conflictEnter.append("h4").attr("class", "conflict-count").call(_t.append("save.conflict.count", { num: index + 1, total: _conflictList.length })); + conflictEnter.append("a").attr("class", "conflict-description").attr("href", "#").text(function(d2) { + return d2.name; + }).on("click", function(d3_event, d2) { + d3_event.preventDefault(); + zoomToEntity(d2.id); + }); + var details = conflictEnter.append("div").attr("class", "conflict-detail-container"); + details.append("ul").attr("class", "conflict-detail-list").selectAll("li").data(function(d2) { + return d2.details || []; + }).enter().append("li").attr("class", "conflict-detail-item").html(function(d2) { + return d2; + }); + details.append("div").attr("class", "conflict-choices").call(addChoices); + details.append("div").attr("class", "conflict-nav-buttons joined cf").selectAll("button").data(["previous", "next"]).enter().append("button").attr("class", "conflict-nav-button action col6").attr("disabled", function(d2, i3) { + return i3 === 0 && index === 0 || i3 === 1 && index === _conflictList.length - 1 || null; + }).on("click", function(d3_event, d2) { + d3_event.preventDefault(); + var container = parent.selectAll(".conflict-container"); + var sign2 = d2 === "previous" ? -1 : 1; + container.selectAll(".conflict").remove(); + container.call(showConflict, index + sign2); + }).each(function(d2) { + _t.append("save.conflict." + d2)(select_default2(this)); }); - return memberships; - } - function selectRelation(d3_event, d2) { - d3_event.preventDefault(); - utilHighlightEntities([d2.relation.id], false, context); - context.enter(modeSelect(context, [d2.relation.id])); } - function zoomToRelation(d3_event, d2) { - d3_event.preventDefault(); - var entity = context.entity(d2.relation.id); - context.map().zoomToEase(entity); - utilHighlightEntities([d2.relation.id], true, context); + function addChoices(selection2) { + var choices = selection2.append("ul").attr("class", "layer-list").selectAll("li").data(function(d2) { + return d2.choices || []; + }); + var choicesEnter = choices.enter().append("li").attr("class", "layer"); + var labelEnter = choicesEnter.append("label"); + labelEnter.append("input").attr("type", "radio").attr("name", function(d2) { + return d2.id; + }).on("change", function(d3_event, d2) { + var ul = this.parentNode.parentNode.parentNode; + ul.__data__.chosen = d2.id; + choose(d3_event, ul, d2); + }); + labelEnter.append("span").text(function(d2) { + return d2.text; + }); + choicesEnter.merge(choices).each(function(d2) { + var ul = this.parentNode; + if (ul.__data__.chosen === d2.id) { + choose(null, ul, d2); + } + }); } - function changeRole(d3_event, d2) { - if (d2 === 0) - return; - if (_inChange) - return; - var newRole = context.cleanRelationRole(select_default2(this).property("value")); - if (!newRole.trim() && typeof d2.role !== "string") - return; - var membersToUpdate = d2.members.filter(function(member) { - return member.role !== newRole; + function choose(d3_event, ul, datum2) { + if (d3_event) + d3_event.preventDefault(); + select_default2(ul).selectAll("li").classed("active", function(d2) { + return d2 === datum2; + }).selectAll("input").property("checked", function(d2) { + return d2 === datum2; }); - if (membersToUpdate.length) { - _inChange = true; - context.perform( - function actionChangeMemberRoles(graph) { - membersToUpdate.forEach(function(member) { - var newMember = Object.assign({}, member, { role: newRole }); - delete newMember.index; - graph = actionChangeMember(d2.relation.id, newMember, member.index)(graph); - }); - return graph; - }, - _t("operations.change_role.annotation", { - n: membersToUpdate.length - }) - ); - context.validator().validate(); - } - _inChange = false; + var extent = geoExtent(); + var entity; + entity = context.graph().hasEntity(datum2.id); + if (entity) + extent._extend(entity.extent(context.graph())); + datum2.action(); + entity = context.graph().hasEntity(datum2.id); + if (entity) + extent._extend(entity.extent(context.graph())); + zoomToEntity(datum2.id, extent); } - function addMembership(d2, role) { - this.blur(); - _showBlank = false; - function actionAddMembers(relationId, ids, role2) { - return function(graph) { - for (var i3 in ids) { - var member = { id: ids[i3], type: graph.entity(ids[i3]).type, role: role2 }; - graph = actionAddMember(relationId, member)(graph); - } - return graph; - }; + function zoomToEntity(id2, extent) { + context.surface().selectAll(".hover").classed("hover", false); + var entity = context.graph().hasEntity(id2); + if (entity) { + if (extent) { + context.map().trimmedExtent(extent); + } else { + context.map().zoomToEase(entity); + } + context.surface().selectAll(utilEntityOrMemberSelector([entity.id], context.graph())).classed("hover", true); } - if (d2.relation) { - context.perform( - actionAddMembers(d2.relation.id, _entityIDs, role), - _t("operations.add_member.annotation", { - n: _entityIDs.length - }) - ); - context.validator().validate(); - } else { - var relation = osmRelation(); - context.perform( - actionAddEntity(relation), - actionAddMembers(relation.id, _entityIDs, role), - _t("operations.add.annotation.relation") - ); - context.enter(modeSelect(context, [relation.id]).newFeature(true)); + } + conflicts.conflictList = function(_2) { + if (!arguments.length) + return _conflictList; + _conflictList = _2; + return conflicts; + }; + conflicts.origChanges = function(_2) { + if (!arguments.length) + return _origChanges; + _origChanges = _2; + return conflicts; + }; + conflicts.shownEntityIds = function() { + if (_conflictList && typeof _shownConflictIndex === "number") { + return [_conflictList[_shownConflictIndex].id]; } + return []; + }; + return utilRebind(conflicts, dispatch14, "on"); + } + + // modules/ui/entity_editor.js + var import_fast_deep_equal10 = __toESM(require_fast_deep_equal()); + + // modules/ui/sections/entity_issues.js + function uiSectionEntityIssues(context) { + var preference = corePreferences("entity-issues.reference.expanded"); + var _expanded = preference === null ? true : preference === "true"; + var _entityIDs = []; + var _issues = []; + var _activeIssueID; + var section = uiSection("entity-issues", context).shouldDisplay(function() { + return _issues.length > 0; + }).label(function() { + return _t.append("inspector.title_count", { title: _t("issues.list_title"), count: _issues.length }); + }).disclosureContent(renderDisclosureContent); + context.validator().on("validated.entity_issues", function() { + reloadIssues(); + section.reRender(); + }).on("focusedIssue.entity_issues", function(issue) { + makeActiveIssue(issue.id); + }); + function reloadIssues() { + _issues = context.validator().getSharedEntityIssues(_entityIDs, { includeDisabledRules: true }); } - function deleteMembership(d3_event, d2) { - this.blur(); - if (d2 === 0) - return; - utilHighlightEntities([d2.relation.id], false, context); - var indexes = d2.members.map(function(member) { - return member.index; + function makeActiveIssue(issueID) { + _activeIssueID = issueID; + section.selection().selectAll(".issue-container").classed("active", function(d2) { + return d2.id === _activeIssueID; }); - context.perform( - actionDeleteMembers(d2.relation.id, indexes), - _t("operations.delete_member.annotation", { - n: _entityIDs.length - }) - ); - context.validator().validate(); } - function fetchNearbyRelations(q2, callback) { - var newRelation = { - relation: null, - value: _t("inspector.new_relation"), - display: _t.append("inspector.new_relation") - }; - var entityID = _entityIDs[0]; - var result = []; - var graph = context.graph(); - function baseDisplayLabel(entity) { - var matched = _mainPresetIndex.match(entity, graph); - var presetName = matched && matched.name() || _t("inspector.relation"); - var entityName = utilDisplayName(entity) || ""; - return presetName + " " + entityName; - } - var explicitRelation = q2 && context.hasEntity(q2.toLowerCase()); - if (explicitRelation && explicitRelation.type === "relation" && explicitRelation.id !== entityID) { - result.push({ - relation: explicitRelation, - value: baseDisplayLabel(explicitRelation) + " " + explicitRelation.id - }); - } else { - context.history().intersects(context.map().extent()).forEach(function(entity) { - if (entity.type !== "relation" || entity.id === entityID) - return; - var value = baseDisplayLabel(entity); - if (q2 && (value + " " + entity.id).toLowerCase().indexOf(q2.toLowerCase()) === -1) - return; - result.push({ relation: entity, value }); - }); - result.sort(function(a2, b2) { - return osmRelation.creationOrder(a2.relation, b2.relation); - }); - var dupeGroups = Object.values(utilArrayGroupBy(result, "value")).filter(function(v2) { - return v2.length > 1; - }); - dupeGroups.forEach(function(group) { - group.forEach(function(obj) { - obj.value += " " + obj.relation.id; - }); + function renderDisclosureContent(selection2) { + selection2.classed("grouped-items-area", true); + _activeIssueID = _issues.length > 0 ? _issues[0].id : null; + var containers = selection2.selectAll(".issue-container").data(_issues, function(d2) { + return d2.key; + }); + containers.exit().remove(); + var containersEnter = containers.enter().append("div").attr("class", "issue-container"); + var itemsEnter = containersEnter.append("div").attr("class", function(d2) { + return "issue severity-" + d2.severity; + }).on("mouseover.highlight", function(d3_event, d2) { + var ids = d2.entityIds.filter(function(e3) { + return _entityIDs.indexOf(e3) === -1; }); - } - result.forEach(function(obj) { - obj.title = obj.value; + utilHighlightEntities(ids, true, context); + }).on("mouseout.highlight", function(d3_event, d2) { + var ids = d2.entityIds.filter(function(e3) { + return _entityIDs.indexOf(e3) === -1; + }); + utilHighlightEntities(ids, false, context); }); - result.unshift(newRelation); - callback(result); - } - function renderDisclosureContent(selection2) { - var memberships = getMemberships(); - var list = selection2.selectAll(".member-list").data([0]); - list = list.enter().append("ul").attr("class", "member-list").merge(list); - var items = list.selectAll("li.member-row-normal").data(memberships, function(d2) { - return d2.hash; + var labelsEnter = itemsEnter.append("div").attr("class", "issue-label"); + var textEnter = labelsEnter.append("button").attr("class", "issue-text").on("click", function(d3_event, d2) { + makeActiveIssue(d2.id); + var extent = d2.extent(context.graph()); + if (extent) { + var setZoom = Math.max(context.map().zoom(), 19); + context.map().unobscuredCenterZoomEase(extent.center(), setZoom); + } }); - items.exit().each(unbind).remove(); - var itemsEnter = items.enter().append("li").attr("class", "member-row member-row-normal form-field"); - itemsEnter.on("mouseover", function(d3_event, d2) { - utilHighlightEntities([d2.relation.id], true, context); - }).on("mouseout", function(d3_event, d2) { - utilHighlightEntities([d2.relation.id], false, context); + textEnter.each(function(d2) { + var iconName = "#iD-icon-" + (d2.severity === "warning" ? "alert" : "error"); + select_default2(this).call(svgIcon(iconName, "issue-icon")); }); - var labelEnter = itemsEnter.append("label").attr("class", "field-label").attr("for", function(d2) { - return d2.domId; + textEnter.append("span").attr("class", "issue-message"); + var infoButton = labelsEnter.append("button").attr("class", "issue-info-button").attr("title", _t("icons.information")).call(svgIcon("#iD-icon-inspect")); + infoButton.on("click", function(d3_event) { + d3_event.stopPropagation(); + d3_event.preventDefault(); + this.blur(); + var container = select_default2(this.parentNode.parentNode.parentNode); + var info = container.selectAll(".issue-info"); + var isExpanded = info.classed("expanded"); + _expanded = !isExpanded; + corePreferences("entity-issues.reference.expanded", _expanded); + if (isExpanded) { + info.transition().duration(200).style("max-height", "0px").style("opacity", "0").on("end", function() { + info.classed("expanded", false); + }); + } else { + info.classed("expanded", true).transition().duration(200).style("max-height", "200px").style("opacity", "1").on("end", function() { + info.style("max-height", null); + }); + } }); - var labelLink = labelEnter.append("span").attr("class", "label-text").append("a").attr("href", "#").on("click", selectRelation); - labelLink.append("span").attr("class", "member-entity-type").text(function(d2) { - var matched = _mainPresetIndex.match(d2.relation, context.graph()); - return matched && matched.name() || _t.html("inspector.relation"); + itemsEnter.append("ul").attr("class", "issue-fix-list"); + containersEnter.append("div").attr("class", "issue-info" + (_expanded ? " expanded" : "")).style("max-height", _expanded ? null : "0").style("opacity", _expanded ? "1" : "0").each(function(d2) { + if (typeof d2.reference === "function") { + select_default2(this).call(d2.reference); + } else { + select_default2(this).call(_t.append("inspector.no_documentation_key")); + } }); - labelLink.append("span").attr("class", "member-entity-name").text(function(d2) { - return utilDisplayName(d2.relation); + containers = containers.merge(containersEnter).classed("active", function(d2) { + return d2.id === _activeIssueID; }); - labelEnter.append("button").attr("class", "remove member-delete").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")).on("click", deleteMembership); - labelEnter.append("button").attr("class", "member-zoom").attr("title", _t("icons.zoom_to")).call(svgIcon("#iD-icon-framed-dot", "monochrome")).on("click", zoomToRelation); - var wrapEnter = itemsEnter.append("div").attr("class", "form-field-input-wrap form-field-input-member"); - wrapEnter.append("input").attr("class", "member-role").attr("id", function(d2) { - return d2.domId; - }).property("type", "text").property("value", function(d2) { - return typeof d2.role === "string" ? d2.role : ""; - }).attr("title", function(d2) { - return Array.isArray(d2.role) ? d2.role.filter(Boolean).join("\n") : d2.role; - }).attr("placeholder", function(d2) { - return Array.isArray(d2.role) ? _t("inspector.multiple_roles") : _t("inspector.role"); - }).classed("mixed", function(d2) { - return Array.isArray(d2.role); - }).call(utilNoAuto).on("blur", changeRole).on("change", changeRole); - if (taginfo) { - wrapEnter.each(bindTypeahead); - } - var newMembership = list.selectAll(".member-row-new").data(_showBlank ? [0] : []); - newMembership.exit().remove(); - var newMembershipEnter = newMembership.enter().append("li").attr("class", "member-row member-row-new form-field"); - var newLabelEnter = newMembershipEnter.append("label").attr("class", "field-label"); - newLabelEnter.append("input").attr("placeholder", _t("inspector.choose_relation")).attr("type", "text").attr("class", "member-entity-input").call(utilNoAuto); - newLabelEnter.append("button").attr("class", "remove member-delete").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")).on("click", function() { - list.selectAll(".member-row-new").remove(); + containers.selectAll(".issue-message").text("").each(function(d2) { + return d2.message(context)(select_default2(this)); }); - var newWrapEnter = newMembershipEnter.append("div").attr("class", "form-field-input-wrap form-field-input-member"); - newWrapEnter.append("input").attr("class", "member-role").property("type", "text").attr("placeholder", _t("inspector.role")).call(utilNoAuto); - newMembership = newMembership.merge(newMembershipEnter); - newMembership.selectAll(".member-entity-input").on("blur", cancelEntity).call( - nearbyCombo.on("accept", acceptEntity).on("cancel", cancelEntity) - ); - var addRow = selection2.selectAll(".add-row").data([0]); - var addRowEnter = addRow.enter().append("div").attr("class", "add-row"); - var addRelationButton = addRowEnter.append("button").attr("class", "add-relation").attr("aria-label", _t("inspector.add_to_relation")); - addRelationButton.call(svgIcon("#iD-icon-plus", "light")); - addRelationButton.call(uiTooltip().title(() => _t.append("inspector.add_to_relation")).placement(_mainLocalizer.textDirection() === "ltr" ? "right" : "left")); - addRowEnter.append("div").attr("class", "space-value"); - addRowEnter.append("div").attr("class", "space-buttons"); - addRow = addRow.merge(addRowEnter); - addRow.select(".add-relation").on("click", function() { - _showBlank = true; - section.reRender(); - list.selectAll(".member-entity-input").node().focus(); + var fixLists = containers.selectAll(".issue-fix-list"); + var fixes = fixLists.selectAll(".issue-fix-item").data(function(d2) { + return d2.fixes ? d2.fixes(context) : []; + }, function(fix) { + return fix.id; }); - function acceptEntity(d2) { - if (!d2) { - cancelEntity(); + fixes.exit().remove(); + var fixesEnter = fixes.enter().append("li").attr("class", "issue-fix-item"); + var buttons = fixesEnter.append("button").on("click", function(d3_event, d2) { + if (select_default2(this).attr("disabled") || !d2.onClick) return; - } - if (d2.relation) - utilHighlightEntities([d2.relation.id], false, context); - var role = context.cleanRelationRole(list.selectAll(".member-row-new .member-role").property("value")); - addMembership(d2, role); - } - function cancelEntity() { - var input = newMembership.selectAll(".member-entity-input"); - input.property("value", ""); - context.surface().selectAll(".highlighted").classed("highlighted", false); - } - function bindTypeahead(d2) { - var row = select_default2(this); - var role = row.selectAll("input.member-role"); - var origValue = role.property("value"); - function sort(value, data) { - var sameletter = []; - var other = []; - for (var i3 = 0; i3 < data.length; i3++) { - if (data[i3].value.substring(0, value.length) === value) { - sameletter.push(data[i3]); - } else { - other.push(data[i3]); - } + if (d2.issue.dateLastRanFix && /* @__PURE__ */ new Date() - d2.issue.dateLastRanFix < 1e3) + return; + d2.issue.dateLastRanFix = /* @__PURE__ */ new Date(); + utilHighlightEntities(d2.issue.entityIds.concat(d2.entityIds), false, context); + new Promise(function(resolve, reject) { + d2.onClick(context, resolve, reject); + if (d2.onClick.length <= 1) { + resolve(); } - return sameletter.concat(other); + }).then(function() { + context.validator().validate(); + }); + }).on("mouseover.highlight", function(d3_event, d2) { + utilHighlightEntities(d2.entityIds, true, context); + }).on("mouseout.highlight", function(d3_event, d2) { + utilHighlightEntities(d2.entityIds, false, context); + }); + buttons.each(function(d2) { + var iconName = d2.icon || "iD-icon-wrench"; + if (iconName.startsWith("maki")) { + iconName += "-15"; } - role.call( - uiCombobox(context, "member-role").fetcher(function(role2, callback) { - var rtype = d2.relation.tags.type; - taginfo.roles({ - debounce: true, - rtype: rtype || "", - geometry: context.graph().geometry(_entityIDs[0]), - query: role2 - }, function(err, data) { - if (!err) - callback(sort(role2, data)); - }); - }).on("cancel", function() { - role.property("value", origValue); - }) - ); - } - function unbind() { - var row = select_default2(this); - row.selectAll("input.member-role").call(uiCombobox.off, context); - } + select_default2(this).call(svgIcon("#" + iconName, "fix-icon")); + }); + buttons.append("span").attr("class", "fix-message").each(function(d2) { + return d2.title(select_default2(this)); + }); + fixesEnter.merge(fixes).selectAll("button").classed("actionable", function(d2) { + return d2.onClick; + }).attr("disabled", function(d2) { + return d2.onClick ? null : "true"; + }).attr("title", function(d2) { + if (d2.disabledReason) { + return d2.disabledReason; + } + return null; + }); } section.entityIDs = function(val) { if (!arguments.length) return _entityIDs; - _entityIDs = val; - _showBlank = false; + if (!_entityIDs || !val || !utilArrayIdentical(_entityIDs, val)) { + _entityIDs = val; + _activeIssueID = null; + reloadIssues(); + } return section; }; return section; } - // modules/ui/sections/selection_list.js - function uiSectionSelectionList(context) { - var _selectedIDs = []; - var section = uiSection("selected-features", context).shouldDisplay(function() { - return _selectedIDs.length > 1; - }).label(function() { - return _t.append("inspector.title_count", { title: _t("inspector.features"), count: _selectedIDs.length }); - }).disclosureContent(renderDisclosureContent); - context.history().on("change.selectionList", function(difference) { - if (difference) { - section.reRender(); - } - }); - section.entityIDs = function(val) { - if (!arguments.length) - return _selectedIDs; - _selectedIDs = val; - return section; - }; - function selectEntity(d3_event, entity) { - context.enter(modeSelect(context, [entity.id])); + // modules/ui/preset_icon.js + function uiPresetIcon() { + let _preset; + let _geometry; + function presetIcon(selection2) { + selection2.each(render); } - function deselectEntity(d3_event, entity) { - var selectedIDs = _selectedIDs.slice(); - var index = selectedIDs.indexOf(entity.id); - if (index > -1) { - selectedIDs.splice(index, 1); - context.enter(modeSelect(context, selectedIDs)); + function getIcon(p2, geom) { + if (p2.isFallback && p2.isFallback()) + return geom === "vertex" ? "" : "iD-icon-" + p2.id; + if (p2.icon) + return p2.icon; + if (geom === "line") + return "iD-other-line"; + if (geom === "vertex") + return "temaki-vertex"; + return "maki-marker-stroked"; + } + function renderPointBorder(container, drawPoint) { + let pointBorder = container.selectAll(".preset-icon-point-border").data(drawPoint ? [0] : []); + pointBorder.exit().remove(); + let pointBorderEnter = pointBorder.enter(); + const w2 = 40; + const h2 = 40; + pointBorderEnter.append("svg").attr("class", "preset-icon-fill preset-icon-point-border").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)).append("path").attr("transform", "translate(11.5, 8)").attr("d", "M 17,8 C 17,13 11,21 8.5,23.5 C 6,21 0,13 0,8 C 0,4 4,-0.5 8.5,-0.5 C 13,-0.5 17,4 17,8 z"); + pointBorder = pointBorderEnter.merge(pointBorder); + } + function renderCategoryBorder(container, category) { + let categoryBorder = container.selectAll(".preset-icon-category-border").data(category ? [0] : []); + categoryBorder.exit().remove(); + let categoryBorderEnter = categoryBorder.enter(); + const d2 = 60; + let svgEnter = categoryBorderEnter.append("svg").attr("class", "preset-icon-fill preset-icon-category-border").attr("width", d2).attr("height", d2).attr("viewBox", "0 0 ".concat(d2, " ").concat(d2)); + svgEnter.append("path").attr("class", "area").attr("d", "M9.5,7.5 L25.5,7.5 L28.5,12.5 L49.5,12.5 C51.709139,12.5 53.5,14.290861 53.5,16.5 L53.5,43.5 C53.5,45.709139 51.709139,47.5 49.5,47.5 L10.5,47.5 C8.290861,47.5 6.5,45.709139 6.5,43.5 L6.5,12.5 L9.5,7.5 Z"); + categoryBorder = categoryBorderEnter.merge(categoryBorder); + if (category) { + categoryBorder.selectAll("path").attr("class", "area ".concat(category.id)); } } - function renderDisclosureContent(selection2) { - var list = selection2.selectAll(".feature-list").data([0]); - list = list.enter().append("ul").attr("class", "feature-list").merge(list); - var entities = _selectedIDs.map(function(id2) { - return context.hasEntity(id2); - }).filter(Boolean); - var items = list.selectAll(".feature-list-item").data(entities, osmEntity.key); - items.exit().remove(); - var enter = items.enter().append("li").attr("class", "feature-list-item").each(function(d2) { - select_default2(this).on("mouseover", function() { - utilHighlightEntities([d2.id], true, context); - }).on("mouseout", function() { - utilHighlightEntities([d2.id], false, context); - }); - }); - var label = enter.append("button").attr("class", "label").on("click", selectEntity); - label.append("span").attr("class", "entity-geom-icon").call(svgIcon("", "pre-text")); - label.append("span").attr("class", "entity-type"); - label.append("span").attr("class", "entity-name"); - enter.append("button").attr("class", "close").attr("title", _t("icons.deselect")).on("click", deselectEntity).call(svgIcon("#iD-icon-close")); - items = items.merge(enter); - items.selectAll(".entity-geom-icon use").attr("href", function() { - var entity = this.parentNode.parentNode.__data__; - return "#iD-icon-" + entity.geometry(context.graph()); + function renderCircleFill(container, drawVertex) { + let vertexFill = container.selectAll(".preset-icon-fill-vertex").data(drawVertex ? [0] : []); + vertexFill.exit().remove(); + let vertexFillEnter = vertexFill.enter(); + const w2 = 60; + const h2 = 60; + const d2 = 40; + vertexFillEnter.append("svg").attr("class", "preset-icon-fill preset-icon-fill-vertex").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)).append("circle").attr("cx", w2 / 2).attr("cy", h2 / 2).attr("r", d2 / 2); + vertexFill = vertexFillEnter.merge(vertexFill); + } + function renderSquareFill(container, drawArea, tagClasses) { + let fill = container.selectAll(".preset-icon-fill-area").data(drawArea ? [0] : []); + fill.exit().remove(); + let fillEnter = fill.enter(); + const d2 = 60; + const w2 = d2; + const h2 = d2; + const l2 = d2 * 2 / 3; + const c1 = (w2 - l2) / 2; + const c2 = c1 + l2; + fillEnter = fillEnter.append("svg").attr("class", "preset-icon-fill preset-icon-fill-area").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)); + ["fill", "stroke"].forEach((klass) => { + fillEnter.append("path").attr("d", "M".concat(c1, " ").concat(c1, " L").concat(c1, " ").concat(c2, " L").concat(c2, " ").concat(c2, " L").concat(c2, " ").concat(c1, " Z")).attr("class", "area ".concat(klass)); }); - items.selectAll(".entity-type").text(function(entity) { - return _mainPresetIndex.match(entity, context.graph()).name(); + const rVertex = 2.5; + [[c1, c1], [c1, c2], [c2, c2], [c2, c1]].forEach((point2) => { + fillEnter.append("circle").attr("class", "vertex").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", rVertex); }); - items.selectAll(".entity-name").text(function(d2) { - var entity = context.entity(d2.id); - return utilDisplayName(entity); + const rMidpoint = 1.25; + [[c1, w2 / 2], [c2, w2 / 2], [h2 / 2, c1], [h2 / 2, c2]].forEach((point2) => { + fillEnter.append("circle").attr("class", "midpoint").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", rMidpoint); }); + fill = fillEnter.merge(fill); + fill.selectAll("path.stroke").attr("class", "area stroke ".concat(tagClasses)); + fill.selectAll("path.fill").attr("class", "area fill ".concat(tagClasses)); } - return section; - } - - // modules/ui/entity_editor.js - function uiEntityEditor(context) { - var dispatch14 = dispatch_default("choose"); - var _state = "select"; - var _coalesceChanges = false; - var _modified = false; - var _base; - var _entityIDs; - var _activePresets = []; - var _newFeature; - var _sections; - function entityEditor(selection2) { - var combinedTags = utilCombinedTags(_entityIDs, context.graph()); - var header = selection2.selectAll(".header").data([0]); - var headerEnter = header.enter().append("div").attr("class", "header fillL"); - var direction = _mainLocalizer.textDirection() === "rtl" ? "forward" : "backward"; - headerEnter.append("button").attr("class", "preset-reset preset-choose").attr("title", _t("inspector.back_tooltip")).call(svgIcon("#iD-icon-".concat(direction))); - headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function() { - context.enter(modeBrowse(context)); - }).call(svgIcon(_modified ? "#iD-icon-apply" : "#iD-icon-close")); - headerEnter.append("h2"); - header = header.merge(headerEnter); - header.selectAll("h2").text("").call(_entityIDs.length === 1 ? _t.append("inspector.edit") : _t.append("inspector.edit_features")); - header.selectAll(".preset-reset").on("click", function() { - dispatch14.call("choose", this, _activePresets); + function renderLine(container, drawLine, tagClasses) { + let line = container.selectAll(".preset-icon-line").data(drawLine ? [0] : []); + line.exit().remove(); + let lineEnter = line.enter(); + const d2 = 60; + const w2 = d2; + const h2 = d2; + const y2 = Math.round(d2 * 0.72); + const l2 = Math.round(d2 * 0.6); + const r2 = 2.5; + const x12 = (w2 - l2) / 2; + const x2 = x12 + l2; + lineEnter = lineEnter.append("svg").attr("class", "preset-icon-line").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)); + ["casing", "stroke"].forEach((klass) => { + lineEnter.append("path").attr("d", "M".concat(x12, " ").concat(y2, " L").concat(x2, " ").concat(y2)).attr("class", "line ".concat(klass)); }); - var body = selection2.selectAll(".inspector-body").data([0]); - var bodyEnter = body.enter().append("div").attr("class", "entity-editor inspector-body sep-top"); - body = body.merge(bodyEnter); - if (!_sections) { - _sections = [ - uiSectionSelectionList(context), - uiSectionFeatureType(context).on("choose", function(presets) { - dispatch14.call("choose", this, presets); - }), - uiSectionEntityIssues(context), - uiSectionPresetFields(context).on("change", changeTags).on("revert", revertTags), - uiSectionRawTagEditor("raw-tag-editor", context).on("change", changeTags), - uiSectionRawMemberEditor(context), - uiSectionRawMembershipEditor(context) - ]; - } - _sections.forEach(function(section) { - if (section.entityIDs) { - section.entityIDs(_entityIDs); - } - if (section.presets) { - section.presets(_activePresets); - } - if (section.tags) { - section.tags(combinedTags); - } - if (section.state) { - section.state(_state); - } - body.call(section.render); + [[x12 - 1, y2], [x2 + 1, y2]].forEach((point2) => { + lineEnter.append("circle").attr("class", "vertex").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", r2); }); - context.history().on("change.entity-editor", historyChanged); - function historyChanged(difference) { - if (selection2.selectAll(".entity-editor").empty()) - return; - if (_state === "hide") - return; - var significant = !difference || difference.didChange.properties || difference.didChange.addition || difference.didChange.deletion; - if (!significant) - return; - _entityIDs = _entityIDs.filter(context.hasEntity); - if (!_entityIDs.length) - return; - var priorActivePreset = _activePresets.length === 1 && _activePresets[0]; - loadActivePresets(); - var graph = context.graph(); - entityEditor.modified(_base !== graph); - entityEditor(selection2); - if (priorActivePreset && _activePresets.length === 1 && priorActivePreset !== _activePresets[0]) { - context.container().selectAll(".entity-editor button.preset-reset .label").style("background-color", "#fff").transition().duration(750).style("background-color", null); - } - } - } - function changeTags(entityIDs, changed, onInput) { - var actions = []; - for (var i3 in entityIDs) { - var entityID = entityIDs[i3]; - var entity = context.entity(entityID); - var tags = Object.assign({}, entity.tags); - if (typeof changed === "function") { - tags = changed(tags); - } else { - for (var k2 in changed) { - if (!k2) - continue; - var v2 = changed[k2]; - if (typeof v2 === "object") { - tags[k2] = tags[v2.oldKey]; - } else if (v2 !== void 0 || tags.hasOwnProperty(k2)) { - tags[k2] = v2; - } - } - } - if (!onInput) { - tags = utilCleanTags(tags); - } - if (!(0, import_fast_deep_equal10.default)(entity.tags, tags)) { - actions.push(actionChangeTags(entityID, tags)); - } - } - if (actions.length) { - var combinedAction = function(graph) { - actions.forEach(function(action) { - graph = action(graph); - }); - return graph; - }; - var annotation = _t("operations.change_tags.annotation"); - if (_coalesceChanges) { - context.overwrite(combinedAction, annotation); - } else { - context.perform(combinedAction, annotation); - _coalesceChanges = !!onInput; - } - } - if (!onInput) { - context.validator().validate(); - } + line = lineEnter.merge(line); + line.selectAll("path.stroke").attr("class", "line stroke ".concat(tagClasses)); + line.selectAll("path.casing").attr("class", "line casing ".concat(tagClasses)); } - function revertTags(keys2) { - var actions = []; - for (var i3 in _entityIDs) { - var entityID = _entityIDs[i3]; - var original = context.graph().base().entities[entityID]; - var changed = {}; - for (var j3 in keys2) { - var key = keys2[j3]; - changed[key] = original ? original.tags[key] : void 0; - } - var entity = context.entity(entityID); - var tags = Object.assign({}, entity.tags); - for (var k2 in changed) { - if (!k2) - continue; - var v2 = changed[k2]; - if (v2 !== void 0 || tags.hasOwnProperty(k2)) { - tags[k2] = v2; - } - } - tags = utilCleanTags(tags); - if (!(0, import_fast_deep_equal10.default)(entity.tags, tags)) { - actions.push(actionChangeTags(entityID, tags)); + function renderRoute(container, drawRoute, p2) { + let route = container.selectAll(".preset-icon-route").data(drawRoute ? [0] : []); + route.exit().remove(); + let routeEnter = route.enter(); + const d2 = 60; + const w2 = d2; + const h2 = d2; + const y12 = Math.round(d2 * 0.8); + const y2 = Math.round(d2 * 0.68); + const l2 = Math.round(d2 * 0.6); + const r2 = 2; + const x12 = (w2 - l2) / 2; + const x2 = x12 + l2 / 3; + const x3 = x2 + l2 / 3; + const x4 = x3 + l2 / 3; + routeEnter = routeEnter.append("svg").attr("class", "preset-icon-route").attr("width", w2).attr("height", h2).attr("viewBox", "0 0 ".concat(w2, " ").concat(h2)); + ["casing", "stroke"].forEach((klass) => { + routeEnter.append("path").attr("d", "M".concat(x12, " ").concat(y12, " L").concat(x2, " ").concat(y2)).attr("class", "segment0 line ".concat(klass)); + routeEnter.append("path").attr("d", "M".concat(x2, " ").concat(y2, " L").concat(x3, " ").concat(y12)).attr("class", "segment1 line ".concat(klass)); + routeEnter.append("path").attr("d", "M".concat(x3, " ").concat(y12, " L").concat(x4, " ").concat(y2)).attr("class", "segment2 line ".concat(klass)); + }); + [[x12, y12], [x2, y2], [x3, y12], [x4, y2]].forEach((point2) => { + routeEnter.append("circle").attr("class", "vertex").attr("cx", point2[0]).attr("cy", point2[1]).attr("r", r2); + }); + route = routeEnter.merge(route); + if (drawRoute) { + let routeType = p2.tags.type === "waterway" ? "waterway" : p2.tags.route; + const segmentPresetIDs = routeSegments[routeType]; + for (let i3 in segmentPresetIDs) { + const segmentPreset = _mainPresetIndex.item(segmentPresetIDs[i3]); + const segmentTagClasses = svgTagClasses().getClassesString(segmentPreset.tags, ""); + route.selectAll("path.stroke.segment".concat(i3)).attr("class", "segment".concat(i3, " line stroke ").concat(segmentTagClasses)); + route.selectAll("path.casing.segment".concat(i3)).attr("class", "segment".concat(i3, " line casing ").concat(segmentTagClasses)); } } - if (actions.length) { - var combinedAction = function(graph) { - actions.forEach(function(action) { - graph = action(graph); - }); - return graph; - }; - var annotation = _t("operations.change_tags.annotation"); - if (_coalesceChanges) { - context.overwrite(combinedAction, annotation); - } else { - context.perform(combinedAction, annotation); - _coalesceChanges = false; + } + function renderSvgIcon(container, picon, geom, isFramed, category, tagClasses) { + const isMaki = picon && /^maki-/.test(picon); + const isTemaki = picon && /^temaki-/.test(picon); + const isFa = picon && /^fa[srb]-/.test(picon); + const isR\u00F6ntgen = picon && /^roentgen-/.test(picon); + const isiDIcon = picon && !(isMaki || isTemaki || isFa || isR\u00F6ntgen); + let icon2 = container.selectAll(".preset-icon").data(picon ? [0] : []); + icon2.exit().remove(); + icon2 = icon2.enter().append("div").attr("class", "preset-icon").call(svgIcon("")).merge(icon2); + icon2.attr("class", "preset-icon " + (geom ? geom + "-geom" : "")).classed("category", category).classed("framed", isFramed).classed("preset-icon-iD", isiDIcon); + icon2.selectAll("svg").attr("class", "icon " + picon + " " + (!isiDIcon && geom !== "line" ? "" : tagClasses)); + icon2.selectAll("use").attr("href", "#" + picon); + } + function renderImageIcon(container, imageURL) { + let imageIcon = container.selectAll("img.image-icon").data(imageURL ? [0] : []); + imageIcon.exit().remove(); + imageIcon = imageIcon.enter().append("img").attr("class", "image-icon").on("load", () => container.classed("showing-img", true)).on("error", () => container.classed("showing-img", false)).merge(imageIcon); + imageIcon.attr("src", imageURL); + } + const routeSegments = { + bicycle: ["highway/cycleway", "highway/cycleway", "highway/cycleway"], + bus: ["highway/unclassified", "highway/secondary", "highway/primary"], + trolleybus: ["highway/unclassified", "highway/secondary", "highway/primary"], + detour: ["highway/tertiary", "highway/residential", "highway/unclassified"], + ferry: ["route/ferry", "route/ferry", "route/ferry"], + foot: ["highway/footway", "highway/footway", "highway/footway"], + hiking: ["highway/path", "highway/path", "highway/path"], + horse: ["highway/bridleway", "highway/bridleway", "highway/bridleway"], + light_rail: ["railway/light_rail", "railway/light_rail", "railway/light_rail"], + monorail: ["railway/monorail", "railway/monorail", "railway/monorail"], + mtb: ["highway/path", "highway/track", "highway/bridleway"], + pipeline: ["man_made/pipeline", "man_made/pipeline", "man_made/pipeline"], + piste: ["piste/downhill", "piste/hike", "piste/nordic"], + power: ["power/line", "power/line", "power/line"], + road: ["highway/secondary", "highway/primary", "highway/trunk"], + subway: ["railway/subway", "railway/subway", "railway/subway"], + train: ["railway/rail", "railway/rail", "railway/rail"], + tram: ["railway/tram", "railway/tram", "railway/tram"], + railway: ["railway/rail", "railway/rail", "railway/rail"], + waterway: ["waterway/stream", "waterway/stream", "waterway/stream"] + }; + function render() { + let p2 = _preset.apply(this, arguments); + let geom = _geometry ? _geometry.apply(this, arguments) : null; + if (geom === "relation" && p2.tags && (p2.tags.type === "route" && p2.tags.route && routeSegments[p2.tags.route] || p2.tags.type === "waterway")) { + geom = "route"; + } + const showThirdPartyIcons = corePreferences("preferences.privacy.thirdpartyicons") || "true"; + const isFallback = p2.isFallback && p2.isFallback(); + const imageURL = showThirdPartyIcons === "true" && p2.imageURL; + const picon = getIcon(p2, geom); + const isCategory = !p2.setTags; + const drawPoint = false; + const drawVertex = picon !== null && geom === "vertex"; + const drawLine = picon && geom === "line" && !isFallback && !isCategory; + const drawArea = picon && geom === "area" && !isFallback && !isCategory; + const drawRoute = picon && geom === "route"; + const isFramed = drawVertex || drawArea || drawLine || drawRoute || isCategory; + let tags = !isCategory ? p2.setTags({}, geom) : {}; + for (let k2 in tags) { + if (tags[k2] === "*") { + tags[k2] = "yes"; } } - context.validator().validate(); + let tagClasses = svgTagClasses().getClassesString(tags, ""); + let selection2 = select_default2(this); + let container = selection2.selectAll(".preset-icon-container").data([0]); + container = container.enter().append("div").attr("class", "preset-icon-container").merge(container); + container.classed("showing-img", !!imageURL).classed("fallback", isFallback); + renderCategoryBorder(container, isCategory && p2); + renderPointBorder(container, drawPoint); + renderCircleFill(container, drawVertex); + renderSquareFill(container, drawArea, tagClasses); + renderLine(container, drawLine, tagClasses); + renderRoute(container, drawRoute, p2); + renderSvgIcon(container, picon, geom, isFramed, isCategory, tagClasses); + renderImageIcon(container, imageURL); } - entityEditor.modified = function(val) { + presetIcon.preset = function(val) { if (!arguments.length) - return _modified; - _modified = val; - return entityEditor; + return _preset; + _preset = utilFunctor(val); + return presetIcon; }; - entityEditor.state = function(val) { + presetIcon.geometry = function(val) { if (!arguments.length) - return _state; - _state = val; - return entityEditor; + return _geometry; + _geometry = utilFunctor(val); + return presetIcon; }; - entityEditor.entityIDs = function(val) { + return presetIcon; + } + + // modules/ui/sections/feature_type.js + function uiSectionFeatureType(context) { + var dispatch14 = dispatch_default("choose"); + var _entityIDs = []; + var _presets = []; + var _tagReference; + var section = uiSection("feature-type", context).label(() => _t.append("inspector.feature_type")).disclosureContent(renderDisclosureContent); + function renderDisclosureContent(selection2) { + selection2.classed("preset-list-item", true); + selection2.classed("mixed-types", _presets.length > 1); + var presetButtonWrap = selection2.selectAll(".preset-list-button-wrap").data([0]).enter().append("div").attr("class", "preset-list-button-wrap"); + var presetButton = presetButtonWrap.append("button").attr("class", "preset-list-button preset-reset").call( + uiTooltip().title(() => _t.append("inspector.back_tooltip")).placement("bottom") + ); + presetButton.append("div").attr("class", "preset-icon-container"); + presetButton.append("div").attr("class", "label").append("div").attr("class", "label-inner"); + presetButtonWrap.append("div").attr("class", "accessory-buttons"); + var tagReferenceBodyWrap = selection2.selectAll(".tag-reference-body-wrap").data([0]); + tagReferenceBodyWrap = tagReferenceBodyWrap.enter().append("div").attr("class", "tag-reference-body-wrap").merge(tagReferenceBodyWrap); + if (_tagReference) { + selection2.selectAll(".preset-list-button-wrap .accessory-buttons").style("display", _presets.length === 1 ? null : "none").call(_tagReference.button); + tagReferenceBodyWrap.style("display", _presets.length === 1 ? null : "none").call(_tagReference.body); + } + selection2.selectAll(".preset-reset").on("click", function() { + dispatch14.call("choose", this, _presets); + }).on("pointerdown pointerup mousedown mouseup", function(d3_event) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + }); + var geometries = entityGeometries(); + selection2.select(".preset-list-item button").call( + uiPresetIcon().geometry(_presets.length === 1 ? geometries.length === 1 && geometries[0] : null).preset(_presets.length === 1 ? _presets[0] : _mainPresetIndex.item("point")) + ); + var names = _presets.length === 1 ? [ + _presets[0].nameLabel(), + _presets[0].subtitleLabel() + ].filter(Boolean) : [_t.append("inspector.multiple_types")]; + var label = selection2.select(".label-inner"); + var nameparts = label.selectAll(".namepart").data(names, (d2) => d2.stringId); + nameparts.exit().remove(); + nameparts.enter().append("div").attr("class", "namepart").text("").each(function(d2) { + d2(select_default2(this)); + }); + } + section.entityIDs = function(val) { if (!arguments.length) return _entityIDs; - _base = context.graph(); - _coalesceChanges = false; - if (val && _entityIDs && utilArrayIdentical(_entityIDs, val)) - return entityEditor; _entityIDs = val; - loadActivePresets(true); - return entityEditor.modified(false); + return section; }; - entityEditor.newFeature = function(val) { + section.presets = function(val) { if (!arguments.length) - return _newFeature; - _newFeature = val; - return entityEditor; + return _presets; + if (!utilArrayIdentical(val, _presets)) { + _presets = val; + if (_presets.length === 1) { + _tagReference = uiTagReference(_presets[0].reference(), context).showing(false); + } + } + return section; }; - function loadActivePresets(isForNewSelection) { - var graph = context.graph(); + function entityGeometries() { var counts = {}; for (var i3 in _entityIDs) { - var entity = graph.hasEntity(_entityIDs[i3]); - if (!entity) - return; - var match = _mainPresetIndex.match(entity, graph); - if (!counts[match.id]) - counts[match.id] = 0; - counts[match.id] += 1; + var geometry = context.graph().geometry(_entityIDs[i3]); + if (!counts[geometry]) + counts[geometry] = 0; + counts[geometry] += 1; } - var matches = Object.keys(counts).sort(function(p1, p2) { - return counts[p2] - counts[p1]; - }).map(function(pID) { - return _mainPresetIndex.item(pID); + return Object.keys(counts).sort(function(geom1, geom2) { + return counts[geom2] - counts[geom1]; }); - if (!isForNewSelection) { - var weakPreset = _activePresets.length === 1 && !_activePresets[0].isFallback() && Object.keys(_activePresets[0].addTags || {}).length === 0; - if (weakPreset && matches.length === 1 && matches[0].isFallback()) - return; - } - entityEditor.presets(matches); } - entityEditor.presets = function(val) { - if (!arguments.length) - return _activePresets; - if (!utilArrayIdentical(val, _activePresets)) { - _activePresets = val; - } - return entityEditor; - }; - return utilRebind(entityEditor, dispatch14, "on"); + return utilRebind(section, dispatch14, "on"); } - // modules/ui/feature_list.js - var sexagesimal = __toESM(require_sexagesimal()); - function uiFeatureList(context) { - var _geocodeResults; - function featureList(selection2) { - var header = selection2.append("div").attr("class", "header fillL"); - header.append("h2").call(_t.append("inspector.feature_list")); - var searchWrap = selection2.append("div").attr("class", "search-header"); - searchWrap.call(svgIcon("#iD-icon-search", "pre-text")); - var search = searchWrap.append("input").attr("placeholder", _t("inspector.search")).attr("type", "search").call(utilNoAuto).on("keypress", keypress).on("keydown", keydown).on("input", inputevent); - var listWrap = selection2.append("div").attr("class", "inspector-body"); - var list = listWrap.append("div").attr("class", "feature-list"); - context.on("exit.feature-list", clearSearch); - context.map().on("drawn.feature-list", mapDrawn); - context.keybinding().on(uiCmd("\u2318F"), focusSearch); - function focusSearch(d3_event) { - var mode = context.mode() && context.mode().id; - if (mode !== "browse") - return; - d3_event.preventDefault(); - search.node().focus(); - } - function keydown(d3_event) { - if (d3_event.keyCode === 27) { - search.node().blur(); + // modules/ui/sections/preset_fields.js + function uiSectionPresetFields(context) { + var section = uiSection("preset-fields", context).label(() => _t.append("inspector.fields")).disclosureContent(renderDisclosureContent); + var dispatch14 = dispatch_default("change", "revert"); + var formFields = uiFormFields(context); + var _state; + var _fieldsArr; + var _presets = []; + var _tags; + var _entityIDs; + function renderDisclosureContent(selection2) { + if (!_fieldsArr) { + var graph = context.graph(); + var geometries = Object.keys(_entityIDs.reduce(function(geoms, entityID) { + geoms[graph.entity(entityID).geometry(graph)] = true; + return geoms; + }, {})); + const loc = _entityIDs.reduce(function(extent, entityID) { + var entity = context.graph().entity(entityID); + return extent.extend(entity.extent(context.graph())); + }, geoExtent()).center(); + var presetsManager = _mainPresetIndex; + var allFields = []; + var allMoreFields = []; + var sharedTotalFields; + _presets.forEach(function(preset) { + var fields = preset.fields(loc); + var moreFields = preset.moreFields(loc); + allFields = utilArrayUnion(allFields, fields); + allMoreFields = utilArrayUnion(allMoreFields, moreFields); + if (!sharedTotalFields) { + sharedTotalFields = utilArrayUnion(fields, moreFields); + } else { + sharedTotalFields = sharedTotalFields.filter(function(field) { + return fields.indexOf(field) !== -1 || moreFields.indexOf(field) !== -1; + }); + } + }); + var sharedFields = allFields.filter(function(field) { + return sharedTotalFields.indexOf(field) !== -1; + }); + var sharedMoreFields = allMoreFields.filter(function(field) { + return sharedTotalFields.indexOf(field) !== -1; + }); + _fieldsArr = []; + sharedFields.forEach(function(field) { + if (field.matchAllGeometry(geometries)) { + _fieldsArr.push( + uiField(context, field, _entityIDs) + ); + } + }); + var singularEntity = _entityIDs.length === 1 && graph.hasEntity(_entityIDs[0]); + if (singularEntity && singularEntity.isHighwayIntersection(graph) && presetsManager.field("restrictions")) { + _fieldsArr.push( + uiField(context, presetsManager.field("restrictions"), _entityIDs) + ); } + var additionalFields = utilArrayUnion(sharedMoreFields, presetsManager.universal()); + additionalFields.sort(function(field1, field2) { + return field1.title().localeCompare(field2.title(), _mainLocalizer.localeCode()); + }); + additionalFields.forEach(function(field) { + if (sharedFields.indexOf(field) === -1 && field.matchAllGeometry(geometries)) { + _fieldsArr.push( + uiField(context, field, _entityIDs, { show: false }) + ); + } + }); + _fieldsArr.forEach(function(field) { + field.on("change", function(t2, onInput) { + dispatch14.call("change", field, _entityIDs, t2, onInput); + }).on("revert", function(keys2) { + dispatch14.call("revert", field, keys2); + }); + }); } - function keypress(d3_event) { - var q2 = search.property("value"), items = list.selectAll(".feature-list-item"); - if (d3_event.keyCode === 13 && // ↩ Return - q2.length && items.size()) { - click(d3_event, items.datum()); - } + _fieldsArr.forEach(function(field) { + field.state(_state).tags(_tags); + }); + selection2.call( + formFields.fieldsArr(_fieldsArr).state(_state).klass("grouped-items-area") + ); + } + section.presets = function(val) { + if (!arguments.length) + return _presets; + if (!_presets || !val || !utilArrayIdentical(_presets, val)) { + _presets = val; + _fieldsArr = null; } - function inputevent() { - _geocodeResults = void 0; - drawList(); + return section; + }; + section.state = function(val) { + if (!arguments.length) + return _state; + _state = val; + return section; + }; + section.tags = function(val) { + if (!arguments.length) + return _tags; + _tags = val; + return section; + }; + section.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + if (!val || !_entityIDs || !utilArrayIdentical(_entityIDs, val)) { + _entityIDs = val; + _fieldsArr = null; } - function clearSearch() { - search.property("value", ""); - drawList(); + return section; + }; + return utilRebind(section, dispatch14, "on"); + } + + // modules/ui/sections/raw_member_editor.js + function uiSectionRawMemberEditor(context) { + var section = uiSection("raw-member-editor", context).shouldDisplay(function() { + if (!_entityIDs || _entityIDs.length !== 1) + return false; + var entity = context.hasEntity(_entityIDs[0]); + return entity && entity.type === "relation"; + }).label(function() { + var entity = context.hasEntity(_entityIDs[0]); + if (!entity) + return ""; + var gt2 = entity.members.length > _maxMembers ? ">" : ""; + var count = gt2 + entity.members.slice(0, _maxMembers).length; + return _t.append("inspector.title_count", { title: _t("inspector.members"), count }); + }).disclosureContent(renderDisclosureContent); + var taginfo = services.taginfo; + var _entityIDs; + var _maxMembers = 1e3; + function downloadMember(d3_event, d2) { + d3_event.preventDefault(); + select_default2(this.parentNode).classed("tag-reference-loading", true); + context.loadEntity(d2.id, function() { + section.reRender(); + }); + } + function zoomToMember(d3_event, d2) { + d3_event.preventDefault(); + var entity = context.entity(d2.id); + context.map().zoomToEase(entity); + utilHighlightEntities([d2.id], true, context); + } + function selectMember(d3_event, d2) { + d3_event.preventDefault(); + utilHighlightEntities([d2.id], false, context); + var entity = context.entity(d2.id); + var mapExtent = context.map().extent(); + if (!entity.intersects(mapExtent, context.graph())) { + context.map().zoomToEase(entity); } - function mapDrawn(e3) { - if (e3.full) { - drawList(); - } + context.enter(modeSelect(context, [d2.id])); + } + function changeRole(d3_event, d2) { + var oldRole = d2.role; + var newRole = context.cleanRelationRole(select_default2(this).property("value")); + if (oldRole !== newRole) { + var member = { id: d2.id, type: d2.type, role: newRole }; + context.perform( + actionChangeMember(d2.relation.id, member, d2.index), + _t("operations.change_role.annotation", { + n: 1 + }) + ); + context.validator().validate(); } - function features() { - var result = []; - var graph = context.graph(); - var visibleCenter = context.map().extent().center(); - var q2 = search.property("value").toLowerCase(); - if (!q2) - return result; - var locationMatch = sexagesimal.pair(q2.toUpperCase()) || q2.match(/^(-?\d+\.?\d*)\s+(-?\d+\.?\d*)$/); - if (locationMatch) { - var loc = [Number(locationMatch[0]), Number(locationMatch[1])]; - result.push({ - id: -1, - geometry: "point", - type: _t("inspector.location"), - name: dmsCoordinatePair([loc[1], loc[0]]), - location: loc - }); - } - var idMatch = !locationMatch && q2.match(/(?:^|\W)(node|way|relation|[nwr])\W{0,2}0*([1-9]\d*)(?:\W|$)/i); - if (idMatch) { - var elemType = idMatch[1].charAt(0); - var elemId = idMatch[2]; - result.push({ - id: elemType + elemId, - geometry: elemType === "n" ? "point" : elemType === "w" ? "line" : "relation", - type: elemType === "n" ? _t("inspector.node") : elemType === "w" ? _t("inspector.way") : _t("inspector.relation"), - name: elemId - }); - } - var allEntities = graph.entities; - var localResults = []; - for (var id2 in allEntities) { - var entity = allEntities[id2]; - if (!entity) - continue; - var name = utilDisplayName(entity) || ""; - if (name.toLowerCase().indexOf(q2) < 0) - continue; - var matched = _mainPresetIndex.match(entity, graph); - var type2 = matched && matched.name() || utilDisplayType(entity.id); - var extent = entity.extent(graph); - var distance = extent ? geoSphericalDistance(visibleCenter, extent.center()) : 0; - localResults.push({ - id: entity.id, - entity, - geometry: entity.geometry(graph), - type: type2, - name, - distance - }); - if (localResults.length > 100) - break; - } - localResults = localResults.sort(function byDistance(a2, b2) { - return a2.distance - b2.distance; - }); - result = result.concat(localResults); - (_geocodeResults || []).forEach(function(d2) { - if (d2.osm_type && d2.osm_id) { - var id3 = osmEntity.id.fromOSM(d2.osm_type, d2.osm_id); - var tags = {}; - tags[d2.class] = d2.type; - var attrs = { id: id3, type: d2.osm_type, tags }; - if (d2.osm_type === "way") { - attrs.nodes = ["a", "a"]; - } - var tempEntity = osmEntity(attrs); - var tempGraph = coreGraph([tempEntity]); - var matched2 = _mainPresetIndex.match(tempEntity, tempGraph); - var type3 = matched2 && matched2.name() || utilDisplayType(id3); - result.push({ - id: tempEntity.id, - geometry: tempEntity.geometry(tempGraph), - type: type3, - name: d2.display_name, - extent: new geoExtent( - [Number(d2.boundingbox[3]), Number(d2.boundingbox[0])], - [Number(d2.boundingbox[2]), Number(d2.boundingbox[1])] - ) - }); - } + } + function deleteMember(d3_event, d2) { + utilHighlightEntities([d2.id], false, context); + context.perform( + actionDeleteMember(d2.relation.id, d2.index), + _t("operations.delete_member.annotation", { + n: 1 + }) + ); + if (!context.hasEntity(d2.relation.id)) { + context.enter(modeBrowse(context)); + } else { + context.validator().validate(); + } + } + function renderDisclosureContent(selection2) { + var entityID = _entityIDs[0]; + var memberships = []; + var entity = context.entity(entityID); + entity.members.slice(0, _maxMembers).forEach(function(member, index) { + memberships.push({ + index, + id: member.id, + type: member.type, + role: member.role, + relation: entity, + member: context.hasEntity(member.id), + domId: utilUniqueDomId(entityID + "-member-" + index) }); - if (q2.match(/^[0-9]+$/)) { - result.push({ - id: "n" + q2, - geometry: "point", - type: _t("inspector.node"), - name: q2 + }); + var list2 = selection2.selectAll(".member-list").data([0]); + list2 = list2.enter().append("ul").attr("class", "member-list").merge(list2); + var items = list2.selectAll("li").data(memberships, function(d2) { + return osmEntity.key(d2.relation) + "," + d2.index + "," + (d2.member ? osmEntity.key(d2.member) : "incomplete"); + }); + items.exit().each(unbind).remove(); + var itemsEnter = items.enter().append("li").attr("class", "member-row form-field").classed("member-incomplete", function(d2) { + return !d2.member; + }); + itemsEnter.each(function(d2) { + var item = select_default2(this); + var label = item.append("label").attr("class", "field-label").attr("for", d2.domId); + if (d2.member) { + item.on("mouseover", function() { + utilHighlightEntities([d2.id], true, context); + }).on("mouseout", function() { + utilHighlightEntities([d2.id], false, context); }); - result.push({ - id: "w" + q2, - geometry: "line", - type: _t("inspector.way"), - name: q2 + var labelLink = label.append("span").attr("class", "label-text").append("a").attr("href", "#").on("click", selectMember); + labelLink.append("span").attr("class", "member-entity-type").text(function(d4) { + var matched = _mainPresetIndex.match(d4.member, context.graph()); + return matched && matched.name() || utilDisplayType(d4.member.id); }); - result.push({ - id: "r" + q2, - geometry: "relation", - type: _t("inspector.relation"), - name: q2 + labelLink.append("span").attr("class", "member-entity-name").classed("has-colour", (d4) => d4.member.type === "relation" && d4.member.tags.colour && isColourValid(d4.member.tags.colour)).style("border-color", (d4) => d4.member.type === "relation" && d4.member.tags.colour).text(function(d4) { + return utilDisplayName(d4.member); }); + label.append("button").attr("title", _t("icons.remove")).attr("class", "remove member-delete").call(svgIcon("#iD-operation-delete")); + label.append("button").attr("class", "member-zoom").attr("title", _t("icons.zoom_to")).call(svgIcon("#iD-icon-framed-dot", "monochrome")).on("click", zoomToMember); + } else { + var labelText = label.append("span").attr("class", "label-text"); + labelText.append("span").attr("class", "member-entity-type").call(_t.append("inspector." + d2.type, { id: d2.id })); + labelText.append("span").attr("class", "member-entity-name").call(_t.append("inspector.incomplete", { id: d2.id })); + label.append("button").attr("class", "member-download").attr("title", _t("icons.download")).call(svgIcon("#iD-icon-load")).on("click", downloadMember); } - return result; + }); + var wrapEnter = itemsEnter.append("div").attr("class", "form-field-input-wrap form-field-input-member"); + wrapEnter.append("input").attr("class", "member-role").attr("id", function(d2) { + return d2.domId; + }).property("type", "text").attr("placeholder", _t("inspector.role")).call(utilNoAuto); + if (taginfo) { + wrapEnter.each(bindTypeahead); } - function drawList() { - var value = search.property("value"); - var results = features(); - list.classed("filtered", value.length); - var resultsIndicator = list.selectAll(".no-results-item").data([0]).enter().append("button").property("disabled", true).attr("class", "no-results-item").call(svgIcon("#iD-icon-alert", "pre-text")); - resultsIndicator.append("span").attr("class", "entity-name"); - list.selectAll(".no-results-item .entity-name").html("").call(_t.append("geocoder.no_results_worldwide")); - if (services.geocoder) { - list.selectAll(".geocode-item").data([0]).enter().append("button").attr("class", "geocode-item secondary-action").on("click", geocoderSearch).append("div").attr("class", "label").append("span").attr("class", "entity-name").call(_t.append("geocoder.search")); + items = items.merge(itemsEnter).order(); + items.select("input.member-role").property("value", function(d2) { + return d2.role; + }).on("blur", changeRole).on("change", changeRole); + items.select("button.member-delete").on("click", deleteMember); + var dragOrigin, targetIndex; + items.call( + drag_default().on("start", function(d3_event) { + dragOrigin = { + x: d3_event.x, + y: d3_event.y + }; + targetIndex = null; + }).on("drag", function(d3_event) { + var x2 = d3_event.x - dragOrigin.x, y2 = d3_event.y - dragOrigin.y; + if (!select_default2(this).classed("dragging") && // don't display drag until dragging beyond a distance threshold + Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2)) <= 5) + return; + var index = items.nodes().indexOf(this); + select_default2(this).classed("dragging", true); + targetIndex = null; + selection2.selectAll("li.member-row").style("transform", function(d2, index2) { + var node = select_default2(this).node(); + if (index === index2) { + return "translate(" + x2 + "px, " + y2 + "px)"; + } else if (index2 > index && d3_event.y > node.offsetTop) { + if (targetIndex === null || index2 > targetIndex) { + targetIndex = index2; + } + return "translateY(-100%)"; + } else if (index2 < index && d3_event.y < node.offsetTop + node.offsetHeight) { + if (targetIndex === null || index2 < targetIndex) { + targetIndex = index2; + } + return "translateY(100%)"; + } + return null; + }); + }).on("end", function(d3_event, d2) { + if (!select_default2(this).classed("dragging")) + return; + var index = items.nodes().indexOf(this); + select_default2(this).classed("dragging", false); + selection2.selectAll("li.member-row").style("transform", null); + if (targetIndex !== null) { + context.perform( + actionMoveMember(d2.relation.id, index, targetIndex), + _t("operations.reorder_members.annotation") + ); + context.validator().validate(); + } + }) + ); + function bindTypeahead(d2) { + var row = select_default2(this); + var role = row.selectAll("input.member-role"); + var origValue = role.property("value"); + function sort(value, data) { + var sameletter = []; + var other = []; + for (var i3 = 0; i3 < data.length; i3++) { + if (data[i3].value.substring(0, value.length) === value) { + sameletter.push(data[i3]); + } else { + other.push(data[i3]); + } + } + return sameletter.concat(other); } - list.selectAll(".no-results-item").style("display", value.length && !results.length ? "block" : "none"); - list.selectAll(".geocode-item").style("display", value && _geocodeResults === void 0 ? "block" : "none"); - list.selectAll(".feature-list-item").data([-1]).remove(); - var items = list.selectAll(".feature-list-item").data(results, function(d2) { - return d2.id; - }); - var enter = items.enter().insert("button", ".geocode-item").attr("class", "feature-list-item").on("mouseover", mouseover).on("mouseout", mouseout).on("click", click); - var label = enter.append("div").attr("class", "label"); - label.each(function(d2) { - select_default2(this).call(svgIcon("#iD-icon-" + d2.geometry, "pre-text")); - }); - label.append("span").attr("class", "entity-type").text(function(d2) { - return d2.type; - }); - label.append("span").attr("class", "entity-name").text(function(d2) { - return d2.name; - }); - enter.style("opacity", 0).transition().style("opacity", 1); - items.order(); - items.exit().remove(); + role.call( + uiCombobox(context, "member-role").fetcher(function(role2, callback) { + var geometry; + if (d2.member) { + geometry = context.graph().geometry(d2.member.id); + } else if (d2.type === "relation") { + geometry = "relation"; + } else if (d2.type === "way") { + geometry = "line"; + } else { + geometry = "point"; + } + var rtype = entity.tags.type; + taginfo.roles({ + debounce: true, + rtype: rtype || "", + geometry, + query: role2 + }, function(err, data) { + if (!err) + callback(sort(role2, data)); + }); + }).on("cancel", function() { + role.property("value", origValue); + }) + ); } - function mouseover(d3_event, d2) { - if (d2.id === -1) - return; - utilHighlightEntities([d2.id], true, context); + function unbind() { + var row = select_default2(this); + row.selectAll("input.member-role").call(uiCombobox.off, context); } - function mouseout(d3_event, d2) { - if (d2.id === -1) - return; - utilHighlightEntities([d2.id], false, context); + } + section.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + _entityIDs = val; + return section; + }; + return section; + } + + // modules/actions/delete_members.js + function actionDeleteMembers(relationId, memberIndexes) { + return function(graph) { + memberIndexes.sort((a2, b2) => b2 - a2); + for (var i3 in memberIndexes) { + graph = actionDeleteMember(relationId, memberIndexes[i3])(graph); } - function click(d3_event, d2) { - d3_event.preventDefault(); - if (d2.location) { - context.map().centerZoomEase([d2.location[1], d2.location[0]], 19); - } else if (d2.entity) { - utilHighlightEntities([d2.id], false, context); - context.enter(modeSelect(context, [d2.entity.id])); - context.map().zoomToEase(d2.entity); + return graph; + }; + } + + // modules/ui/sections/raw_membership_editor.js + function uiSectionRawMembershipEditor(context) { + var section = uiSection("raw-membership-editor", context).shouldDisplay(function() { + return _entityIDs && _entityIDs.length; + }).label(function() { + var parents = getSharedParentRelations(); + var gt2 = parents.length > _maxMemberships ? ">" : ""; + var count = gt2 + parents.slice(0, _maxMemberships).length; + return _t.append("inspector.title_count", { title: _t("inspector.relations"), count }); + }).disclosureContent(renderDisclosureContent); + var taginfo = services.taginfo; + var nearbyCombo = uiCombobox(context, "parent-relation").minItems(1).fetcher(fetchNearbyRelations).itemsMouseEnter(function(d3_event, d2) { + if (d2.relation) + utilHighlightEntities([d2.relation.id], true, context); + }).itemsMouseLeave(function(d3_event, d2) { + if (d2.relation) + utilHighlightEntities([d2.relation.id], false, context); + }); + var _inChange = false; + var _entityIDs = []; + var _showBlank; + var _maxMemberships = 1e3; + function getSharedParentRelations() { + var parents = []; + for (var i3 = 0; i3 < _entityIDs.length; i3++) { + var entity = context.graph().hasEntity(_entityIDs[i3]); + if (!entity) + continue; + if (i3 === 0) { + parents = context.graph().parentRelations(entity); } else { - context.zoomToEntity(d2.id); + parents = utilArrayIntersection(parents, context.graph().parentRelations(entity)); } + if (!parents.length) + break; } - function geocoderSearch() { - services.geocoder.search(search.property("value"), function(err, resp) { - _geocodeResults = resp || []; - drawList(); - }); - } + return parents; } - return featureList; - } - - // modules/ui/improveOSM_comments.js - function uiImproveOsmComments() { - let _qaItem; - function issueComments(selection2) { - let comments = selection2.selectAll(".comments-container").data([0]); - comments = comments.enter().append("div").attr("class", "comments-container").merge(comments); - services.improveOSM.getComments(_qaItem).then((d2) => { - if (!d2.comments) - return; - const commentEnter = comments.selectAll(".comment").data(d2.comments).enter().append("div").attr("class", "comment"); - commentEnter.append("div").attr("class", "comment-avatar").call(svgIcon("#iD-icon-avatar", "comment-avatar-icon")); - const mainEnter = commentEnter.append("div").attr("class", "comment-main"); - const metadataEnter = mainEnter.append("div").attr("class", "comment-metadata"); - metadataEnter.append("div").attr("class", "comment-author").each(function(d4) { - const osm = services.osm; - let selection3 = select_default2(this); - if (osm && d4.username) { - selection3 = selection3.append("a").attr("class", "comment-author-link").attr("href", osm.userURL(d4.username)).attr("target", "_blank"); + function getMemberships() { + var memberships = []; + var relations = getSharedParentRelations().slice(0, _maxMemberships); + var isMultiselect = _entityIDs.length > 1; + var i3, relation, membership, index, member, indexedMember; + for (i3 = 0; i3 < relations.length; i3++) { + relation = relations[i3]; + membership = { + relation, + members: [], + hash: osmEntity.key(relation) + }; + for (index = 0; index < relation.members.length; index++) { + member = relation.members[index]; + if (_entityIDs.indexOf(member.id) !== -1) { + indexedMember = Object.assign({}, member, { index }); + membership.members.push(indexedMember); + membership.hash += "," + index.toString(); + if (!isMultiselect) { + memberships.push(membership); + membership = { + relation, + members: [], + hash: osmEntity.key(relation) + }; + } } - selection3.text((d5) => d5.username); + } + if (membership.members.length) + memberships.push(membership); + } + memberships.forEach(function(membership2) { + membership2.domId = utilUniqueDomId("membership-" + membership2.relation.id); + var roles = []; + membership2.members.forEach(function(member2) { + if (roles.indexOf(member2.role) === -1) + roles.push(member2.role); }); - metadataEnter.append("div").attr("class", "comment-date").html((d4) => _t.html("note.status.commented", { when: localeDateString2(d4.timestamp) })); - mainEnter.append("div").attr("class", "comment-text").append("p").text((d4) => d4.text); - }).catch((err) => { - console.log(err); + membership2.role = roles.length === 1 ? roles[0] : roles; }); + return memberships; } - function localeDateString2(s2) { - if (!s2) - return null; - const options2 = { day: "numeric", month: "short", year: "numeric" }; - const d2 = new Date(s2 * 1e3); - if (isNaN(d2.getTime())) - return null; - return d2.toLocaleDateString(_mainLocalizer.localeCode(), options2); + function selectRelation(d3_event, d2) { + d3_event.preventDefault(); + utilHighlightEntities([d2.relation.id], false, context); + context.enter(modeSelect(context, [d2.relation.id])); } - issueComments.issue = function(val) { - if (!arguments.length) - return _qaItem; - _qaItem = val; - return issueComments; - }; - return issueComments; - } - - // modules/ui/improveOSM_details.js - function uiImproveOsmDetails(context) { - let _qaItem; - function issueDetail(d2) { - if (d2.desc) - return d2.desc; - const issueKey = d2.issueKey; - d2.replacements = d2.replacements || {}; - d2.replacements.default = { html: _t.html("inspector.unknown") }; - return _t.html("QA.improveOSM.error_types.".concat(issueKey, ".description"), d2.replacements); + function zoomToRelation(d3_event, d2) { + d3_event.preventDefault(); + var entity = context.entity(d2.relation.id); + context.map().zoomToEase(entity); + utilHighlightEntities([d2.relation.id], true, context); } - function improveOsmDetails(selection2) { - const details = selection2.selectAll(".error-details").data( - _qaItem ? [_qaItem] : [], - (d2) => "".concat(d2.id, "-").concat(d2.status || 0) - ); - details.exit().remove(); - const detailsEnter = details.enter().append("div").attr("class", "error-details qa-details-container"); - const descriptionEnter = detailsEnter.append("div").attr("class", "qa-details-subsection"); - descriptionEnter.append("h4").call(_t.append("QA.keepRight.detail_description")); - descriptionEnter.append("div").attr("class", "qa-details-description-text").html(issueDetail); - let relatedEntities = []; - descriptionEnter.selectAll(".error_entity_link, .error_object_link").attr("href", "#").each(function() { - const link2 = select_default2(this); - const isObjectLink = link2.classed("error_object_link"); - const entityID = isObjectLink ? utilEntityRoot(_qaItem.objectType) + _qaItem.objectId : this.textContent; - const entity = context.hasEntity(entityID); - relatedEntities.push(entityID); - link2.on("mouseenter", () => { - utilHighlightEntities([entityID], true, context); - }).on("mouseleave", () => { - utilHighlightEntities([entityID], false, context); - }).on("click", (d3_event) => { - d3_event.preventDefault(); - utilHighlightEntities([entityID], false, context); - const osmlayer = context.layers().layer("osm"); - if (!osmlayer.enabled()) { - osmlayer.enabled(true); - } - context.map().centerZoom(_qaItem.loc, 20); - if (entity) { - context.enter(modeSelect(context, [entityID])); - } else { - context.loadEntity(entityID, (err, result) => { - if (err) - return; - const entity2 = result.data.find((e3) => e3.id === entityID); - if (entity2) - context.enter(modeSelect(context, [entityID])); + function changeRole(d3_event, d2) { + if (d2 === 0) + return; + if (_inChange) + return; + var newRole = context.cleanRelationRole(select_default2(this).property("value")); + if (!newRole.trim() && typeof d2.role !== "string") + return; + var membersToUpdate = d2.members.filter(function(member) { + return member.role !== newRole; + }); + if (membersToUpdate.length) { + _inChange = true; + context.perform( + function actionChangeMemberRoles(graph) { + membersToUpdate.forEach(function(member) { + var newMember = Object.assign({}, member, { role: newRole }); + delete newMember.index; + graph = actionChangeMember(d2.relation.id, newMember, member.index)(graph); }); + return graph; + }, + _t("operations.change_role.annotation", { + n: membersToUpdate.length + }) + ); + context.validator().validate(); + } + _inChange = false; + } + function addMembership(d2, role) { + this.blur(); + _showBlank = false; + function actionAddMembers(relationId, ids, role2) { + return function(graph) { + for (var i3 in ids) { + var member = { id: ids[i3], type: graph.entity(ids[i3]).type, role: role2 }; + graph = actionAddMember(relationId, member)(graph); } + return graph; + }; + } + if (d2.relation) { + context.perform( + actionAddMembers(d2.relation.id, _entityIDs, role), + _t("operations.add_member.annotation", { + n: _entityIDs.length + }) + ); + context.validator().validate(); + } else { + var relation = osmRelation(); + context.perform( + actionAddEntity(relation), + actionAddMembers(relation.id, _entityIDs, role), + _t("operations.add.annotation.relation") + ); + context.enter(modeSelect(context, [relation.id]).newFeature(true)); + } + } + function deleteMembership(d3_event, d2) { + this.blur(); + if (d2 === 0) + return; + utilHighlightEntities([d2.relation.id], false, context); + var indexes = d2.members.map(function(member) { + return member.index; + }); + context.perform( + actionDeleteMembers(d2.relation.id, indexes), + _t("operations.delete_member.annotation", { + n: _entityIDs.length + }) + ); + context.validator().validate(); + } + function fetchNearbyRelations(q2, callback) { + var newRelation = { + relation: null, + value: _t("inspector.new_relation"), + display: _t.append("inspector.new_relation") + }; + var entityID = _entityIDs[0]; + var result = []; + var graph = context.graph(); + function baseDisplayValue(entity) { + var matched = _mainPresetIndex.match(entity, graph); + var presetName = matched && matched.name() || _t("inspector.relation"); + var entityName = utilDisplayName(entity) || ""; + return presetName + " " + entityName; + } + function baseDisplayLabel(entity) { + var matched = _mainPresetIndex.match(entity, graph); + var presetName = matched && matched.name() || _t("inspector.relation"); + var entityName = utilDisplayName(entity) || ""; + return (selection2) => { + selection2.append("b").text(presetName + " "); + selection2.append("span").classed("has-colour", entity.tags.colour && isColourValid(entity.tags.colour)).style("border-color", entity.tags.colour).text(entityName); + }; + } + var explicitRelation = q2 && context.hasEntity(q2.toLowerCase()); + if (explicitRelation && explicitRelation.type === "relation" && explicitRelation.id !== entityID) { + result.push({ + relation: explicitRelation, + value: baseDisplayValue(explicitRelation) + " " + explicitRelation.id, + display: baseDisplayLabel(explicitRelation) + }); + } else { + context.history().intersects(context.map().extent()).forEach(function(entity) { + if (entity.type !== "relation" || entity.id === entityID) + return; + var value = baseDisplayValue(entity); + if (q2 && (value + " " + entity.id).toLowerCase().indexOf(q2.toLowerCase()) === -1) + return; + result.push({ + relation: entity, + value, + display: baseDisplayLabel(entity) + }); + }); + result.sort(function(a2, b2) { + return osmRelation.creationOrder(a2.relation, b2.relation); + }); + var dupeGroups = Object.values(utilArrayGroupBy(result, "value")).filter(function(v2) { + return v2.length > 1; + }); + dupeGroups.forEach(function(group) { + group.forEach(function(obj) { + obj.value += " " + obj.relation.id; + }); }); - if (entity) { - let name = utilDisplayName(entity); - if (!name && !isObjectLink) { - const preset = _mainPresetIndex.match(entity, context.graph()); - name = preset && !preset.isFallback() && preset.name(); - } - if (name) { - this.innerText = name; + } + result.forEach(function(obj) { + obj.title = obj.value; + }); + result.unshift(newRelation); + callback(result); + } + function renderDisclosureContent(selection2) { + var memberships = getMemberships(); + var list2 = selection2.selectAll(".member-list").data([0]); + list2 = list2.enter().append("ul").attr("class", "member-list").merge(list2); + var items = list2.selectAll("li.member-row-normal").data(memberships, function(d2) { + return d2.hash; + }); + items.exit().each(unbind).remove(); + var itemsEnter = items.enter().append("li").attr("class", "member-row member-row-normal form-field"); + itemsEnter.on("mouseover", function(d3_event, d2) { + utilHighlightEntities([d2.relation.id], true, context); + }).on("mouseout", function(d3_event, d2) { + utilHighlightEntities([d2.relation.id], false, context); + }); + var labelEnter = itemsEnter.append("label").attr("class", "field-label").attr("for", function(d2) { + return d2.domId; + }); + var labelLink = labelEnter.append("span").attr("class", "label-text").append("a").attr("href", "#").on("click", selectRelation); + labelLink.append("span").attr("class", "member-entity-type").text(function(d2) { + var matched = _mainPresetIndex.match(d2.relation, context.graph()); + return matched && matched.name() || _t.html("inspector.relation"); + }); + labelLink.append("span").attr("class", "member-entity-name").classed("has-colour", (d2) => d2.relation.tags.colour && isColourValid(d2.relation.tags.colour)).style("border-color", (d2) => d2.relation.tags.colour).text(function(d2) { + return utilDisplayName(d2.relation); + }); + labelEnter.append("button").attr("class", "remove member-delete").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")).on("click", deleteMembership); + labelEnter.append("button").attr("class", "member-zoom").attr("title", _t("icons.zoom_to")).call(svgIcon("#iD-icon-framed-dot", "monochrome")).on("click", zoomToRelation); + var wrapEnter = itemsEnter.append("div").attr("class", "form-field-input-wrap form-field-input-member"); + wrapEnter.append("input").attr("class", "member-role").attr("id", function(d2) { + return d2.domId; + }).property("type", "text").property("value", function(d2) { + return typeof d2.role === "string" ? d2.role : ""; + }).attr("title", function(d2) { + return Array.isArray(d2.role) ? d2.role.filter(Boolean).join("\n") : d2.role; + }).attr("placeholder", function(d2) { + return Array.isArray(d2.role) ? _t("inspector.multiple_roles") : _t("inspector.role"); + }).classed("mixed", function(d2) { + return Array.isArray(d2.role); + }).call(utilNoAuto).on("blur", changeRole).on("change", changeRole); + if (taginfo) { + wrapEnter.each(bindTypeahead); + } + var newMembership = list2.selectAll(".member-row-new").data(_showBlank ? [0] : []); + newMembership.exit().remove(); + var newMembershipEnter = newMembership.enter().append("li").attr("class", "member-row member-row-new form-field"); + var newLabelEnter = newMembershipEnter.append("label").attr("class", "field-label"); + newLabelEnter.append("input").attr("placeholder", _t("inspector.choose_relation")).attr("type", "text").attr("class", "member-entity-input").call(utilNoAuto); + newLabelEnter.append("button").attr("class", "remove member-delete").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")).on("click", function() { + list2.selectAll(".member-row-new").remove(); + }); + var newWrapEnter = newMembershipEnter.append("div").attr("class", "form-field-input-wrap form-field-input-member"); + newWrapEnter.append("input").attr("class", "member-role").property("type", "text").attr("placeholder", _t("inspector.role")).call(utilNoAuto); + newMembership = newMembership.merge(newMembershipEnter); + newMembership.selectAll(".member-entity-input").on("blur", cancelEntity).call( + nearbyCombo.on("accept", acceptEntity).on("cancel", cancelEntity) + ); + var addRow = selection2.selectAll(".add-row").data([0]); + var addRowEnter = addRow.enter().append("div").attr("class", "add-row"); + var addRelationButton = addRowEnter.append("button").attr("class", "add-relation").attr("aria-label", _t("inspector.add_to_relation")); + addRelationButton.call(svgIcon("#iD-icon-plus", "light")); + addRelationButton.call(uiTooltip().title(() => _t.append("inspector.add_to_relation")).placement(_mainLocalizer.textDirection() === "ltr" ? "right" : "left")); + addRowEnter.append("div").attr("class", "space-value"); + addRowEnter.append("div").attr("class", "space-buttons"); + addRow = addRow.merge(addRowEnter); + addRow.select(".add-relation").on("click", function() { + _showBlank = true; + section.reRender(); + list2.selectAll(".member-entity-input").node().focus(); + }); + function acceptEntity(d2) { + if (!d2) { + cancelEntity(); + return; + } + if (d2.relation) + utilHighlightEntities([d2.relation.id], false, context); + var role = context.cleanRelationRole(list2.selectAll(".member-row-new .member-role").property("value")); + addMembership(d2, role); + } + function cancelEntity() { + var input = newMembership.selectAll(".member-entity-input"); + input.property("value", ""); + context.surface().selectAll(".highlighted").classed("highlighted", false); + } + function bindTypeahead(d2) { + var row = select_default2(this); + var role = row.selectAll("input.member-role"); + var origValue = role.property("value"); + function sort(value, data) { + var sameletter = []; + var other = []; + for (var i3 = 0; i3 < data.length; i3++) { + if (data[i3].value.substring(0, value.length) === value) { + sameletter.push(data[i3]); + } else { + other.push(data[i3]); + } } + return sameletter.concat(other); } - }); - context.features().forceVisible(relatedEntities); - context.map().pan([0, 0]); + role.call( + uiCombobox(context, "member-role").fetcher(function(role2, callback) { + var rtype = d2.relation.tags.type; + taginfo.roles({ + debounce: true, + rtype: rtype || "", + geometry: context.graph().geometry(_entityIDs[0]), + query: role2 + }, function(err, data) { + if (!err) + callback(sort(role2, data)); + }); + }).on("cancel", function() { + role.property("value", origValue); + }) + ); + } + function unbind() { + var row = select_default2(this); + row.selectAll("input.member-role").call(uiCombobox.off, context); + } } - improveOsmDetails.issue = function(val) { + section.entityIDs = function(val) { if (!arguments.length) - return _qaItem; - _qaItem = val; - return improveOsmDetails; + return _entityIDs; + _entityIDs = val; + _showBlank = false; + return section; }; - return improveOsmDetails; + return section; } - // modules/ui/improveOSM_header.js - function uiImproveOsmHeader() { - let _qaItem; - function issueTitle(d2) { - const issueKey = d2.issueKey; - d2.replacements = d2.replacements || {}; - d2.replacements.default = { html: _t.html("inspector.unknown") }; - return _t.html("QA.improveOSM.error_types.".concat(issueKey, ".title"), d2.replacements); - } - function improveOsmHeader(selection2) { - const header = selection2.selectAll(".qa-header").data( - _qaItem ? [_qaItem] : [], - (d2) => "".concat(d2.id, "-").concat(d2.status || 0) - ); - header.exit().remove(); - const headerEnter = header.enter().append("div").attr("class", "qa-header"); - const svgEnter = headerEnter.append("div").attr("class", "qa-header-icon").classed("new", (d2) => d2.id < 0).append("svg").attr("width", "20px").attr("height", "30px").attr("viewbox", "0 0 20 30").attr("class", (d2) => "preset-icon-28 qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.itemType)); - svgEnter.append("polygon").attr("fill", "currentColor").attr("class", "qaItem-fill").attr("points", "16,3 4,3 1,6 1,17 4,20 7,20 10,27 13,20 16,20 19,17.033 19,6"); - svgEnter.append("use").attr("class", "icon-annotation").attr("width", "12px").attr("height", "12px").attr("transform", "translate(4, 5.5)").attr("xlink:href", (d2) => d2.icon ? "#" + d2.icon : ""); - headerEnter.append("div").attr("class", "qa-header-label").html(issueTitle); - } - improveOsmHeader.issue = function(val) { + // modules/ui/sections/selection_list.js + function uiSectionSelectionList(context) { + var _selectedIDs = []; + var section = uiSection("selected-features", context).shouldDisplay(function() { + return _selectedIDs.length > 1; + }).label(function() { + return _t.append("inspector.title_count", { title: _t("inspector.features"), count: _selectedIDs.length }); + }).disclosureContent(renderDisclosureContent); + context.history().on("change.selectionList", function(difference2) { + if (difference2) { + section.reRender(); + } + }); + section.entityIDs = function(val) { if (!arguments.length) - return _qaItem; - _qaItem = val; - return improveOsmHeader; + return _selectedIDs; + _selectedIDs = val; + return section; }; - return improveOsmHeader; - } - - // modules/ui/improveOSM_editor.js - function uiImproveOsmEditor(context) { - const dispatch14 = dispatch_default("change"); - const qaDetails = uiImproveOsmDetails(context); - const qaComments = uiImproveOsmComments(context); - const qaHeader = uiImproveOsmHeader(context); - let _qaItem; - function improveOsmEditor(selection2) { - const headerEnter = selection2.selectAll(".header").data([0]).enter().append("div").attr("class", "header fillL"); - headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", () => context.enter(modeBrowse(context))).call(svgIcon("#iD-icon-close")); - headerEnter.append("h2").call(_t.append("QA.improveOSM.title")); - let body = selection2.selectAll(".body").data([0]); - body = body.enter().append("div").attr("class", "body").merge(body); - const editor = body.selectAll(".qa-editor").data([0]); - editor.enter().append("div").attr("class", "modal-section qa-editor").merge(editor).call(qaHeader.issue(_qaItem)).call(qaDetails.issue(_qaItem)).call(qaComments.issue(_qaItem)).call(improveOsmSaveSection); + function selectEntity(d3_event, entity) { + context.enter(modeSelect(context, [entity.id])); } - function improveOsmSaveSection(selection2) { - const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); - const isShown = _qaItem && (isSelected || _qaItem.newComment || _qaItem.comment); - let saveSection = selection2.selectAll(".qa-save").data( - isShown ? [_qaItem] : [], - (d2) => "".concat(d2.id, "-").concat(d2.status || 0) - ); - saveSection.exit().remove(); - const saveSectionEnter = saveSection.enter().append("div").attr("class", "qa-save save-section cf"); - saveSectionEnter.append("h4").attr("class", ".qa-save-header").call(_t.append("note.newComment")); - saveSectionEnter.append("textarea").attr("class", "new-comment-input").attr("placeholder", _t("QA.keepRight.comment_placeholder")).attr("maxlength", 1e3).property("value", (d2) => d2.newComment).call(utilNoAuto).on("input", changeInput).on("blur", changeInput); - saveSection = saveSectionEnter.merge(saveSection).call(qaSaveButtons); - function changeInput() { - const input = select_default2(this); - let val = input.property("value").trim(); - if (val === "") { - val = void 0; - } - _qaItem = _qaItem.update({ newComment: val }); - const qaService = services.improveOSM; - if (qaService) { - qaService.replaceItem(_qaItem); - } - saveSection.call(qaSaveButtons); + function deselectEntity(d3_event, entity) { + var selectedIDs = _selectedIDs.slice(); + var index = selectedIDs.indexOf(entity.id); + if (index > -1) { + selectedIDs.splice(index, 1); + context.enter(modeSelect(context, selectedIDs)); } } - function qaSaveButtons(selection2) { - const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); - let buttonSection = selection2.selectAll(".buttons").data(isSelected ? [_qaItem] : [], (d2) => d2.status + d2.id); - buttonSection.exit().remove(); - const buttonEnter = buttonSection.enter().append("div").attr("class", "buttons"); - buttonEnter.append("button").attr("class", "button comment-button action").call(_t.append("QA.keepRight.save_comment")); - buttonEnter.append("button").attr("class", "button close-button action"); - buttonEnter.append("button").attr("class", "button ignore-button action"); - buttonSection = buttonSection.merge(buttonEnter); - buttonSection.select(".comment-button").attr("disabled", (d2) => d2.newComment ? null : true).on("click.comment", function(d3_event, d2) { - this.blur(); - const qaService = services.improveOSM; - if (qaService) { - qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); - } + function renderDisclosureContent(selection2) { + var list2 = selection2.selectAll(".feature-list").data([0]); + list2 = list2.enter().append("ul").attr("class", "feature-list").merge(list2); + var entities = _selectedIDs.map(function(id2) { + return context.hasEntity(id2); + }).filter(Boolean); + var items = list2.selectAll(".feature-list-item").data(entities, osmEntity.key); + items.exit().remove(); + var enter = items.enter().append("li").attr("class", "feature-list-item").each(function(d2) { + select_default2(this).on("mouseover", function() { + utilHighlightEntities([d2.id], true, context); + }).on("mouseout", function() { + utilHighlightEntities([d2.id], false, context); + }); }); - buttonSection.select(".close-button").html((d2) => { - const andComment = d2.newComment ? "_comment" : ""; - return _t.html("QA.keepRight.close".concat(andComment)); - }).on("click.close", function(d3_event, d2) { - this.blur(); - const qaService = services.improveOSM; - if (qaService) { - d2.newStatus = "SOLVED"; - qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); - } + var label = enter.append("button").attr("class", "label").on("click", selectEntity); + label.append("span").attr("class", "entity-geom-icon").call(svgIcon("", "pre-text")); + label.append("span").attr("class", "entity-type"); + label.append("span").attr("class", "entity-name"); + enter.append("button").attr("class", "close").attr("title", _t("icons.deselect")).on("click", deselectEntity).call(svgIcon("#iD-icon-close")); + items = items.merge(enter); + items.selectAll(".entity-geom-icon use").attr("href", function() { + var entity = this.parentNode.parentNode.__data__; + return "#iD-icon-" + entity.geometry(context.graph()); }); - buttonSection.select(".ignore-button").html((d2) => { - const andComment = d2.newComment ? "_comment" : ""; - return _t.html("QA.keepRight.ignore".concat(andComment)); - }).on("click.ignore", function(d3_event, d2) { - this.blur(); - const qaService = services.improveOSM; - if (qaService) { - d2.newStatus = "INVALID"; - qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); - } + items.selectAll(".entity-type").text(function(entity) { + return _mainPresetIndex.match(entity, context.graph()).name(); + }); + items.selectAll(".entity-name").text(function(d2) { + var entity = context.entity(d2.id); + return utilDisplayName(entity); }); } - improveOsmEditor.error = function(val) { - if (!arguments.length) - return _qaItem; - _qaItem = val; - return improveOsmEditor; - }; - return utilRebind(improveOsmEditor, dispatch14, "on"); + return section; } - // modules/ui/preset_list.js - function uiPresetList(context) { - var dispatch14 = dispatch_default("cancel", "choose"); + // modules/ui/entity_editor.js + function uiEntityEditor(context) { + var dispatch14 = dispatch_default("choose"); + var _state = "select"; + var _coalesceChanges = false; + var _modified = false; + var _base; var _entityIDs; - var _currLoc; - var _currentPresets; - var _autofocus = false; - function presetList(selection2) { - if (!_entityIDs) - return; - var presets = _mainPresetIndex.matchAllGeometry(entityGeometries()); - selection2.html(""); - var messagewrap = selection2.append("div").attr("class", "header fillL"); - var message = messagewrap.append("h2").call(_t.append("inspector.choose")); - var direction = _mainLocalizer.textDirection() === "rtl" ? "backward" : "forward"; - messagewrap.append("button").attr("class", "preset-choose").attr("title", _entityIDs.length === 1 ? _t("inspector.edit") : _t("inspector.edit_features")).on("click", function() { - dispatch14.call("cancel", this); - }).call(svgIcon("#iD-icon-".concat(direction))); - function initialKeydown(d3_event) { - if (search.property("value").length === 0 && (d3_event.keyCode === utilKeybinding.keyCodes["\u232B"] || d3_event.keyCode === utilKeybinding.keyCodes["\u2326"])) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - operationDelete(context, _entityIDs)(); - } else if (search.property("value").length === 0 && (d3_event.ctrlKey || d3_event.metaKey) && d3_event.keyCode === utilKeybinding.keyCodes.z) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - context.undo(); - } else if (!d3_event.ctrlKey && !d3_event.metaKey) { - select_default2(this).on("keydown", keydown); - keydown.call(this, d3_event); - } + var _activePresets = []; + var _newFeature; + var _sections; + function entityEditor(selection2) { + var combinedTags = utilCombinedTags(_entityIDs, context.graph()); + var header = selection2.selectAll(".header").data([0]); + var headerEnter = header.enter().append("div").attr("class", "header fillL"); + var direction = _mainLocalizer.textDirection() === "rtl" ? "forward" : "backward"; + headerEnter.append("button").attr("class", "preset-reset preset-choose").attr("title", _t("inspector.back_tooltip")).call(svgIcon("#iD-icon-".concat(direction))); + headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function() { + context.enter(modeBrowse(context)); + }).call(svgIcon(_modified ? "#iD-icon-apply" : "#iD-icon-close")); + headerEnter.append("h2"); + header = header.merge(headerEnter); + header.selectAll("h2").text("").call(_entityIDs.length === 1 ? _t.append("inspector.edit") : _t.append("inspector.edit_features")); + header.selectAll(".preset-reset").on("click", function() { + dispatch14.call("choose", this, _activePresets); + }); + var body = selection2.selectAll(".inspector-body").data([0]); + var bodyEnter = body.enter().append("div").attr("class", "entity-editor inspector-body sep-top"); + body = body.merge(bodyEnter); + if (!_sections) { + _sections = [ + uiSectionSelectionList(context), + uiSectionFeatureType(context).on("choose", function(presets) { + dispatch14.call("choose", this, presets); + }), + uiSectionEntityIssues(context), + uiSectionPresetFields(context).on("change", changeTags).on("revert", revertTags), + uiSectionRawTagEditor("raw-tag-editor", context).on("change", changeTags), + uiSectionRawMemberEditor(context), + uiSectionRawMembershipEditor(context) + ]; } - function keydown(d3_event) { - if (d3_event.keyCode === utilKeybinding.keyCodes["\u2193"] && // if insertion point is at the end of the string - search.node().selectionStart === search.property("value").length) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - var buttons = list.selectAll(".preset-list-button"); - if (!buttons.empty()) - buttons.nodes()[0].focus(); + _sections.forEach(function(section) { + if (section.entityIDs) { + section.entityIDs(_entityIDs); } - } - function keypress(d3_event) { - var value = search.property("value"); - if (d3_event.keyCode === 13 && // ↩ Return - value.length) { - list.selectAll(".preset-list-item:first-child").each(function(d2) { - d2.choose.call(this); - }); + if (section.presets) { + section.presets(_activePresets); } - } - function inputevent() { - var value = search.property("value"); - list.classed("filtered", value.length); - var results, messageText; - if (value.length) { - results = presets.search(value, entityGeometries()[0], _currLoc); - messageText = _t.html("inspector.results", { - n: results.collection.length, - search: value - }); - } else { - var entityPresets2 = _entityIDs.map((entityID) => _mainPresetIndex.match(context.graph().entity(entityID), context.graph())); - results = _mainPresetIndex.defaults(entityGeometries()[0], 36, !context.inIntro(), _currLoc, entityPresets2); - messageText = _t.html("inspector.choose"); + if (section.tags) { + section.tags(combinedTags); } - list.call(drawList, results); - message.html(messageText); - } - var searchWrap = selection2.append("div").attr("class", "search-header"); - searchWrap.call(svgIcon("#iD-icon-search", "pre-text")); - var search = searchWrap.append("input").attr("class", "preset-search-input").attr("placeholder", _t("inspector.search")).attr("type", "search").call(utilNoAuto).on("keydown", initialKeydown).on("keypress", keypress).on("input", debounce_default(inputevent)); - if (_autofocus) { - search.node().focus(); - setTimeout(function() { - search.node().focus(); - }, 0); - } - var listWrap = selection2.append("div").attr("class", "inspector-body"); - var entityPresets = _entityIDs.map((entityID) => _mainPresetIndex.match(context.graph().entity(entityID), context.graph())); - var list = listWrap.append("div").attr("class", "preset-list").call(drawList, _mainPresetIndex.defaults(entityGeometries()[0], 36, !context.inIntro(), _currLoc, entityPresets)); - context.features().on("change.preset-list", updateForFeatureHiddenState); - } - function drawList(list, presets) { - presets = presets.matchAllGeometry(entityGeometries()); - var collection = presets.collection.reduce(function(collection2, preset) { - if (!preset) - return collection2; - if (preset.members) { - if (preset.members.collection.filter(function(preset2) { - return preset2.addable(); - }).length > 1) { - collection2.push(CategoryItem(preset)); - } - } else if (preset.addable()) { - collection2.push(PresetItem(preset)); + if (section.state) { + section.state(_state); } - return collection2; - }, []); - var items = list.selectAll(".preset-list-item").data(collection, function(d2) { - return d2.preset.id; + body.call(section.render); }); - items.order(); - items.exit().remove(); - items.enter().append("div").attr("class", function(item) { - return "preset-list-item preset-" + item.preset.id.replace("/", "-"); - }).classed("current", function(item) { - return _currentPresets.indexOf(item.preset) !== -1; - }).each(function(item) { - select_default2(this).call(item); - }).style("opacity", 0).transition().style("opacity", 1); - updateForFeatureHiddenState(); - } - function itemKeydown(d3_event) { - var item = select_default2(this.closest(".preset-list-item")); - var parentItem = select_default2(item.node().parentNode.closest(".preset-list-item")); - if (d3_event.keyCode === utilKeybinding.keyCodes["\u2193"]) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - var nextItem = select_default2(item.node().nextElementSibling); - if (nextItem.empty()) { - if (!parentItem.empty()) { - nextItem = select_default2(parentItem.node().nextElementSibling); - } - } else if (select_default2(this).classed("expanded")) { - nextItem = item.select(".subgrid .preset-list-item:first-child"); - } - if (!nextItem.empty()) { - nextItem.select(".preset-list-button").node().focus(); - } - } else if (d3_event.keyCode === utilKeybinding.keyCodes["\u2191"]) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - var previousItem = select_default2(item.node().previousElementSibling); - if (previousItem.empty()) { - if (!parentItem.empty()) { - previousItem = parentItem; - } - } else if (previousItem.select(".preset-list-button").classed("expanded")) { - previousItem = previousItem.select(".subgrid .preset-list-item:last-child"); - } - if (!previousItem.empty()) { - previousItem.select(".preset-list-button").node().focus(); - } else { - var search = select_default2(this.closest(".preset-list-pane")).select(".preset-search-input"); - search.node().focus(); - } - } else if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2192" : "\u2190"]) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - if (!parentItem.empty()) { - parentItem.select(".preset-list-button").node().focus(); - } - } else if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2190" : "\u2192"]) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - item.datum().choose.call(select_default2(this).node()); + context.history().on("change.entity-editor", historyChanged); + function historyChanged(difference2) { + if (selection2.selectAll(".entity-editor").empty()) + return; + if (_state === "hide") + return; + var significant = !difference2 || difference2.didChange.properties || difference2.didChange.addition || difference2.didChange.deletion; + if (!significant) + return; + _entityIDs = _entityIDs.filter(context.hasEntity); + if (!_entityIDs.length) + return; + var priorActivePreset = _activePresets.length === 1 && _activePresets[0]; + loadActivePresets(); + var graph = context.graph(); + entityEditor.modified(_base !== graph); + entityEditor(selection2); + if (priorActivePreset && _activePresets.length === 1 && priorActivePreset !== _activePresets[0]) { + context.container().selectAll(".entity-editor button.preset-reset .label").style("background-color", "#fff").transition().duration(750).style("background-color", null); + } } } - function CategoryItem(preset) { - var box, sublist, shown = false; - function item(selection2) { - var wrap2 = selection2.append("div").attr("class", "preset-list-button-wrap category"); - function click() { - var isExpanded = select_default2(this).classed("expanded"); - var iconName = isExpanded ? _mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward" : "#iD-icon-down"; - select_default2(this).classed("expanded", !isExpanded).attr("title", !isExpanded ? _t("icons.collapse") : _t("icons.expand")); - select_default2(this).selectAll("div.label-inner svg.icon use").attr("href", iconName); - item.choose(); - } - var geometries = entityGeometries(); - var button = wrap2.append("button").attr("class", "preset-list-button").attr("title", _t("icons.expand")).classed("expanded", false).call(uiPresetIcon().geometry(geometries.length === 1 && geometries[0]).preset(preset)).on("click", click).on("keydown", function(d3_event) { - if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2190" : "\u2192"]) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - if (!select_default2(this).classed("expanded")) { - click.call(this, d3_event); - } - } else if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2192" : "\u2190"]) { - d3_event.preventDefault(); - d3_event.stopPropagation(); - if (select_default2(this).classed("expanded")) { - click.call(this, d3_event); + function changeTags(entityIDs, changed, onInput) { + var actions = []; + for (var i3 in entityIDs) { + var entityID = entityIDs[i3]; + var entity = context.entity(entityID); + var tags = Object.assign({}, entity.tags); + if (typeof changed === "function") { + tags = changed(tags); + } else { + for (var k2 in changed) { + if (!k2) + continue; + var v2 = changed[k2]; + if (typeof v2 === "object") { + tags[k2] = tags[v2.oldKey]; + } else if (v2 !== void 0 || tags.hasOwnProperty(k2)) { + tags[k2] = v2; } - } else { - itemKeydown.call(this, d3_event); } - }); - var label = button.append("div").attr("class", "label").append("div").attr("class", "label-inner"); - label.append("div").attr("class", "namepart").call(svgIcon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward", "inline")).append("span").call(preset.nameLabel()).append("span").text("\u2026"); - box = selection2.append("div").attr("class", "subgrid").style("max-height", "0px").style("opacity", 0); - box.append("div").attr("class", "arrow"); - sublist = box.append("div").attr("class", "preset-list fillL3"); + } + if (!onInput) { + tags = utilCleanTags(tags); + } + if (!(0, import_fast_deep_equal10.default)(entity.tags, tags)) { + actions.push(actionChangeTags(entityID, tags)); + } } - item.choose = function() { - if (!box || !sublist) - return; - if (shown) { - shown = false; - box.transition().duration(200).style("opacity", "0").style("max-height", "0px").style("padding-bottom", "0px"); + if (actions.length) { + var combinedAction = function(graph) { + actions.forEach(function(action) { + graph = action(graph); + }); + return graph; + }; + var annotation = _t("operations.change_tags.annotation"); + if (_coalesceChanges) { + context.overwrite(combinedAction, annotation); } else { - shown = true; - var members = preset.members.matchAllGeometry(entityGeometries()); - sublist.call(drawList, members); - box.transition().duration(200).style("opacity", "1").style("max-height", 200 + members.collection.length * 190 + "px").style("padding-bottom", "10px"); + context.perform(combinedAction, annotation); + _coalesceChanges = !!onInput; } - }; - item.preset = preset; - return item; - } - function PresetItem(preset) { - function item(selection2) { - var wrap2 = selection2.append("div").attr("class", "preset-list-button-wrap"); - var geometries = entityGeometries(); - var button = wrap2.append("button").attr("class", "preset-list-button").call(uiPresetIcon().geometry(geometries.length === 1 && geometries[0]).preset(preset)).on("click", item.choose).on("keydown", itemKeydown); - var label = button.append("div").attr("class", "label").append("div").attr("class", "label-inner"); - var nameparts = [ - preset.nameLabel(), - preset.subtitleLabel() - ].filter(Boolean); - label.selectAll(".namepart").data(nameparts, (d2) => d2.stringId).enter().append("div").attr("class", "namepart").text("").each(function(d2) { - d2(select_default2(this)); - }); - wrap2.call(item.reference.button); - selection2.call(item.reference.body); } - item.choose = function() { - if (select_default2(this).classed("disabled")) - return; - if (!context.inIntro()) { - _mainPresetIndex.setMostRecent(preset, entityGeometries()[0]); - } - context.perform( - function(graph) { - for (var i3 in _entityIDs) { - var entityID = _entityIDs[i3]; - var oldPreset = _mainPresetIndex.match(graph.entity(entityID), graph); - graph = actionChangePreset(entityID, oldPreset, preset)(graph); - } - return graph; - }, - _t("operations.change_tags.annotation") - ); + if (!onInput) { context.validator().validate(); - dispatch14.call("choose", this, preset); - }; - item.help = function(d3_event) { - d3_event.stopPropagation(); - item.reference.toggle(); - }; - item.preset = preset; - item.reference = uiTagReference(preset.reference(), context); - return item; + } } - function updateForFeatureHiddenState() { - if (!_entityIDs.every(context.hasEntity)) - return; - var geometries = entityGeometries(); - var button = context.container().selectAll(".preset-list .preset-list-button"); - button.call(uiTooltip().destroyAny); - button.each(function(item, index) { - var hiddenPresetFeaturesId; - for (var i3 in geometries) { - hiddenPresetFeaturesId = context.features().isHiddenPreset(item.preset, geometries[i3]); - if (hiddenPresetFeaturesId) - break; + function revertTags(keys2) { + var actions = []; + for (var i3 in _entityIDs) { + var entityID = _entityIDs[i3]; + var original = context.graph().base().entities[entityID]; + var changed = {}; + for (var j2 in keys2) { + var key = keys2[j2]; + changed[key] = original ? original.tags[key] : void 0; } - var isHiddenPreset = !context.inIntro() && !!hiddenPresetFeaturesId && (_currentPresets.length !== 1 || item.preset !== _currentPresets[0]); - select_default2(this).classed("disabled", isHiddenPreset); - if (isHiddenPreset) { - var isAutoHidden = context.features().autoHidden(hiddenPresetFeaturesId); - select_default2(this).call( - uiTooltip().title(() => _t.append("inspector.hidden_preset." + (isAutoHidden ? "zoom" : "manual"), { - features: _t("feature." + hiddenPresetFeaturesId + ".description") - })).placement(index < 2 ? "bottom" : "top") - ); + var entity = context.entity(entityID); + var tags = Object.assign({}, entity.tags); + for (var k2 in changed) { + if (!k2) + continue; + var v2 = changed[k2]; + if (v2 !== void 0 || tags.hasOwnProperty(k2)) { + tags[k2] = v2; + } } - }); + tags = utilCleanTags(tags); + if (!(0, import_fast_deep_equal10.default)(entity.tags, tags)) { + actions.push(actionChangeTags(entityID, tags)); + } + } + if (actions.length) { + var combinedAction = function(graph) { + actions.forEach(function(action) { + graph = action(graph); + }); + return graph; + }; + var annotation = _t("operations.change_tags.annotation"); + if (_coalesceChanges) { + context.overwrite(combinedAction, annotation); + } else { + context.perform(combinedAction, annotation); + _coalesceChanges = false; + } + } + context.validator().validate(); } - presetList.autofocus = function(val) { + entityEditor.modified = function(val) { if (!arguments.length) - return _autofocus; - _autofocus = val; - return presetList; + return _modified; + _modified = val; + return entityEditor; }; - presetList.entityIDs = function(val) { + entityEditor.state = function(val) { + if (!arguments.length) + return _state; + _state = val; + return entityEditor; + }; + entityEditor.entityIDs = function(val) { if (!arguments.length) return _entityIDs; + _base = context.graph(); + _coalesceChanges = false; + if (val && _entityIDs && utilArrayIdentical(_entityIDs, val)) + return entityEditor; _entityIDs = val; - _currLoc = null; - if (_entityIDs && _entityIDs.length) { - const extent = _entityIDs.reduce(function(extent2, entityID) { - var entity = context.graph().entity(entityID); - return extent2.extend(entity.extent(context.graph())); - }, geoExtent()); - _currLoc = extent.center(); - var presets = _entityIDs.map(function(entityID) { - return _mainPresetIndex.match(context.entity(entityID), context.graph()); - }); - presetList.presets(presets); - } - return presetList; + loadActivePresets(true); + return entityEditor.modified(false); }; - presetList.presets = function(val) { + entityEditor.newFeature = function(val) { if (!arguments.length) - return _currentPresets; - _currentPresets = val; - return presetList; + return _newFeature; + _newFeature = val; + return entityEditor; }; - function entityGeometries() { + function loadActivePresets(isForNewSelection) { + var graph = context.graph(); var counts = {}; for (var i3 in _entityIDs) { - var entityID = _entityIDs[i3]; - var entity = context.entity(entityID); - var geometry = entity.geometry(context.graph()); - if (geometry === "vertex" && entity.isOnAddressLine(context.graph())) { - geometry = "point"; - } - if (!counts[geometry]) - counts[geometry] = 0; - counts[geometry] += 1; + var entity = graph.hasEntity(_entityIDs[i3]); + if (!entity) + return; + var match = _mainPresetIndex.match(entity, graph); + if (!counts[match.id]) + counts[match.id] = 0; + counts[match.id] += 1; } - return Object.keys(counts).sort(function(geom1, geom2) { - return counts[geom2] - counts[geom1]; + var matches = Object.keys(counts).sort(function(p1, p2) { + return counts[p2] - counts[p1]; + }).map(function(pID) { + return _mainPresetIndex.item(pID); }); - } - return utilRebind(presetList, dispatch14, "on"); - } - - // modules/ui/view_on_osm.js - function uiViewOnOSM(context) { - var _what; - function viewOnOSM(selection2) { - var url; - if (_what instanceof osmEntity) { - url = context.connection().entityURL(_what); - } else if (_what instanceof osmNote) { - url = context.connection().noteURL(_what); + if (!isForNewSelection) { + var weakPreset = _activePresets.length === 1 && !_activePresets[0].isFallback() && Object.keys(_activePresets[0].addTags || {}).length === 0; + if (weakPreset && matches.length === 1 && matches[0].isFallback()) + return; } - var data = !_what || _what.isNew() ? [] : [_what]; - var link2 = selection2.selectAll(".view-on-osm").data(data, function(d2) { - return d2.id; - }); - link2.exit().remove(); - var linkEnter = link2.enter().append("a").attr("class", "view-on-osm").attr("target", "_blank").attr("href", url).call(svgIcon("#iD-icon-out-link", "inline")); - linkEnter.append("span").call(_t.append("inspector.view_on_osm")); + entityEditor.presets(matches); } - viewOnOSM.what = function(_2) { + entityEditor.presets = function(val) { if (!arguments.length) - return _what; - _what = _2; - return viewOnOSM; + return _activePresets; + if (!utilArrayIdentical(val, _activePresets)) { + _activePresets = val; + } + return entityEditor; }; - return viewOnOSM; + return utilRebind(entityEditor, dispatch14, "on"); } - // modules/ui/inspector.js - function uiInspector(context) { - var presetList = uiPresetList(context); - var entityEditor = uiEntityEditor(context); - var wrap2 = select_default2(null), presetPane = select_default2(null), editorPane = select_default2(null); - var _state = "select"; - var _entityIDs; - var _newFeature = false; - function inspector(selection2) { - presetList.entityIDs(_entityIDs).autofocus(_newFeature).on("choose", inspector.setPreset).on("cancel", function() { - inspector.setPreset(); - }); - entityEditor.state(_state).entityIDs(_entityIDs).on("choose", inspector.showList); - wrap2 = selection2.selectAll(".panewrap").data([0]); - var enter = wrap2.enter().append("div").attr("class", "panewrap"); - enter.append("div").attr("class", "preset-list-pane pane"); - enter.append("div").attr("class", "entity-editor-pane pane"); - wrap2 = wrap2.merge(enter); - presetPane = wrap2.selectAll(".preset-list-pane"); - editorPane = wrap2.selectAll(".entity-editor-pane"); - function shouldDefaultToPresetList() { - if (_state !== "select") - return false; - if (_entityIDs.length !== 1) - return false; - var entityID = _entityIDs[0]; - var entity = context.hasEntity(entityID); - if (!entity) - return false; - if (entity.hasNonGeometryTags()) - return false; - if (_newFeature) - return true; - if (entity.geometry(context.graph()) !== "vertex") - return false; - if (context.graph().parentRelations(entity).length) - return false; - if (context.validator().getEntityIssues(entityID).length) - return false; - if (entity.isHighwayIntersection(context.graph())) - return false; - return true; - } - if (shouldDefaultToPresetList()) { - wrap2.style("right", "-100%"); - editorPane.classed("hide", true); - presetPane.classed("hide", false).call(presetList); - } else { - wrap2.style("right", "0%"); - presetPane.classed("hide", true); - editorPane.classed("hide", false).call(entityEditor); - } - var footer = selection2.selectAll(".footer").data([0]); - footer = footer.enter().append("div").attr("class", "footer").merge(footer); - footer.call( - uiViewOnOSM(context).what(context.hasEntity(_entityIDs.length === 1 && _entityIDs[0])) - ); - } - inspector.showList = function(presets) { - presetPane.classed("hide", false); - wrap2.transition().styleTween("right", function() { - return value_default("0%", "-100%"); - }).on("end", function() { - editorPane.classed("hide", true); - }); - if (presets) { - presetList.presets(presets); - } - presetPane.call(presetList.autofocus(true)); + // modules/ui/feature_list.js + var sexagesimal = __toESM(require_sexagesimal()); + + // modules/modes/draw_area.js + function modeDrawArea(context, wayID, startGraph, button) { + var mode = { + button, + id: "draw-area" }; - inspector.setPreset = function(preset) { - if (preset && preset.id === "type/multipolygon") { - presetPane.call(presetList.autofocus(true)); - } else { - editorPane.classed("hide", false); - wrap2.transition().styleTween("right", function() { - return value_default("-100%", "0%"); - }).on("end", function() { - presetPane.classed("hide", true); - }); - if (preset) { - entityEditor.presets([preset]); - } - editorPane.call(entityEditor); - } + var behavior = behaviorDrawWay(context, wayID, mode, startGraph).on("rejectedSelfIntersection.modeDrawArea", function() { + context.ui().flash.iconName("#iD-icon-no").label(_t.append("self_intersection.error.areas"))(); + }); + mode.wayID = wayID; + mode.enter = function() { + context.install(behavior); }; - inspector.state = function(val) { - if (!arguments.length) - return _state; - _state = val; - entityEditor.state(_state); - context.container().selectAll(".field-help-body").remove(); - return inspector; + mode.exit = function() { + context.uninstall(behavior); }; - inspector.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - _entityIDs = val; - return inspector; + mode.selectedIDs = function() { + return [wayID]; }; - inspector.newFeature = function(val) { - if (!arguments.length) - return _newFeature; - _newFeature = val; - return inspector; + mode.activeID = function() { + return behavior && behavior.activeID() || []; }; - return inspector; + return mode; } - // modules/ui/keepRight_details.js - function uiKeepRightDetails(context) { - let _qaItem; - function issueDetail(d2) { - const { itemType, parentIssueType } = d2; - const unknown = { html: _t.html("inspector.unknown") }; - let replacements = d2.replacements || {}; - replacements.default = unknown; - if (_mainLocalizer.hasTextForStringId("QA.keepRight.errorTypes.".concat(itemType, ".title"))) { - return _t.html("QA.keepRight.errorTypes.".concat(itemType, ".description"), replacements); - } else { - return _t.html("QA.keepRight.errorTypes.".concat(parentIssueType, ".description"), replacements); - } + // modules/modes/add_area.js + function modeAddArea(context, mode) { + mode.id = "add-area"; + var behavior = behaviorAddWay(context).on("start", start2).on("startFromWay", startFromWay).on("startFromNode", startFromNode); + function defaultTags(loc) { + var defaultTags2 = { area: "yes" }; + if (mode.preset) + defaultTags2 = mode.preset.setTags(defaultTags2, "area", false, loc); + return defaultTags2; } - function keepRightDetails(selection2) { - const details = selection2.selectAll(".error-details").data( - _qaItem ? [_qaItem] : [], - (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + function actionClose(wayId) { + return function(graph) { + return graph.replace(graph.entity(wayId).close()); + }; + } + function start2(loc) { + var startGraph = context.graph(); + var node = osmNode({ loc }); + var way = osmWay({ tags: defaultTags(loc) }); + context.perform( + actionAddEntity(node), + actionAddEntity(way), + actionAddVertex(way.id, node.id), + actionClose(way.id) ); - details.exit().remove(); - const detailsEnter = details.enter().append("div").attr("class", "error-details qa-details-container"); - const descriptionEnter = detailsEnter.append("div").attr("class", "qa-details-subsection"); - descriptionEnter.append("h4").call(_t.append("QA.keepRight.detail_description")); - descriptionEnter.append("div").attr("class", "qa-details-description-text").html(issueDetail); - let relatedEntities = []; - descriptionEnter.selectAll(".error_entity_link, .error_object_link").attr("href", "#").each(function() { - const link2 = select_default2(this); - const isObjectLink = link2.classed("error_object_link"); - const entityID = isObjectLink ? utilEntityRoot(_qaItem.objectType) + _qaItem.objectId : this.textContent; - const entity = context.hasEntity(entityID); - relatedEntities.push(entityID); - link2.on("mouseenter", () => { - utilHighlightEntities([entityID], true, context); - }).on("mouseleave", () => { - utilHighlightEntities([entityID], false, context); - }).on("click", (d3_event) => { - d3_event.preventDefault(); - utilHighlightEntities([entityID], false, context); - const osmlayer = context.layers().layer("osm"); - if (!osmlayer.enabled()) { - osmlayer.enabled(true); - } - context.map().centerZoomEase(_qaItem.loc, 20); - if (entity) { - context.enter(modeSelect(context, [entityID])); - } else { - context.loadEntity(entityID, (err, result) => { - if (err) - return; - const entity2 = result.data.find((e3) => e3.id === entityID); - if (entity2) - context.enter(modeSelect(context, [entityID])); - }); - } - }); - if (entity) { - let name = utilDisplayName(entity); - if (!name && !isObjectLink) { - const preset = _mainPresetIndex.match(entity, context.graph()); - name = preset && !preset.isFallback() && preset.name(); - } - if (name) { - this.innerText = name; - } - } - }); - context.features().forceVisible(relatedEntities); - context.map().pan([0, 0]); + context.enter(modeDrawArea(context, way.id, startGraph, mode.button)); + } + function startFromWay(loc, edge) { + var startGraph = context.graph(); + var node = osmNode({ loc }); + var way = osmWay({ tags: defaultTags(loc) }); + context.perform( + actionAddEntity(node), + actionAddEntity(way), + actionAddVertex(way.id, node.id), + actionClose(way.id), + actionAddMidpoint({ loc, edge }, node) + ); + context.enter(modeDrawArea(context, way.id, startGraph, mode.button)); + } + function startFromNode(node) { + var startGraph = context.graph(); + var way = osmWay({ tags: defaultTags(node.loc) }); + context.perform( + actionAddEntity(way), + actionAddVertex(way.id, node.id), + actionClose(way.id) + ); + context.enter(modeDrawArea(context, way.id, startGraph, mode.button)); } - keepRightDetails.issue = function(val) { - if (!arguments.length) - return _qaItem; - _qaItem = val; - return keepRightDetails; + mode.enter = function() { + context.install(behavior); }; - return keepRightDetails; + mode.exit = function() { + context.uninstall(behavior); + }; + return mode; } - // modules/ui/keepRight_header.js - function uiKeepRightHeader() { - let _qaItem; - function issueTitle(d2) { - const { itemType, parentIssueType } = d2; - const unknown = _t.html("inspector.unknown"); - let replacements = d2.replacements || {}; - replacements.default = { html: unknown }; - if (_mainLocalizer.hasTextForStringId("QA.keepRight.errorTypes.".concat(itemType, ".title"))) { - return _t.html("QA.keepRight.errorTypes.".concat(itemType, ".title"), replacements); - } else { - return _t.html("QA.keepRight.errorTypes.".concat(parentIssueType, ".title"), replacements); - } + // modules/modes/add_line.js + function modeAddLine(context, mode) { + mode.id = "add-line"; + var behavior = behaviorAddWay(context).on("start", start2).on("startFromWay", startFromWay).on("startFromNode", startFromNode); + function defaultTags(loc) { + var defaultTags2 = {}; + if (mode.preset) + defaultTags2 = mode.preset.setTags(defaultTags2, "line", false, loc); + return defaultTags2; } - function keepRightHeader(selection2) { - const header = selection2.selectAll(".qa-header").data( - _qaItem ? [_qaItem] : [], - (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + function start2(loc) { + var startGraph = context.graph(); + var node = osmNode({ loc }); + var way = osmWay({ tags: defaultTags(loc) }); + context.perform( + actionAddEntity(node), + actionAddEntity(way), + actionAddVertex(way.id, node.id) ); - header.exit().remove(); - const headerEnter = header.enter().append("div").attr("class", "qa-header"); - const iconEnter = headerEnter.append("div").attr("class", "qa-header-icon").classed("new", (d2) => d2.id < 0); - iconEnter.append("div").attr("class", (d2) => "preset-icon-28 qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.parentIssueType)).call(svgIcon("#iD-icon-bolt", "qaItem-fill")); - headerEnter.append("div").attr("class", "qa-header-label").html(issueTitle); + context.enter(modeDrawLine(context, way.id, startGraph, mode.button)); } - keepRightHeader.issue = function(val) { - if (!arguments.length) - return _qaItem; - _qaItem = val; - return keepRightHeader; - }; - return keepRightHeader; - } - - // modules/ui/view_on_keepRight.js - function uiViewOnKeepRight() { - let _qaItem; - function viewOnKeepRight(selection2) { - let url; - if (services.keepRight && _qaItem instanceof QAItem) { - url = services.keepRight.issueURL(_qaItem); - } - const link2 = selection2.selectAll(".view-on-keepRight").data(url ? [url] : []); - link2.exit().remove(); - const linkEnter = link2.enter().append("a").attr("class", "view-on-keepRight").attr("target", "_blank").attr("rel", "noopener").attr("href", (d2) => d2).call(svgIcon("#iD-icon-out-link", "inline")); - linkEnter.append("span").call(_t.append("inspector.view_on_keepRight")); + function startFromWay(loc, edge) { + var startGraph = context.graph(); + var node = osmNode({ loc }); + var way = osmWay({ tags: defaultTags(loc) }); + context.perform( + actionAddEntity(node), + actionAddEntity(way), + actionAddVertex(way.id, node.id), + actionAddMidpoint({ loc, edge }, node) + ); + context.enter(modeDrawLine(context, way.id, startGraph, mode.button)); } - viewOnKeepRight.what = function(val) { - if (!arguments.length) - return _qaItem; - _qaItem = val; - return viewOnKeepRight; + function startFromNode(node) { + var startGraph = context.graph(); + var way = osmWay({ tags: defaultTags(node.loc) }); + context.perform( + actionAddEntity(way), + actionAddVertex(way.id, node.id) + ); + context.enter(modeDrawLine(context, way.id, startGraph, mode.button)); + } + mode.enter = function() { + context.install(behavior); }; - return viewOnKeepRight; + mode.exit = function() { + context.uninstall(behavior); + }; + return mode; } - // modules/ui/keepRight_editor.js - function uiKeepRightEditor(context) { - const dispatch14 = dispatch_default("change"); - const qaDetails = uiKeepRightDetails(context); - const qaHeader = uiKeepRightHeader(context); - let _qaItem; - function keepRightEditor(selection2) { - const headerEnter = selection2.selectAll(".header").data([0]).enter().append("div").attr("class", "header fillL"); - headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", () => context.enter(modeBrowse(context))).call(svgIcon("#iD-icon-close")); - headerEnter.append("h2").call(_t.append("QA.keepRight.title")); - let body = selection2.selectAll(".body").data([0]); - body = body.enter().append("div").attr("class", "body").merge(body); - const editor = body.selectAll(".qa-editor").data([0]); - editor.enter().append("div").attr("class", "modal-section qa-editor").merge(editor).call(qaHeader.issue(_qaItem)).call(qaDetails.issue(_qaItem)).call(keepRightSaveSection); - const footer = selection2.selectAll(".footer").data([0]); - footer.enter().append("div").attr("class", "footer").merge(footer).call(uiViewOnKeepRight(context).what(_qaItem)); + // modules/modes/add_point.js + function modeAddPoint(context, mode) { + mode.id = "add-point"; + var behavior = behaviorDraw(context).on("click", add).on("clickWay", addWay).on("clickNode", addNode).on("cancel", cancel).on("finish", cancel); + function defaultTags(loc) { + var defaultTags2 = {}; + if (mode.preset) + defaultTags2 = mode.preset.setTags(defaultTags2, "point", false, loc); + return defaultTags2; } - function keepRightSaveSection(selection2) { - const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); - const isShown = _qaItem && (isSelected || _qaItem.newComment || _qaItem.comment); - let saveSection = selection2.selectAll(".qa-save").data( - isShown ? [_qaItem] : [], - (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + function add(loc) { + var node = osmNode({ loc, tags: defaultTags(loc) }); + context.perform( + actionAddEntity(node), + _t("operations.add.annotation.point") ); - saveSection.exit().remove(); - const saveSectionEnter = saveSection.enter().append("div").attr("class", "qa-save save-section cf"); - saveSectionEnter.append("h4").attr("class", ".qa-save-header").call(_t.append("QA.keepRight.comment")); - saveSectionEnter.append("textarea").attr("class", "new-comment-input").attr("placeholder", _t("QA.keepRight.comment_placeholder")).attr("maxlength", 1e3).property("value", (d2) => d2.newComment || d2.comment).call(utilNoAuto).on("input", changeInput).on("blur", changeInput); - saveSection = saveSectionEnter.merge(saveSection).call(qaSaveButtons); - function changeInput() { - const input = select_default2(this); - let val = input.property("value").trim(); - if (val === _qaItem.comment) { - val = void 0; - } - _qaItem = _qaItem.update({ newComment: val }); - const qaService = services.keepRight; - if (qaService) { - qaService.replaceItem(_qaItem); - } - saveSection.call(qaSaveButtons); - } + enterSelectMode(node); } - function qaSaveButtons(selection2) { - const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); - let buttonSection = selection2.selectAll(".buttons").data(isSelected ? [_qaItem] : [], (d2) => d2.status + d2.id); - buttonSection.exit().remove(); - const buttonEnter = buttonSection.enter().append("div").attr("class", "buttons"); - buttonEnter.append("button").attr("class", "button comment-button action").call(_t.append("QA.keepRight.save_comment")); - buttonEnter.append("button").attr("class", "button close-button action"); - buttonEnter.append("button").attr("class", "button ignore-button action"); - buttonSection = buttonSection.merge(buttonEnter); - buttonSection.select(".comment-button").attr("disabled", (d2) => d2.newComment ? null : true).on("click.comment", function(d3_event, d2) { - this.blur(); - const qaService = services.keepRight; - if (qaService) { - qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); - } - }); - buttonSection.select(".close-button").html((d2) => { - const andComment = d2.newComment ? "_comment" : ""; - return _t.html("QA.keepRight.close".concat(andComment)); - }).on("click.close", function(d3_event, d2) { - this.blur(); - const qaService = services.keepRight; - if (qaService) { - d2.newStatus = "ignore_t"; - qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); - } - }); - buttonSection.select(".ignore-button").html((d2) => { - const andComment = d2.newComment ? "_comment" : ""; - return _t.html("QA.keepRight.ignore".concat(andComment)); - }).on("click.ignore", function(d3_event, d2) { - this.blur(); - const qaService = services.keepRight; - if (qaService) { - d2.newStatus = "ignore"; - qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); - } - }); + function addWay(loc, edge) { + var node = osmNode({ tags: defaultTags(loc) }); + context.perform( + actionAddMidpoint({ loc, edge }, node), + _t("operations.add.annotation.vertex") + ); + enterSelectMode(node); } - keepRightEditor.error = function(val) { - if (!arguments.length) - return _qaItem; - _qaItem = val; - return keepRightEditor; - }; - return utilRebind(keepRightEditor, dispatch14, "on"); - } - - // modules/ui/lasso.js - function uiLasso(context) { - var group, polygon2; - lasso.coordinates = []; - function lasso(selection2) { - context.container().classed("lasso", true); - group = selection2.append("g").attr("class", "lasso hide"); - polygon2 = group.append("path").attr("class", "lasso-path"); - group.call(uiToggle(true)); + function enterSelectMode(node) { + context.enter( + modeSelect(context, [node.id]).newFeature(true) + ); } - function draw() { - if (polygon2) { - polygon2.data([lasso.coordinates]).attr("d", function(d2) { - return "M" + d2.join(" L") + " Z"; - }); + function addNode(node) { + const _defaultTags = defaultTags(node.loc); + if (Object.keys(_defaultTags).length === 0) { + enterSelectMode(node); + return; + } + var tags = Object.assign({}, node.tags); + for (var key in _defaultTags) { + tags[key] = _defaultTags[key]; } + context.perform( + actionChangeTags(node.id, tags), + _t("operations.add.annotation.point") + ); + enterSelectMode(node); } - lasso.extent = function() { - return lasso.coordinates.reduce(function(extent, point2) { - return extent.extend(geoExtent(point2)); - }, geoExtent()); - }; - lasso.p = function(_2) { - if (!arguments.length) - return lasso; - lasso.coordinates.push(_2); - draw(); - return lasso; + function cancel() { + context.enter(modeBrowse(context)); + } + mode.enter = function() { + context.install(behavior); }; - lasso.close = function() { - if (group) { - group.call(uiToggle(false, function() { - select_default2(this).remove(); - })); - } - context.container().classed("lasso", false); + mode.exit = function() { + context.uninstall(behavior); }; - return lasso; + return mode; } // modules/ui/note_comments.js @@ -69539,9 +71056,9 @@ if (services.osm && _note instanceof osmNote && !_note.isNew()) { url = services.osm.noteReportURL(_note); } - var link2 = selection2.selectAll(".note-report").data(url ? [url] : []); - link2.exit().remove(); - var linkEnter = link2.enter().append("a").attr("class", "note-report").attr("target", "_blank").attr("href", function(d2) { + var link3 = selection2.selectAll(".note-report").data(url ? [url] : []); + link3.exit().remove(); + var linkEnter = link3.enter().append("a").attr("class", "note-report").attr("target", "_blank").attr("href", function(d2) { return d2; }).call(svgIcon("#iD-icon-out-link", "inline")); linkEnter.append("span").call(_t.append("note.report")); @@ -69555,6 +71072,33 @@ return noteReport; } + // modules/ui/view_on_osm.js + function uiViewOnOSM(context) { + var _what; + function viewOnOSM(selection2) { + var url; + if (_what instanceof osmEntity) { + url = context.connection().entityURL(_what); + } else if (_what instanceof osmNote) { + url = context.connection().noteURL(_what); + } + var data = !_what || _what.isNew() ? [] : [_what]; + var link3 = selection2.selectAll(".view-on-osm").data(data, function(d2) { + return d2.id; + }); + link3.exit().remove(); + var linkEnter = link3.enter().append("a").attr("class", "view-on-osm").attr("target", "_blank").attr("href", url).call(svgIcon("#iD-icon-out-link", "inline")); + linkEnter.append("span").call(_t.append("inspector.view_on_osm")); + } + viewOnOSM.what = function(_2) { + if (!arguments.length) + return _what; + _what = _2; + return viewOnOSM; + }; + return viewOnOSM; + } + // modules/ui/note_editor.js function uiNoteEditor(context) { var dispatch14 = dispatch_default("change"); @@ -69746,172 +71290,132 @@ return utilRebind(noteEditor, dispatch14, "on"); } - // modules/ui/source_switch.js - function uiSourceSwitch(context) { - var keys2; - function click(d3_event) { - d3_event.preventDefault(); - var osm = context.connection(); - if (!osm) - return; - if (context.inIntro()) + // modules/modes/select_note.js + function modeSelectNote(context, selectedNoteID) { + var mode = { + id: "select-note", + button: "browse" + }; + var _keybinding = utilKeybinding("select-note"); + var _noteEditor = uiNoteEditor(context).on("change", function() { + context.map().pan([0, 0]); + var note = checkSelectedID(); + if (!note) return; - if (context.history().hasChanges() && !window.confirm(_t("source_switch.lose_changes"))) + context.ui().sidebar.show(_noteEditor.note(note)); + }); + var _behaviors = [ + behaviorBreathe(context), + behaviorHover(context), + behaviorSelect(context), + behaviorLasso(context), + modeDragNode(context).behavior, + modeDragNote(context).behavior + ]; + var _newFeature = false; + function checkSelectedID() { + if (!services.osm) return; - var isLive = select_default2(this).classed("live"); - isLive = !isLive; - context.enter(modeBrowse(context)); - context.history().clearSaved(); - context.flush(); - select_default2(this).html(isLive ? _t.html("source_switch.live") : _t.html("source_switch.dev")).classed("live", isLive).classed("chip", isLive); - osm.switch(isLive ? keys2[0] : keys2[1]); - } - var sourceSwitch = function(selection2) { - selection2.append("a").attr("href", "#").call(_t.append("source_switch.live")).attr("class", "live chip").on("click", click); - }; - sourceSwitch.keys = function(_2) { - if (!arguments.length) - return keys2; - keys2 = _2; - return sourceSwitch; - }; - return sourceSwitch; - } - - // modules/ui/spinner.js - function uiSpinner(context) { - var osm = context.connection(); - return function(selection2) { - var img = selection2.append("img").attr("src", context.imagePath("loader-black.gif")).style("opacity", 0); - if (osm) { - osm.on("loading.spinner", function() { - img.transition().style("opacity", 1); - }).on("loaded.spinner", function() { - img.transition().style("opacity", 0); - }); + var note = services.osm.getNote(selectedNoteID); + if (!note) { + context.enter(modeBrowse(context)); } - }; - } - - // modules/ui/sections/privacy.js - function uiSectionPrivacy(context) { - let section = uiSection("preferences-third-party", context).label(() => _t.append("preferences.privacy.title")).disclosureContent(renderDisclosureContent); - function renderDisclosureContent(selection2) { - selection2.selectAll(".privacy-options-list").data([0]).enter().append("ul").attr("class", "layer-list privacy-options-list"); - let thirdPartyIconsEnter = selection2.select(".privacy-options-list").selectAll(".privacy-third-party-icons-item").data([corePreferences("preferences.privacy.thirdpartyicons") || "true"]).enter().append("li").attr("class", "privacy-third-party-icons-item").append("label").call( - uiTooltip().title(() => _t.append("preferences.privacy.third_party_icons.tooltip")).placement("bottom") - ); - thirdPartyIconsEnter.append("input").attr("type", "checkbox").on("change", (d3_event, d2) => { - d3_event.preventDefault(); - corePreferences("preferences.privacy.thirdpartyicons", d2 === "true" ? "false" : "true"); - }); - thirdPartyIconsEnter.append("span").call(_t.append("preferences.privacy.third_party_icons.description")); - selection2.selectAll(".privacy-third-party-icons-item").classed("active", (d2) => d2 === "true").select("input").property("checked", (d2) => d2 === "true"); - selection2.selectAll(".privacy-link").data([0]).enter().append("div").attr("class", "privacy-link").append("a").attr("target", "_blank").call(svgIcon("#iD-icon-out-link", "inline")).attr("href", "https://github.com/openstreetmap/iD/blob/release/PRIVACY.md").append("span").call(_t.append("preferences.privacy.privacy_link")); + return note; } - corePreferences.onChange("preferences.privacy.thirdpartyicons", section.reRender); - return section; - } - - // modules/ui/splash.js - function uiSplash(context) { - return (selection2) => { - if (context.history().hasRestorableChanges()) + function selectNote(d3_event, drawn) { + if (!checkSelectedID()) return; - let updateMessage = ""; - const sawPrivacyVersion = corePreferences("sawPrivacyVersion"); - let showSplash = !corePreferences("sawSplash"); - if (sawPrivacyVersion !== context.privacyVersion) { - updateMessage = _t("splash.privacy_update"); - showSplash = true; + var selection2 = context.surface().selectAll(".layer-notes .note-" + selectedNoteID); + if (selection2.empty()) { + var source = d3_event && d3_event.type === "zoom" && d3_event.sourceEvent; + if (drawn && source && (source.type === "pointermove" || source.type === "mousemove" || source.type === "touchmove")) { + context.enter(modeBrowse(context)); + } + } else { + selection2.classed("selected", true); + context.selectedNoteID(selectedNoteID); } - if (!showSplash) + } + function esc() { + if (context.container().select(".combobox").size()) return; - corePreferences("sawSplash", true); - corePreferences("sawPrivacyVersion", context.privacyVersion); - _mainFileFetcher.get("intro_graph"); - let modalSelection = uiModal(selection2); - modalSelection.select(".modal").attr("class", "modal-splash modal"); - let introModal = modalSelection.select(".content").append("div").attr("class", "fillL"); - introModal.append("div").attr("class", "modal-section").append("h3").call(_t.append("splash.welcome")); - let modalSection = introModal.append("div").attr("class", "modal-section"); - modalSection.append("p").html(_t.html("splash.text", { - version: context.version, - website: { html: '' + _t.html("splash.changelog") + "" }, - github: { html: 'github.com' } - })); - modalSection.append("p").html(_t.html("splash.privacy", { - updateMessage, - privacyLink: { html: '' + _t("splash.privacy_policy") + "" } - })); - uiSectionPrivacy(context).label(() => _t.append("splash.privacy_settings")).render(modalSection); - let buttonWrap = introModal.append("div").attr("class", "modal-actions"); - let walkthrough = buttonWrap.append("button").attr("class", "walkthrough").on("click", () => { - context.container().call(uiIntro(context)); - modalSelection.close(); - }); - walkthrough.append("svg").attr("class", "logo logo-walkthrough").append("use").attr("xlink:href", "#iD-logo-walkthrough"); - walkthrough.append("div").call(_t.append("splash.walkthrough")); - let startEditing = buttonWrap.append("button").attr("class", "start-editing").on("click", modalSelection.close); - startEditing.append("svg").attr("class", "logo logo-features").append("use").attr("xlink:href", "#iD-logo-features"); - startEditing.append("div").call(_t.append("splash.start")); - modalSelection.select("button.close").attr("class", "hide"); - }; - } - - // modules/ui/status.js - function uiStatus(context) { - var osm = context.connection(); - return function(selection2) { - if (!osm) + context.enter(modeBrowse(context)); + } + mode.zoomToSelected = function() { + if (!services.osm) return; - function update(err, apiStatus) { - selection2.html(""); - if (err) { - if (apiStatus === "connectionSwitched") { - return; - } else if (apiStatus === "rateLimited") { - selection2.call(_t.append("osm_api_status.message.rateLimit")).append("a").attr("href", "#").attr("class", "api-status-login").attr("target", "_blank").call(svgIcon("#iD-icon-out-link", "inline")).append("span").call(_t.append("login")).on("click.login", function(d3_event) { - d3_event.preventDefault(); - osm.authenticate(); - }); - } else { - var throttledRetry = throttle_default(function() { - context.loadTiles(context.projection); - osm.reloadApiStatus(); - }, 2e3); - selection2.call(_t.append("osm_api_status.message.error", { suffix: " " })).append("a").attr("href", "#").call(_t.append("osm_api_status.retry")).on("click.retry", function(d3_event) { - d3_event.preventDefault(); - throttledRetry(); - }); - } - } else if (apiStatus === "readonly") { - selection2.call(_t.append("osm_api_status.message.readonly")); - } else if (apiStatus === "offline") { - selection2.call(_t.append("osm_api_status.message.offline")); - } - selection2.attr("class", "api-status " + (err ? "error" : apiStatus)); + var note = services.osm.getNote(selectedNoteID); + if (note) { + context.map().centerZoomEase(note.loc, 20); } - osm.on("apiStatusChange.uiStatus", update); - context.history().on("storage_error", () => { - selection2.selectAll("span.local-storage-full").remove(); - selection2.append("span").attr("class", "local-storage-full").call(_t.append("osm_api_status.message.local_storage_full")); - selection2.classed("error", true); - }); - window.setInterval(function() { - osm.reloadApiStatus(); - }, 9e4); - osm.reloadApiStatus(); }; + mode.newFeature = function(val) { + if (!arguments.length) + return _newFeature; + _newFeature = val; + return mode; + }; + mode.enter = function() { + var note = checkSelectedID(); + if (!note) + return; + _behaviors.forEach(context.install); + _keybinding.on(_t("inspector.zoom_to.key"), mode.zoomToSelected).on("\u238B", esc, true); + select_default2(document).call(_keybinding); + selectNote(); + var sidebar = context.ui().sidebar; + sidebar.show(_noteEditor.note(note).newNote(_newFeature)); + sidebar.expand(sidebar.intersects(note.extent())); + context.map().on("drawn.select", selectNote); + }; + mode.exit = function() { + _behaviors.forEach(context.uninstall); + select_default2(document).call(_keybinding.unbind); + context.surface().selectAll(".layer-notes .selected").classed("selected hover", false); + context.map().on("drawn.select", null); + context.ui().sidebar.hide(); + context.selectedNoteID(null); + }; + return mode; + } + + // modules/modes/add_note.js + function modeAddNote(context) { + var mode = { + id: "add-note", + button: "note", + description: _t.append("modes.add_note.description"), + key: _t("modes.add_note.key") + }; + var behavior = behaviorDraw(context).on("click", add).on("cancel", cancel).on("finish", cancel); + function add(loc) { + var osm = services.osm; + if (!osm) + return; + var note = osmNote({ loc, status: "open", comments: [] }); + osm.replaceNote(note); + context.map().pan([0, 0]); + context.selectedNoteID(note.id).enter(modeSelectNote(context, note.id).newFeature(true)); + } + function cancel() { + context.enter(modeBrowse(context)); + } + mode.enter = function() { + context.install(behavior); + }; + mode.exit = function() { + context.uninstall(behavior); + }; + return mode; } // node_modules/osm-community-index/lib/simplify.js var import_diacritics2 = __toESM(require_diacritics(), 1); - function simplify(str2) { - if (typeof str2 !== "string") + function simplify(str) { + if (typeof str !== "string") return ""; return import_diacritics2.default.remove( - str2.replace(/&/g, "and").replace(/(İ|i̇)/ig, "i").replace(/[\s\-=_!"#%'*{},.\/:;?\(\)\[\]@\\$\^*+<>«»~`’\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2000-\u206f\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00-\u2e7f\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\ufeff\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g, "").toLowerCase() + str.replace(/&/g, "and").replace(/(İ|i̇)/ig, "i").replace(/[\s\-=_!"#%'*{},.\/:;?\(\)\[\]@\\$\^*+<>«»~`’\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2000-\u206f\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00-\u2e7f\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\ufeff\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g, "").toLowerCase() ); } @@ -69985,11 +71489,11 @@ } return result; } - function linkify(url, text2) { + function linkify(url, text) { if (!url) return void 0; - text2 = text2 || url; - return '').concat(text2, ""); + text = text || url; + return '').concat(text, ""); } } @@ -70064,6 +71568,18 @@ summaryDetail.append("div").html(_t.html("success.changeset_id", { changeset_id: { html: '').concat(_changeset2.id, "") } })); + if (showDonationMessage !== false) { + const donationUrl = "https://supporting.openstreetmap.org/"; + let supporting = body.append("div").attr("class", "save-supporting"); + supporting.append("h3").call(_t.append("success.supporting.title")); + supporting.append("p").call(_t.append("success.supporting.details")); + table = supporting.append("table").attr("class", "supporting-table"); + row = table.append("tr").attr("class", "supporting-row"); + row.append("td").attr("class", "cell-icon supporting-icon").append("a").attr("target", "_blank").attr("href", donationUrl).append("svg").attr("class", "logo-small").append("use").attr("xlink:href", "#iD-donation"); + let supportingDetail = row.append("td").attr("class", "cell-detail supporting-detail"); + supportingDetail.append("a").attr("class", "cell-detail support-the-map").attr("target", "_blank").attr("href", donationUrl).call(_t.append("success.supporting.donation.title")); + supportingDetail.append("div").call(_t.append("success.supporting.donation.details")); + } ensureOSMCommunityIndex().then((oci) => { const loc = context.map().center(); const validHere = _sharedLocationManager.locationSetsAt(loc); @@ -70181,572 +71697,600 @@ return utilRebind(success, dispatch14, "on"); } - // modules/ui/version.js - var sawVersion = null; - var isNewVersion = false; - var isNewUser = false; - function uiVersion(context) { - var currVersion = context.version; - var matchedVersion = currVersion.match(/\d+\.\d+\.\d+.*/); - if (sawVersion === null && matchedVersion !== null) { - if (corePreferences("sawVersion")) { - isNewUser = false; - isNewVersion = corePreferences("sawVersion") !== currVersion && currVersion.indexOf("-") === -1; - } else { - isNewUser = true; - isNewVersion = true; - } - corePreferences("sawVersion", currVersion); - sawVersion = currVersion; - } - return function(selection2) { - selection2.append("a").attr("target", "_blank").attr("href", "https://github.com/openstreetmap/iD").text(currVersion); - if (isNewVersion && !isNewUser) { - selection2.append("a").attr("class", "badge").attr("target", "_blank").attr("href", "https://github.com/openstreetmap/iD/blob/release/CHANGELOG.md#whats-new").call(svgIcon("#maki-gift")).call( - uiTooltip().title(() => _t.append("version.whats_new", { version: currVersion })).placement("top").scrollContainer(context.container().select(".main-footer-wrap")) - ); - } - }; - } - - // modules/ui/zoom.js - function uiZoom(context) { - var zooms = [{ - id: "zoom-in", - icon: "iD-icon-plus", - title: _t.append("zoom.in"), - action: zoomIn, - disabled: function() { - return !context.map().canZoomIn(); - }, - disabledTitle: _t.append("zoom.disabled.in"), - key: "+" - }, { - id: "zoom-out", - icon: "iD-icon-minus", - title: _t.append("zoom.out"), - action: zoomOut, - disabled: function() { - return !context.map().canZoomOut(); - }, - disabledTitle: _t.append("zoom.disabled.out"), - key: "-" - }]; - function zoomIn(d3_event) { - if (d3_event.shiftKey) - return; - d3_event.preventDefault(); - context.map().zoomIn(); + // modules/modes/save.js + function modeSave(context) { + var mode = { id: "save" }; + var keybinding = utilKeybinding("modeSave"); + var commit = uiCommit(context).on("cancel", cancel); + var _conflictsUi; + var _location; + var _success; + var uploader = context.uploader().on("saveStarted.modeSave", function() { + keybindingOff(); + }).on("willAttemptUpload.modeSave", prepareForSuccess).on("progressChanged.modeSave", showProgress).on("resultNoChanges.modeSave", function() { + cancel(); + }).on("resultErrors.modeSave", showErrors).on("resultConflicts.modeSave", showConflicts).on("resultSuccess.modeSave", showSuccess); + function cancel() { + context.enter(modeBrowse(context)); } - function zoomOut(d3_event) { - if (d3_event.shiftKey) - return; - d3_event.preventDefault(); - context.map().zoomOut(); + function showProgress(num, total) { + var modal = context.container().select(".loading-modal .modal-section"); + var progress = modal.selectAll(".progress").data([0]); + progress.enter().append("div").attr("class", "progress").merge(progress).text(_t("save.conflict_progress", { num, total })); } - function zoomInFurther(d3_event) { - if (d3_event.shiftKey) - return; - d3_event.preventDefault(); - context.map().zoomInFurther(); + function showConflicts(changeset, conflicts, origChanges) { + var selection2 = context.container().select(".sidebar").append("div").attr("class", "sidebar-component"); + context.container().selectAll(".main-content").classed("active", true).classed("inactive", false); + _conflictsUi = uiConflicts(context).conflictList(conflicts).origChanges(origChanges).on("cancel", function() { + context.container().selectAll(".main-content").classed("active", false).classed("inactive", true); + selection2.remove(); + keybindingOn(); + uploader.cancelConflictResolution(); + }).on("save", function() { + context.container().selectAll(".main-content").classed("active", false).classed("inactive", true); + selection2.remove(); + uploader.processResolvedConflicts(changeset); + }); + selection2.call(_conflictsUi); } - function zoomOutFurther(d3_event) { - if (d3_event.shiftKey) - return; - d3_event.preventDefault(); - context.map().zoomOutFurther(); + function showErrors(errors) { + keybindingOn(); + var selection2 = uiConfirm(context.container()); + selection2.select(".modal-section.header").append("h3").text(_t("save.error")); + addErrors(selection2, errors); + selection2.okButton(); } - return function(selection2) { - var tooltipBehavior = uiTooltip().placement(_mainLocalizer.textDirection() === "rtl" ? "right" : "left").title(function(d2) { - if (d2.disabled()) { - return d2.disabledTitle; - } - return d2.title; - }).keys(function(d2) { - return [d2.key]; + function addErrors(selection2, data) { + var message = selection2.select(".modal-section.message-text"); + var items = message.selectAll(".error-container").data(data); + var enter = items.enter().append("div").attr("class", "error-container"); + enter.append("a").attr("class", "error-description").attr("href", "#").classed("hide-toggle", true).text(function(d2) { + return d2.msg || _t("save.unknown_error_details"); + }).on("click", function(d3_event) { + d3_event.preventDefault(); + var error = select_default2(this); + var detail = select_default2(this.nextElementSibling); + var exp2 = error.classed("expanded"); + detail.style("display", exp2 ? "none" : "block"); + error.classed("expanded", !exp2); }); - var lastPointerUpType; - var buttons = selection2.selectAll("button").data(zooms).enter().append("button").attr("class", function(d2) { - return d2.id; - }).on("pointerup.editor", function(d3_event) { - lastPointerUpType = d3_event.pointerType; - }).on("click.editor", function(d3_event, d2) { - if (!d2.disabled()) { - d2.action(d3_event); - } else if (lastPointerUpType === "touch" || lastPointerUpType === "pen") { - context.ui().flash.duration(2e3).iconName("#" + d2.icon).iconClass("disabled").label(d2.disabledTitle)(); - } - lastPointerUpType = null; - }).call(tooltipBehavior); - buttons.each(function(d2) { - select_default2(this).call(svgIcon("#" + d2.icon, "light")); + var details = enter.append("div").attr("class", "error-detail-container").style("display", "none"); + details.append("ul").attr("class", "error-detail-list").selectAll("li").data(function(d2) { + return d2.details || []; + }).enter().append("li").attr("class", "error-detail-item").text(function(d2) { + return d2; }); - utilKeybinding.plusKeys.forEach(function(key) { - context.keybinding().on([key], zoomIn); - context.keybinding().on([uiCmd("\u2325" + key)], zoomInFurther); + items.exit().remove(); + } + function showSuccess(changeset) { + commit.reset(); + var ui = _success.changeset(changeset).location(_location).on("cancel", function() { + context.ui().sidebar.hide(); }); - utilKeybinding.minusKeys.forEach(function(key) { - context.keybinding().on([key], zoomOut); - context.keybinding().on([uiCmd("\u2325" + key)], zoomOutFurther); + context.enter(modeBrowse(context).sidebar(ui)); + } + function keybindingOn() { + select_default2(document).call(keybinding.on("\u238B", cancel, true)); + } + function keybindingOff() { + select_default2(document).call(keybinding.unbind); + } + function prepareForSuccess() { + _success = uiSuccess(context); + _location = null; + if (!services.geocoder) + return; + services.geocoder.reverse(context.map().center(), function(err, result) { + if (err || !result || !result.address) + return; + var addr = result.address; + var place = addr && (addr.town || addr.city || addr.county) || ""; + var region = addr && (addr.state || addr.country) || ""; + var separator = place && region ? _t("success.thank_you_where.separator") : ""; + _location = _t( + "success.thank_you_where.format", + { place, separator, region } + ); }); - function updateButtonStates() { - buttons.classed("disabled", function(d2) { - return d2.disabled(); - }).each(function() { - var selection3 = select_default2(this); - if (!selection3.select(".tooltip.in").empty()) { - selection3.call(tooltipBehavior.updateContent); + } + mode.selectedIDs = function() { + return _conflictsUi ? _conflictsUi.shownEntityIds() : []; + }; + mode.enter = function() { + context.ui().sidebar.expand(); + function done() { + context.ui().sidebar.show(commit); + } + keybindingOn(); + context.container().selectAll(".main-content").classed("active", false).classed("inactive", true); + var osm = context.connection(); + if (!osm) { + cancel(); + return; + } + if (osm.authenticated()) { + done(); + } else { + osm.authenticate(function(err) { + if (err) { + cancel(); + } else { + done(); } }); } - updateButtonStates(); - context.map().on("move.uiZoom", updateButtonStates); }; + mode.exit = function() { + keybindingOff(); + context.container().selectAll(".main-content").classed("active", true).classed("inactive", false); + context.ui().sidebar.hide(); + }; + return mode; } - // modules/ui/sections/raw_tag_editor.js - function uiSectionRawTagEditor(id2, context) { - var section = uiSection(id2, context).classes("raw-tag-editor").label(function() { - var count = Object.keys(_tags).filter(function(d2) { - return d2; - }).length; - return _t.append("inspector.title_count", { title: _t("inspector.tags"), count }); - }).expandedByDefault(false).disclosureContent(renderDisclosureContent); - var taginfo = services.taginfo; - var dispatch14 = dispatch_default("change"); - var availableViews = [ - { id: "list", icon: "#fas-th-list" }, - { id: "text", icon: "#fas-i-cursor" } - ]; - let _discardTags = {}; - _mainFileFetcher.get("discarded").then((d2) => { - _discardTags = d2; - }).catch(() => { - }); - var _tagView = corePreferences("raw-tag-editor-view") || "list"; - var _readOnlyTags = []; - var _orderedKeys = []; - var _showBlank = false; - var _pendingChange = null; - var _state; - var _presets; - var _tags; - var _entityIDs; - var _didInteract = false; - function interacted() { - _didInteract = true; - } - function renderDisclosureContent(wrap2) { - _orderedKeys = _orderedKeys.filter(function(key) { - return _tags[key] !== void 0; - }); - var all = Object.keys(_tags).sort(); - var missingKeys = utilArrayDifference(all, _orderedKeys); - for (var i3 in missingKeys) { - _orderedKeys.push(missingKeys[i3]); - } - var rowData = _orderedKeys.map(function(key, i4) { - return { index: i4, key, value: _tags[key] }; - }); - if (!rowData.length || _showBlank) { - _showBlank = false; - rowData.push({ index: rowData.length, key: "", value: "" }); - } - var options2 = wrap2.selectAll(".raw-tag-options").data([0]); - options2.exit().remove(); - var optionsEnter = options2.enter().insert("div", ":first-child").attr("class", "raw-tag-options").attr("role", "tablist"); - var optionEnter = optionsEnter.selectAll(".raw-tag-option").data(availableViews, function(d2) { - return d2.id; - }).enter(); - optionEnter.append("button").attr("class", function(d2) { - return "raw-tag-option raw-tag-option-" + d2.id + (_tagView === d2.id ? " selected" : ""); - }).attr("aria-selected", function(d2) { - return _tagView === d2.id; - }).attr("role", "tab").attr("title", function(d2) { - return _t("icons." + d2.id); - }).on("click", function(d3_event, d2) { - _tagView = d2.id; - corePreferences("raw-tag-editor-view", d2.id); - wrap2.selectAll(".raw-tag-option").classed("selected", function(datum2) { - return datum2 === d2; - }).attr("aria-selected", function(datum2) { - return datum2 === d2; + // modules/ui/improveOSM_comments.js + function uiImproveOsmComments() { + let _qaItem; + function issueComments(selection2) { + let comments = selection2.selectAll(".comments-container").data([0]); + comments = comments.enter().append("div").attr("class", "comments-container").merge(comments); + services.improveOSM.getComments(_qaItem).then((d2) => { + if (!d2.comments) + return; + const commentEnter = comments.selectAll(".comment").data(d2.comments).enter().append("div").attr("class", "comment"); + commentEnter.append("div").attr("class", "comment-avatar").call(svgIcon("#iD-icon-avatar", "comment-avatar-icon")); + const mainEnter = commentEnter.append("div").attr("class", "comment-main"); + const metadataEnter = mainEnter.append("div").attr("class", "comment-metadata"); + metadataEnter.append("div").attr("class", "comment-author").each(function(d4) { + const osm = services.osm; + let selection3 = select_default2(this); + if (osm && d4.username) { + selection3 = selection3.append("a").attr("class", "comment-author-link").attr("href", osm.userURL(d4.username)).attr("target", "_blank"); + } + selection3.text((d5) => d5.username); }); - wrap2.selectAll(".tag-text").classed("hide", d2.id !== "text").each(setTextareaHeight); - wrap2.selectAll(".tag-list, .add-row").classed("hide", d2.id !== "list"); - }).each(function(d2) { - select_default2(this).call(svgIcon(d2.icon)); - }); - var textData = rowsToText(rowData); - var textarea = wrap2.selectAll(".tag-text").data([0]); - textarea = textarea.enter().append("textarea").attr("class", "tag-text" + (_tagView !== "text" ? " hide" : "")).call(utilNoAuto).attr("placeholder", _t("inspector.key_value")).attr("spellcheck", "false").merge(textarea); - textarea.call(utilGetSetValue, textData).each(setTextareaHeight).on("input", setTextareaHeight).on("focus", interacted).on("blur", textChanged).on("change", textChanged); - var list = wrap2.selectAll(".tag-list").data([0]); - list = list.enter().append("ul").attr("class", "tag-list" + (_tagView !== "list" ? " hide" : "")).merge(list); - var addRowEnter = wrap2.selectAll(".add-row").data([0]).enter().append("div").attr("class", "add-row" + (_tagView !== "list" ? " hide" : "")); - addRowEnter.append("button").attr("class", "add-tag").attr("aria-label", _t("inspector.add_to_tag")).call(svgIcon("#iD-icon-plus", "light")).call(uiTooltip().title(() => _t.append("inspector.add_to_tag")).placement(_mainLocalizer.textDirection() === "ltr" ? "right" : "left")).on("click", addTag); - addRowEnter.append("div").attr("class", "space-value"); - addRowEnter.append("div").attr("class", "space-buttons"); - var items = list.selectAll(".tag-row").data(rowData, function(d2) { - return d2.key; - }); - items.exit().each(unbind).remove(); - var itemsEnter = items.enter().append("li").attr("class", "tag-row").classed("readonly", isReadOnly); - var innerWrap = itemsEnter.append("div").attr("class", "inner-wrap"); - innerWrap.append("div").attr("class", "key-wrap").append("input").property("type", "text").attr("class", "key").call(utilNoAuto).on("focus", interacted).on("blur", keyChange).on("change", keyChange); - innerWrap.append("div").attr("class", "value-wrap").append("input").property("type", "text").attr("class", "value").call(utilNoAuto).on("focus", interacted).on("blur", valueChange).on("change", valueChange).on("keydown.push-more", pushMore); - innerWrap.append("button").attr("class", "form-field-button remove").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")); - items = items.merge(itemsEnter).sort(function(a2, b2) { - return a2.index - b2.index; - }); - items.each(function(d2) { - var row = select_default2(this); - var key = row.select("input.key"); - var value = row.select("input.value"); - if (_entityIDs && taginfo && _state !== "hover") { - bindTypeahead(key, value); - } - var referenceOptions = { key: d2.key }; - if (typeof d2.value === "string") { - referenceOptions.value = d2.value; - } - var reference = uiTagReference(referenceOptions, context); - if (_state === "hover") { - reference.showing(false); - } - row.select(".inner-wrap").call(reference.button); - row.call(reference.body); - row.select("button.remove"); - }); - items.selectAll("input.key").attr("title", function(d2) { - return d2.key; - }).call(utilGetSetValue, function(d2) { - return d2.key; - }).attr("readonly", function(d2) { - return isReadOnly(d2) || null; - }); - items.selectAll("input.value").attr("title", function(d2) { - return Array.isArray(d2.value) ? d2.value.filter(Boolean).join("\n") : d2.value; - }).classed("mixed", function(d2) { - return Array.isArray(d2.value); - }).attr("placeholder", function(d2) { - return typeof d2.value === "string" ? null : _t("inspector.multiple_values"); - }).call(utilGetSetValue, function(d2) { - return typeof d2.value === "string" ? d2.value : ""; - }).attr("readonly", function(d2) { - return isReadOnly(d2) || null; + metadataEnter.append("div").attr("class", "comment-date").html((d4) => _t.html("note.status.commented", { when: localeDateString2(d4.timestamp) })); + mainEnter.append("div").attr("class", "comment-text").append("p").text((d4) => d4.text); + }).catch((err) => { + console.log(err); }); - items.selectAll("button.remove").on( - ("PointerEvent" in window ? "pointer" : "mouse") + "down", - // 'click' fires too late - #5878 - (d3_event, d2) => { - if (d3_event.button !== 0) - return; - removeTag(d3_event, d2); - } - ); } - function isReadOnly(d2) { - for (var i3 = 0; i3 < _readOnlyTags.length; i3++) { - if (d2.key.match(_readOnlyTags[i3]) !== null) { - return true; + function localeDateString2(s2) { + if (!s2) + return null; + const options2 = { day: "numeric", month: "short", year: "numeric" }; + const d2 = new Date(s2 * 1e3); + if (isNaN(d2.getTime())) + return null; + return d2.toLocaleDateString(_mainLocalizer.localeCode(), options2); + } + issueComments.issue = function(val) { + if (!arguments.length) + return _qaItem; + _qaItem = val; + return issueComments; + }; + return issueComments; + } + + // modules/ui/improveOSM_details.js + function uiImproveOsmDetails(context) { + let _qaItem; + function issueDetail(d2) { + if (d2.desc) + return d2.desc; + const issueKey = d2.issueKey; + d2.replacements = d2.replacements || {}; + d2.replacements.default = { html: _t.html("inspector.unknown") }; + return _t.html("QA.improveOSM.error_types.".concat(issueKey, ".description"), d2.replacements); + } + function improveOsmDetails(selection2) { + const details = selection2.selectAll(".error-details").data( + _qaItem ? [_qaItem] : [], + (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + ); + details.exit().remove(); + const detailsEnter = details.enter().append("div").attr("class", "error-details qa-details-container"); + const descriptionEnter = detailsEnter.append("div").attr("class", "qa-details-subsection"); + descriptionEnter.append("h4").call(_t.append("QA.keepRight.detail_description")); + descriptionEnter.append("div").attr("class", "qa-details-description-text").html(issueDetail); + let relatedEntities = []; + descriptionEnter.selectAll(".error_entity_link, .error_object_link").attr("href", "#").each(function() { + const link3 = select_default2(this); + const isObjectLink = link3.classed("error_object_link"); + const entityID = isObjectLink ? utilEntityRoot(_qaItem.objectType) + _qaItem.objectId : this.textContent; + const entity = context.hasEntity(entityID); + relatedEntities.push(entityID); + link3.on("mouseenter", () => { + utilHighlightEntities([entityID], true, context); + }).on("mouseleave", () => { + utilHighlightEntities([entityID], false, context); + }).on("click", (d3_event) => { + d3_event.preventDefault(); + utilHighlightEntities([entityID], false, context); + const osmlayer = context.layers().layer("osm"); + if (!osmlayer.enabled()) { + osmlayer.enabled(true); + } + context.map().centerZoom(_qaItem.loc, 20); + if (entity) { + context.enter(modeSelect(context, [entityID])); + } else { + context.loadEntity(entityID, (err, result) => { + if (err) + return; + const entity2 = result.data.find((e3) => e3.id === entityID); + if (entity2) + context.enter(modeSelect(context, [entityID])); + }); + } + }); + if (entity) { + let name = utilDisplayName(entity); + if (!name && !isObjectLink) { + const preset = _mainPresetIndex.match(entity, context.graph()); + name = preset && !preset.isFallback() && preset.name(); + } + if (name) { + this.innerText = name; + } } - } - return false; + }); + context.features().forceVisible(relatedEntities); + context.map().pan([0, 0]); } - function setTextareaHeight() { - if (_tagView !== "text") - return; - var selection2 = select_default2(this); - var matches = selection2.node().value.match(/\n/g); - var lineCount = 2 + Number(matches && matches.length); - var lineHeight = 20; - selection2.style("height", lineCount * lineHeight + "px"); + improveOsmDetails.issue = function(val) { + if (!arguments.length) + return _qaItem; + _qaItem = val; + return improveOsmDetails; + }; + return improveOsmDetails; + } + + // modules/ui/improveOSM_header.js + function uiImproveOsmHeader() { + let _qaItem; + function issueTitle(d2) { + const issueKey = d2.issueKey; + d2.replacements = d2.replacements || {}; + d2.replacements.default = { html: _t.html("inspector.unknown") }; + return _t.html("QA.improveOSM.error_types.".concat(issueKey, ".title"), d2.replacements); } - function stringify3(s2) { - return JSON.stringify(s2).slice(1, -1); + function improveOsmHeader(selection2) { + const header = selection2.selectAll(".qa-header").data( + _qaItem ? [_qaItem] : [], + (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + ); + header.exit().remove(); + const headerEnter = header.enter().append("div").attr("class", "qa-header"); + const svgEnter = headerEnter.append("div").attr("class", "qa-header-icon").classed("new", (d2) => d2.id < 0).append("svg").attr("width", "20px").attr("height", "30px").attr("viewbox", "0 0 20 30").attr("class", (d2) => "preset-icon-28 qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.itemType)); + svgEnter.append("polygon").attr("fill", "currentColor").attr("class", "qaItem-fill").attr("points", "16,3 4,3 1,6 1,17 4,20 7,20 10,27 13,20 16,20 19,17.033 19,6"); + svgEnter.append("use").attr("class", "icon-annotation").attr("width", "12px").attr("height", "12px").attr("transform", "translate(4, 5.5)").attr("xlink:href", (d2) => d2.icon ? "#" + d2.icon : ""); + headerEnter.append("div").attr("class", "qa-header-label").html(issueTitle); } - function unstringify(s2) { - var leading = ""; - var trailing = ""; - if (s2.length < 1 || s2.charAt(0) !== '"') { - leading = '"'; - } - if (s2.length < 2 || s2.charAt(s2.length - 1) !== '"' || s2.charAt(s2.length - 1) === '"' && s2.charAt(s2.length - 2) === "\\") { - trailing = '"'; - } - return JSON.parse(leading + s2 + trailing); + improveOsmHeader.issue = function(val) { + if (!arguments.length) + return _qaItem; + _qaItem = val; + return improveOsmHeader; + }; + return improveOsmHeader; + } + + // modules/ui/improveOSM_editor.js + function uiImproveOsmEditor(context) { + const dispatch14 = dispatch_default("change"); + const qaDetails = uiImproveOsmDetails(context); + const qaComments = uiImproveOsmComments(context); + const qaHeader = uiImproveOsmHeader(context); + let _qaItem; + function improveOsmEditor(selection2) { + const headerEnter = selection2.selectAll(".header").data([0]).enter().append("div").attr("class", "header fillL"); + headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", () => context.enter(modeBrowse(context))).call(svgIcon("#iD-icon-close")); + headerEnter.append("h2").call(_t.append("QA.improveOSM.title")); + let body = selection2.selectAll(".body").data([0]); + body = body.enter().append("div").attr("class", "body").merge(body); + const editor = body.selectAll(".qa-editor").data([0]); + editor.enter().append("div").attr("class", "modal-section qa-editor").merge(editor).call(qaHeader.issue(_qaItem)).call(qaDetails.issue(_qaItem)).call(qaComments.issue(_qaItem)).call(improveOsmSaveSection); } - function rowsToText(rows) { - var str2 = rows.filter(function(row) { - return row.key && row.key.trim() !== ""; - }).map(function(row) { - var rawVal = row.value; - if (typeof rawVal !== "string") - rawVal = "*"; - var val = rawVal ? stringify3(rawVal) : ""; - return stringify3(row.key) + "=" + val; - }).join("\n"); - if (_state !== "hover" && str2.length) { - return str2 + "\n"; + function improveOsmSaveSection(selection2) { + const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); + const isShown = _qaItem && (isSelected || _qaItem.newComment || _qaItem.comment); + let saveSection = selection2.selectAll(".qa-save").data( + isShown ? [_qaItem] : [], + (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + ); + saveSection.exit().remove(); + const saveSectionEnter = saveSection.enter().append("div").attr("class", "qa-save save-section cf"); + saveSectionEnter.append("h4").attr("class", ".qa-save-header").call(_t.append("note.newComment")); + saveSectionEnter.append("textarea").attr("class", "new-comment-input").attr("placeholder", _t("QA.keepRight.comment_placeholder")).attr("maxlength", 1e3).property("value", (d2) => d2.newComment).call(utilNoAuto).on("input", changeInput).on("blur", changeInput); + saveSection = saveSectionEnter.merge(saveSection).call(qaSaveButtons); + function changeInput() { + const input = select_default2(this); + let val = input.property("value").trim(); + if (val === "") { + val = void 0; + } + _qaItem = _qaItem.update({ newComment: val }); + const qaService = services.improveOSM; + if (qaService) { + qaService.replaceItem(_qaItem); + } + saveSection.call(qaSaveButtons); } - return str2; } - function textChanged() { - var newText = this.value.trim(); - var newTags = {}; - newText.split("\n").forEach(function(row) { - var m2 = row.match(/^\s*([^=]+)=(.*)$/); - if (m2 !== null) { - var k2 = context.cleanTagKey(unstringify(m2[1].trim())); - var v2 = context.cleanTagValue(unstringify(m2[2].trim())); - newTags[k2] = v2; + function qaSaveButtons(selection2) { + const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); + let buttonSection = selection2.selectAll(".buttons").data(isSelected ? [_qaItem] : [], (d2) => d2.status + d2.id); + buttonSection.exit().remove(); + const buttonEnter = buttonSection.enter().append("div").attr("class", "buttons"); + buttonEnter.append("button").attr("class", "button comment-button action").call(_t.append("QA.keepRight.save_comment")); + buttonEnter.append("button").attr("class", "button close-button action"); + buttonEnter.append("button").attr("class", "button ignore-button action"); + buttonSection = buttonSection.merge(buttonEnter); + buttonSection.select(".comment-button").attr("disabled", (d2) => d2.newComment ? null : true).on("click.comment", function(d3_event, d2) { + this.blur(); + const qaService = services.improveOSM; + if (qaService) { + qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); } }); - var tagDiff = utilTagDiff(_tags, newTags); - if (!tagDiff.length) - return; - _pendingChange = _pendingChange || {}; - tagDiff.forEach(function(change) { - if (isReadOnly({ key: change.key })) - return; - if (change.newVal === "*" && typeof change.oldVal !== "string") - return; - if (change.type === "-") { - _pendingChange[change.key] = void 0; - } else if (change.type === "+") { - _pendingChange[change.key] = change.newVal || ""; + buttonSection.select(".close-button").html((d2) => { + const andComment = d2.newComment ? "_comment" : ""; + return _t.html("QA.keepRight.close".concat(andComment)); + }).on("click.close", function(d3_event, d2) { + this.blur(); + const qaService = services.improveOSM; + if (qaService) { + d2.newStatus = "SOLVED"; + qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); + } + }); + buttonSection.select(".ignore-button").html((d2) => { + const andComment = d2.newComment ? "_comment" : ""; + return _t.html("QA.keepRight.ignore".concat(andComment)); + }).on("click.ignore", function(d3_event, d2) { + this.blur(); + const qaService = services.improveOSM; + if (qaService) { + d2.newStatus = "INVALID"; + qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); } }); - if (Object.keys(_pendingChange).length === 0) { - _pendingChange = null; - return; - } - scheduleChange(); } - function pushMore(d3_event) { - if (d3_event.keyCode === 9 && !d3_event.shiftKey && section.selection().selectAll(".tag-list li:last-child input.value").node() === this && utilGetSetValue(select_default2(this))) { - addTag(); + improveOsmEditor.error = function(val) { + if (!arguments.length) + return _qaItem; + _qaItem = val; + return improveOsmEditor; + }; + return utilRebind(improveOsmEditor, dispatch14, "on"); + } + + // modules/ui/keepRight_details.js + function uiKeepRightDetails(context) { + let _qaItem; + function issueDetail(d2) { + const { itemType, parentIssueType } = d2; + const unknown = { html: _t.html("inspector.unknown") }; + let replacements = d2.replacements || {}; + replacements.default = unknown; + if (_mainLocalizer.hasTextForStringId("QA.keepRight.errorTypes.".concat(itemType, ".title"))) { + return _t.html("QA.keepRight.errorTypes.".concat(itemType, ".description"), replacements); + } else { + return _t.html("QA.keepRight.errorTypes.".concat(parentIssueType, ".description"), replacements); } } - function bindTypeahead(key, value) { - if (isReadOnly(key.datum())) - return; - if (Array.isArray(value.datum().value)) { - value.call(uiCombobox(context, "tag-value").minItems(1).fetcher(function(value2, callback) { - var keyString = utilGetSetValue(key); - if (!_tags[keyString]) - return; - var data = _tags[keyString].filter(Boolean).map(function(tagValue) { - return { - value: tagValue, - title: tagValue - }; - }); - callback(data); - })); - return; - } - var geometry = context.graph().geometry(_entityIDs[0]); - key.call(uiCombobox(context, "tag-key").fetcher(function(value2, callback) { - taginfo.keys({ - debounce: true, - geometry, - query: value2 - }, function(err, data) { - if (!err) { - const filtered = data.filter((d2) => _tags[d2.value] === void 0).filter((d2) => !(d2.value in _discardTags)).filter((d2) => d2.value.toLowerCase().includes(value2.toLowerCase())); - callback(sort(value2, filtered)); + function keepRightDetails(selection2) { + const details = selection2.selectAll(".error-details").data( + _qaItem ? [_qaItem] : [], + (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + ); + details.exit().remove(); + const detailsEnter = details.enter().append("div").attr("class", "error-details qa-details-container"); + const descriptionEnter = detailsEnter.append("div").attr("class", "qa-details-subsection"); + descriptionEnter.append("h4").call(_t.append("QA.keepRight.detail_description")); + descriptionEnter.append("div").attr("class", "qa-details-description-text").html(issueDetail); + let relatedEntities = []; + descriptionEnter.selectAll(".error_entity_link, .error_object_link").attr("href", "#").each(function() { + const link3 = select_default2(this); + const isObjectLink = link3.classed("error_object_link"); + const entityID = isObjectLink ? utilEntityRoot(_qaItem.objectType) + _qaItem.objectId : this.textContent; + const entity = context.hasEntity(entityID); + relatedEntities.push(entityID); + link3.on("mouseenter", () => { + utilHighlightEntities([entityID], true, context); + }).on("mouseleave", () => { + utilHighlightEntities([entityID], false, context); + }).on("click", (d3_event) => { + d3_event.preventDefault(); + utilHighlightEntities([entityID], false, context); + const osmlayer = context.layers().layer("osm"); + if (!osmlayer.enabled()) { + osmlayer.enabled(true); } - }); - })); - value.call(uiCombobox(context, "tag-value").fetcher(function(value2, callback) { - taginfo.values({ - debounce: true, - key: utilGetSetValue(key), - geometry, - query: value2 - }, function(err, data) { - if (!err) { - const filtered = data.filter((d2) => d2.value.toLowerCase().includes(value2.toLowerCase())); - callback(sort(value2, filtered)); + context.map().centerZoomEase(_qaItem.loc, 20); + if (entity) { + context.enter(modeSelect(context, [entityID])); + } else { + context.loadEntity(entityID, (err, result) => { + if (err) + return; + const entity2 = result.data.find((e3) => e3.id === entityID); + if (entity2) + context.enter(modeSelect(context, [entityID])); + }); } }); - }).caseSensitive(allowUpperCaseTagValues.test(utilGetSetValue(key)))); - function sort(value2, data) { - var sameletter = []; - var other = []; - for (var i3 = 0; i3 < data.length; i3++) { - if (data[i3].value.substring(0, value2.length) === value2) { - sameletter.push(data[i3]); - } else { - other.push(data[i3]); + if (entity) { + let name = utilDisplayName(entity); + if (!name && !isObjectLink) { + const preset = _mainPresetIndex.match(entity, context.graph()); + name = preset && !preset.isFallback() && preset.name(); } - } - return sameletter.concat(other); - } - } - function unbind() { - var row = select_default2(this); - row.selectAll("input.key").call(uiCombobox.off, context); - row.selectAll("input.value").call(uiCombobox.off, context); - } - function keyChange(d3_event, d2) { - if (select_default2(this).attr("readonly")) - return; - var kOld = d2.key; - if (_pendingChange && _pendingChange.hasOwnProperty(kOld) && _pendingChange[kOld] === void 0) - return; - var kNew = context.cleanTagKey(this.value.trim()); - if (isReadOnly({ key: kNew })) { - this.value = kOld; - return; - } - if (kNew && kNew !== kOld && _tags[kNew] !== void 0) { - this.value = kOld; - section.selection().selectAll(".tag-list input.value").each(function(d4) { - if (d4.key === kNew) { - var input = select_default2(this).node(); - input.focus(); - input.select(); + if (name) { + this.innerText = name; } - }); - return; - } - _pendingChange = _pendingChange || {}; - if (kOld) { - if (kOld === kNew) - return; - _pendingChange[kNew] = _pendingChange[kOld] || { oldKey: kOld }; - _pendingChange[kOld] = void 0; - } else { - let row = this.parentNode.parentNode; - let inputVal = select_default2(row).selectAll("input.value"); - let vNew = context.cleanTagValue(utilGetSetValue(inputVal)); - _pendingChange[kNew] = vNew; - utilGetSetValue(inputVal, vNew); - } - var existingKeyIndex = _orderedKeys.indexOf(kOld); - if (existingKeyIndex !== -1) - _orderedKeys[existingKeyIndex] = kNew; - d2.key = kNew; - this.value = kNew; - scheduleChange(); - } - function valueChange(d3_event, d2) { - if (isReadOnly(d2)) - return; - if (typeof d2.value !== "string" && !this.value) - return; - if (_pendingChange && _pendingChange.hasOwnProperty(d2.key) && _pendingChange[d2.key] === void 0) - return; - _pendingChange = _pendingChange || {}; - _pendingChange[d2.key] = context.cleanTagValue(this.value); - scheduleChange(); + } + }); + context.features().forceVisible(relatedEntities); + context.map().pan([0, 0]); } - function removeTag(d3_event, d2) { - if (isReadOnly(d2)) - return; - if (d2.key === "") { - _showBlank = false; - section.reRender(); + keepRightDetails.issue = function(val) { + if (!arguments.length) + return _qaItem; + _qaItem = val; + return keepRightDetails; + }; + return keepRightDetails; + } + + // modules/ui/keepRight_header.js + function uiKeepRightHeader() { + let _qaItem; + function issueTitle(d2) { + const { itemType, parentIssueType } = d2; + const unknown = _t.html("inspector.unknown"); + let replacements = d2.replacements || {}; + replacements.default = { html: unknown }; + if (_mainLocalizer.hasTextForStringId("QA.keepRight.errorTypes.".concat(itemType, ".title"))) { + return _t.html("QA.keepRight.errorTypes.".concat(itemType, ".title"), replacements); } else { - _orderedKeys = _orderedKeys.filter(function(key) { - return key !== d2.key; - }); - _pendingChange = _pendingChange || {}; - _pendingChange[d2.key] = void 0; - scheduleChange(); + return _t.html("QA.keepRight.errorTypes.".concat(parentIssueType, ".title"), replacements); } } - function addTag() { - window.setTimeout(function() { - _showBlank = true; - section.reRender(); - section.selection().selectAll(".tag-list li:last-child input.key").node().focus(); - }, 20); - } - function scheduleChange() { - var entityIDs = _entityIDs; - window.setTimeout(function() { - if (!_pendingChange) - return; - dispatch14.call("change", this, entityIDs, _pendingChange); - _pendingChange = null; - }, 10); + function keepRightHeader(selection2) { + const header = selection2.selectAll(".qa-header").data( + _qaItem ? [_qaItem] : [], + (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + ); + header.exit().remove(); + const headerEnter = header.enter().append("div").attr("class", "qa-header"); + const iconEnter = headerEnter.append("div").attr("class", "qa-header-icon").classed("new", (d2) => d2.id < 0); + iconEnter.append("div").attr("class", (d2) => "preset-icon-28 qaItem ".concat(d2.service, " itemId-").concat(d2.id, " itemType-").concat(d2.parentIssueType)).call(svgIcon("#iD-icon-bolt", "qaItem-fill")); + headerEnter.append("div").attr("class", "qa-header-label").html(issueTitle); } - section.state = function(val) { - if (!arguments.length) - return _state; - if (_state !== val) { - _orderedKeys = []; - _state = val; - } - return section; - }; - section.presets = function(val) { - if (!arguments.length) - return _presets; - _presets = val; - if (_presets && _presets.length && _presets[0].isFallback()) { - section.disclosureExpanded(true); - } else if (!_didInteract) { - section.disclosureExpanded(null); - } - return section; - }; - section.tags = function(val) { + keepRightHeader.issue = function(val) { if (!arguments.length) - return _tags; - _tags = val; - return section; + return _qaItem; + _qaItem = val; + return keepRightHeader; }; - section.entityIDs = function(val) { - if (!arguments.length) - return _entityIDs; - if (!_entityIDs || !val || !utilArrayIdentical(_entityIDs, val)) { - _entityIDs = val; - _orderedKeys = []; + return keepRightHeader; + } + + // modules/ui/view_on_keepRight.js + function uiViewOnKeepRight() { + let _qaItem; + function viewOnKeepRight(selection2) { + let url; + if (services.keepRight && _qaItem instanceof QAItem) { + url = services.keepRight.issueURL(_qaItem); } - return section; - }; - section.readOnlyTags = function(val) { + const link3 = selection2.selectAll(".view-on-keepRight").data(url ? [url] : []); + link3.exit().remove(); + const linkEnter = link3.enter().append("a").attr("class", "view-on-keepRight").attr("target", "_blank").attr("rel", "noopener").attr("href", (d2) => d2).call(svgIcon("#iD-icon-out-link", "inline")); + linkEnter.append("span").call(_t.append("inspector.view_on_keepRight")); + } + viewOnKeepRight.what = function(val) { if (!arguments.length) - return _readOnlyTags; - _readOnlyTags = val; - return section; + return _qaItem; + _qaItem = val; + return viewOnKeepRight; }; - return utilRebind(section, dispatch14, "on"); + return viewOnKeepRight; } - // modules/ui/data_editor.js - function uiDataEditor(context) { - var dataHeader = uiDataHeader(); - var rawTagEditor = uiSectionRawTagEditor("custom-data-tag-editor", context).expandedByDefault(true).readOnlyTags([/./]); - var _datum; - function dataEditor(selection2) { - var header = selection2.selectAll(".header").data([0]); - var headerEnter = header.enter().append("div").attr("class", "header fillL"); - headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function() { - context.enter(modeBrowse(context)); - }).call(svgIcon("#iD-icon-close")); - headerEnter.append("h2").call(_t.append("map_data.title")); - var body = selection2.selectAll(".body").data([0]); + // modules/ui/keepRight_editor.js + function uiKeepRightEditor(context) { + const dispatch14 = dispatch_default("change"); + const qaDetails = uiKeepRightDetails(context); + const qaHeader = uiKeepRightHeader(context); + let _qaItem; + function keepRightEditor(selection2) { + const headerEnter = selection2.selectAll(".header").data([0]).enter().append("div").attr("class", "header fillL"); + headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", () => context.enter(modeBrowse(context))).call(svgIcon("#iD-icon-close")); + headerEnter.append("h2").call(_t.append("QA.keepRight.title")); + let body = selection2.selectAll(".body").data([0]); body = body.enter().append("div").attr("class", "body").merge(body); - var editor = body.selectAll(".data-editor").data([0]); - editor.enter().append("div").attr("class", "modal-section data-editor").merge(editor).call(dataHeader.datum(_datum)); - var rte = body.selectAll(".raw-tag-editor").data([0]); - rte.enter().append("div").attr("class", "raw-tag-editor data-editor").merge(rte).call( - rawTagEditor.tags(_datum && _datum.properties || {}).state("hover").render - ).selectAll("textarea.tag-text").attr("readonly", true).classed("readonly", true); + const editor = body.selectAll(".qa-editor").data([0]); + editor.enter().append("div").attr("class", "modal-section qa-editor").merge(editor).call(qaHeader.issue(_qaItem)).call(qaDetails.issue(_qaItem)).call(keepRightSaveSection); + const footer = selection2.selectAll(".footer").data([0]); + footer.enter().append("div").attr("class", "footer").merge(footer).call(uiViewOnKeepRight(context).what(_qaItem)); + } + function keepRightSaveSection(selection2) { + const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); + const isShown = _qaItem && (isSelected || _qaItem.newComment || _qaItem.comment); + let saveSection = selection2.selectAll(".qa-save").data( + isShown ? [_qaItem] : [], + (d2) => "".concat(d2.id, "-").concat(d2.status || 0) + ); + saveSection.exit().remove(); + const saveSectionEnter = saveSection.enter().append("div").attr("class", "qa-save save-section cf"); + saveSectionEnter.append("h4").attr("class", ".qa-save-header").call(_t.append("QA.keepRight.comment")); + saveSectionEnter.append("textarea").attr("class", "new-comment-input").attr("placeholder", _t("QA.keepRight.comment_placeholder")).attr("maxlength", 1e3).property("value", (d2) => d2.newComment || d2.comment).call(utilNoAuto).on("input", changeInput).on("blur", changeInput); + saveSection = saveSectionEnter.merge(saveSection).call(qaSaveButtons); + function changeInput() { + const input = select_default2(this); + let val = input.property("value").trim(); + if (val === _qaItem.comment) { + val = void 0; + } + _qaItem = _qaItem.update({ newComment: val }); + const qaService = services.keepRight; + if (qaService) { + qaService.replaceItem(_qaItem); + } + saveSection.call(qaSaveButtons); + } } - dataEditor.datum = function(val) { + function qaSaveButtons(selection2) { + const isSelected = _qaItem && _qaItem.id === context.selectedErrorID(); + let buttonSection = selection2.selectAll(".buttons").data(isSelected ? [_qaItem] : [], (d2) => d2.status + d2.id); + buttonSection.exit().remove(); + const buttonEnter = buttonSection.enter().append("div").attr("class", "buttons"); + buttonEnter.append("button").attr("class", "button comment-button action").call(_t.append("QA.keepRight.save_comment")); + buttonEnter.append("button").attr("class", "button close-button action"); + buttonEnter.append("button").attr("class", "button ignore-button action"); + buttonSection = buttonSection.merge(buttonEnter); + buttonSection.select(".comment-button").attr("disabled", (d2) => d2.newComment ? null : true).on("click.comment", function(d3_event, d2) { + this.blur(); + const qaService = services.keepRight; + if (qaService) { + qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); + } + }); + buttonSection.select(".close-button").html((d2) => { + const andComment = d2.newComment ? "_comment" : ""; + return _t.html("QA.keepRight.close".concat(andComment)); + }).on("click.close", function(d3_event, d2) { + this.blur(); + const qaService = services.keepRight; + if (qaService) { + d2.newStatus = "ignore_t"; + qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); + } + }); + buttonSection.select(".ignore-button").html((d2) => { + const andComment = d2.newComment ? "_comment" : ""; + return _t.html("QA.keepRight.ignore".concat(andComment)); + }).on("click.ignore", function(d3_event, d2) { + this.blur(); + const qaService = services.keepRight; + if (qaService) { + d2.newStatus = "ignore"; + qaService.postUpdate(d2, (err, item) => dispatch14.call("change", item)); + } + }); + } + keepRightEditor.error = function(val) { if (!arguments.length) - return _datum; - _datum = val; - return this; + return _qaItem; + _qaItem = val; + return keepRightEditor; }; - return dataEditor; + return utilRebind(keepRightEditor, dispatch14, "on"); } // modules/ui/osmose_details.js @@ -70794,10 +72338,10 @@ } elemsDiv.append("h4").call(_t.append("QA.osmose.elems_title")); elemsDiv.append("ul").selectAll("li").data(d2.elems).enter().append("li").append("a").attr("href", "#").attr("class", "error_entity_link").text((d4) => d4).each(function() { - const link2 = select_default2(this); + const link3 = select_default2(this); const entityID = this.textContent; const entity = context.hasEntity(entityID); - link2.on("mouseenter", () => { + link3.on("mouseenter", () => { utilHighlightEntities([entityID], true, context); }).on("mouseleave", () => { utilHighlightEntities([entityID], false, context); @@ -70886,9 +72430,9 @@ if (services.osmose && _qaItem instanceof QAItem) { url = services.osmose.itemURL(_qaItem); } - const link2 = selection2.selectAll(".view-on-osmose").data(url ? [url] : []); - link2.exit().remove(); - const linkEnter = link2.enter().append("a").attr("class", "view-on-osmose").attr("target", "_blank").attr("rel", "noopener").attr("href", (d2) => d2).call(svgIcon("#iD-icon-out-link", "inline")); + const link3 = selection2.selectAll(".view-on-osmose").data(url ? [url] : []); + link3.exit().remove(); + const linkEnter = link3.enter().append("a").attr("class", "view-on-osmose").attr("target", "_blank").attr("rel", "noopener").attr("href", (d2) => d2).call(svgIcon("#iD-icon-out-link", "inline")); linkEnter.append("span").call(_t.append("inspector.view_on_osmose")); } viewOnOsmose.what = function(val) { @@ -70963,825 +72507,1828 @@ return utilRebind(osmoseEditor, dispatch14, "on"); } - // modules/ui/sidebar.js - function uiSidebar(context) { - var inspector = uiInspector(context); - var dataEditor = uiDataEditor(context); - var noteEditor = uiNoteEditor(context); - var improveOsmEditor = uiImproveOsmEditor(context); - var keepRightEditor = uiKeepRightEditor(context); - var osmoseEditor = uiOsmoseEditor(context); - var _current; - var _wasData = false; - var _wasNote = false; - var _wasQaItem = false; - var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; - function sidebar(selection2) { - var container = context.container(); - var minWidth = 240; - var sidebarWidth; - var containerWidth; - var dragOffset; - selection2.style("min-width", minWidth + "px").style("max-width", "400px").style("width", "33.3333%"); - var resizer = selection2.append("div").attr("class", "sidebar-resizer").on(_pointerPrefix + "down.sidebar-resizer", pointerdown); - var downPointerId, lastClientX, containerLocGetter; - function pointerdown(d3_event) { - if (downPointerId) + // modules/modes/select_error.js + function modeSelectError(context, selectedErrorID, selectedErrorService) { + var mode = { + id: "select-error", + button: "browse" + }; + var keybinding = utilKeybinding("select-error"); + var errorService = services[selectedErrorService]; + var errorEditor; + switch (selectedErrorService) { + case "improveOSM": + errorEditor = uiImproveOsmEditor(context).on("change", function() { + context.map().pan([0, 0]); + var error = checkSelectedID(); + if (!error) + return; + context.ui().sidebar.show(errorEditor.error(error)); + }); + break; + case "keepRight": + errorEditor = uiKeepRightEditor(context).on("change", function() { + context.map().pan([0, 0]); + var error = checkSelectedID(); + if (!error) + return; + context.ui().sidebar.show(errorEditor.error(error)); + }); + break; + case "osmose": + errorEditor = uiOsmoseEditor(context).on("change", function() { + context.map().pan([0, 0]); + var error = checkSelectedID(); + if (!error) + return; + context.ui().sidebar.show(errorEditor.error(error)); + }); + break; + } + var behaviors = [ + behaviorBreathe(context), + behaviorHover(context), + behaviorSelect(context), + behaviorLasso(context), + modeDragNode(context).behavior, + modeDragNote(context).behavior + ]; + function checkSelectedID() { + if (!errorService) + return; + var error = errorService.getError(selectedErrorID); + if (!error) { + context.enter(modeBrowse(context)); + } + return error; + } + mode.zoomToSelected = function() { + if (!errorService) + return; + var error = errorService.getError(selectedErrorID); + if (error) { + context.map().centerZoomEase(error.loc, 20); + } + }; + mode.enter = function() { + var error = checkSelectedID(); + if (!error) + return; + behaviors.forEach(context.install); + keybinding.on(_t("inspector.zoom_to.key"), mode.zoomToSelected).on("\u238B", esc, true); + select_default2(document).call(keybinding); + selectError(); + var sidebar = context.ui().sidebar; + sidebar.show(errorEditor.error(error)); + context.map().on("drawn.select-error", selectError); + function selectError(d3_event, drawn) { + if (!checkSelectedID()) return; - if ("button" in d3_event && d3_event.button !== 0) + var selection2 = context.surface().selectAll(".itemId-" + selectedErrorID + "." + selectedErrorService); + if (selection2.empty()) { + var source = d3_event && d3_event.type === "zoom" && d3_event.sourceEvent; + if (drawn && source && (source.type === "pointermove" || source.type === "mousemove" || source.type === "touchmove")) { + context.enter(modeBrowse(context)); + } + } else { + selection2.classed("selected", true); + context.selectedErrorID(selectedErrorID); + } + } + function esc() { + if (context.container().select(".combobox").size()) return; - downPointerId = d3_event.pointerId || "mouse"; - lastClientX = d3_event.clientX; - containerLocGetter = utilFastMouse(container.node()); - dragOffset = utilFastMouse(resizer.node())(d3_event)[0] - 1; - sidebarWidth = selection2.node().getBoundingClientRect().width; - containerWidth = container.node().getBoundingClientRect().width; - var widthPct = sidebarWidth / containerWidth * 100; - selection2.style("width", widthPct + "%").style("max-width", "85%"); - resizer.classed("dragging", true); - select_default2(window).on("touchmove.sidebar-resizer", function(d3_event2) { - d3_event2.preventDefault(); - }, { passive: false }).on(_pointerPrefix + "move.sidebar-resizer", pointermove).on(_pointerPrefix + "up.sidebar-resizer pointercancel.sidebar-resizer", pointerup); + context.enter(modeBrowse(context)); } - function pointermove(d3_event) { - if (downPointerId !== (d3_event.pointerId || "mouse")) + }; + mode.exit = function() { + behaviors.forEach(context.uninstall); + select_default2(document).call(keybinding.unbind); + context.surface().selectAll(".qaItem.selected").classed("selected hover", false); + context.map().on("drawn.select-error", null); + context.ui().sidebar.hide(); + context.selectedErrorID(null); + context.features().forceVisible([]); + }; + return mode; + } + + // modules/ui/feature_list.js + function uiFeatureList(context) { + var _geocodeResults; + function featureList(selection2) { + var header = selection2.append("div").attr("class", "header fillL"); + header.append("h2").call(_t.append("inspector.feature_list")); + var searchWrap = selection2.append("div").attr("class", "search-header"); + searchWrap.call(svgIcon("#iD-icon-search", "pre-text")); + var search = searchWrap.append("input").attr("placeholder", _t("inspector.search")).attr("type", "search").call(utilNoAuto).on("keypress", keypress).on("keydown", keydown).on("input", inputevent); + var listWrap = selection2.append("div").attr("class", "inspector-body"); + var list2 = listWrap.append("div").attr("class", "feature-list"); + context.on("exit.feature-list", clearSearch); + context.map().on("drawn.feature-list", mapDrawn); + context.keybinding().on(uiCmd("\u2318F"), focusSearch); + function focusSearch(d3_event) { + var mode = context.mode() && context.mode().id; + if (mode !== "browse") + return; + d3_event.preventDefault(); + search.node().focus(); + } + function keydown(d3_event) { + if (d3_event.keyCode === 27) { + search.node().blur(); + } + } + function keypress(d3_event) { + var q2 = search.property("value"), items = list2.selectAll(".feature-list-item"); + if (d3_event.keyCode === 13 && // ↩ Return + q2.length && items.size()) { + click(d3_event, items.datum()); + } + } + function inputevent() { + _geocodeResults = void 0; + drawList(); + } + function clearSearch() { + search.property("value", ""); + drawList(); + } + function mapDrawn(e3) { + if (e3.full) { + drawList(); + } + } + function features() { + var result = []; + var graph = context.graph(); + var visibleCenter = context.map().extent().center(); + var q2 = search.property("value").toLowerCase(); + if (!q2) + return result; + var locationMatch = sexagesimal.pair(q2.toUpperCase()) || dmsMatcher(q2); + if (locationMatch) { + var loc = [Number(locationMatch[0]), Number(locationMatch[1])]; + result.push({ + id: -1, + geometry: "point", + type: _t("inspector.location"), + name: dmsCoordinatePair([loc[1], loc[0]]), + location: loc + }); + } + var idMatch = !locationMatch && q2.match(/(?:^|\W)(node|way|relation|note|[nwr])\W{0,2}0*([1-9]\d*)(?:\W|$)/i); + if (idMatch) { + var elemType = idMatch[1] === "note" ? idMatch[1] : idMatch[1].charAt(0); + var elemId = idMatch[2]; + result.push({ + id: elemType + elemId, + geometry: elemType === "n" ? "point" : elemType === "w" ? "line" : elemType === "note" ? "note" : "relation", + type: elemType === "n" ? _t("inspector.node") : elemType === "w" ? _t("inspector.way") : elemType === "note" ? _t("note.note") : _t("inspector.relation"), + name: elemId + }); + } + var allEntities = graph.entities; + var localResults = []; + for (var id2 in allEntities) { + var entity = allEntities[id2]; + if (!entity) + continue; + var name = utilDisplayName(entity) || ""; + if (name.toLowerCase().indexOf(q2) < 0) + continue; + var matched = _mainPresetIndex.match(entity, graph); + var type2 = matched && matched.name() || utilDisplayType(entity.id); + var extent = entity.extent(graph); + var distance = extent ? geoSphericalDistance(visibleCenter, extent.center()) : 0; + localResults.push({ + id: entity.id, + entity, + geometry: entity.geometry(graph), + type: type2, + name, + distance + }); + if (localResults.length > 100) + break; + } + localResults = localResults.sort(function byDistance(a2, b2) { + return a2.distance - b2.distance; + }); + result = result.concat(localResults); + (_geocodeResults || []).forEach(function(d2) { + if (d2.osm_type && d2.osm_id) { + var id3 = osmEntity.id.fromOSM(d2.osm_type, d2.osm_id); + var tags = {}; + tags[d2.class] = d2.type; + var attrs = { id: id3, type: d2.osm_type, tags }; + if (d2.osm_type === "way") { + attrs.nodes = ["a", "a"]; + } + var tempEntity = osmEntity(attrs); + var tempGraph = coreGraph([tempEntity]); + var matched2 = _mainPresetIndex.match(tempEntity, tempGraph); + var type3 = matched2 && matched2.name() || utilDisplayType(id3); + result.push({ + id: tempEntity.id, + geometry: tempEntity.geometry(tempGraph), + type: type3, + name: d2.display_name, + extent: new geoExtent( + [Number(d2.boundingbox[3]), Number(d2.boundingbox[0])], + [Number(d2.boundingbox[2]), Number(d2.boundingbox[1])] + ) + }); + } + }); + if (q2.match(/^[0-9]+$/)) { + result.push({ + id: "n" + q2, + geometry: "point", + type: _t("inspector.node"), + name: q2 + }); + result.push({ + id: "w" + q2, + geometry: "line", + type: _t("inspector.way"), + name: q2 + }); + result.push({ + id: "r" + q2, + geometry: "relation", + type: _t("inspector.relation"), + name: q2 + }); + result.push({ + id: "note" + q2, + geometry: "note", + type: _t("note.note"), + name: q2 + }); + } + return result; + } + function drawList() { + var value = search.property("value"); + var results = features(); + list2.classed("filtered", value.length); + var resultsIndicator = list2.selectAll(".no-results-item").data([0]).enter().append("button").property("disabled", true).attr("class", "no-results-item").call(svgIcon("#iD-icon-alert", "pre-text")); + resultsIndicator.append("span").attr("class", "entity-name"); + list2.selectAll(".no-results-item .entity-name").html("").call(_t.append("geocoder.no_results_worldwide")); + if (services.geocoder) { + list2.selectAll(".geocode-item").data([0]).enter().append("button").attr("class", "geocode-item secondary-action").on("click", geocoderSearch).append("div").attr("class", "label").append("span").attr("class", "entity-name").call(_t.append("geocoder.search")); + } + list2.selectAll(".no-results-item").style("display", value.length && !results.length ? "block" : "none"); + list2.selectAll(".geocode-item").style("display", value && _geocodeResults === void 0 ? "block" : "none"); + list2.selectAll(".feature-list-item").data([-1]).remove(); + var items = list2.selectAll(".feature-list-item").data(results, function(d2) { + return d2.id; + }); + var enter = items.enter().insert("button", ".geocode-item").attr("class", "feature-list-item").on("mouseover", mouseover).on("mouseout", mouseout).on("click", click); + var label = enter.append("div").attr("class", "label"); + label.each(function(d2) { + select_default2(this).call(svgIcon("#iD-icon-" + d2.geometry, "pre-text")); + }); + label.append("span").attr("class", "entity-type").text(function(d2) { + return d2.type; + }); + label.append("span").attr("class", "entity-name").classed("has-colour", (d2) => d2.entity && d2.entity.type === "relation" && d2.entity.tags.colour && isColourValid(d2.entity.tags.colour)).style("border-color", (d2) => d2.entity && d2.entity.type === "relation" && d2.entity.tags.colour).text(function(d2) { + return d2.name; + }); + enter.style("opacity", 0).transition().style("opacity", 1); + items.order(); + items.exit().remove(); + } + function mouseover(d3_event, d2) { + if (d2.id === -1) + return; + utilHighlightEntities([d2.id], true, context); + } + function mouseout(d3_event, d2) { + if (d2.id === -1) return; + utilHighlightEntities([d2.id], false, context); + } + function click(d3_event, d2) { + d3_event.preventDefault(); + if (d2.location) { + context.map().centerZoomEase([d2.location[1], d2.location[0]], 19); + } else if (d2.entity) { + utilHighlightEntities([d2.id], false, context); + context.enter(modeSelect(context, [d2.entity.id])); + context.map().zoomToEase(d2.entity); + } else if (d2.geometry === "note") { + const noteId = d2.id.replace(/\D/g, ""); + context.loadNote(noteId, (err, result) => { + if (err) + return; + const entity = result.data.find((e3) => e3.id === noteId); + if (entity) { + const note = services.osm.getNote(noteId); + context.map().centerZoom(note.loc, 15); + const noteLayer = context.layers().layer("notes"); + noteLayer.enabled(true); + context.enter(modeSelectNote(context, noteId)); + } + }); + } else { + context.zoomToEntity(d2.id); + } + } + function geocoderSearch() { + services.geocoder.search(search.property("value"), function(err, resp) { + _geocodeResults = resp || []; + drawList(); + }); + } + } + return featureList; + } + + // modules/ui/preset_list.js + function uiPresetList(context) { + var dispatch14 = dispatch_default("cancel", "choose"); + var _entityIDs; + var _currLoc; + var _currentPresets; + var _autofocus = false; + function presetList(selection2) { + if (!_entityIDs) + return; + var presets = _mainPresetIndex.matchAllGeometry(entityGeometries()); + selection2.html(""); + var messagewrap = selection2.append("div").attr("class", "header fillL"); + var message = messagewrap.append("h2").call(_t.append("inspector.choose")); + var direction = _mainLocalizer.textDirection() === "rtl" ? "backward" : "forward"; + messagewrap.append("button").attr("class", "preset-choose").attr("title", _entityIDs.length === 1 ? _t("inspector.edit") : _t("inspector.edit_features")).on("click", function() { + dispatch14.call("cancel", this); + }).call(svgIcon("#iD-icon-".concat(direction))); + function initialKeydown(d3_event) { + if (search.property("value").length === 0 && (d3_event.keyCode === utilKeybinding.keyCodes["\u232B"] || d3_event.keyCode === utilKeybinding.keyCodes["\u2326"])) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + operationDelete(context, _entityIDs)(); + } else if (search.property("value").length === 0 && (d3_event.ctrlKey || d3_event.metaKey) && d3_event.keyCode === utilKeybinding.keyCodes.z) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + context.undo(); + } else if (!d3_event.ctrlKey && !d3_event.metaKey) { + select_default2(this).on("keydown", keydown); + keydown.call(this, d3_event); + } + } + function keydown(d3_event) { + if (d3_event.keyCode === utilKeybinding.keyCodes["\u2193"] && // if insertion point is at the end of the string + search.node().selectionStart === search.property("value").length) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + var buttons = list2.selectAll(".preset-list-button"); + if (!buttons.empty()) + buttons.nodes()[0].focus(); + } + } + function keypress(d3_event) { + var value = search.property("value"); + if (d3_event.keyCode === 13 && // ↩ Return + value.length) { + list2.selectAll(".preset-list-item:first-child").each(function(d2) { + d2.choose.call(this); + }); + } + } + function inputevent() { + var value = search.property("value"); + list2.classed("filtered", value.length); + var results, messageText; + if (value.length) { + results = presets.search(value, entityGeometries()[0], _currLoc); + messageText = _t.html("inspector.results", { + n: results.collection.length, + search: value + }); + } else { + var entityPresets2 = _entityIDs.map((entityID) => _mainPresetIndex.match(context.graph().entity(entityID), context.graph())); + results = _mainPresetIndex.defaults(entityGeometries()[0], 36, !context.inIntro(), _currLoc, entityPresets2); + messageText = _t.html("inspector.choose"); + } + list2.call(drawList, results); + message.html(messageText); + } + var searchWrap = selection2.append("div").attr("class", "search-header"); + searchWrap.call(svgIcon("#iD-icon-search", "pre-text")); + var search = searchWrap.append("input").attr("class", "preset-search-input").attr("placeholder", _t("inspector.search")).attr("type", "search").call(utilNoAuto).on("keydown", initialKeydown).on("keypress", keypress).on("input", debounce_default(inputevent)); + if (_autofocus) { + search.node().focus(); + setTimeout(function() { + search.node().focus(); + }, 0); + } + var listWrap = selection2.append("div").attr("class", "inspector-body"); + var entityPresets = _entityIDs.map((entityID) => _mainPresetIndex.match(context.graph().entity(entityID), context.graph())); + var list2 = listWrap.append("div").attr("class", "preset-list").call(drawList, _mainPresetIndex.defaults(entityGeometries()[0], 36, !context.inIntro(), _currLoc, entityPresets)); + context.features().on("change.preset-list", updateForFeatureHiddenState); + } + function drawList(list2, presets) { + presets = presets.matchAllGeometry(entityGeometries()); + var collection = presets.collection.reduce(function(collection2, preset) { + if (!preset) + return collection2; + if (preset.members) { + if (preset.members.collection.filter(function(preset2) { + return preset2.addable(); + }).length > 1) { + collection2.push(CategoryItem(preset)); + } + } else if (preset.addable()) { + collection2.push(PresetItem(preset)); + } + return collection2; + }, []); + var items = list2.selectAll(".preset-list-item").data(collection, function(d2) { + return d2.preset.id; + }); + items.order(); + items.exit().remove(); + items.enter().append("div").attr("class", function(item) { + return "preset-list-item preset-" + item.preset.id.replace("/", "-"); + }).classed("current", function(item) { + return _currentPresets.indexOf(item.preset) !== -1; + }).each(function(item) { + select_default2(this).call(item); + }).style("opacity", 0).transition().style("opacity", 1); + updateForFeatureHiddenState(); + } + function itemKeydown(d3_event) { + var item = select_default2(this.closest(".preset-list-item")); + var parentItem = select_default2(item.node().parentNode.closest(".preset-list-item")); + if (d3_event.keyCode === utilKeybinding.keyCodes["\u2193"]) { d3_event.preventDefault(); - var dx = d3_event.clientX - lastClientX; - lastClientX = d3_event.clientX; - var isRTL = _mainLocalizer.textDirection() === "rtl"; - var scaleX = isRTL ? 0 : 1; - var xMarginProperty = isRTL ? "margin-right" : "margin-left"; - var x2 = containerLocGetter(d3_event)[0] - dragOffset; - sidebarWidth = isRTL ? containerWidth - x2 : x2; - var isCollapsed = selection2.classed("collapsed"); - var shouldCollapse = sidebarWidth < minWidth; - selection2.classed("collapsed", shouldCollapse); - if (shouldCollapse) { - if (!isCollapsed) { - selection2.style(xMarginProperty, "-400px").style("width", "400px"); - context.ui().onResize([(sidebarWidth - dx) * scaleX, 0]); + d3_event.stopPropagation(); + var nextItem = select_default2(item.node().nextElementSibling); + if (nextItem.empty()) { + if (!parentItem.empty()) { + nextItem = select_default2(parentItem.node().nextElementSibling); } - } else { - var widthPct = sidebarWidth / containerWidth * 100; - selection2.style(xMarginProperty, null).style("width", widthPct + "%"); - if (isCollapsed) { - context.ui().onResize([-sidebarWidth * scaleX, 0]); - } else { - context.ui().onResize([-dx * scaleX, 0]); + } else if (select_default2(this).classed("expanded")) { + nextItem = item.select(".subgrid .preset-list-item:first-child"); + } + if (!nextItem.empty()) { + nextItem.select(".preset-list-button").node().focus(); + } + } else if (d3_event.keyCode === utilKeybinding.keyCodes["\u2191"]) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + var previousItem = select_default2(item.node().previousElementSibling); + if (previousItem.empty()) { + if (!parentItem.empty()) { + previousItem = parentItem; } + } else if (previousItem.select(".preset-list-button").classed("expanded")) { + previousItem = previousItem.select(".subgrid .preset-list-item:last-child"); } + if (!previousItem.empty()) { + previousItem.select(".preset-list-button").node().focus(); + } else { + var search = select_default2(this.closest(".preset-list-pane")).select(".preset-search-input"); + search.node().focus(); + } + } else if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2192" : "\u2190"]) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + if (!parentItem.empty()) { + parentItem.select(".preset-list-button").node().focus(); + } + } else if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2190" : "\u2192"]) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + item.datum().choose.call(select_default2(this).node()); } - function pointerup(d3_event) { - if (downPointerId !== (d3_event.pointerId || "mouse")) - return; - downPointerId = null; - resizer.classed("dragging", false); - select_default2(window).on("touchmove.sidebar-resizer", null).on(_pointerPrefix + "move.sidebar-resizer", null).on(_pointerPrefix + "up.sidebar-resizer pointercancel.sidebar-resizer", null); - } - var featureListWrap = selection2.append("div").attr("class", "feature-list-pane").call(uiFeatureList(context)); - var inspectorWrap = selection2.append("div").attr("class", "inspector-hidden inspector-wrap"); - var hoverModeSelect = function(targets) { - context.container().selectAll(".feature-list-item button").classed("hover", false); - if (context.selectedIDs().length > 1 && targets && targets.length) { - var elements = context.container().selectAll(".feature-list-item button").filter(function(node) { - return targets.indexOf(node) !== -1; - }); - if (!elements.empty()) { - elements.classed("hover", true); - } + } + function CategoryItem(preset) { + var box, sublist, shown = false; + function item(selection2) { + var wrap2 = selection2.append("div").attr("class", "preset-list-button-wrap category"); + function click() { + var isExpanded = select_default2(this).classed("expanded"); + var iconName = isExpanded ? _mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward" : "#iD-icon-down"; + select_default2(this).classed("expanded", !isExpanded).attr("title", !isExpanded ? _t("icons.collapse") : _t("icons.expand")); + select_default2(this).selectAll("div.label-inner svg.icon use").attr("href", iconName); + item.choose(); } - }; - sidebar.hoverModeSelect = throttle_default(hoverModeSelect, 200); - function hover(targets) { - var datum2 = targets && targets.length && targets[0]; - if (datum2 && datum2.__featurehash__) { - _wasData = true; - sidebar.show(dataEditor.datum(datum2)); - selection2.selectAll(".sidebar-component").classed("inspector-hover", true); - } else if (datum2 instanceof osmNote) { - if (context.mode().id === "drag-note") - return; - _wasNote = true; - var osm = services.osm; - if (osm) { - datum2 = osm.getNote(datum2.id); - } - sidebar.show(noteEditor.note(datum2)); - selection2.selectAll(".sidebar-component").classed("inspector-hover", true); - } else if (datum2 instanceof QAItem) { - _wasQaItem = true; - var errService = services[datum2.service]; - if (errService) { - datum2 = errService.getError(datum2.id); - } - var errEditor; - if (datum2.service === "keepRight") { - errEditor = keepRightEditor; - } else if (datum2.service === "osmose") { - errEditor = osmoseEditor; + var geometries = entityGeometries(); + var button = wrap2.append("button").attr("class", "preset-list-button").attr("title", _t("icons.expand")).classed("expanded", false).call(uiPresetIcon().geometry(geometries.length === 1 && geometries[0]).preset(preset)).on("click", click).on("keydown", function(d3_event) { + if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2190" : "\u2192"]) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + if (!select_default2(this).classed("expanded")) { + click.call(this, d3_event); + } + } else if (d3_event.keyCode === utilKeybinding.keyCodes[_mainLocalizer.textDirection() === "rtl" ? "\u2192" : "\u2190"]) { + d3_event.preventDefault(); + d3_event.stopPropagation(); + if (select_default2(this).classed("expanded")) { + click.call(this, d3_event); + } } else { - errEditor = improveOsmEditor; - } - context.container().selectAll(".qaItem." + datum2.service).classed("hover", function(d2) { - return d2.id === datum2.id; - }); - sidebar.show(errEditor.error(datum2)); - selection2.selectAll(".sidebar-component").classed("inspector-hover", true); - } else if (!_current && datum2 instanceof osmEntity) { - featureListWrap.classed("inspector-hidden", true); - inspectorWrap.classed("inspector-hidden", false).classed("inspector-hover", true); - if (!inspector.entityIDs() || !utilArrayIdentical(inspector.entityIDs(), [datum2.id]) || inspector.state() !== "hover") { - inspector.state("hover").entityIDs([datum2.id]).newFeature(false); - inspectorWrap.call(inspector); + itemKeydown.call(this, d3_event); } - } else if (!_current) { - featureListWrap.classed("inspector-hidden", false); - inspectorWrap.classed("inspector-hidden", true); - inspector.state("hide"); - } else if (_wasData || _wasNote || _wasQaItem) { - _wasNote = false; - _wasData = false; - _wasQaItem = false; - context.container().selectAll(".note").classed("hover", false); - context.container().selectAll(".qaItem").classed("hover", false); - sidebar.hide(); - } + }); + var label = button.append("div").attr("class", "label").append("div").attr("class", "label-inner"); + label.append("div").attr("class", "namepart").call(svgIcon(_mainLocalizer.textDirection() === "rtl" ? "#iD-icon-backward" : "#iD-icon-forward", "inline")).append("span").call(preset.nameLabel()).append("span").text("\u2026"); + box = selection2.append("div").attr("class", "subgrid").style("max-height", "0px").style("opacity", 0); + box.append("div").attr("class", "arrow"); + sublist = box.append("div").attr("class", "preset-list fillL3"); } - sidebar.hover = throttle_default(hover, 200); - sidebar.intersects = function(extent) { - var rect = selection2.node().getBoundingClientRect(); - return extent.intersects([ - context.projection.invert([0, rect.height]), - context.projection.invert([rect.width, 0]) - ]); - }; - sidebar.select = function(ids, newFeature) { - sidebar.hide(); - if (ids && ids.length) { - var entity = ids.length === 1 && context.entity(ids[0]); - if (entity && newFeature && selection2.classed("collapsed")) { - var extent = entity.extent(context.graph()); - sidebar.expand(sidebar.intersects(extent)); - } - featureListWrap.classed("inspector-hidden", true); - inspectorWrap.classed("inspector-hidden", false).classed("inspector-hover", false); - inspector.state("select").entityIDs(ids).newFeature(newFeature); - inspectorWrap.call(inspector); + item.choose = function() { + if (!box || !sublist) + return; + if (shown) { + shown = false; + box.transition().duration(200).style("opacity", "0").style("max-height", "0px").style("padding-bottom", "0px"); } else { - inspector.state("hide"); + shown = true; + var members = preset.members.matchAllGeometry(entityGeometries()); + sublist.call(drawList, members); + box.transition().duration(200).style("opacity", "1").style("max-height", 200 + members.collection.length * 190 + "px").style("padding-bottom", "10px"); } }; - sidebar.showPresetList = function() { - inspector.showList(); - }; - sidebar.show = function(component, element) { - featureListWrap.classed("inspector-hidden", true); - inspectorWrap.classed("inspector-hidden", true); - if (_current) - _current.remove(); - _current = selection2.append("div").attr("class", "sidebar-component").call(component, element); - }; - sidebar.hide = function() { - featureListWrap.classed("inspector-hidden", false); - inspectorWrap.classed("inspector-hidden", true); - if (_current) - _current.remove(); - _current = null; - }; - sidebar.expand = function(moveMap) { - if (selection2.classed("collapsed")) { - sidebar.toggle(moveMap); + item.preset = preset; + return item; + } + function PresetItem(preset) { + function item(selection2) { + var wrap2 = selection2.append("div").attr("class", "preset-list-button-wrap"); + var geometries = entityGeometries(); + var button = wrap2.append("button").attr("class", "preset-list-button").call(uiPresetIcon().geometry(geometries.length === 1 && geometries[0]).preset(preset)).on("click", item.choose).on("keydown", itemKeydown); + var label = button.append("div").attr("class", "label").append("div").attr("class", "label-inner"); + var nameparts = [ + preset.nameLabel(), + preset.subtitleLabel() + ].filter(Boolean); + label.selectAll(".namepart").data(nameparts, (d2) => d2.stringId).enter().append("div").attr("class", "namepart").text("").each(function(d2) { + d2(select_default2(this)); + }); + wrap2.call(item.reference.button); + selection2.call(item.reference.body); + } + item.choose = function() { + if (select_default2(this).classed("disabled")) + return; + if (!context.inIntro()) { + _mainPresetIndex.setMostRecent(preset, entityGeometries()[0]); } + context.perform( + function(graph) { + for (var i3 in _entityIDs) { + var entityID = _entityIDs[i3]; + var oldPreset = _mainPresetIndex.match(graph.entity(entityID), graph); + graph = actionChangePreset(entityID, oldPreset, preset)(graph); + } + return graph; + }, + _t("operations.change_tags.annotation") + ); + context.validator().validate(); + dispatch14.call("choose", this, preset); }; - sidebar.collapse = function(moveMap) { - if (!selection2.classed("collapsed")) { - sidebar.toggle(moveMap); - } + item.help = function(d3_event) { + d3_event.stopPropagation(); + item.reference.toggle(); }; - sidebar.toggle = function(moveMap) { - if (context.inIntro()) - return; - var isCollapsed = selection2.classed("collapsed"); - var isCollapsing = !isCollapsed; - var isRTL = _mainLocalizer.textDirection() === "rtl"; - var scaleX = isRTL ? 0 : 1; - var xMarginProperty = isRTL ? "margin-right" : "margin-left"; - sidebarWidth = selection2.node().getBoundingClientRect().width; - selection2.style("width", sidebarWidth + "px"); - var startMargin, endMargin, lastMargin; - if (isCollapsing) { - startMargin = lastMargin = 0; - endMargin = -sidebarWidth; - } else { - startMargin = lastMargin = -sidebarWidth; - endMargin = 0; + item.preset = preset; + item.reference = uiTagReference(preset.reference(), context); + return item; + } + function updateForFeatureHiddenState() { + if (!_entityIDs.every(context.hasEntity)) + return; + var geometries = entityGeometries(); + var button = context.container().selectAll(".preset-list .preset-list-button"); + button.call(uiTooltip().destroyAny); + button.each(function(item, index) { + var hiddenPresetFeaturesId; + for (var i3 in geometries) { + hiddenPresetFeaturesId = context.features().isHiddenPreset(item.preset, geometries[i3]); + if (hiddenPresetFeaturesId) + break; } - if (!isCollapsing) { - selection2.classed("collapsed", isCollapsing); + var isHiddenPreset = !context.inIntro() && !!hiddenPresetFeaturesId && (_currentPresets.length !== 1 || item.preset !== _currentPresets[0]); + select_default2(this).classed("disabled", isHiddenPreset); + if (isHiddenPreset) { + var isAutoHidden = context.features().autoHidden(hiddenPresetFeaturesId); + select_default2(this).call( + uiTooltip().title(() => _t.append("inspector.hidden_preset." + (isAutoHidden ? "zoom" : "manual"), { + features: _t("feature." + hiddenPresetFeaturesId + ".description") + })).placement(index < 2 ? "bottom" : "top") + ); } - selection2.transition().style(xMarginProperty, endMargin + "px").tween("panner", function() { - var i3 = number_default(startMargin, endMargin); - return function(t2) { - var dx = lastMargin - Math.round(i3(t2)); - lastMargin = lastMargin - dx; - context.ui().onResize(moveMap ? void 0 : [dx * scaleX, 0]); - }; - }).on("end", function() { - if (isCollapsing) { - selection2.classed("collapsed", isCollapsing); - } - if (!isCollapsing) { - var containerWidth2 = container.node().getBoundingClientRect().width; - var widthPct = sidebarWidth / containerWidth2 * 100; - selection2.style(xMarginProperty, null).style("width", widthPct + "%"); - } + }); + } + presetList.autofocus = function(val) { + if (!arguments.length) + return _autofocus; + _autofocus = val; + return presetList; + }; + presetList.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + _entityIDs = val; + _currLoc = null; + if (_entityIDs && _entityIDs.length) { + const extent = _entityIDs.reduce(function(extent2, entityID) { + var entity = context.graph().entity(entityID); + return extent2.extend(entity.extent(context.graph())); + }, geoExtent()); + _currLoc = extent.center(); + var presets = _entityIDs.map(function(entityID) { + return _mainPresetIndex.match(context.entity(entityID), context.graph()); }); - }; - resizer.on("dblclick", function(d3_event) { - d3_event.preventDefault(); - if (d3_event.sourceEvent) { - d3_event.sourceEvent.preventDefault(); + presetList.presets(presets); + } + return presetList; + }; + presetList.presets = function(val) { + if (!arguments.length) + return _currentPresets; + _currentPresets = val; + return presetList; + }; + function entityGeometries() { + var counts = {}; + for (var i3 in _entityIDs) { + var entityID = _entityIDs[i3]; + var entity = context.entity(entityID); + var geometry = entity.geometry(context.graph()); + if (geometry === "vertex" && entity.isOnAddressLine(context.graph())) { + geometry = "point"; } - sidebar.toggle(); + if (!counts[geometry]) + counts[geometry] = 0; + counts[geometry] += 1; + } + return Object.keys(counts).sort(function(geom1, geom2) { + return counts[geom2] - counts[geom1]; }); - context.map().on("crossEditableZoom.sidebar", function(within) { - if (!within && !selection2.select(".inspector-hover").empty()) { - hover([]); - } + } + return utilRebind(presetList, dispatch14, "on"); + } + + // modules/ui/inspector.js + function uiInspector(context) { + var presetList = uiPresetList(context); + var entityEditor = uiEntityEditor(context); + var wrap2 = select_default2(null), presetPane = select_default2(null), editorPane = select_default2(null); + var _state = "select"; + var _entityIDs; + var _newFeature = false; + function inspector(selection2) { + presetList.entityIDs(_entityIDs).autofocus(_newFeature).on("choose", inspector.setPreset).on("cancel", function() { + inspector.setPreset(); }); + entityEditor.state(_state).entityIDs(_entityIDs).on("choose", inspector.showList); + wrap2 = selection2.selectAll(".panewrap").data([0]); + var enter = wrap2.enter().append("div").attr("class", "panewrap"); + enter.append("div").attr("class", "preset-list-pane pane"); + enter.append("div").attr("class", "entity-editor-pane pane"); + wrap2 = wrap2.merge(enter); + presetPane = wrap2.selectAll(".preset-list-pane"); + editorPane = wrap2.selectAll(".entity-editor-pane"); + function shouldDefaultToPresetList() { + if (_state !== "select") + return false; + if (_entityIDs.length !== 1) + return false; + var entityID = _entityIDs[0]; + var entity = context.hasEntity(entityID); + if (!entity) + return false; + if (entity.hasNonGeometryTags()) + return false; + if (_newFeature) + return true; + if (entity.geometry(context.graph()) !== "vertex") + return false; + if (context.graph().parentRelations(entity).length) + return false; + if (context.validator().getEntityIssues(entityID).length) + return false; + if (entity.isHighwayIntersection(context.graph())) + return false; + return true; + } + if (shouldDefaultToPresetList()) { + wrap2.style("right", "-100%"); + editorPane.classed("hide", true); + presetPane.classed("hide", false).call(presetList); + } else { + wrap2.style("right", "0%"); + presetPane.classed("hide", true); + editorPane.classed("hide", false).call(entityEditor); + } + var footer = selection2.selectAll(".footer").data([0]); + footer = footer.enter().append("div").attr("class", "footer").merge(footer); + footer.call( + uiViewOnOSM(context).what(context.hasEntity(_entityIDs.length === 1 && _entityIDs[0])) + ); } - sidebar.showPresetList = function() { - }; - sidebar.hover = function() { - }; - sidebar.hover.cancel = function() { + inspector.showList = function(presets) { + presetPane.classed("hide", false); + wrap2.transition().styleTween("right", function() { + return value_default("0%", "-100%"); + }).on("end", function() { + editorPane.classed("hide", true); + }); + if (presets) { + presetList.presets(presets); + } + presetPane.call(presetList.autofocus(true)); }; - sidebar.intersects = function() { + inspector.setPreset = function(preset) { + if (preset && preset.id === "type/multipolygon") { + presetPane.call(presetList.autofocus(true)); + } else { + editorPane.classed("hide", false); + wrap2.transition().styleTween("right", function() { + return value_default("-100%", "0%"); + }).on("end", function() { + presetPane.classed("hide", true); + }); + if (preset) { + entityEditor.presets([preset]); + } + editorPane.call(entityEditor); + } }; - sidebar.select = function() { + inspector.state = function(val) { + if (!arguments.length) + return _state; + _state = val; + entityEditor.state(_state); + context.container().selectAll(".field-help-body").remove(); + return inspector; }; - sidebar.show = function() { + inspector.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + _entityIDs = val; + return inspector; }; - sidebar.hide = function() { + inspector.newFeature = function(val) { + if (!arguments.length) + return _newFeature; + _newFeature = val; + return inspector; }; - sidebar.expand = function() { + return inspector; + } + + // modules/ui/lasso.js + function uiLasso(context) { + var group, polygon2; + lasso.coordinates = []; + function lasso(selection2) { + context.container().classed("lasso", true); + group = selection2.append("g").attr("class", "lasso hide"); + polygon2 = group.append("path").attr("class", "lasso-path"); + group.call(uiToggle(true)); + } + function draw() { + if (polygon2) { + polygon2.data([lasso.coordinates]).attr("d", function(d2) { + return "M" + d2.join(" L") + " Z"; + }); + } + } + lasso.extent = function() { + return lasso.coordinates.reduce(function(extent, point2) { + return extent.extend(geoExtent(point2)); + }, geoExtent()); }; - sidebar.collapse = function() { + lasso.p = function(_2) { + if (!arguments.length) + return lasso; + lasso.coordinates.push(_2); + draw(); + return lasso; }; - sidebar.toggle = function() { + lasso.close = function() { + if (group) { + group.call(uiToggle(false, function() { + select_default2(this).remove(); + })); + } + context.container().classed("lasso", false); }; - return sidebar; + return lasso; } - // modules/modes/draw_area.js - function modeDrawArea(context, wayID, startGraph, button) { - var mode = { - button, - id: "draw-area" + // modules/ui/source_switch.js + function uiSourceSwitch(context) { + var keys2; + function click(d3_event) { + d3_event.preventDefault(); + var osm = context.connection(); + if (!osm) + return; + if (context.inIntro()) + return; + if (context.history().hasChanges() && !window.confirm(_t("source_switch.lose_changes"))) + return; + var isLive = select_default2(this).classed("live"); + isLive = !isLive; + context.enter(modeBrowse(context)); + context.history().clearSaved(); + context.flush(); + select_default2(this).html(isLive ? _t.html("source_switch.live") : _t.html("source_switch.dev")).classed("live", isLive).classed("chip", isLive); + osm.switch(isLive ? keys2[0] : keys2[1]); + } + var sourceSwitch = function(selection2) { + selection2.append("a").attr("href", "#").call(_t.append("source_switch.live")).attr("class", "live chip").on("click", click); }; - var behavior = behaviorDrawWay(context, wayID, mode, startGraph).on("rejectedSelfIntersection.modeDrawArea", function() { - context.ui().flash.iconName("#iD-icon-no").label(_t.append("self_intersection.error.areas"))(); - }); - mode.wayID = wayID; - mode.enter = function() { - context.install(behavior); + sourceSwitch.keys = function(_2) { + if (!arguments.length) + return keys2; + keys2 = _2; + return sourceSwitch; }; - mode.exit = function() { - context.uninstall(behavior); + return sourceSwitch; + } + + // modules/ui/spinner.js + function uiSpinner(context) { + var osm = context.connection(); + return function(selection2) { + var img = selection2.append("img").attr("src", context.imagePath("loader-black.gif")).style("opacity", 0); + if (osm) { + osm.on("loading.spinner", function() { + img.transition().style("opacity", 1); + }).on("loaded.spinner", function() { + img.transition().style("opacity", 0); + }); + } }; - mode.selectedIDs = function() { - return [wayID]; + } + + // modules/ui/sections/privacy.js + function uiSectionPrivacy(context) { + let section = uiSection("preferences-third-party", context).label(() => _t.append("preferences.privacy.title")).disclosureContent(renderDisclosureContent); + function renderDisclosureContent(selection2) { + selection2.selectAll(".privacy-options-list").data([0]).enter().append("ul").attr("class", "layer-list privacy-options-list"); + let thirdPartyIconsEnter = selection2.select(".privacy-options-list").selectAll(".privacy-third-party-icons-item").data([corePreferences("preferences.privacy.thirdpartyicons") || "true"]).enter().append("li").attr("class", "privacy-third-party-icons-item").append("label").call( + uiTooltip().title(() => _t.append("preferences.privacy.third_party_icons.tooltip")).placement("bottom") + ); + thirdPartyIconsEnter.append("input").attr("type", "checkbox").on("change", (d3_event, d2) => { + d3_event.preventDefault(); + corePreferences("preferences.privacy.thirdpartyicons", d2 === "true" ? "false" : "true"); + }); + thirdPartyIconsEnter.append("span").call(_t.append("preferences.privacy.third_party_icons.description")); + selection2.selectAll(".privacy-third-party-icons-item").classed("active", (d2) => d2 === "true").select("input").property("checked", (d2) => d2 === "true"); + selection2.selectAll(".privacy-link").data([0]).enter().append("div").attr("class", "privacy-link").append("a").attr("target", "_blank").call(svgIcon("#iD-icon-out-link", "inline")).attr("href", "https://github.com/openstreetmap/iD/blob/release/PRIVACY.md").append("span").call(_t.append("preferences.privacy.privacy_link")); + } + corePreferences.onChange("preferences.privacy.thirdpartyicons", section.reRender); + return section; + } + + // modules/ui/splash.js + function uiSplash(context) { + return (selection2) => { + if (context.history().hasRestorableChanges()) + return; + let updateMessage = ""; + const sawPrivacyVersion = corePreferences("sawPrivacyVersion"); + let showSplash = !corePreferences("sawSplash"); + if (sawPrivacyVersion !== context.privacyVersion) { + updateMessage = _t("splash.privacy_update"); + showSplash = true; + } + if (!showSplash) + return; + corePreferences("sawSplash", true); + corePreferences("sawPrivacyVersion", context.privacyVersion); + _mainFileFetcher.get("intro_graph"); + let modalSelection = uiModal(selection2); + modalSelection.select(".modal").attr("class", "modal-splash modal"); + let introModal = modalSelection.select(".content").append("div").attr("class", "fillL"); + introModal.append("div").attr("class", "modal-section").append("h3").call(_t.append("splash.welcome")); + let modalSection = introModal.append("div").attr("class", "modal-section"); + modalSection.append("p").html(_t.html("splash.text", { + version: context.version, + website: { html: '' + _t.html("splash.changelog") + "" }, + github: { html: 'github.com' } + })); + modalSection.append("p").html(_t.html("splash.privacy", { + updateMessage, + privacyLink: { html: '' + _t("splash.privacy_policy") + "" } + })); + uiSectionPrivacy(context).label(() => _t.append("splash.privacy_settings")).render(modalSection); + let buttonWrap = introModal.append("div").attr("class", "modal-actions"); + let walkthrough = buttonWrap.append("button").attr("class", "walkthrough").on("click", () => { + context.container().call(uiIntro(context)); + modalSelection.close(); + }); + walkthrough.append("svg").attr("class", "logo logo-walkthrough").append("use").attr("xlink:href", "#iD-logo-walkthrough"); + walkthrough.append("div").call(_t.append("splash.walkthrough")); + let startEditing = buttonWrap.append("button").attr("class", "start-editing").on("click", modalSelection.close); + startEditing.append("svg").attr("class", "logo logo-features").append("use").attr("xlink:href", "#iD-logo-features"); + startEditing.append("div").call(_t.append("splash.start")); + modalSelection.select("button.close").attr("class", "hide"); }; - mode.activeID = function() { - return behavior && behavior.activeID() || []; + } + + // modules/ui/status.js + function uiStatus(context) { + var osm = context.connection(); + return function(selection2) { + if (!osm) + return; + function update(err, apiStatus) { + selection2.html(""); + if (err) { + if (apiStatus === "connectionSwitched") { + return; + } else if (apiStatus === "rateLimited") { + selection2.call(_t.append("osm_api_status.message.rateLimit")).append("a").attr("href", "#").attr("class", "api-status-login").attr("target", "_blank").call(svgIcon("#iD-icon-out-link", "inline")).append("span").call(_t.append("login")).on("click.login", function(d3_event) { + d3_event.preventDefault(); + osm.authenticate(); + }); + } else { + var throttledRetry = throttle_default(function() { + context.loadTiles(context.projection); + osm.reloadApiStatus(); + }, 2e3); + selection2.call(_t.append("osm_api_status.message.error", { suffix: " " })).append("a").attr("href", "#").call(_t.append("osm_api_status.retry")).on("click.retry", function(d3_event) { + d3_event.preventDefault(); + throttledRetry(); + }); + } + } else if (apiStatus === "readonly") { + selection2.call(_t.append("osm_api_status.message.readonly")); + } else if (apiStatus === "offline") { + selection2.call(_t.append("osm_api_status.message.offline")); + } + selection2.attr("class", "api-status " + (err ? "error" : apiStatus)); + } + osm.on("apiStatusChange.uiStatus", update); + context.history().on("storage_error", () => { + selection2.selectAll("span.local-storage-full").remove(); + selection2.append("span").attr("class", "local-storage-full").call(_t.append("osm_api_status.message.local_storage_full")); + selection2.classed("error", true); + }); + window.setInterval(function() { + osm.reloadApiStatus(); + }, 9e4); + osm.reloadApiStatus(); }; - return mode; } - // modules/modes/add_area.js - function modeAddArea(context, mode) { - mode.id = "add-area"; - var behavior = behaviorAddWay(context).on("start", start2).on("startFromWay", startFromWay).on("startFromNode", startFromNode); - function defaultTags(loc) { - var defaultTags2 = { area: "yes" }; - if (mode.preset) - defaultTags2 = mode.preset.setTags(defaultTags2, "area", false, loc); - return defaultTags2; + // modules/ui/version.js + var sawVersion = null; + var isNewVersion = false; + var isNewUser = false; + function uiVersion(context) { + var currVersion = context.version; + var matchedVersion = currVersion.match(/\d+\.\d+\.\d+.*/); + if (sawVersion === null && matchedVersion !== null) { + if (corePreferences("sawVersion")) { + isNewUser = false; + isNewVersion = corePreferences("sawVersion") !== currVersion && currVersion.indexOf("-") === -1; + } else { + isNewUser = true; + isNewVersion = true; + } + corePreferences("sawVersion", currVersion); + sawVersion = currVersion; } - function actionClose(wayId) { - return function(graph) { - return graph.replace(graph.entity(wayId).close()); - }; + return function(selection2) { + selection2.append("a").attr("target", "_blank").attr("href", "https://github.com/openstreetmap/iD").text(currVersion); + if (isNewVersion && !isNewUser) { + selection2.append("a").attr("class", "badge").attr("target", "_blank").attr("href", "https://github.com/openstreetmap/iD/blob/release/CHANGELOG.md#whats-new").call(svgIcon("#maki-gift")).call( + uiTooltip().title(() => _t.append("version.whats_new", { version: currVersion })).placement("top").scrollContainer(context.container().select(".main-footer-wrap")) + ); + } + }; + } + + // modules/ui/zoom.js + function uiZoom(context) { + var zooms = [{ + id: "zoom-in", + icon: "iD-icon-plus", + title: _t.append("zoom.in"), + action: zoomIn, + disabled: function() { + return !context.map().canZoomIn(); + }, + disabledTitle: _t.append("zoom.disabled.in"), + key: "+" + }, { + id: "zoom-out", + icon: "iD-icon-minus", + title: _t.append("zoom.out"), + action: zoomOut, + disabled: function() { + return !context.map().canZoomOut(); + }, + disabledTitle: _t.append("zoom.disabled.out"), + key: "-" + }]; + function zoomIn(d3_event) { + if (d3_event.shiftKey) + return; + d3_event.preventDefault(); + context.map().zoomIn(); } - function start2(loc) { - var startGraph = context.graph(); - var node = osmNode({ loc }); - var way = osmWay({ tags: defaultTags(loc) }); - context.perform( - actionAddEntity(node), - actionAddEntity(way), - actionAddVertex(way.id, node.id), - actionClose(way.id) - ); - context.enter(modeDrawArea(context, way.id, startGraph, mode.button)); + function zoomOut(d3_event) { + if (d3_event.shiftKey) + return; + d3_event.preventDefault(); + context.map().zoomOut(); } - function startFromWay(loc, edge) { - var startGraph = context.graph(); - var node = osmNode({ loc }); - var way = osmWay({ tags: defaultTags(loc) }); - context.perform( - actionAddEntity(node), - actionAddEntity(way), - actionAddVertex(way.id, node.id), - actionClose(way.id), - actionAddMidpoint({ loc, edge }, node) - ); - context.enter(modeDrawArea(context, way.id, startGraph, mode.button)); + function zoomInFurther(d3_event) { + if (d3_event.shiftKey) + return; + d3_event.preventDefault(); + context.map().zoomInFurther(); } - function startFromNode(node) { - var startGraph = context.graph(); - var way = osmWay({ tags: defaultTags(node.loc) }); - context.perform( - actionAddEntity(way), - actionAddVertex(way.id, node.id), - actionClose(way.id) - ); - context.enter(modeDrawArea(context, way.id, startGraph, mode.button)); + function zoomOutFurther(d3_event) { + if (d3_event.shiftKey) + return; + d3_event.preventDefault(); + context.map().zoomOutFurther(); } - mode.enter = function() { - context.install(behavior); - }; - mode.exit = function() { - context.uninstall(behavior); + return function(selection2) { + var tooltipBehavior = uiTooltip().placement(_mainLocalizer.textDirection() === "rtl" ? "right" : "left").title(function(d2) { + if (d2.disabled()) { + return d2.disabledTitle; + } + return d2.title; + }).keys(function(d2) { + return [d2.key]; + }); + var lastPointerUpType; + var buttons = selection2.selectAll("button").data(zooms).enter().append("button").attr("class", function(d2) { + return d2.id; + }).on("pointerup.editor", function(d3_event) { + lastPointerUpType = d3_event.pointerType; + }).on("click.editor", function(d3_event, d2) { + if (!d2.disabled()) { + d2.action(d3_event); + } else if (lastPointerUpType === "touch" || lastPointerUpType === "pen") { + context.ui().flash.duration(2e3).iconName("#" + d2.icon).iconClass("disabled").label(d2.disabledTitle)(); + } + lastPointerUpType = null; + }).call(tooltipBehavior); + buttons.each(function(d2) { + select_default2(this).call(svgIcon("#" + d2.icon, "light")); + }); + utilKeybinding.plusKeys.forEach(function(key) { + context.keybinding().on([key], zoomIn); + context.keybinding().on([uiCmd("\u2325" + key)], zoomInFurther); + }); + utilKeybinding.minusKeys.forEach(function(key) { + context.keybinding().on([key], zoomOut); + context.keybinding().on([uiCmd("\u2325" + key)], zoomOutFurther); + }); + function updateButtonStates() { + buttons.classed("disabled", function(d2) { + return d2.disabled(); + }).each(function() { + var selection3 = select_default2(this); + if (!selection3.select(".tooltip.in").empty()) { + selection3.call(tooltipBehavior.updateContent); + } + }); + } + updateButtonStates(); + context.map().on("move.uiZoom", updateButtonStates); }; - return mode; } - // modules/modes/add_line.js - function modeAddLine(context, mode) { - mode.id = "add-line"; - var behavior = behaviorAddWay(context).on("start", start2).on("startFromWay", startFromWay).on("startFromNode", startFromNode); - function defaultTags(loc) { - var defaultTags2 = {}; - if (mode.preset) - defaultTags2 = mode.preset.setTags(defaultTags2, "line", false, loc); - return defaultTags2; - } - function start2(loc) { - var startGraph = context.graph(); - var node = osmNode({ loc }); - var way = osmWay({ tags: defaultTags(loc) }); - context.perform( - actionAddEntity(node), - actionAddEntity(way), - actionAddVertex(way.id, node.id) - ); - context.enter(modeDrawLine(context, way.id, startGraph, mode.button)); - } - function startFromWay(loc, edge) { - var startGraph = context.graph(); - var node = osmNode({ loc }); - var way = osmWay({ tags: defaultTags(loc) }); - context.perform( - actionAddEntity(node), - actionAddEntity(way), - actionAddVertex(way.id, node.id), - actionAddMidpoint({ loc, edge }, node) - ); - context.enter(modeDrawLine(context, way.id, startGraph, mode.button)); + // modules/ui/sections/raw_tag_editor.js + function uiSectionRawTagEditor(id2, context) { + var section = uiSection(id2, context).classes("raw-tag-editor").label(function() { + var count = Object.keys(_tags).filter(function(d2) { + return d2; + }).length; + return _t.append("inspector.title_count", { title: _t("inspector.tags"), count }); + }).expandedByDefault(false).disclosureContent(renderDisclosureContent); + var taginfo = services.taginfo; + var dispatch14 = dispatch_default("change"); + var availableViews = [ + { id: "list", icon: "#fas-th-list" }, + { id: "text", icon: "#fas-i-cursor" } + ]; + let _discardTags = {}; + _mainFileFetcher.get("discarded").then((d2) => { + _discardTags = d2; + }).catch(() => { + }); + var _tagView = corePreferences("raw-tag-editor-view") || "list"; + var _readOnlyTags = []; + var _orderedKeys = []; + var _showBlank = false; + var _pendingChange = null; + var _state; + var _presets; + var _tags; + var _entityIDs; + var _didInteract = false; + function interacted() { + _didInteract = true; } - function startFromNode(node) { - var startGraph = context.graph(); - var way = osmWay({ tags: defaultTags(node.loc) }); - context.perform( - actionAddEntity(way), - actionAddVertex(way.id, node.id) + function renderDisclosureContent(wrap2) { + _orderedKeys = _orderedKeys.filter(function(key) { + return _tags[key] !== void 0; + }); + var all = Object.keys(_tags).sort(); + var missingKeys = utilArrayDifference(all, _orderedKeys); + for (var i3 in missingKeys) { + _orderedKeys.push(missingKeys[i3]); + } + var rowData = _orderedKeys.map(function(key, i4) { + return { index: i4, key, value: _tags[key] }; + }); + if (!rowData.length || _showBlank) { + _showBlank = false; + rowData.push({ index: rowData.length, key: "", value: "" }); + } + var options2 = wrap2.selectAll(".raw-tag-options").data([0]); + options2.exit().remove(); + var optionsEnter = options2.enter().insert("div", ":first-child").attr("class", "raw-tag-options").attr("role", "tablist"); + var optionEnter = optionsEnter.selectAll(".raw-tag-option").data(availableViews, function(d2) { + return d2.id; + }).enter(); + optionEnter.append("button").attr("class", function(d2) { + return "raw-tag-option raw-tag-option-" + d2.id + (_tagView === d2.id ? " selected" : ""); + }).attr("aria-selected", function(d2) { + return _tagView === d2.id; + }).attr("role", "tab").attr("title", function(d2) { + return _t("icons." + d2.id); + }).on("click", function(d3_event, d2) { + _tagView = d2.id; + corePreferences("raw-tag-editor-view", d2.id); + wrap2.selectAll(".raw-tag-option").classed("selected", function(datum2) { + return datum2 === d2; + }).attr("aria-selected", function(datum2) { + return datum2 === d2; + }); + wrap2.selectAll(".tag-text").classed("hide", d2.id !== "text").each(setTextareaHeight); + wrap2.selectAll(".tag-list, .add-row").classed("hide", d2.id !== "list"); + }).each(function(d2) { + select_default2(this).call(svgIcon(d2.icon)); + }); + var textData = rowsToText(rowData); + var textarea = wrap2.selectAll(".tag-text").data([0]); + textarea = textarea.enter().append("textarea").attr("class", "tag-text" + (_tagView !== "text" ? " hide" : "")).call(utilNoAuto).attr("placeholder", _t("inspector.key_value")).attr("spellcheck", "false").merge(textarea); + textarea.call(utilGetSetValue, textData).each(setTextareaHeight).on("input", setTextareaHeight).on("focus", interacted).on("blur", textChanged).on("change", textChanged); + var list2 = wrap2.selectAll(".tag-list").data([0]); + list2 = list2.enter().append("ul").attr("class", "tag-list" + (_tagView !== "list" ? " hide" : "")).merge(list2); + var addRowEnter = wrap2.selectAll(".add-row").data([0]).enter().append("div").attr("class", "add-row" + (_tagView !== "list" ? " hide" : "")); + addRowEnter.append("button").attr("class", "add-tag").attr("aria-label", _t("inspector.add_to_tag")).call(svgIcon("#iD-icon-plus", "light")).call(uiTooltip().title(() => _t.append("inspector.add_to_tag")).placement(_mainLocalizer.textDirection() === "ltr" ? "right" : "left")).on("click", addTag); + addRowEnter.append("div").attr("class", "space-value"); + addRowEnter.append("div").attr("class", "space-buttons"); + var items = list2.selectAll(".tag-row").data(rowData, function(d2) { + return d2.key; + }); + items.exit().each(unbind).remove(); + var itemsEnter = items.enter().append("li").attr("class", "tag-row").classed("readonly", isReadOnly); + var innerWrap = itemsEnter.append("div").attr("class", "inner-wrap"); + innerWrap.append("div").attr("class", "key-wrap").append("input").property("type", "text").attr("class", "key").call(utilNoAuto).on("focus", interacted).on("blur", keyChange).on("change", keyChange); + innerWrap.append("div").attr("class", "value-wrap").append("input").property("type", "text").attr("class", "value").call(utilNoAuto).on("focus", interacted).on("blur", valueChange).on("change", valueChange).on("keydown.push-more", pushMore); + innerWrap.append("button").attr("class", "form-field-button remove").attr("title", _t("icons.remove")).call(svgIcon("#iD-operation-delete")); + items = items.merge(itemsEnter).sort(function(a2, b2) { + return a2.index - b2.index; + }); + items.each(function(d2) { + var row = select_default2(this); + var key = row.select("input.key"); + var value = row.select("input.value"); + if (_entityIDs && taginfo && _state !== "hover") { + bindTypeahead(key, value); + } + var referenceOptions = { key: d2.key }; + if (typeof d2.value === "string") { + referenceOptions.value = d2.value; + } + var reference = uiTagReference(referenceOptions, context); + if (_state === "hover") { + reference.showing(false); + } + row.select(".inner-wrap").call(reference.button); + row.call(reference.body); + row.select("button.remove"); + }); + items.selectAll("input.key").attr("title", function(d2) { + return d2.key; + }).call(utilGetSetValue, function(d2) { + return d2.key; + }).attr("readonly", function(d2) { + return isReadOnly(d2) || null; + }); + items.selectAll("input.value").attr("title", function(d2) { + return Array.isArray(d2.value) ? d2.value.filter(Boolean).join("\n") : d2.value; + }).classed("mixed", function(d2) { + return Array.isArray(d2.value); + }).attr("placeholder", function(d2) { + return typeof d2.value === "string" ? null : _t("inspector.multiple_values"); + }).call(utilGetSetValue, function(d2) { + return typeof d2.value === "string" ? d2.value : ""; + }).attr("readonly", function(d2) { + return isReadOnly(d2) || null; + }); + items.selectAll("button.remove").on( + ("PointerEvent" in window ? "pointer" : "mouse") + "down", + // 'click' fires too late - #5878 + (d3_event, d2) => { + if (d3_event.button !== 0) + return; + removeTag(d3_event, d2); + } ); - context.enter(modeDrawLine(context, way.id, startGraph, mode.button)); - } - mode.enter = function() { - context.install(behavior); - }; - mode.exit = function() { - context.uninstall(behavior); - }; - return mode; - } - - // modules/modes/add_point.js - function modeAddPoint(context, mode) { - mode.id = "add-point"; - var behavior = behaviorDraw(context).on("click", add).on("clickWay", addWay).on("clickNode", addNode).on("cancel", cancel).on("finish", cancel); - function defaultTags(loc) { - var defaultTags2 = {}; - if (mode.preset) - defaultTags2 = mode.preset.setTags(defaultTags2, "point", false, loc); - return defaultTags2; } - function add(loc) { - var node = osmNode({ loc, tags: defaultTags(loc) }); - context.perform( - actionAddEntity(node), - _t("operations.add.annotation.point") - ); - enterSelectMode(node); + function isReadOnly(d2) { + for (var i3 = 0; i3 < _readOnlyTags.length; i3++) { + if (d2.key.match(_readOnlyTags[i3]) !== null) { + return true; + } + } + return false; } - function addWay(loc, edge) { - var node = osmNode({ tags: defaultTags(loc) }); - context.perform( - actionAddMidpoint({ loc, edge }, node), - _t("operations.add.annotation.vertex") - ); - enterSelectMode(node); + function setTextareaHeight() { + if (_tagView !== "text") + return; + var selection2 = select_default2(this); + var matches = selection2.node().value.match(/\n/g); + var lineCount = 2 + Number(matches && matches.length); + var lineHeight = 20; + selection2.style("height", lineCount * lineHeight + "px"); } - function enterSelectMode(node) { - context.enter( - modeSelect(context, [node.id]).newFeature(true) - ); + function stringify3(s2) { + return JSON.stringify(s2).slice(1, -1); } - function addNode(node) { - const _defaultTags = defaultTags(node.loc); - if (Object.keys(_defaultTags).length === 0) { - enterSelectMode(node); - return; + function unstringify(s2) { + var leading = ""; + var trailing = ""; + if (s2.length < 1 || s2.charAt(0) !== '"') { + leading = '"'; } - var tags = Object.assign({}, node.tags); - for (var key in _defaultTags) { - tags[key] = _defaultTags[key]; + if (s2.length < 2 || s2.charAt(s2.length - 1) !== '"' || s2.charAt(s2.length - 1) === '"' && s2.charAt(s2.length - 2) === "\\") { + trailing = '"'; } - context.perform( - actionChangeTags(node.id, tags), - _t("operations.add.annotation.point") - ); - enterSelectMode(node); + return JSON.parse(leading + s2 + trailing); } - function cancel() { - context.enter(modeBrowse(context)); + function rowsToText(rows) { + var str = rows.filter(function(row) { + return row.key && row.key.trim() !== ""; + }).map(function(row) { + var rawVal = row.value; + if (typeof rawVal !== "string") + rawVal = "*"; + var val = rawVal ? stringify3(rawVal) : ""; + return stringify3(row.key) + "=" + val; + }).join("\n"); + if (_state !== "hover" && str.length) { + return str + "\n"; + } + return str; } - mode.enter = function() { - context.install(behavior); - }; - mode.exit = function() { - context.uninstall(behavior); - }; - return mode; - } - - // modules/modes/select_note.js - function modeSelectNote(context, selectedNoteID) { - var mode = { - id: "select-note", - button: "browse" - }; - var _keybinding = utilKeybinding("select-note"); - var _noteEditor = uiNoteEditor(context).on("change", function() { - context.map().pan([0, 0]); - var note = checkSelectedID(); - if (!note) + function textChanged() { + var newText = this.value.trim(); + var newTags = {}; + newText.split("\n").forEach(function(row) { + var m2 = row.match(/^\s*([^=]+)=(.*)$/); + if (m2 !== null) { + var k2 = context.cleanTagKey(unstringify(m2[1].trim())); + var v2 = context.cleanTagValue(unstringify(m2[2].trim())); + newTags[k2] = v2; + } + }); + var tagDiff = utilTagDiff(_tags, newTags); + if (!tagDiff.length) return; - context.ui().sidebar.show(_noteEditor.note(note)); - }); - var _behaviors = [ - behaviorBreathe(context), - behaviorHover(context), - behaviorSelect(context), - behaviorLasso(context), - modeDragNode(context).behavior, - modeDragNote(context).behavior - ]; - var _newFeature = false; - function checkSelectedID() { - if (!services.osm) + _pendingChange = _pendingChange || {}; + tagDiff.forEach(function(change) { + if (isReadOnly({ key: change.key })) + return; + if (change.newVal === "*" && typeof change.oldVal !== "string") + return; + if (change.type === "-") { + _pendingChange[change.key] = void 0; + } else if (change.type === "+") { + _pendingChange[change.key] = change.newVal || ""; + } + }); + if (Object.keys(_pendingChange).length === 0) { + _pendingChange = null; return; - var note = services.osm.getNote(selectedNoteID); - if (!note) { - context.enter(modeBrowse(context)); } - return note; + scheduleChange(); } - function selectNote(d3_event, drawn) { - if (!checkSelectedID()) + function pushMore(d3_event) { + if (d3_event.keyCode === 9 && !d3_event.shiftKey && section.selection().selectAll(".tag-list li:last-child input.value").node() === this && utilGetSetValue(select_default2(this))) { + addTag(); + } + } + function bindTypeahead(key, value) { + if (isReadOnly(key.datum())) return; - var selection2 = context.surface().selectAll(".layer-notes .note-" + selectedNoteID); - if (selection2.empty()) { - var source = d3_event && d3_event.type === "zoom" && d3_event.sourceEvent; - if (drawn && source && (source.type === "pointermove" || source.type === "mousemove" || source.type === "touchmove")) { - context.enter(modeBrowse(context)); + if (Array.isArray(value.datum().value)) { + value.call(uiCombobox(context, "tag-value").minItems(1).fetcher(function(value2, callback) { + var keyString = utilGetSetValue(key); + if (!_tags[keyString]) + return; + var data = _tags[keyString].map(function(tagValue) { + if (!tagValue) { + return { + value: " ", + title: _t("inspector.empty"), + display: (selection2) => selection2.text("").classed("virtual-option", true).call(_t.append("inspector.empty")) + }; + } + return { + value: tagValue, + title: tagValue + }; + }); + callback(data); + })); + return; + } + var geometry = context.graph().geometry(_entityIDs[0]); + key.call(uiCombobox(context, "tag-key").fetcher(function(value2, callback) { + taginfo.keys({ + debounce: true, + geometry, + query: value2 + }, function(err, data) { + if (!err) { + const filtered = data.filter((d2) => _tags[d2.value] === void 0).filter((d2) => !(d2.value in _discardTags)).filter((d2) => !/_\d$/.test(d2)).filter((d2) => d2.value.toLowerCase().includes(value2.toLowerCase())); + callback(sort(value2, filtered)); + } + }); + })); + value.call(uiCombobox(context, "tag-value").fetcher(function(value2, callback) { + taginfo.values({ + debounce: true, + key: utilGetSetValue(key), + geometry, + query: value2 + }, function(err, data) { + if (!err) { + const filtered = data.filter((d2) => d2.value.toLowerCase().includes(value2.toLowerCase())); + callback(sort(value2, filtered)); + } + }); + }).caseSensitive(allowUpperCaseTagValues.test(utilGetSetValue(key)))); + function sort(value2, data) { + var sameletter = []; + var other = []; + for (var i3 = 0; i3 < data.length; i3++) { + if (data[i3].value.substring(0, value2.length) === value2) { + sameletter.push(data[i3]); + } else { + other.push(data[i3]); + } } - } else { - selection2.classed("selected", true); - context.selectedNoteID(selectedNoteID); + return sameletter.concat(other); } } - function esc() { - if (context.container().select(".combobox").size()) - return; - context.enter(modeBrowse(context)); + function unbind() { + var row = select_default2(this); + row.selectAll("input.key").call(uiCombobox.off, context); + row.selectAll("input.value").call(uiCombobox.off, context); } - mode.zoomToSelected = function() { - if (!services.osm) + function keyChange(d3_event, d2) { + if (select_default2(this).attr("readonly")) return; - var note = services.osm.getNote(selectedNoteID); - if (note) { - context.map().centerZoomEase(note.loc, 20); - } - }; - mode.newFeature = function(val) { - if (!arguments.length) - return _newFeature; - _newFeature = val; - return mode; - }; - mode.enter = function() { - var note = checkSelectedID(); - if (!note) + var kOld = d2.key; + if (_pendingChange && _pendingChange.hasOwnProperty(kOld) && _pendingChange[kOld] === void 0) return; - _behaviors.forEach(context.install); - _keybinding.on(_t("inspector.zoom_to.key"), mode.zoomToSelected).on("\u238B", esc, true); - select_default2(document).call(_keybinding); - selectNote(); - var sidebar = context.ui().sidebar; - sidebar.show(_noteEditor.note(note).newNote(_newFeature)); - sidebar.expand(sidebar.intersects(note.extent())); - context.map().on("drawn.select", selectNote); - }; - mode.exit = function() { - _behaviors.forEach(context.uninstall); - select_default2(document).call(_keybinding.unbind); - context.surface().selectAll(".layer-notes .selected").classed("selected hover", false); - context.map().on("drawn.select", null); - context.ui().sidebar.hide(); - context.selectedNoteID(null); - }; - return mode; - } - - // modules/modes/add_note.js - function modeAddNote(context) { - var mode = { - id: "add-note", - button: "note", - description: _t.append("modes.add_note.description"), - key: _t("modes.add_note.key") - }; - var behavior = behaviorDraw(context).on("click", add).on("cancel", cancel).on("finish", cancel); - function add(loc) { - var osm = services.osm; - if (!osm) + var kNew = context.cleanTagKey(this.value.trim()); + if (isReadOnly({ key: kNew })) { + this.value = kOld; return; - var note = osmNote({ loc, status: "open", comments: [] }); - osm.replaceNote(note); - context.map().pan([0, 0]); - context.selectedNoteID(note.id).enter(modeSelectNote(context, note.id).newFeature(true)); - } - function cancel() { - context.enter(modeBrowse(context)); - } - mode.enter = function() { - context.install(behavior); - }; - mode.exit = function() { - context.uninstall(behavior); - }; - return mode; - } - - // modules/modes/save.js - function modeSave(context) { - var mode = { id: "save" }; - var keybinding = utilKeybinding("modeSave"); - var commit = uiCommit(context).on("cancel", cancel); - var _conflictsUi; - var _location; - var _success; - var uploader = context.uploader().on("saveStarted.modeSave", function() { - keybindingOff(); - }).on("willAttemptUpload.modeSave", prepareForSuccess).on("progressChanged.modeSave", showProgress).on("resultNoChanges.modeSave", function() { - cancel(); - }).on("resultErrors.modeSave", showErrors).on("resultConflicts.modeSave", showConflicts).on("resultSuccess.modeSave", showSuccess); - function cancel() { - context.enter(modeBrowse(context)); - } - function showProgress(num, total) { - var modal = context.container().select(".loading-modal .modal-section"); - var progress = modal.selectAll(".progress").data([0]); - progress.enter().append("div").attr("class", "progress").merge(progress).text(_t("save.conflict_progress", { num, total })); - } - function showConflicts(changeset, conflicts, origChanges) { - var selection2 = context.container().select(".sidebar").append("div").attr("class", "sidebar-component"); - context.container().selectAll(".main-content").classed("active", true).classed("inactive", false); - _conflictsUi = uiConflicts(context).conflictList(conflicts).origChanges(origChanges).on("cancel", function() { - context.container().selectAll(".main-content").classed("active", false).classed("inactive", true); - selection2.remove(); - keybindingOn(); - uploader.cancelConflictResolution(); - }).on("save", function() { - context.container().selectAll(".main-content").classed("active", false).classed("inactive", true); - selection2.remove(); - uploader.processResolvedConflicts(changeset); - }); - selection2.call(_conflictsUi); - } - function showErrors(errors) { - keybindingOn(); - var selection2 = uiConfirm(context.container()); - selection2.select(".modal-section.header").append("h3").text(_t("save.error")); - addErrors(selection2, errors); - selection2.okButton(); - } - function addErrors(selection2, data) { - var message = selection2.select(".modal-section.message-text"); - var items = message.selectAll(".error-container").data(data); - var enter = items.enter().append("div").attr("class", "error-container"); - enter.append("a").attr("class", "error-description").attr("href", "#").classed("hide-toggle", true).text(function(d2) { - return d2.msg || _t("save.unknown_error_details"); - }).on("click", function(d3_event) { - d3_event.preventDefault(); - var error = select_default2(this); - var detail = select_default2(this.nextElementSibling); - var exp2 = error.classed("expanded"); - detail.style("display", exp2 ? "none" : "block"); - error.classed("expanded", !exp2); - }); - var details = enter.append("div").attr("class", "error-detail-container").style("display", "none"); - details.append("ul").attr("class", "error-detail-list").selectAll("li").data(function(d2) { - return d2.details || []; - }).enter().append("li").attr("class", "error-detail-item").text(function(d2) { - return d2; - }); - items.exit().remove(); + } + if (kNew && kNew !== kOld && _tags[kNew] !== void 0) { + this.value = kOld; + section.selection().selectAll(".tag-list input.value").each(function(d4) { + if (d4.key === kNew) { + var input = select_default2(this).node(); + input.focus(); + input.select(); + } + }); + return; + } + _pendingChange = _pendingChange || {}; + if (kOld) { + if (kOld === kNew) + return; + _pendingChange[kNew] = _pendingChange[kOld] || { oldKey: kOld }; + _pendingChange[kOld] = void 0; + } else { + let row = this.parentNode.parentNode; + let inputVal = select_default2(row).selectAll("input.value"); + let vNew = context.cleanTagValue(utilGetSetValue(inputVal)); + _pendingChange[kNew] = vNew; + utilGetSetValue(inputVal, vNew); + } + var existingKeyIndex = _orderedKeys.indexOf(kOld); + if (existingKeyIndex !== -1) + _orderedKeys[existingKeyIndex] = kNew; + d2.key = kNew; + this.value = kNew; + scheduleChange(); } - function showSuccess(changeset) { - commit.reset(); - var ui = _success.changeset(changeset).location(_location).on("cancel", function() { - context.ui().sidebar.hide(); - }); - context.enter(modeBrowse(context).sidebar(ui)); + function valueChange(d3_event, d2) { + if (isReadOnly(d2)) + return; + if (typeof d2.value !== "string" && !this.value) + return; + if (!this.value.trim()) + return removeTag(d3_event, d2); + if (_pendingChange && _pendingChange.hasOwnProperty(d2.key) && _pendingChange[d2.key] === void 0) + return; + _pendingChange = _pendingChange || {}; + _pendingChange[d2.key] = context.cleanTagValue(this.value); + scheduleChange(); } - function keybindingOn() { - select_default2(document).call(keybinding.on("\u238B", cancel, true)); + function removeTag(d3_event, d2) { + if (isReadOnly(d2)) + return; + if (d2.key === "") { + _showBlank = false; + section.reRender(); + } else { + _orderedKeys = _orderedKeys.filter(function(key) { + return key !== d2.key; + }); + _pendingChange = _pendingChange || {}; + _pendingChange[d2.key] = void 0; + scheduleChange(); + } } - function keybindingOff() { - select_default2(document).call(keybinding.unbind); + function addTag() { + window.setTimeout(function() { + _showBlank = true; + section.reRender(); + section.selection().selectAll(".tag-list li:last-child input.key").node().focus(); + }, 20); } - function prepareForSuccess() { - _success = uiSuccess(context); - _location = null; - if (!services.geocoder) - return; - services.geocoder.reverse(context.map().center(), function(err, result) { - if (err || !result || !result.address) + function scheduleChange() { + var entityIDs = _entityIDs; + window.setTimeout(function() { + if (!_pendingChange) return; - var addr = result.address; - var place = addr && (addr.town || addr.city || addr.county) || ""; - var region = addr && (addr.state || addr.country) || ""; - var separator = place && region ? _t("success.thank_you_where.separator") : ""; - _location = _t( - "success.thank_you_where.format", - { place, separator, region } - ); - }); + dispatch14.call("change", this, entityIDs, _pendingChange); + _pendingChange = null; + }, 10); } - mode.selectedIDs = function() { - return _conflictsUi ? _conflictsUi.shownEntityIds() : []; - }; - mode.enter = function() { - context.ui().sidebar.expand(); - function done() { - context.ui().sidebar.show(commit); - } - keybindingOn(); - context.container().selectAll(".main-content").classed("active", false).classed("inactive", true); - var osm = context.connection(); - if (!osm) { - cancel(); - return; + section.state = function(val) { + if (!arguments.length) + return _state; + if (_state !== val) { + _orderedKeys = []; + _state = val; } - if (osm.authenticated()) { - done(); - } else { - osm.authenticate(function(err) { - if (err) { - cancel(); - } else { - done(); - } - }); + return section; + }; + section.presets = function(val) { + if (!arguments.length) + return _presets; + _presets = val; + if (_presets && _presets.length && _presets[0].isFallback()) { + section.disclosureExpanded(true); + } else if (!_didInteract) { + section.disclosureExpanded(null); } + return section; }; - mode.exit = function() { - keybindingOff(); - context.container().selectAll(".main-content").classed("active", true).classed("inactive", false); - context.ui().sidebar.hide(); + section.tags = function(val) { + if (!arguments.length) + return _tags; + _tags = val; + return section; }; - return mode; + section.entityIDs = function(val) { + if (!arguments.length) + return _entityIDs; + if (!_entityIDs || !val || !utilArrayIdentical(_entityIDs, val)) { + _entityIDs = val; + _orderedKeys = []; + } + return section; + }; + section.readOnlyTags = function(val) { + if (!arguments.length) + return _readOnlyTags; + _readOnlyTags = val; + return section; + }; + return utilRebind(section, dispatch14, "on"); } - // modules/modes/select_error.js - function modeSelectError(context, selectedErrorID, selectedErrorService) { - var mode = { - id: "select-error", - button: "browse" - }; - var keybinding = utilKeybinding("select-error"); - var errorService = services[selectedErrorService]; - var errorEditor; - switch (selectedErrorService) { - case "improveOSM": - errorEditor = uiImproveOsmEditor(context).on("change", function() { - context.map().pan([0, 0]); - var error = checkSelectedID(); - if (!error) - return; - context.ui().sidebar.show(errorEditor.error(error)); - }); - break; - case "keepRight": - errorEditor = uiKeepRightEditor(context).on("change", function() { - context.map().pan([0, 0]); - var error = checkSelectedID(); - if (!error) - return; - context.ui().sidebar.show(errorEditor.error(error)); - }); - break; - case "osmose": - errorEditor = uiOsmoseEditor(context).on("change", function() { - context.map().pan([0, 0]); - var error = checkSelectedID(); - if (!error) - return; - context.ui().sidebar.show(errorEditor.error(error)); - }); - break; - } - var behaviors = [ - behaviorBreathe(context), - behaviorHover(context), - behaviorSelect(context), - behaviorLasso(context), - modeDragNode(context).behavior, - modeDragNote(context).behavior - ]; - function checkSelectedID() { - if (!errorService) - return; - var error = errorService.getError(selectedErrorID); - if (!error) { + // modules/ui/data_editor.js + function uiDataEditor(context) { + var dataHeader = uiDataHeader(); + var rawTagEditor = uiSectionRawTagEditor("custom-data-tag-editor", context).expandedByDefault(true).readOnlyTags([/./]); + var _datum; + function dataEditor(selection2) { + var header = selection2.selectAll(".header").data([0]); + var headerEnter = header.enter().append("div").attr("class", "header fillL"); + headerEnter.append("button").attr("class", "close").attr("title", _t("icons.close")).on("click", function() { context.enter(modeBrowse(context)); - } - return error; + }).call(svgIcon("#iD-icon-close")); + headerEnter.append("h2").call(_t.append("map_data.title")); + var body = selection2.selectAll(".body").data([0]); + body = body.enter().append("div").attr("class", "body").merge(body); + var editor = body.selectAll(".data-editor").data([0]); + editor.enter().append("div").attr("class", "modal-section data-editor").merge(editor).call(dataHeader.datum(_datum)); + var rte = body.selectAll(".raw-tag-editor").data([0]); + rte.enter().append("div").attr("class", "raw-tag-editor data-editor").merge(rte).call( + rawTagEditor.tags(_datum && _datum.properties || {}).state("hover").render + ).selectAll("textarea.tag-text").attr("readonly", true).classed("readonly", true); } - mode.zoomToSelected = function() { - if (!errorService) - return; - var error = errorService.getError(selectedErrorID); - if (error) { - context.map().centerZoomEase(error.loc, 20); - } + dataEditor.datum = function(val) { + if (!arguments.length) + return _datum; + _datum = val; + return this; }; - mode.enter = function() { - var error = checkSelectedID(); - if (!error) - return; - behaviors.forEach(context.install); - keybinding.on(_t("inspector.zoom_to.key"), mode.zoomToSelected).on("\u238B", esc, true); - select_default2(document).call(keybinding); - selectError(); - var sidebar = context.ui().sidebar; - sidebar.show(errorEditor.error(error)); - context.map().on("drawn.select-error", selectError); - function selectError(d3_event, drawn) { - if (!checkSelectedID()) + return dataEditor; + } + + // modules/ui/sidebar.js + function uiSidebar(context) { + var inspector = uiInspector(context); + var dataEditor = uiDataEditor(context); + var noteEditor = uiNoteEditor(context); + var improveOsmEditor = uiImproveOsmEditor(context); + var keepRightEditor = uiKeepRightEditor(context); + var osmoseEditor = uiOsmoseEditor(context); + var _current; + var _wasData = false; + var _wasNote = false; + var _wasQaItem = false; + var _pointerPrefix = "PointerEvent" in window ? "pointer" : "mouse"; + function sidebar(selection2) { + var container = context.container(); + var minWidth = 240; + var sidebarWidth; + var containerWidth; + var dragOffset; + selection2.style("min-width", minWidth + "px").style("max-width", "400px").style("width", "33.3333%"); + var resizer = selection2.append("div").attr("class", "sidebar-resizer").on(_pointerPrefix + "down.sidebar-resizer", pointerdown); + var downPointerId, lastClientX, containerLocGetter; + function pointerdown(d3_event) { + if (downPointerId) return; - var selection2 = context.surface().selectAll(".itemId-" + selectedErrorID + "." + selectedErrorService); - if (selection2.empty()) { - var source = d3_event && d3_event.type === "zoom" && d3_event.sourceEvent; - if (drawn && source && (source.type === "pointermove" || source.type === "mousemove" || source.type === "touchmove")) { - context.enter(modeBrowse(context)); + if ("button" in d3_event && d3_event.button !== 0) + return; + downPointerId = d3_event.pointerId || "mouse"; + lastClientX = d3_event.clientX; + containerLocGetter = utilFastMouse(container.node()); + dragOffset = utilFastMouse(resizer.node())(d3_event)[0] - 1; + sidebarWidth = selection2.node().getBoundingClientRect().width; + containerWidth = container.node().getBoundingClientRect().width; + var widthPct = sidebarWidth / containerWidth * 100; + selection2.style("width", widthPct + "%").style("max-width", "85%"); + resizer.classed("dragging", true); + select_default2(window).on("touchmove.sidebar-resizer", function(d3_event2) { + d3_event2.preventDefault(); + }, { passive: false }).on(_pointerPrefix + "move.sidebar-resizer", pointermove).on(_pointerPrefix + "up.sidebar-resizer pointercancel.sidebar-resizer", pointerup); + } + function pointermove(d3_event) { + if (downPointerId !== (d3_event.pointerId || "mouse")) + return; + d3_event.preventDefault(); + var dx = d3_event.clientX - lastClientX; + lastClientX = d3_event.clientX; + var isRTL = _mainLocalizer.textDirection() === "rtl"; + var scaleX = isRTL ? 0 : 1; + var xMarginProperty = isRTL ? "margin-right" : "margin-left"; + var x2 = containerLocGetter(d3_event)[0] - dragOffset; + sidebarWidth = isRTL ? containerWidth - x2 : x2; + var isCollapsed = selection2.classed("collapsed"); + var shouldCollapse = sidebarWidth < minWidth; + selection2.classed("collapsed", shouldCollapse); + if (shouldCollapse) { + if (!isCollapsed) { + selection2.style(xMarginProperty, "-400px").style("width", "400px"); + context.ui().onResize([(sidebarWidth - dx) * scaleX, 0]); } } else { - selection2.classed("selected", true); - context.selectedErrorID(selectedErrorID); + var widthPct = sidebarWidth / containerWidth * 100; + selection2.style(xMarginProperty, null).style("width", widthPct + "%"); + if (isCollapsed) { + context.ui().onResize([-sidebarWidth * scaleX, 0]); + } else { + context.ui().onResize([-dx * scaleX, 0]); + } } } - function esc() { - if (context.container().select(".combobox").size()) + function pointerup(d3_event) { + if (downPointerId !== (d3_event.pointerId || "mouse")) return; - context.enter(modeBrowse(context)); + downPointerId = null; + resizer.classed("dragging", false); + select_default2(window).on("touchmove.sidebar-resizer", null).on(_pointerPrefix + "move.sidebar-resizer", null).on(_pointerPrefix + "up.sidebar-resizer pointercancel.sidebar-resizer", null); + } + var featureListWrap = selection2.append("div").attr("class", "feature-list-pane").call(uiFeatureList(context)); + var inspectorWrap = selection2.append("div").attr("class", "inspector-hidden inspector-wrap"); + var hoverModeSelect = function(targets) { + context.container().selectAll(".feature-list-item button").classed("hover", false); + if (context.selectedIDs().length > 1 && targets && targets.length) { + var elements = context.container().selectAll(".feature-list-item button").filter(function(node) { + return targets.indexOf(node) !== -1; + }); + if (!elements.empty()) { + elements.classed("hover", true); + } + } + }; + sidebar.hoverModeSelect = throttle_default(hoverModeSelect, 200); + function hover(targets) { + var datum2 = targets && targets.length && targets[0]; + if (datum2 && datum2.__featurehash__) { + _wasData = true; + sidebar.show(dataEditor.datum(datum2)); + selection2.selectAll(".sidebar-component").classed("inspector-hover", true); + } else if (datum2 instanceof osmNote) { + if (context.mode().id === "drag-note") + return; + _wasNote = true; + var osm = services.osm; + if (osm) { + datum2 = osm.getNote(datum2.id); + } + sidebar.show(noteEditor.note(datum2)); + selection2.selectAll(".sidebar-component").classed("inspector-hover", true); + } else if (datum2 instanceof QAItem) { + _wasQaItem = true; + var errService = services[datum2.service]; + if (errService) { + datum2 = errService.getError(datum2.id); + } + var errEditor; + if (datum2.service === "keepRight") { + errEditor = keepRightEditor; + } else if (datum2.service === "osmose") { + errEditor = osmoseEditor; + } else { + errEditor = improveOsmEditor; + } + context.container().selectAll(".qaItem." + datum2.service).classed("hover", function(d2) { + return d2.id === datum2.id; + }); + sidebar.show(errEditor.error(datum2)); + selection2.selectAll(".sidebar-component").classed("inspector-hover", true); + } else if (!_current && datum2 instanceof osmEntity) { + featureListWrap.classed("inspector-hidden", true); + inspectorWrap.classed("inspector-hidden", false).classed("inspector-hover", true); + if (!inspector.entityIDs() || !utilArrayIdentical(inspector.entityIDs(), [datum2.id]) || inspector.state() !== "hover") { + inspector.state("hover").entityIDs([datum2.id]).newFeature(false); + inspectorWrap.call(inspector); + } + } else if (!_current) { + featureListWrap.classed("inspector-hidden", false); + inspectorWrap.classed("inspector-hidden", true); + inspector.state("hide"); + } else if (_wasData || _wasNote || _wasQaItem) { + _wasNote = false; + _wasData = false; + _wasQaItem = false; + context.container().selectAll(".note").classed("hover", false); + context.container().selectAll(".qaItem").classed("hover", false); + sidebar.hide(); + } } + sidebar.hover = throttle_default(hover, 200); + sidebar.intersects = function(extent) { + var rect = selection2.node().getBoundingClientRect(); + return extent.intersects([ + context.projection.invert([0, rect.height]), + context.projection.invert([rect.width, 0]) + ]); + }; + sidebar.select = function(ids, newFeature) { + sidebar.hide(); + if (ids && ids.length) { + var entity = ids.length === 1 && context.entity(ids[0]); + if (entity && newFeature && selection2.classed("collapsed")) { + var extent = entity.extent(context.graph()); + sidebar.expand(sidebar.intersects(extent)); + } + featureListWrap.classed("inspector-hidden", true); + inspectorWrap.classed("inspector-hidden", false).classed("inspector-hover", false); + inspector.state("select").entityIDs(ids).newFeature(newFeature); + inspectorWrap.call(inspector); + } else { + inspector.state("hide"); + } + }; + sidebar.showPresetList = function() { + inspector.showList(); + }; + sidebar.show = function(component, element) { + featureListWrap.classed("inspector-hidden", true); + inspectorWrap.classed("inspector-hidden", true); + if (_current) + _current.remove(); + _current = selection2.append("div").attr("class", "sidebar-component").call(component, element); + }; + sidebar.hide = function() { + featureListWrap.classed("inspector-hidden", false); + inspectorWrap.classed("inspector-hidden", true); + if (_current) + _current.remove(); + _current = null; + }; + sidebar.expand = function(moveMap) { + if (selection2.classed("collapsed")) { + sidebar.toggle(moveMap); + } + }; + sidebar.collapse = function(moveMap) { + if (!selection2.classed("collapsed")) { + sidebar.toggle(moveMap); + } + }; + sidebar.toggle = function(moveMap) { + if (context.inIntro()) + return; + var isCollapsed = selection2.classed("collapsed"); + var isCollapsing = !isCollapsed; + var isRTL = _mainLocalizer.textDirection() === "rtl"; + var scaleX = isRTL ? 0 : 1; + var xMarginProperty = isRTL ? "margin-right" : "margin-left"; + sidebarWidth = selection2.node().getBoundingClientRect().width; + selection2.style("width", sidebarWidth + "px"); + var startMargin, endMargin, lastMargin; + if (isCollapsing) { + startMargin = lastMargin = 0; + endMargin = -sidebarWidth; + } else { + startMargin = lastMargin = -sidebarWidth; + endMargin = 0; + } + if (!isCollapsing) { + selection2.classed("collapsed", isCollapsing); + } + selection2.transition().style(xMarginProperty, endMargin + "px").tween("panner", function() { + var i3 = number_default(startMargin, endMargin); + return function(t2) { + var dx = lastMargin - Math.round(i3(t2)); + lastMargin = lastMargin - dx; + context.ui().onResize(moveMap ? void 0 : [dx * scaleX, 0]); + }; + }).on("end", function() { + if (isCollapsing) { + selection2.classed("collapsed", isCollapsing); + } + if (!isCollapsing) { + var containerWidth2 = container.node().getBoundingClientRect().width; + var widthPct = sidebarWidth / containerWidth2 * 100; + selection2.style(xMarginProperty, null).style("width", widthPct + "%"); + } + }); + }; + resizer.on("dblclick", function(d3_event) { + d3_event.preventDefault(); + if (d3_event.sourceEvent) { + d3_event.sourceEvent.preventDefault(); + } + sidebar.toggle(); + }); + context.map().on("crossEditableZoom.sidebar", function(within) { + if (!within && !selection2.select(".inspector-hover").empty()) { + hover([]); + } + }); + } + sidebar.showPresetList = function() { }; - mode.exit = function() { - behaviors.forEach(context.uninstall); - select_default2(document).call(keybinding.unbind); - context.surface().selectAll(".qaItem.selected").classed("selected hover", false); - context.map().on("drawn.select-error", null); - context.ui().sidebar.hide(); - context.selectedErrorID(null); - context.features().forceVisible([]); + sidebar.hover = function() { }; - return mode; + sidebar.hover.cancel = function() { + }; + sidebar.intersects = function() { + }; + sidebar.select = function() { + }; + sidebar.show = function() { + }; + sidebar.hide = function() { + }; + sidebar.expand = function() { + }; + sidebar.collapse = function() { + }; + sidebar.toggle = function() { + }; + return sidebar; } // modules/ui/tools/modes.js @@ -72138,8 +74685,8 @@ }); var debouncedUpdate = debounce_default(update, 500, { leading: true, trailing: true }); context.map().on("move.undo_redo", debouncedUpdate).on("drawn.undo_redo", debouncedUpdate); - context.history().on("change.undo_redo", function(difference) { - if (difference) + context.history().on("change.undo_redo", function(difference2) { + if (difference2) update(); }); context.on("enter.undo_redo", update); @@ -72330,9 +74877,9 @@ }; pane.renderPane = function(selection2) { _paneSelection = selection2.append("div").attr("class", "fillL map-pane hide " + id2 + "-pane").attr("pane", id2); - var heading = _paneSelection.append("div").attr("class", "pane-heading"); - heading.append("h2").text("").call(_label); - heading.append("button").attr("title", _t("icons.close")).on("click", hidePane).call(svgIcon("#iD-icon-close")); + var heading2 = _paneSelection.append("div").attr("class", "pane-heading"); + heading2.append("h2").text("").call(_label); + heading2.append("button").attr("title", _t("icons.close")).on("click", hidePane).call(svgIcon("#iD-icon-close")); _paneSelection.append("div").attr("class", "pane-content").call(pane.renderContent); if (_key) { context.keybinding().on(_key, pane.togglePane); @@ -72429,7 +74976,7 @@ var _currSettings = { template: corePreferences("background-custom-template") }; - var example = "https://{switch:a,b,c}.tile.openstreetmap.org/{zoom}/{x}/{y}.png"; + var example = "https://tile.openstreetmap.org/{zoom}/{x}/{y}.png"; var modal = uiConfirm(selection2).okButton(); modal.classed("settings-modal settings-custom-background", true); modal.select(".modal-section.header").append("h3").call(_t.append("settings.custom_background.header")); @@ -73018,7 +75565,7 @@ var docs = docKeys.map(function(key) { var helpkey = "help." + key[0]; var helpPaneReplacements = { version: context.version }; - var text2 = key[1].reduce(function(all, part) { + var text = key[1].reduce(function(all, part) { var subkey = helpkey + "." + part; var depth = headings[subkey]; var hhh = depth ? Array(depth + 1).join("#") + " " : ""; @@ -73026,7 +75573,7 @@ }, ""); return { title: _t.html(helpkey + ".title"), - content: marked(text2.trim()).replace(//g, "").replace(/<\/code>/g, "") + content: marked(text.trim()).replace(//g, "").replace(/<\/code>/g, "") }; }); var helpPane = uiPane("help", context).key(_t("help.key")).label(_t.append("help.title")).description(_t.append("help.title")).iconName("iD-icon-help"); @@ -73132,9 +75679,9 @@ selection2.call(drawIssuesList, issues); } function drawIssuesList(selection2, issues) { - var list = selection2.selectAll(".issues-list").data([0]); - list = list.enter().append("ul").attr("class", "layer-list issues-list " + severity + "s-list").merge(list); - var items = list.selectAll("li").data(issues, function(d2) { + var list2 = selection2.selectAll(".issues-list").data([0]); + list2 = list2.enter().append("ul").attr("class", "layer-list issues-list " + severity + "s-list").merge(list2); + var items = list2.selectAll("li").data(issues, function(d2) { return d2.key; }); items.exit().remove(); @@ -73867,12 +76414,12 @@ context.layers().on("change", () => updatePhotoList(photoList.select("ul"))); } function updatePhotoList(container) { - var _a; + var _a2; function locationUnavailable(d2) { return !(isArray_default(d2.loc) && isNumber_default(d2.loc[0]) && isNumber_default(d2.loc[1])); } container.selectAll("li.placeholder").remove(); - let selection2 = container.selectAll("li").data((_a = photoLayer.getPhotos()) != null ? _a : [], (d2) => d2.id); + let selection2 = container.selectAll("li").data((_a2 = photoLayer.getPhotos()) != null ? _a2 : [], (d2) => d2.id); selection2.exit().remove(); const selectionEnter = selection2.enter().append("li"); selectionEnter.append("span").classed("filename", true); @@ -73929,8 +76476,8 @@ return layerSupported(d2) && d2.layer.enabled(); } function layerRendered(d2) { - var _a, _b, _c; - return (_c = (_b = (_a = d2.layer).rendered) == null ? void 0 : _b.call(_a, context.map().zoom())) != null ? _c : true; + var _a2, _b, _c; + return (_c = (_b = (_a2 = d2.layer).rendered) == null ? void 0 : _b.call(_a2, context.map().zoom())) != null ? _c : true; } var ul = selection2.selectAll(".layer-list-photos").data([0]); ul = ul.enter().append("ul").attr("class", "layer-list layer-list-photos").merge(ul); @@ -74439,9 +76986,9 @@ if (surfaceNode.focus) { surfaceNode.focus(); } - operations.forEach(function(operation) { - if (operation.point) - operation.point(anchorPoint); + operations.forEach(function(operation2) { + if (operation2.point) + operation2.point(anchorPoint); }); _editMenu.anchorLoc(anchorPoint).triggerType(triggerType).operations(operations); context.map().supersurface.call(_editMenu); @@ -74587,6 +77134,12 @@ _connection.loadEntityRelations(entityID, afterLoad(cid, callback)); } }; + context.loadNote = (entityID, callback) => { + if (_connection) { + const cid = _connection.getConnectionId(); + _connection.loadEntityNote(entityID, afterLoad(cid, callback)); + } + }; context.zoomToEntity = (entityID, zoomTo) => { context.loadEntity(entityID, (err, result) => { if (err) @@ -74984,11 +77537,11 @@ // node_modules/name-suggestion-index/lib/simplify.js var import_diacritics3 = __toESM(require_diacritics(), 1); - function simplify2(str2) { - if (typeof str2 !== "string") + function simplify2(str) { + if (typeof str !== "string") return ""; return import_diacritics3.default.remove( - str2.replace(/&/g, "and").replace(/İ/ig, "i").replace(/[\s\-=_!"#%'*{},.\/:;?\(\)\[\]@\\$\^*+<>«»~`’\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2000-\u206f\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00-\u2e7f\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\ufeff\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g, "").toLowerCase() + str.replace(/&/g, "and").replace(/İ/ig, "i").replace(/[\s\-=_!"#%'*{},.\/:;?\(\)\[\]@\\$\^*+<>«»~`’\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2000-\u206f\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00-\u2e7f\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\ufeff\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g, "").toLowerCase() ); } @@ -75746,6 +78299,17 @@ _mainFileFetcher.get("nsi_features") ]).then((vals) => { Object.values(vals[0].presets).forEach((preset) => preset.suggestion = true); + Object.values(vals[0].presets).forEach((preset) => { + if (preset.tags["brand:wikidata"]) { + preset.removeTags = { "brand:wikipedia": "*", ...preset.removeTags || preset.addTags || preset.tags }; + } + if (preset.tags["operator:wikidata"]) { + preset.removeTags = { "operator:wikipedia": "*", ...preset.removeTags || preset.addTags || preset.tags }; + } + if (preset.tags["network:wikidata"]) { + preset.removeTags = { "network:wikipedia": "*", ...preset.removeTags || preset.addTags || preset.tags }; + } + }); _mainPresetIndex.merge({ presets: vals[0].presets, featureCollection: vals[1] @@ -76032,8 +78596,8 @@ if (hits[0].match !== "primary" && hits[0].match !== "alternate") break; let itemID, item; - for (let j3 = 0; j3 < hits.length; j3++) { - const hit = hits[j3]; + for (let j2 = 0; j2 < hits.length; j2++) { + const hit = hits[j2]; itemID = hit.itemID; if (_nsi.dissolved[itemID]) continue; @@ -76686,7 +79250,7 @@ var _loadViewerPromise3; var _vegbilderCache; async function fetchAvailableLayers() { - var _a, _b, _c; + var _a2, _b, _c; const params = { service: "WFS", request: "GetCapabilities", @@ -76695,7 +79259,7 @@ const urlForRequest = owsEndpoint + utilQsString(params); const response = await xml_default(urlForRequest); const xPathSelector = "/wfs:WFS_Capabilities/wfs:FeatureTypeList/wfs:FeatureType/wfs:Name"; - const regexMatcher = new RegExp("^vegbilder_1_0:Vegbilder(?_360)?_(?\\d{4})$"); + const regexMatcher = /^vegbilder_1_0:Vegbilder(?_360)?_(?\d{4})$/; const NSResolver = response.createNSResolver(response); const l2 = response.evaluate( xPathSelector, @@ -76706,7 +79270,7 @@ let node; const availableLayers = []; while ((node = l2.iterateNext()) !== null) { - const match = (_a = node.textContent) == null ? void 0 : _a.match(regexMatcher); + const match = (_a2 = node.textContent) == null ? void 0 : _a2.match(regexMatcher); if (match) { availableLayers.push({ name: match[0], @@ -76767,7 +79331,7 @@ let featureCollection; try { featureCollection = await json_default(urlForRequest, options2); - } catch (e3) { + } catch { cache.loaded.set(tileid, false); return; } finally { @@ -77088,7 +79652,7 @@ // Reset is only necessary when interacting with the viewport because // this implicitly changes the currently selected bubble/sequence setStyles: function(context, hovered, reset) { - var _a, _b; + var _a2, _b; if (reset) { context.container().selectAll(".viewfield-group").classed("highlighted", false).classed("hovered", false).classed("currentView", false); context.container().selectAll(".sequence").classed("highlighted", false).classed("currentView", false); @@ -77096,7 +79660,7 @@ const hoveredImageKey = hovered == null ? void 0 : hovered.key; const hoveredSequence = this.getSequenceForImage(hovered); const hoveredSequenceKey = hoveredSequence == null ? void 0 : hoveredSequence.key; - const hoveredImageKeys = (_a = hoveredSequence == null ? void 0 : hoveredSequence.images.map((d2) => d2.key)) != null ? _a : []; + const hoveredImageKeys = (_a2 = hoveredSequence == null ? void 0 : hoveredSequence.images.map((d2) => d2.key)) != null ? _a2 : []; const viewer = context.container().select(".photoviewer"); const selected = viewer.empty() ? void 0 : viewer.datum(); const selectedImageKey = selected == null ? void 0 : selected.key; @@ -77138,9 +79702,28 @@ }; // node_modules/osm-auth/src/osm-auth.mjs - var import_store = __toESM(require_store_legacy(), 1); function osmAuth(o2) { var oauth2 = {}; + var _store = null; + try { + _store = window.localStorage; + } catch (e3) { + var _mock = /* @__PURE__ */ new Map(); + _store = { + isMocked: true, + hasItem: (k2) => _mock.has(k2), + getItem: (k2) => _mock.get(k2), + setItem: (k2, v2) => _mock.set(k2, v2), + removeItem: (k2) => _mock.delete(k2), + clear: () => _mock.clear() + }; + } + function token(k2, v2) { + if (arguments.length === 1) + return _store.getItem(o2.url + k2); + else if (arguments.length === 2) + return _store.setItem(o2.url + k2, v2); + } oauth2.authenticated = function() { return !!token("oauth2_access_token"); }; @@ -77157,8 +79740,14 @@ return; } oauth2.logout(); - _generatePkceChallenge(function(pkce) { - _authenticate(pkce, callback); + _preopenPopup(function(error, popup) { + if (error) { + callback(error); + } else { + _generatePkceChallenge(function(pkce) { + _authenticate(pkce, popup, callback); + }); + } }); }; oauth2.authenticateAsync = function() { @@ -77169,15 +79758,45 @@ return new Promise((resolve, reject) => { var errback = (err, result) => { if (err) { - reject(new Error(err)); + reject(err); } else { resolve(result); } }; - _generatePkceChallenge((pkce) => _authenticate(pkce, errback)); + _preopenPopup((error, popup) => { + if (error) { + errback(error); + } else { + _generatePkceChallenge((pkce) => _authenticate(pkce, popup, errback)); + } + }); }); }; - function _authenticate(pkce, callback) { + function _preopenPopup(callback) { + if (o2.singlepage) { + callback(null, void 0); + return; + } + var w2 = 550; + var h2 = 610; + var settings = [ + ["width", w2], + ["height", h2], + ["left", window.screen.width / 2 - w2 / 2], + ["top", window.screen.height / 2 - h2 / 2] + ].map(function(x2) { + return x2.join("="); + }).join(","); + var popup = window.open("about:blank", "oauth_window", settings); + if (popup) { + callback(null, popup); + } else { + var error = new Error("Popup was blocked"); + error.status = "popup-blocked"; + callback(error); + } + } + function _authenticate(pkce, popup, callback) { var state = generateState(); var url = o2.url + "/oauth2/authorize?" + utilQsString2({ client_id: o2.client_id, @@ -77189,8 +79808,8 @@ code_challenge_method: pkce.code_challenge_method }); if (o2.singlepage) { - if (!import_store.default.enabled) { - var error = new Error("local storage unavailable, but require in singlepage mode"); + if (_store.isMocked) { + var error = new Error("localStorage unavailable, but required in singlepage mode"); error.status = "pkce-localstorage-unavailable"; callback(error); return; @@ -77204,24 +79823,8 @@ window.location = url; } } else { - var w2 = 600; - var h2 = 550; - var settings = [ - ["width", w2], - ["height", h2], - ["left", window.screen.width / 2 - w2 / 2], - ["top", window.screen.height / 2 - h2 / 2] - ].map(function(x2) { - return x2.join("="); - }).join(","); - var popup = window.open("about:blank", "oauth_window", settings); oauth2.popupWindow = popup; popup.location = url; - if (!popup) { - error = new Error("Popup was blocked"); - error.status = "popup-blocked"; - callback(error); - } } window.authComplete = function(url2) { var params2 = utilStringQs2(url2.split("?")[1]); @@ -77323,7 +79926,7 @@ } } function _doXHR() { - var url = options2.prefix !== false ? o2.url + options2.path : options2.path; + var url = options2.prefix !== false ? o2.apiUrl + options2.path : options2.path; return oauth2.rawxhr( options2.method, url, @@ -77377,6 +79980,7 @@ if (!arguments.length) return o2; o2 = val; + o2.apiUrl = o2.apiUrl || "https://api.openstreetmap.org"; o2.url = o2.url || "https://www.openstreetmap.org"; o2.auto = o2.auto || false; o2.singlepage = o2.singlepage || false; @@ -77386,23 +79990,6 @@ }; return oauth2.preauth(o2); }; - var token; - if (import_store.default.enabled) { - token = function(x2, y2) { - if (arguments.length === 1) - return import_store.default.get(o2.url + x2); - else if (arguments.length === 2) - return import_store.default.set(o2.url + x2, y2); - }; - } else { - var storage = {}; - token = function(x2, y2) { - if (arguments.length === 1) - return storage[o2.url + x2]; - else if (arguments.length === 2) - return storage[o2.url + x2] = y2; - }; - } oauth2.options(o2); return oauth2; } @@ -77413,12 +80000,12 @@ return encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]); }).join("&"); } - function utilStringQs2(str2) { + function utilStringQs2(str) { var i3 = 0; - while (i3 < str2.length && (str2[i3] === "?" || str2[i3] === "#")) + while (i3 < str.length && (str[i3] === "?" || str[i3] === "#")) i3++; - str2 = str2.slice(i3); - return str2.split("&").reduce(function(obj, pair3) { + str = str.slice(i3); + return str.split("&").reduce(function(obj, pair3) { var parts = pair3.split("="); if (parts.length === 2) { obj[parts[0]] = decodeURIComponent(parts[1]); @@ -77485,6 +80072,7 @@ var redirectPath = window.location.origin + window.location.pathname; var oauth = osmAuth({ url: urlroot, + apiUrl: apiUrlroot, client_id: osmApiConnections[0].client_id, client_secret: osmApiConnections[0].client_secret, scope: "read_prefs write_prefs write_api read_gpx write_notes", @@ -77600,8 +80188,8 @@ if (comment.nodeName === "comment") { var childNodes = comment.childNodes; var parsedComment = {}; - for (var j3 = 0; j3 < childNodes.length; j3++) { - var node = childNodes[j3]; + for (var j2 = 0; j2 < childNodes.length; j2++) { + var node = childNodes[j2]; var nodeName = node.nodeName; if (nodeName === "#text") continue; @@ -77801,15 +80389,19 @@ var props = {}; props.id = uid; props.loc = getLoc(attrs); - var coincident = false; - var epsilon3 = 1e-5; - do { - if (coincident) { - props.loc = geoVecAdd(props.loc, [epsilon3, epsilon3]); - } - var bbox2 = geoExtent(props.loc).bbox(); - coincident = _noteCache.rtree.search(bbox2).length; - } while (coincident); + if (!_noteCache.note[uid]) { + let coincident = false; + const epsilon3 = 1e-5; + do { + if (coincident) { + props.loc = geoVecAdd(props.loc, [epsilon3, epsilon3]); + } + const bbox2 = geoExtent(props.loc).bbox(); + coincident = _noteCache.rtree.search(bbox2).length; + } while (coincident); + } else { + props.loc = _noteCache.note[uid].loc; + } for (var i3 = 0; i3 < childNodes.length; i3++) { var node = childNodes[i3]; var nodeName = node.nodeName; @@ -77824,7 +80416,7 @@ var note = new osmNote(props); var item = encodeNoteRtree(note); _noteCache.note[note.id] = note; - _noteCache.rtree.insert(item); + updateRtree4(item, true); return note; }, user: function parseUser2(obj, uid) { @@ -77952,12 +80544,15 @@ getUrlRoot: function() { return urlroot; }, + getApiUrlRoot: function() { + return apiUrlroot; + }, changesetURL: function(changesetID) { return urlroot + "/changeset/" + changesetID; }, changesetsURL: function(center, zoom) { - var precision2 = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)); - return urlroot + "/history#map=" + Math.floor(zoom) + "/" + center[1].toFixed(precision2) + "/" + center[0].toFixed(precision2); + var precision3 = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)); + return urlroot + "/history#map=" + Math.floor(zoom) + "/" + center[1].toFixed(precision3) + "/" + center[0].toFixed(precision3); }, entityURL: function(entity) { return urlroot + "/" + entity.type + "/" + entity.osmId(); @@ -78014,8 +80609,7 @@ if (this.authenticated()) { return oauth.xhr({ method: "GET", - prefix: false, - path: apiUrlroot + path + path }, done); } else { var url = apiUrlroot + path; @@ -78058,6 +80652,19 @@ options2 ); }, + // Load a single note by id , XML format + // GET /api/0.6/notes/#id + loadEntityNote: function(id2, callback) { + var options2 = { skipSeen: false }; + this.loadFromAPI( + "/api/0.6/notes/" + id2, + function(err, entities) { + if (callback) + callback(err, { data: entities }); + }, + options2 + ); + }, // Load a single entity with a specific version // GET /api/0.6/[node|way|relation]/#id/#version loadEntityVersion: function(id2, version, callback) { @@ -78126,8 +80733,7 @@ } else { var options2 = { method: "PUT", - prefix: false, - path: apiUrlroot + "/api/0.6/changeset/create", + path: "/api/0.6/changeset/create", headers: { "Content-Type": "text/xml" }, content: JXON.stringify(changeset.asJXON()) }; @@ -78145,8 +80751,7 @@ changeset = changeset.update({ id: changesetID }); var options3 = { method: "POST", - prefix: false, - path: apiUrlroot + "/api/0.6/changeset/" + changesetID + "/upload", + path: "/api/0.6/changeset/" + changesetID + "/upload", headers: { "Content-Type": "text/xml" }, content: JXON.stringify(changeset.osmChangeJXON(changes)) }; @@ -78166,8 +80771,7 @@ if (this.getConnectionId() === cid) { oauth.xhr({ method: "PUT", - prefix: false, - path: apiUrlroot + "/api/0.6/changeset/" + changeset.id + "/close", + path: "/api/0.6/changeset/" + changeset.id + "/close", headers: { "Content-Type": "text/xml" } }, function() { return true; @@ -78197,8 +80801,7 @@ utilArrayChunk(toLoad, 150).forEach((function(arr) { oauth.xhr({ method: "GET", - prefix: false, - path: apiUrlroot + "/api/0.6/users.json?users=" + arr.join() + path: "/api/0.6/users.json?users=" + arr.join() }, wrapcb(this, done, _connectionID)); }).bind(this)); function done(err, payload) { @@ -78221,8 +80824,7 @@ } oauth.xhr({ method: "GET", - prefix: false, - path: apiUrlroot + "/api/0.6/user/" + uid + ".json" + path: "/api/0.6/user/" + uid + ".json" }, wrapcb(this, done, _connectionID)); function done(err, payload) { if (err) @@ -78243,8 +80845,7 @@ } oauth.xhr({ method: "GET", - prefix: false, - path: apiUrlroot + "/api/0.6/user/details.json" + path: "/api/0.6/user/details.json" }, wrapcb(this, done, _connectionID)); function done(err, payload) { if (err) @@ -78273,8 +80874,7 @@ } oauth.xhr({ method: "GET", - prefix: false, - path: apiUrlroot + "/api/0.6/changesets?user=" + user.id + path: "/api/0.6/changesets?user=" + user.id }, wrapcb(this, done, _connectionID)); } function done(err, xml) { @@ -78476,8 +81076,7 @@ var path = "/api/0.6/notes?" + utilQsString({ lon: note.loc[0], lat: note.loc[1], text: comment }); _noteCache.inflightPost[note.id] = oauth.xhr({ method: "POST", - prefix: false, - path: urlroot + path + path }, wrapcb(this, done, _connectionID)); function done(err, xml) { delete _noteCache.inflightPost[note.id]; @@ -78522,8 +81121,7 @@ } _noteCache.inflightPost[note.id] = oauth.xhr({ method: "POST", - prefix: false, - path: urlroot + path + path }, wrapcb(this, done, _connectionID)); function done(err, xml) { delete _noteCache.inflightPost[note.id]; @@ -78556,8 +81154,14 @@ switch: function(newOptions) { urlroot = newOptions.url; apiUrlroot = newOptions.apiUrl || urlroot; - var oldOptions = utilObjectOmit(oauth.options(), "access_token"); - oauth.options(Object.assign(oldOptions, newOptions)); + if (newOptions.url && !newOptions.apiUrl) { + newOptions = { + ...newOptions, + apiUrl: newOptions.url + }; + } + const oldOptions = utilObjectOmit(oauth.options(), "access_token"); + oauth.options({ ...oldOptions, ...newOptions }); this.reset(); this.userChangesets(function() { }); @@ -78949,8 +81553,8 @@ var wikis = [rtypeWiki, tagWiki, keyWiki]; for (i3 in wikis) { var wiki = wikis[i3]; - for (var j3 in langCodes) { - var code = langCodes[j3]; + for (var j2 in langCodes) { + var code = langCodes[j2]; var referenceId = langCodes[0].split("-")[0] !== "en" && code.split("-")[0] === "en" ? "inspector.wiki_en_reference" : "inspector.wiki_reference"; var info = getWikiInfo(wiki, code, referenceId); if (info) { @@ -78986,64 +81590,11 @@ // modules/services/streetside.js var import_rbush11 = __toESM(require_rbush_min()); - - // modules/util/jsonp_request.js - var jsonpCache = {}; - window.jsonpCache = jsonpCache; - function jsonpRequest(url, callback) { - var request3 = { - abort: function() { - } - }; - if (window.JSONP_FIX) { - if (window.JSONP_DELAY === 0) { - callback(window.JSONP_FIX); - } else { - var t2 = window.setTimeout(function() { - callback(window.JSONP_FIX); - }, window.JSONP_DELAY || 0); - request3.abort = function() { - window.clearTimeout(t2); - }; - } - return request3; - } - function rand() { - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - var c2 = ""; - var i3 = -1; - while (++i3 < 15) - c2 += chars.charAt(Math.floor(Math.random() * 52)); - return c2; - } - function create2(url2) { - var e3 = url2.match(/callback=(\w+)/); - var c2 = e3 ? e3[1] : rand(); - jsonpCache[c2] = function(data) { - if (jsonpCache[c2]) { - callback(data); - } - finalize(); - }; - function finalize() { - delete jsonpCache[c2]; - script.remove(); - } - request3.abort = finalize; - return "jsonpCache." + c2; - } - var cb = create2(url); - var script = select_default2("head").append("script").attr("type", "text/javascript").attr("src", url.replace(/(\{|%7B)callback(\}|%7D)/, cb)); - return request3; - } - - // modules/services/streetside.js - var bubbleApi = "https://dev.virtualearth.net/mapcontrol/HumanScaleServices/GetBubbles.ashx?"; - var streetsideImagesApi = "https://t.ssl.ak.tiles.virtualearth.net/tiles/"; - var bubbleAppKey = "AuftgJsO0Xs8Ts4M1xZUQJQXJNsvmh3IV8DkNieCiy3tCwCUMq76-WpkrBtNAuEm"; + var streetsideApi = "https://dev.virtualearth.net/REST/v1/Imagery/MetaData/Streetside?mapArea={bbox}&key={key}&count={count}"; + var maxResults2 = 500; + var bubbleAppKey = utilAesDecrypt("5c875730b09c6b422433e807e1ff060b6536c791dbfffcffc4c6b18a1bdba1f14593d151adb50e19e1be1ab19aef813bf135d0f103475e5c724dec94389e45d0"); var pannellumViewerCSS2 = "pannellum/pannellum.css"; var pannellumViewerJS2 = "pannellum/pannellum.js"; - var maxResults2 = 2e3; var tileZoom3 = 16.5; var tiler7 = utilTiler().zoomExtent([tileZoom3, tileZoom3]).skipNullIsland(true); var dispatch11 = dispatch_default("loadedImages", "viewerChanged"); @@ -79097,37 +81648,37 @@ const id2 = tile.id + "," + String(nextPage); if (cache.loaded[id2] || cache.inflight[id2]) return; - cache.inflight[id2] = getBubbles(url, tile, (bubbles) => { + cache.inflight[id2] = getBubbles(url, tile, (response) => { cache.loaded[id2] = true; delete cache.inflight[id2]; - if (!bubbles) + if (!response) return; - bubbles.shift(); - const features = bubbles.map((bubble) => { - if (cache.points[bubble.id]) + if (response.resourceSets[0].resources.length === maxResults2) { + const split = tile.extent.split(); + loadNextTilePage2(which, url, { id: tile.id + ",a", extent: split[0] }); + loadNextTilePage2(which, url, { id: tile.id + ",b", extent: split[1] }); + loadNextTilePage2(which, url, { id: tile.id + ",c", extent: split[2] }); + loadNextTilePage2(which, url, { id: tile.id + ",d", extent: split[3] }); + } + const features = response.resourceSets[0].resources.map((bubble) => { + const bubbleId = bubble.imageUrl; + if (cache.points[bubbleId]) return null; - const loc = [bubble.lo, bubble.la]; + const loc = [bubble.lon, bubble.lat]; const d2 = { loc, - key: bubble.id, + key: bubbleId, + imageUrl: bubble.imageUrl.replace( + "{subdomain}", + bubble.imageUrlSubdomains[0] + ), ca: bubble.he, - captured_at: bubble.cd, + captured_at: bubble.vintageEnd, captured_by: "microsoft", - // nbn: bubble.nbn, - // pbn: bubble.pbn, - // ad: bubble.ad, - // rn: bubble.rn, - pr: bubble.pr, - // previous - ne: bubble.ne, - // next pano: true, sequenceKey: null }; - cache.points[bubble.id] = d2; - if (bubble.pr === void 0) { - cache.leaders.push(bubble.id); - } + cache.points[bubbleId] = d2; return { minX: loc[0], minY: loc[1], @@ -79137,67 +81688,32 @@ }; }).filter(Boolean); cache.rtree.load(features); - connectSequences(); if (which === "bubbles") { dispatch11.call("loadedImages"); } }); } - function connectSequences() { - let cache = _ssCache.bubbles; - let keepLeaders = []; - for (let i3 = 0; i3 < cache.leaders.length; i3++) { - let bubble = cache.points[cache.leaders[i3]]; - let seen = {}; - let sequence = { key: bubble.key, bubbles: [] }; - let complete = false; - do { - sequence.bubbles.push(bubble); - seen[bubble.key] = true; - if (bubble.ne === void 0) { - complete = true; - } else { - bubble = cache.points[bubble.ne]; - } - } while (bubble && !seen[bubble.key] && !complete); - if (complete) { - _ssCache.sequences[sequence.key] = sequence; - for (let j3 = 0; j3 < sequence.bubbles.length; j3++) { - sequence.bubbles[j3].sequenceKey = sequence.key; - } - sequence.geojson = { - type: "LineString", - properties: { - captured_at: sequence.bubbles[0] ? sequence.bubbles[0].captured_at : null, - captured_by: sequence.bubbles[0] ? sequence.bubbles[0].captured_by : null, - key: sequence.key - }, - coordinates: sequence.bubbles.map((d2) => d2.loc) - }; - } else { - keepLeaders.push(cache.leaders[i3]); - } - } - cache.leaders = keepLeaders; - } function getBubbles(url, tile, callback) { let rect = tile.extent.rectangle(); - let urlForRequest = url + utilQsString({ - n: rect[3], - s: rect[1], - e: rect[2], - w: rect[0], - c: maxResults2, - appkey: bubbleAppKey, - jsCallback: "{callback}" - }); - return jsonpRequest(urlForRequest, (data) => { - if (!data || data.error) { + let urlForRequest = url.replace("{key}", bubbleAppKey).replace("{bbox}", [rect[1], rect[0], rect[3], rect[2]].join(",")).replace("{count}", maxResults2); + const controller = new AbortController(); + fetch(urlForRequest, { signal: controller.signal }).then(function(response) { + if (!response.ok) { + throw new Error(response.status + " " + response.statusText); + } + return response.json(); + }).then(function(result) { + if (!result) { callback(null); + } + return callback(result || []); + }).catch(function(err) { + if (err.name === "AbortError") { } else { - callback(data); + throw new Error(err); } }); + return controller; } function partitionViewport4(projection2) { let z2 = geoScaleToZoom(projection2.scale()); @@ -79636,7 +82152,7 @@ Object.values(_ssCache.bubbles.inflight).forEach(abortRequest6); } _ssCache = { - bubbles: { inflight: {}, loaded: {}, nextPage: {}, rtree: new import_rbush11.default(), points: {}, leaders: [] }, + bubbles: { inflight: {}, loaded: {}, nextPage: {}, rtree: new import_rbush11.default(), points: {} }, sequences: {} }; }, @@ -79672,7 +82188,7 @@ loadBubbles: function(projection2, margin) { if (margin === void 0) margin = 2; - loadTiles3("bubbles", bubbleApi, projection2, margin); + loadTiles3("bubbles", streetsideApi, projection2, margin); }, viewer: function() { return _pannellumViewer2; @@ -79872,13 +82388,6 @@ let line2 = attribution.append("div").attr("class", "attribution-row"); line2.append("a").attr("class", "image-view-link").attr("target", "_blank").attr("href", "https://www.bing.com/maps?cp=" + d2.loc[1] + "~" + d2.loc[0] + "&lvl=17&dir=" + d2.ca + "&style=x&v=2&sV=1").call(_t.append("streetside.view_on_bing")); line2.append("a").attr("class", "image-report-link").attr("target", "_blank").attr("href", "https://www.bing.com/maps/privacyreport/streetsideprivacyreport?bubbleid=" + encodeURIComponent(d2.key) + "&focus=photo&lat=" + d2.loc[1] + "&lng=" + d2.loc[0] + "&z=17").call(_t.append("streetside.report")); - let bubbleIdQuadKey = d2.key.toString(4); - const paddingNeeded = 16 - bubbleIdQuadKey.length; - for (let i3 = 0; i3 < paddingNeeded; i3++) { - bubbleIdQuadKey = "0" + bubbleIdQuadKey; - } - const imgUrlPrefix = streetsideImagesApi + "hs" + bubbleIdQuadKey; - const imgUrlSuffix = ".jpg?g=13515&n=z"; const faceKeys = ["01", "02", "03", "10", "11", "12"]; let quadKeys = getQuadKeys(); let faces = faceKeys.map((faceKey) => { @@ -79886,7 +82395,7 @@ const xy = qkToXY(quadKey); return { face: faceKey, - url: imgUrlPrefix + faceKey + quadKey + imgUrlSuffix, + url: d2.imageUrl.replace("{faceId}", faceKey).replace("{tileId}", quadKey), x: xy[0], y: xy[1] }; @@ -80157,8 +82666,8 @@ if (err) { callback(err); } else { - var f3 = filterKeys(params.filter); - var result = d2.data.filter(f3).sort(sortKeys).map(valKey); + var f2 = filterKeys(params.filter); + var result = d2.data.filter(f2).sort(sortKeys).map(valKey); _taginfoCache[url] = result; callback(null, result); } @@ -80180,8 +82689,8 @@ if (err) { callback(err); } else { - var f3 = filterMultikeys(prefix); - var result = d2.data.filter(f3).map(valKey); + var f2 = filterMultikeys(prefix); + var result = d2.data.filter(f2).map(valKey); _taginfoCache[url] = result; callback(null, result); } @@ -80208,8 +82717,8 @@ callback(err); } else { var allowUpperCase = allowUpperCaseTagValues.test(params.key); - var f3 = filterValues(allowUpperCase); - var result = d2.data.filter(f3).map(valKeyDescription); + var f2 = filterValues(allowUpperCase); + var result = d2.data.filter(f2).map(valKeyDescription); _taginfoCache[url] = result; callback(null, result); } @@ -80231,8 +82740,8 @@ if (err) { callback(err); } else { - var f3 = filterRoles(geometry); - var result = d2.data.filter(f3).map(roleKey); + var f2 = filterRoles(geometry); + var result = d2.data.filter(f2).map(roleKey); _taginfoCache[url] = result; callback(null, result); } @@ -80268,7 +82777,7 @@ // modules/services/vector_tile.js var import_fast_deep_equal11 = __toESM(require_fast_deep_equal()); var import_fast_json_stable_stringify2 = __toESM(require_fast_json_stable_stringify()); - var import_polygon_clipping2 = __toESM(require_polygon_clipping_umd()); + var import_polygon_clipping = __toESM(require_polygon_clipping_umd()); var import_pbf2 = __toESM(require_pbf()); var import_vector_tile2 = __toESM(require_vector_tile()); var tiler8 = utilTiler().tileSize(512).margin(1); @@ -80315,7 +82824,7 @@ var merged = mergeCache[propertyhash]; if (merged && merged.length) { var other = merged[0]; - var coords = import_polygon_clipping2.default.union( + var coords = import_polygon_clipping.default.union( feature3.geometry.coordinates, other.geometry.coordinates ); @@ -80323,9 +82832,9 @@ continue; } merged.push(feature3); - for (var j3 = 0; j3 < merged.length; j3++) { - merged[j3].geometry.coordinates = coords; - merged[j3].__featurehash__ = featurehash; + for (var j2 = 0; j2 < merged.length; j2++) { + merged[j2].geometry.coordinates = coords; + merged[j2].__featurehash__ = featurehash; } } else { mergeCache[propertyhash] = [feature3]; @@ -80398,8 +82907,8 @@ var features = source.loaded[tiles[i3].id]; if (!features || !features.length) continue; - for (var j3 = 0; j3 < features.length; j3++) { - var feature3 = features[j3]; + for (var j2 = 0; j2 < features.length; j2++) { + var feature3 = features[j2]; var hash = feature3.__featurehash__; if (seen[hash]) continue; @@ -80720,10 +83229,10 @@ throw new Error("No Results"); } if (callback) { - var list = result.query.pages[Object.keys(result.query.pages)[0]]; + var list2 = result.query.pages[Object.keys(result.query.pages)[0]]; var translations = {}; - if (list && list.langlinks) { - list.langlinks.forEach(function(d2) { + if (list2 && list2.langlinks) { + list2.langlinks.forEach(function(d2) { translations[d2.lang] = d2["*"]; }); } @@ -81622,19 +84131,19 @@ }) : []; } var _candidates = candidateWays(); - var operation = function() { + var operation2 = function() { var candidate = _candidates[0]; context.enter( modeDrawLine(context, candidate.id, context.graph(), "line", candidate.affix(_vertex.id), true) ); }; - operation.relatedEntityIds = function() { + operation2.relatedEntityIds = function() { return _candidates.length ? [_candidates[0].id] : []; }; - operation.available = function() { + operation2.available = function() { return _geometries.vertex.length === 1 && _geometries.line.length <= 1 && !context.features().hasHiddenConnections(_vertex, context.graph()); }; - operation.disabled = function() { + operation2.disabled = function() { if (_candidates.length === 0) { return "not_eligible"; } else if (_candidates.length > 1) { @@ -81642,18 +84151,18 @@ } return false; }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.continue." + disable) : _t.append("operations.continue.description"); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.continue.annotation.line"); }; - operation.id = "continue"; - operation.keys = [_t("operations.continue.key")]; - operation.title = _t.append("operations.continue.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "continue"; + operation2.keys = [_t("operations.continue.key")]; + operation2.title = _t.append("operations.continue.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/copy.js @@ -81664,7 +84173,7 @@ return entity.hasInterestingTags() || entity.geometry(context.graph()) !== "vertex"; }); } - var operation = function() { + var operation2 = function() { var graph = context.graph(); var selected = groupEntities(getFilteredIdsToCopy(), graph); var canCopy = []; @@ -81728,37 +84237,37 @@ } return descendants; } - operation.available = function() { + operation2.available = function() { return getFilteredIdsToCopy().length > 0; }; - operation.disabled = function() { + operation2.disabled = function() { var extent = utilTotalExtent(getFilteredIdsToCopy(), context.graph()); if (extent.percentContainedIn(context.map().extent()) < 0.8) { return "too_large"; } return false; }; - operation.availableForKeypress = function() { + operation2.availableForKeypress = function() { var selection2 = window.getSelection && window.getSelection(); return !selection2 || !selection2.toString(); }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.copy." + disable, { n: selectedIDs.length }) : _t.append("operations.copy.description", { n: selectedIDs.length }); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.copy.annotation", { n: selectedIDs.length }); }; var _point; - operation.point = function(val) { + operation2.point = function(val) { _point = val; - return operation; + return operation2; }; - operation.id = "copy"; - operation.keys = [uiCmd("\u2318C")]; - operation.title = _t.append("operations.copy.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "copy"; + operation2.keys = [uiCmd("\u2318C")]; + operation2.title = _t.append("operations.copy.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/disconnect.js @@ -81854,21 +84363,21 @@ } } var _extent = utilTotalExtent(_disconnectingVertexIds, context.graph()); - var operation = function() { + var operation2 = function() { context.perform(function(graph) { return _actions.reduce(function(graph2, action) { return action(graph2); }, graph); - }, operation.annotation()); + }, operation2.annotation()); context.validator().validate(); }; - operation.relatedEntityIds = function() { + operation2.relatedEntityIds = function() { if (_vertexIDs.length) { return _disconnectingWayIds; } return _disconnectingVertexIds; }; - operation.available = function() { + operation2.available = function() { if (_actions.length === 0) return false; if (_otherIDs.length !== 0) @@ -81882,7 +84391,7 @@ return false; return true; }; - operation.disabled = function() { + operation2.disabled = function() { var reason; for (var actionIndex in _actions) { reason = _actions[actionIndex].disabled(context.graph()); @@ -81915,18 +84424,18 @@ return false; } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.disconnect." + disable) : _t.append("operations.disconnect.description." + _descriptionID); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.disconnect.annotation." + _annotationID); }; - operation.id = "disconnect"; - operation.keys = [_t("operations.disconnect.key")]; - operation.title = _t.append("operations.disconnect.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "disconnect"; + operation2.keys = [_t("operations.disconnect.key")]; + operation2.title = _t.append("operations.disconnect.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/downgrade.js @@ -81975,9 +84484,9 @@ } return null; } - var buildingKeysToKeep = ["architect", "building", "height", "layer", "source", "type", "wheelchair"]; + var buildingKeysToKeep = ["architect", "building", "height", "layer", "nycdoitt:bin", "source", "type", "wheelchair"]; var addressKeysToKeep = ["source"]; - var operation = function() { + var operation2 = function() { context.perform(function(graph) { for (var i3 in selectedIDs) { var entityID = selectedIDs[i3]; @@ -82001,14 +84510,14 @@ graph = actionChangeTags(entityID, tags)(graph); } return graph; - }, operation.annotation()); + }, operation2.annotation()); context.validator().validate(); context.enter(modeSelect(context, selectedIDs)); }; - operation.available = function() { + operation2.available = function() { return _downgradeType; }; - operation.disabled = function() { + operation2.disabled = function() { if (selectedIDs.some(hasWikidataTag)) { return "has_wikidata_tag"; } @@ -82018,11 +84527,11 @@ return entity.tags.wikidata && entity.tags.wikidata.trim().length > 0; } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.downgrade." + disable + "." + _multi) : _t.append("operations.downgrade.description." + _downgradeType); }; - operation.annotation = function() { + operation2.annotation = function() { var suffix; if (_downgradeType === "building_address") { suffix = "generic"; @@ -82031,11 +84540,11 @@ } return _t("operations.downgrade.annotation." + suffix, { n: _affectedFeatureCount }); }; - operation.id = "downgrade"; - operation.keys = [uiCmd("\u232B")]; - operation.title = _t.append("operations.downgrade.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "downgrade"; + operation2.keys = [uiCmd("\u232B")]; + operation2.title = _t.append("operations.downgrade.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/extract.js @@ -82061,23 +84570,23 @@ _extent = _extent ? _extent.extend(entity.extent(graph)) : entity.extent(graph); return actionExtract(entityID, context.projection); }).filter(Boolean); - var operation = function() { + var operation2 = function() { var combinedAction = function(graph) { _actions.forEach(function(action) { graph = action(graph); }); return graph; }; - context.perform(combinedAction, operation.annotation()); + context.perform(combinedAction, operation2.annotation()); var extractedNodeIDs = _actions.map(function(action) { return action.getExtractedNodeID(); }); context.enter(modeSelect(context, extractedNodeIDs)); }; - operation.available = function() { + operation2.available = function() { return _actions.length && selectedIDs.length === _actions.length; }; - operation.disabled = function() { + operation2.disabled = function() { if (_extent && _extent.percentContainedIn(context.map().extent()) < 0.8) { return "too_large"; } else if (selectedIDs.some(function(entityID) { @@ -82087,22 +84596,22 @@ } return false; }; - operation.tooltip = function() { - var disableReason = operation.disabled(); + operation2.tooltip = function() { + var disableReason = operation2.disabled(); if (disableReason) { return _t.append("operations.extract." + disableReason + "." + _amount); } else { return _t.append("operations.extract.description." + _geometryID + "." + _amount); } }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.extract.annotation", { n: selectedIDs.length }); }; - operation.id = "extract"; - operation.keys = [_t("operations.extract.key")]; - operation.title = _t.append("operations.extract.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "extract"; + operation2.keys = [_t("operations.extract.key")]; + operation2.title = _t.append("operations.extract.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/merge.js @@ -82129,10 +84638,10 @@ return mergePolygon; return mergeNodes; } - var operation = function() { - if (operation.disabled()) + var operation2 = function() { + if (operation2.disabled()) return; - context.perform(_action, operation.annotation()); + context.perform(_action, operation2.annotation()); context.validator().validate(); var resultIDs = selectedIDs.filter(context.hasEntity); if (resultIDs.length > 1) { @@ -82144,10 +84653,10 @@ } context.enter(modeSelect(context, resultIDs)); }; - operation.available = function() { + operation2.available = function() { return selectedIDs.length >= 2; }; - operation.disabled = function() { + operation2.disabled = function() { var actionDisabled = _action.disabled(context.graph()); if (actionDisabled) return actionDisabled; @@ -82157,8 +84666,8 @@ } return false; }; - operation.tooltip = function() { - var disabled = operation.disabled(); + operation2.tooltip = function() { + var disabled = operation2.disabled(); if (disabled) { if (disabled === "conflicting_relations") { return _t.append("operations.merge.conflicting_relations"); @@ -82173,20 +84682,20 @@ } return _t.append("operations.merge.description"); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.merge.annotation", { n: selectedIDs.length }); }; - operation.id = "merge"; - operation.keys = [_t("operations.merge.key")]; - operation.title = _t.append("operations.merge.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "merge"; + operation2.keys = [_t("operations.merge.key")]; + operation2.title = _t.append("operations.merge.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/paste.js function operationPaste(context) { var _pastePoint; - var operation = function() { + var operation2 = function() { if (!_pastePoint) return; var oldIDs = context.copyIDs(); @@ -82217,20 +84726,20 @@ } var copyPoint = context.copyLonLat() && projection2(context.copyLonLat()) || projection2(extent.center()); var delta = geoVecSubtract(_pastePoint, copyPoint); - context.replace(actionMove(newIDs, delta, projection2), operation.annotation()); + context.replace(actionMove(newIDs, delta, projection2), operation2.annotation()); context.enter(modeSelect(context, newIDs)); }; - operation.point = function(val) { + operation2.point = function(val) { _pastePoint = val; - return operation; + return operation2; }; - operation.available = function() { + operation2.available = function() { return context.mode().id === "browse"; }; - operation.disabled = function() { + operation2.disabled = function() { return !context.copyIDs().length; }; - operation.tooltip = function() { + operation2.tooltip = function() { var oldGraph = context.copyGraph(); var ids = context.copyIDs(); if (!ids.length) { @@ -82238,25 +84747,25 @@ } return _t.append("operations.paste.description", { feature: utilDisplayLabel(oldGraph.entity(ids[0]), oldGraph), n: ids.length }); }; - operation.annotation = function() { + operation2.annotation = function() { var ids = context.copyIDs(); return _t("operations.paste.annotation", { n: ids.length }); }; - operation.id = "paste"; - operation.keys = [uiCmd("\u2318V")]; - operation.title = _t.append("operations.paste.title"); - return operation; + operation2.id = "paste"; + operation2.keys = [uiCmd("\u2318V")]; + operation2.title = _t.append("operations.paste.title"); + return operation2; } // modules/operations/reverse.js function operationReverse(context, selectedIDs) { - var operation = function() { + var operation2 = function() { context.perform(function combinedReverseAction(graph) { actions().forEach(function(action) { graph = action(graph); }); return graph; - }, operation.annotation()); + }, operation2.annotation()); context.validator().validate(); }; function actions(situation) { @@ -82289,24 +84798,24 @@ return "point"; return "feature"; } - operation.available = function(situation) { + operation2.available = function(situation) { return actions(situation).length > 0; }; - operation.disabled = function() { + operation2.disabled = function() { return false; }; - operation.tooltip = function() { + operation2.tooltip = function() { return _t.append("operations.reverse.description." + reverseTypeID()); }; - operation.annotation = function() { + operation2.annotation = function() { var acts = actions(); return _t("operations.reverse.annotation." + reverseTypeID(), { n: acts.length }); }; - operation.id = "reverse"; - operation.keys = [_t("operations.reverse.key")]; - operation.title = _t.append("operations.reverse.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "reverse"; + operation2.keys = [_t("operations.reverse.key")]; + operation2.title = _t.append("operations.reverse.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/split.js @@ -82337,20 +84846,20 @@ } _waysAmount = _ways.length === 1 ? "single" : "multiple"; } - var operation = function() { - var difference = context.perform(_action, operation.annotation()); - var idsToSelect = _vertexIds.concat(difference.extantIDs().filter(function(id2) { + var operation2 = function() { + var difference2 = context.perform(_action, operation2.annotation()); + var idsToSelect = _vertexIds.concat(difference2.extantIDs().filter(function(id2) { return context.entity(id2).type === "way"; })); context.enter(modeSelect(context, idsToSelect)); }; - operation.relatedEntityIds = function() { + operation2.relatedEntityIds = function() { return _selectedWayIds.length ? [] : _ways.map((way) => way.id); }; - operation.available = function() { + operation2.available = function() { return _isAvailable; }; - operation.disabled = function() { + operation2.disabled = function() { var reason = _action.disabled(context.graph()); if (reason) { return reason; @@ -82359,25 +84868,25 @@ } return false; }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.split." + disable) : _t.append("operations.split.description." + _geometry + "." + _waysAmount + "." + _nodesAmount + "_node"); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.split.annotation." + _geometry, { n: _ways.length }); }; - operation.icon = function() { + operation2.icon = function() { if (_waysAmount === "multiple") { return "#iD-operation-split-multiple"; } else { return "#iD-operation-split"; } }; - operation.id = "split"; - operation.keys = [_t("operations.split.key")]; - operation.title = _t.append("operations.split.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "split"; + operation2.keys = [_t("operations.split.key")]; + operation2.title = _t.append("operations.split.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/operations/straighten.js @@ -82436,18 +84945,18 @@ } return null; } - function operation() { + function operation2() { if (!_action) return; - context.perform(_action, operation.annotation()); + context.perform(_action, operation2.annotation()); window.setTimeout(function() { context.validator().validate(); }, 300); } - operation.available = function() { + operation2.available = function() { return Boolean(_action); }; - operation.disabled = function() { + operation2.disabled = function() { var reason = _action.disabled(context.graph()); if (reason) { return reason; @@ -82477,18 +84986,18 @@ return false; } }; - operation.tooltip = function() { - var disable = operation.disabled(); + operation2.tooltip = function() { + var disable = operation2.disabled(); return disable ? _t.append("operations.straighten." + disable + "." + _amount) : _t.append("operations.straighten.description." + _geometry + (_wayIDs.length === 1 ? "" : "s")); }; - operation.annotation = function() { + operation2.annotation = function() { return _t("operations.straighten.annotation." + _geometry, { n: _wayIDs.length ? _wayIDs.length : _nodeIDs.length }); }; - operation.id = "straighten"; - operation.keys = [_t("operations.straighten.key")]; - operation.title = _t.append("operations.straighten.title"); - operation.behavior = behaviorOperation(context).which(operation); - return operation; + operation2.id = "straighten"; + operation2.keys = [_t("operations.straighten.key")]; + operation2.title = _t.append("operations.straighten.title"); + operation2.behavior = behaviorOperation(context).which(operation2); + return operation2; } // modules/modes/select.js @@ -82620,9 +85129,9 @@ return mode; }; function loadOperations() { - _operations.forEach(function(operation) { - if (operation.behavior) { - context.uninstall(operation.behavior); + _operations.forEach(function(operation2) { + if (operation2.behavior) { + context.uninstall(operation2.behavior); } }); _operations = Object.values(operations_exports).map(function(o2) { @@ -82634,12 +85143,12 @@ operationCopy(context, selectedIDs), operationDowngrade(context, selectedIDs), operationDelete(context, selectedIDs) - ]).filter(function(operation) { - return operation.available(); + ]).filter(function(operation2) { + return operation2.available(); }); - _operations.forEach(function(operation) { - if (operation.behavior) { - context.install(operation.behavior); + _operations.forEach(function(operation2) { + if (operation2.behavior) { + context.install(operation2.behavior); } }); context.ui().closeEditMenu(); @@ -82857,13 +85366,13 @@ if (!parentId) return; var way = context.entity(parentId); - var length = way.nodes.length; + var length2 = way.nodes.length; var curr = way.nodes.indexOf(selectedIDs[0]); var index = -1; if (curr > 0) { index = curr - 1; } else if (way.isClosed()) { - index = length - 2; + index = length2 - 2; } if (index !== -1) { context.enter( @@ -82878,10 +85387,10 @@ if (!parentId) return; var way = context.entity(parentId); - var length = way.nodes.length; + var length2 = way.nodes.length; var curr = way.nodes.indexOf(selectedIDs[0]); var index = -1; - if (curr < length - 1) { + if (curr < length2 - 1) { index = curr + 1; } else if (way.isClosed()) { index = 0; @@ -82936,9 +85445,9 @@ mode.exit = function() { _newFeature = false; _focusedVertexIds = null; - _operations.forEach(function(operation) { - if (operation.behavior) { - context.uninstall(operation.behavior); + _operations.forEach(function(operation2) { + if (operation2.behavior) { + context.uninstall(operation2.behavior); } }); _operations = []; @@ -83147,7 +85656,7 @@ var map2 = context.map(); var center = map2.center(); var zoom = map2.zoom(); - var precision2 = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)); + var precision3 = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)); var oldParams = utilObjectOmit( utilStringQs(window.location.hash), ["comment", "source", "hashtags", "walkthrough"] @@ -83160,7 +85669,7 @@ if (selected.length) { newParams.id = selected.join(","); } - newParams.map = zoom.toFixed(2) + "/" + center[1].toFixed(precision2) + "/" + center[0].toFixed(precision2); + newParams.map = zoom.toFixed(2) + "/" + center[1].toFixed(precision3) + "/" + center[0].toFixed(precision3); return Object.assign(oldParams, newParams); } function computedHash() {