line-ends.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. function lineEnds({ select = null, tolerance = 1, root: rootSlack = 2, mark = 7, least = 0.3, cover = 0.5, show = false } = {}) {
  2. const plate = (select && document.querySelector(select)) || document.querySelector(".iso-plate") || document.body;
  3. const box = plate.getBoundingClientRect();
  4. const style = document.createElement("style");
  5. style.textContent = `${select || ".iso-plate"} *{pointer-events:none!important}${select || ".iso-plate"} svg,${select || ".iso-plate"} svg *{pointer-events:visiblePainted!important}`;
  6. document.head.append(style);
  7. const skipClass = ["iso-edge", "iso-bevel", "iso-crease", "tb-edge"];
  8. const svgs = [...plate.querySelectorAll("svg")];
  9. const shapes = svgs.flatMap((svg) => [...svg.querySelectorAll("path, line, polyline, polygon, circle, ellipse, rect")]).filter((el) => !el.closest("defs, clipPath, mask, pattern, marker, symbol"));
  10. const opacityOf = (el) => {
  11. let alpha = 1;
  12. for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
  13. const cs = getComputedStyle(node);
  14. if (cs.display === "none") return 0;
  15. alpha *= Number(cs.opacity);
  16. if (node === plate) break;
  17. }
  18. return getComputedStyle(el).visibility === "hidden" ? 0 : alpha;
  19. };
  20. const numbers = (text) => (text.match(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi) || []).map(Number);
  21. const subpathsOf = (d) => {
  22. const out = [];
  23. let current = null;
  24. let x = 0;
  25. let y = 0;
  26. let sx = 0;
  27. let sy = 0;
  28. let control = null;
  29. const push = (px, py) => {
  30. current.points.push([px, py]);
  31. x = px;
  32. y = py;
  33. };
  34. const start = (px, py) => {
  35. current = { points: [[px, py]], closed: false };
  36. out.push(current);
  37. x = sx = px;
  38. y = sy = py;
  39. };
  40. const cubic = (x1, y1, x2, y2, px, py) => {
  41. const x0 = x;
  42. const y0 = y;
  43. for (let i = 1; i <= 8; i++) {
  44. const t = i / 8;
  45. const u = 1 - t;
  46. push(u * u * u * x0 + 3 * u * u * t * x1 + 3 * u * t * t * x2 + t * t * t * px, u * u * u * y0 + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * py);
  47. }
  48. control = [x2, y2];
  49. };
  50. const quad = (x1, y1, px, py) => {
  51. const x0 = x;
  52. const y0 = y;
  53. for (let i = 1; i <= 6; i++) {
  54. const t = i / 6;
  55. const u = 1 - t;
  56. push(u * u * x0 + 2 * u * t * x1 + t * t * px, u * u * y0 + 2 * u * t * y1 + t * t * py);
  57. }
  58. control = [x1, y1];
  59. };
  60. for (const [, command, args] of d.matchAll(/([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)/g)) {
  61. const v = numbers(args);
  62. const rel = command === command.toLowerCase();
  63. const C = command.toUpperCase();
  64. const ox = () => (rel ? x : 0);
  65. const oy = () => (rel ? y : 0);
  66. if (C === "Z") {
  67. if (current) {
  68. current.closed = true;
  69. push(sx, sy);
  70. }
  71. current = null;
  72. continue;
  73. }
  74. if (C === "M") {
  75. for (let i = 0; i + 1 < v.length; i += 2) {
  76. if (i === 0) start(v[0] + ox(), v[1] + oy());
  77. else push(v[i] + ox(), v[i + 1] + oy());
  78. }
  79. control = null;
  80. continue;
  81. }
  82. if (!current) start(x, y);
  83. if (C === "L") for (let i = 0; i + 1 < v.length; i += 2) push(v[i] + ox(), v[i + 1] + oy());
  84. else if (C === "H") for (const value of v) push(value + ox(), y);
  85. else if (C === "V") for (const value of v) push(x, value + oy());
  86. else if (C === "C") for (let i = 0; i + 5 < v.length; i += 6) cubic(v[i] + ox(), v[i + 1] + oy(), v[i + 2] + ox(), v[i + 3] + oy(), v[i + 4] + ox(), v[i + 5] + oy());
  87. else if (C === "S")
  88. for (let i = 0; i + 3 < v.length; i += 4) {
  89. const reflected = control ? [2 * x - control[0], 2 * y - control[1]] : [x, y];
  90. cubic(reflected[0], reflected[1], v[i] + ox(), v[i + 1] + oy(), v[i + 2] + ox(), v[i + 3] + oy());
  91. }
  92. else if (C === "Q") for (let i = 0; i + 3 < v.length; i += 4) quad(v[i] + ox(), v[i + 1] + oy(), v[i + 2] + ox(), v[i + 3] + oy());
  93. else if (C === "T")
  94. for (let i = 0; i + 1 < v.length; i += 2) {
  95. const reflected = control ? [2 * x - control[0], 2 * y - control[1]] : [x, y];
  96. quad(reflected[0], reflected[1], v[i] + ox(), v[i + 1] + oy());
  97. }
  98. else if (C === "A") for (let i = 0; i + 6 < v.length; i += 7) push(v[i + 5] + ox(), v[i + 6] + oy());
  99. if (C !== "C" && C !== "S" && C !== "Q" && C !== "T") control = null;
  100. }
  101. return out;
  102. };
  103. const geometryOf = (el) => {
  104. const tag = el.tagName.toLowerCase();
  105. const num = (name) => Number(el.getAttribute(name) || 0);
  106. if (tag === "path") return subpathsOf(el.getAttribute("d") || "");
  107. if (tag === "line") return [{ points: [[num("x1"), num("y1")], [num("x2"), num("y2")]], closed: false }];
  108. if (tag === "polyline" || tag === "polygon") {
  109. const v = numbers(el.getAttribute("points") || "");
  110. const points = [];
  111. for (let i = 0; i + 1 < v.length; i += 2) points.push([v[i], v[i + 1]]);
  112. if (tag === "polygon" && points.length) points.push(points[0]);
  113. return [{ points, closed: tag === "polygon" }];
  114. }
  115. if (tag === "rect") {
  116. const [x, y, w, h] = [num("x"), num("y"), num("width"), num("height")];
  117. return [{ points: [[x, y], [x + w, y], [x + w, y + h], [x, y + h], [x, y]], closed: true }];
  118. }
  119. return [];
  120. };
  121. const cell = 6;
  122. const grid = new Map();
  123. const add = (gx, gy, entry) => {
  124. const id = `${gx},${gy}`;
  125. if (!grid.has(id)) grid.set(id, []);
  126. grid.get(id).push(entry);
  127. };
  128. const lines = [];
  129. let scale = 1;
  130. for (const el of shapes) {
  131. const cs = getComputedStyle(el);
  132. const alpha = opacityOf(el);
  133. if (alpha < 0.1) continue;
  134. const ctm = el.getScreenCTM();
  135. if (!ctm) continue;
  136. const map = ([px, py]) => [ctm.a * px + ctm.c * py + ctm.e, ctm.b * px + ctm.d * py + ctm.f];
  137. const tag = el.tagName.toLowerCase();
  138. const stroked = cs.stroke !== "none" && parseFloat(cs.strokeWidth) > 0 && Number(cs.strokeOpacity) > 0.05;
  139. const filled = cs.fill !== "none" && Number(cs.fillOpacity) > 0.05;
  140. if (tag === "circle" || tag === "ellipse") {
  141. if (!stroked && !filled) continue;
  142. const c = map([Number(el.getAttribute("cx") || 0), Number(el.getAttribute("cy") || 0)]);
  143. const r = Number(el.getAttribute("r") || el.getAttribute("rx") || 0) * Math.hypot(ctm.a, ctm.b);
  144. const entry = { el, kind: "dot", c, r };
  145. for (let gx = Math.floor((c[0] - r) / cell); gx <= Math.floor((c[0] + r) / cell); gx++) for (let gy = Math.floor((c[1] - r) / cell); gy <= Math.floor((c[1] + r) / cell); gy++) add(gx, gy, entry);
  146. continue;
  147. }
  148. if (!stroked) continue;
  149. const owner = el.closest("svg");
  150. const viewCtm = owner && owner.getScreenCTM();
  151. if (viewCtm) scale = Math.hypot(viewCtm.a, viewCtm.b) || scale;
  152. const subpaths = geometryOf(el).map((sub, index) => ({ ...sub, index, flat: sub.points.map(map) }));
  153. subpaths.forEach((sub) => {
  154. for (let i = 0; i < sub.flat.length - 1; i++) {
  155. const a = sub.flat[i];
  156. const b = sub.flat[i + 1];
  157. const entry = { el, kind: "segment", a, b, sub: sub.index, i };
  158. for (let gx = Math.floor(Math.min(a[0], b[0]) / cell); gx <= Math.floor(Math.max(a[0], b[0]) / cell); gx++) for (let gy = Math.floor(Math.min(a[1], b[1]) / cell); gy <= Math.floor(Math.max(a[1], b[1]) / cell); gy++) add(gx, gy, entry);
  159. }
  160. });
  161. const checked = el.classList.contains("iso-line") && !skipClass.some((name) => el.classList.contains(name)) && alpha >= least;
  162. if (checked) lines.push({ el, subpaths, alpha, free: el.getAttribute("data-free") });
  163. }
  164. const near = (p, reach) => {
  165. const out = new Set();
  166. for (let gx = Math.floor((p[0] - reach) / cell); gx <= Math.floor((p[0] + reach) / cell); gx++) for (let gy = Math.floor((p[1] - reach) / cell); gy <= Math.floor((p[1] + reach) / cell); gy++) for (const entry of grid.get(`${gx},${gy}`) || []) out.add(entry);
  167. return out;
  168. };
  169. const segmentDistance = (p, a, b) => {
  170. const dx = b[0] - a[0];
  171. const dy = b[1] - a[1];
  172. const span = dx * dx + dy * dy;
  173. const t = span > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / span)) : 0;
  174. return Math.hypot(p[0] - a[0] - dx * t, p[1] - a[1] - dy * t);
  175. };
  176. const lengthOf = (flat) => flat.reduce((sum, p, i) => (i ? sum + Math.hypot(p[0] - flat[i - 1][0], p[1] - flat[i - 1][1]) : 0), 0);
  177. const hidden = (el, p) => {
  178. const stack = document.elementsFromPoint(p[0], p[1]);
  179. const at = stack.indexOf(el);
  180. const above = at < 0 ? stack : stack.slice(0, at);
  181. return above.some((node) => {
  182. if (!(node instanceof SVGGeometryElement) || node.contains(el)) return false;
  183. const cs = getComputedStyle(node);
  184. return cs.fill !== "none" && Number(cs.fillOpacity) * opacityOf(node) >= cover && node.isPointInFill(new DOMPoint(...inverse(node, p)));
  185. });
  186. };
  187. const inverse = (node, p) => {
  188. const m = node.getScreenCTM().inverse();
  189. return [m.a * p[0] + m.c * p[1] + m.e, m.b * p[0] + m.d * p[1] + m.f];
  190. };
  191. const clearance = (line, sub, end, p, reach) => {
  192. let best = Infinity;
  193. const own = sub.flat;
  194. const skipNear = 2 * reach;
  195. const along = [0];
  196. for (let i = 1; i < own.length; i++) along.push(along[i - 1] + Math.hypot(own[i][0] - own[i - 1][0], own[i][1] - own[i - 1][1]));
  197. const total = along[along.length - 1];
  198. for (const entry of near(p, reach * 4)) {
  199. if (entry.kind === "dot") {
  200. best = Math.min(best, Math.max(0, Math.hypot(p[0] - entry.c[0], p[1] - entry.c[1]) - entry.r));
  201. continue;
  202. }
  203. if (entry.el === line.el && entry.sub === sub.index) {
  204. const from = along[entry.i];
  205. const to = along[entry.i + 1];
  206. const gapFrom = end === "start" ? from : total - to;
  207. if (gapFrom < skipNear) continue;
  208. }
  209. best = Math.min(best, segmentDistance(p, entry.a, entry.b));
  210. }
  211. return best;
  212. };
  213. const describe = (el) => {
  214. const item = el.closest("[data-part], [data-name], [data-item], .it");
  215. const tag = item && item !== el ? (item.getAttribute("data-part") || item.getAttribute("data-name") || item.getAttribute("data-item") || `it k ${item.getAttribute("data-k") || ""}`) : "";
  216. return `${el.getAttribute("class")}${el.getAttribute("data-tone") ? ` ${el.getAttribute("data-tone")}` : ""}${tag ? ` in ${tag}` : ""}`;
  217. };
  218. const problems = [];
  219. let ends = 0;
  220. const slack = tolerance * scale;
  221. const rooted = rootSlack * scale;
  222. for (const line of lines) {
  223. for (const sub of line.subpaths) {
  224. if (sub.closed || sub.flat.length < 2) continue;
  225. const first = sub.flat[0];
  226. const last = sub.flat[sub.flat.length - 1];
  227. if (Math.hypot(first[0] - last[0], first[1] - last[1]) < 0.05 * scale) continue;
  228. const length = lengthOf(sub.flat);
  229. if (length < 0.2 * scale) continue;
  230. const result = {};
  231. for (const [end, p] of [["start", first], ["end", last]]) {
  232. if (line.free === "" || line.free === "both" || line.free === end) {
  233. result[end] = 0;
  234. continue;
  235. }
  236. ends++;
  237. result[end] = hidden(line.el, p) ? 0 : clearance(line, sub, end, p, Math.max(slack, rooted));
  238. }
  239. const straight = sub.flat.length === 2 || sub.flat.every((q) => segmentDistance(q, first, last) < 0.15 * scale);
  240. const isMark = straight && length <= mark * scale;
  241. const fail = (end) => result[end] !== undefined && result[end] > slack;
  242. let bad = [];
  243. if (isMark) {
  244. const best = Math.min(result.start ?? Infinity, result.end ?? Infinity);
  245. if (!(best <= rooted)) bad = ["start", "end"].filter((end) => result[end] !== undefined && result[end] > 0);
  246. } else bad = ["start", "end"].filter(fail);
  247. for (const end of bad) {
  248. const p = end === "start" ? first : last;
  249. problems.push({ what: describe(line.el), d: (line.el.getAttribute("d") || "").slice(0, 36), end, mark: isMark, gap: result[end] / scale, at: [Math.round((p[0] - box.left) * 10) / 10, Math.round((p[1] - box.top) * 10) / 10], client: p, opacity: Math.round(line.alpha * 100) / 100, length: Math.round((length / scale) * 10) / 10 });
  250. }
  251. }
  252. }
  253. style.remove();
  254. problems.sort((a, b) => b.gap - a.gap);
  255. if (show) {
  256. const ns = "http://www.w3.org/2000/svg";
  257. const overlay = document.createElementNS(ns, "svg");
  258. overlay.setAttribute("data-line-ends", "");
  259. overlay.setAttribute("style", `position:fixed;left:0;top:0;width:${innerWidth}px;height:${innerHeight}px;pointer-events:none;z-index:2147483647;overflow:visible`);
  260. for (const problem of problems) {
  261. const ring = document.createElementNS(ns, "circle");
  262. ring.setAttribute("cx", problem.client[0]);
  263. ring.setAttribute("cy", problem.client[1]);
  264. ring.setAttribute("r", 5);
  265. ring.setAttribute("style", "fill:none;stroke:#ff0050;stroke-width:1.5");
  266. overlay.append(ring);
  267. }
  268. document.body.append(overlay);
  269. }
  270. return { ends, lines: lines.length, problems: problems.map(({ client, ...rest }) => rest) };
  271. }
  272. export const LINE_ENDS = lineEnds.toString();