@euphrasiologist/lwphylo 1.1.14 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,1249 @@
1
- const n={circular:()=>{let n=200,t=2,e=[0,0],r={},i=0,s=0,c=n*n,a=10;function o(){const e=Math.exp(t);return i=e/(e-1)*n,s=t/n,c=n*n,l}function l(n){!function(){if(!r||"function"!=typeof r.xscale||"function"!=typeof r.yscale)throw new Error("phisheye.circular: call .scales(xscale, yscale) before using the fisheye.")}();const t=r.xscale(n.x),o=r.yscale(n.y),l=t-e[0],h=o-e[1],d=l*l+h*h;if(0===d||d>=c)return{x:t,y:o,z:d>=c?1:a};const u=Math.sqrt(d),f=i*(1-Math.exp(-u*s))/u*.75+.25;return{x:e[0]+l*f,y:e[1]+h*f,z:Math.min(f,a)}}return l.radius=function(t){return arguments.length?(n=Math.max(0,+t),o()):n},l.distortion=function(n){return arguments.length?(t=Math.max(0,+n),o()):t},l.focus=function(n){if(!arguments.length)return e.slice();if(!Array.isArray(n)||2!==n.length)throw new Error("focus expects [x, y] in pixels.");return e=[+n[0],+n[1]],l},l.scales=function(n,t){return arguments.length?(r={xscale:n,yscale:t},l):r},l.setScales=l.scales,l.clampZ=function(n){return arguments.length?(a=Math.max(1,+n),l):a},l.focusFromEvent=function(n,t){const e=t.getBoundingClientRect(),r=n.clientX-e.left,i=n.clientY-e.top;return l.focus([r,i])},o()}};function t(n,e,r,i,s){const c=2*Math.PI,a=n=>(n%c+c)%c,o=a(i),l=a(s),h=(l-o+c)%c,d=(o-l+c)%c,u=d<h?1:0,f=Math.min(h,d),p=f>Math.PI?1:0;if(f<1e-9){const i=t(n,e,r,o);return`M ${i.x} ${i.y}`}const I=t(n,e,r,o),g=t(n,e,r,l);return`M ${I.x} ${I.y} A ${r} ${r} 0 ${p} ${u} ${g.x} ${g.y}`}function e(n,e,r,i,s){const c=2*Math.PI,a=n=>(n%c+c)%c;let o=a(i),l=a(s),h=l-o;h<0&&(h+=c);const d=h>Math.PI?1:0,u=t(n,e,r,o),f=t(n,e,r,l);return["M",u.x,u.y,"A",r,r,0,d,1,f.x,f.y].join(" ")}function r(n,t=[]){t.push(n);for(let e=0;e<(n.children?.length||0);e++)t=r(n.children[e],t);return t}function i(n,t=!0){var e=[];for(const t of r(n))null===t.parent?e.push({parentId:null,parentLabel:null,thisId:t.id,thisLabel:t.label,children:t.children.map(n=>n.id),branchLength:0,isTip:!1,x:t.x,y:t.y,angle:t.angle}):e.push({parentId:t.parent.id,parentLabel:t.parent.label,thisId:t.id,thisLabel:t.label,children:t.children.map(n=>n.id),branchLength:t.branchLength,isTip:0==t.children.length,x:t.x,y:t.y,angle:t.angle});return t&&(e=e.sort(function(n,t){return n.thisId-t.thisId})),e}function s(n){const t=2*Math.PI,e=i(n,!0),r=new Map(e.map(n=>[n.thisId,n])),s=new Map(e.map(n=>[n.thisId,n.children||[]]));let c=null;for(const n of e)if(null==n.parentId){c=n.thisId;break}const a=[];!function n(t){const e=s.get(t)||[];if(0!==e.length)for(const t of e)n(t);else a.push(t)}(c);const o=Math.max(1,a.length),l=new Map;a.forEach((n,e)=>{l.set(n,e/o*t)}),function n(e){const r=s.get(e)||[];for(const t of r)n(t);if(r.length>0){let n=0,i=0;for(const t of r){const e=l.get(t);n+=Math.cos(e),i+=Math.sin(e)}l.set(e,(Math.atan2(i,n)%t+t)%t)}}(c);const h=new Map;h.set(c,0),function n(t){const e=s.get(t)||[],i=h.get(t)||0;for(const t of e){const e=r.get(t),s=e?.branchLength??0;h.set(t,i+s),n(t)}}(c);for(const n of e){const t=l.get(n.thisId)??0,e=h.get(n.thisId)??0;n.angle=t,n.r=e,n.x=e*Math.cos(t),n.y=e*Math.sin(t)}return e}function c(n){const t={};return t.data=s(n),t.radii=function(n){const t=s(n),e=new Map(t.map(n=>[n.thisId,n])),r=t.find(n=>null==n.parentId)?.thisId,i=[];for(const n of t){if(n.thisId===r)continue;const t=e.get(n.parentId);if(!t)continue;const s=n.angle,c=t.r,a=n.r;i.push({parentId:t.thisId,childId:n.thisId,x0:c*Math.cos(s),y0:c*Math.sin(s),x1:a*Math.cos(s),y1:a*Math.sin(s),isTip:!!n.isTip})}return i}(n),t.arcs=function(n){const t=2*Math.PI;new Map(n.map(n=>[n.thisId,n]));const e=new Map;let r=null;for(const t of n)null==t.parentId&&(r=t.thisId),e.has(t.parentId)||e.set(t.parentId,[]),e.get(t.parentId).push(t);const i=[];for(const s of n){const n=s.thisId;if(n===r)continue;const c=e.get(n)||[];if(c.length<2)continue;const a=c.map(n=>(n.angle%t+t)%t).sort((n,t)=>n-t),o=a[0],l=a[a.length-1],h=l-o,d=t-h;let u,f,p;h<=d?(u=o,f=l,p=h):(u=l,f=o,p=d),p<1e-6||!isFinite(s.r)||s.r<=0||i.push({start:u,end:f,radius:s.r,thisId:n,parentId:s.parentId})}return i}(t.data),t}function a(n){const t=i(n),e=new Map(t.map((n,t)=>[n.thisId,t])),r=[];!function n(t){t.children&&0!==t.children.length?t.children.forEach(n):r.push(t.id)}(n);const s=new Map(r.map((n,t)=>[n,t+1]));return function n(r){const i=e.get(r.id);if(!r.children||0===r.children.length){const n=s.get(r.id);return t[i].y0=n,t[i].y1=n,n}const c=function(n){let t=0,e=0;for(let r of n)null!=r&&(r=+r)>=r&&(++t,e+=r);if(t)return e/t}(r.children.map(n));return t[i].y0=c,t[i].y1=c,c}(n),function n(r,i){const s=e.get(r.id),c=i??0,a=c+(t[s].branchLength??0);t[s].x0=c,t[s].x1=a,r.children&&r.children.length&&r.children.forEach(t=>n(t,a))}(n,0),t.map(n=>{const{y:t,x:e,angle:r,...i}=n;return i})}function o(n){const t=a(n),e=function(n){const t=a(n),e=new Map;for(const n of t){if(null==n.parentId)continue;const t=e.get(n.parentId);t?t.push(n):e.set(n.parentId,[n])}const r=[];for(const[n,t]of e.entries()){if(!t.length)continue;const e=t.map(n=>n.y0),i=Math.min(...e),s=Math.max(...e),c=t[0].x0;r.push({parentId:n,x0:c,x1:c,y0:i,y1:s,heights:s-i})}return r}(n),r=function(n){const t=a(n),e=new Map(t.map(n=>[n.thisId,n])),r=[];for(const n of t){if(null==n.parentId)continue;const t=e.get(n.parentId);if(!t)continue;const i=n.x0,s=n.y0,c=t.y0,a=Math.min(s,c),o=Math.max(s,c);r.push({parentId:n.parentId,childId:n.thisId,x:i,y0:a,y1:o})}return r}(n);new Map(t.map(n=>[n.thisId,n]));const i=t.filter(n=>null!=n.parentId).map(n=>({parentId:n.parentId,childId:n.thisId,thisId:n.thisId,thisLabel:n.thisLabel,isTip:n.isTip,x0:n.x0,x1:n.x1,y0:n.y0,y1:n.y0}));return{data:t,vertical_lines:e,child_vertical_lines:r,horizontal_lines:i}}function l(n){null===n.parent&&(function n(t){if(!t.children||0===t.children.length)return t.ntips=1,1;let e=0;for(const r of t.children)e+=n(r);return t.ntips=e,e}(n),n.start=0,n.end=2,n.angle=0,n.ntips=function(n){var t=0;for(const e of function(n){const t=[n],e=[];for(;t.length;){const n=t.shift();e.push(n);for(const e of n.children)t.push(e)}return e}(n))0==e.children.length&&t++;return t}(n),n.x=0,n.y=0);let t=n.start;for(let e=0;e<n.children.length;e++){const r=n.children[e],i=(n.end-n.start)*(r.ntips/n.ntips);r.start=t,r.end=t+i,r.angle=r.start+(r.end-r.start)/2,t=r.end;const s=r.angle*Math.PI,c=r.branchLength??0;r.x=n.x+c*Math.sin(s),r.y=n.y+c*Math.cos(s),l(r)}return n}function h(n){var t={},e=i(l(n));return t.data=e,t.edges=function(n,t=!1){const e=[...n].sort((n,t)=>n.thisId-t.thisId),r=new Map(e.map(n=>[n.thisId,n])),i=[];for(const n of e){if(null==n.parentId)continue;const e=r.get(n.parentId);e&&(t?(i.push({x1:n.x,y1:n.y,id1:n.thisId,x2:e.x,y2:n.y,id2:void 0}),i.push({x1:e.x,y1:n.y,id1:void 0,x2:e.x,y2:e.y,id2:n.parentId})):i.push({x1:n.x,y1:n.y,id1:n.thisId,x2:e.x,y2:e.y,id2:n.parentId}))}return i}(e),t}function d(n,t){const e=function(n,t="thisId"){return new Map(n.map(n=>[n[t],n]))}(t),r=e.get(n.parentId);return r?{px:r.fisheye.x,py:r.fisheye.y}:null}function u(n){const t=(n=String(n).replace(/\s+/g,"")).split(/(;|\(|\)|,)/),e={parent:null,children:[]};let r=e,i=0;for(const n of t)if(n&&";"!==n)if("("===n){const n={parent:r,children:[]};r.children.push(n),r=n}else if(","===n){r=r.parent;const n={parent:r,children:[]};r.children.push(n),r=n}else if(")"===n){if(r=r.parent,null===r)break}else{const t=n.split(":");1===t.length?n.startsWith(":")?(r.label="",r.branchLength=parseFloat(t[0])):(r.label=t[0],r.branchLength=null):2===t.length?(r.label=t[0],r.branchLength=parseFloat(t[1])):(console.warn(n,"Unhandled token with multiple ':' characters"),r.label=t[0]||"",r.branchLength=parseFloat(t[t.length-1])),r.id=i++}return null==e.id&&(e.id=i),e}function f(n,t){let e={};n.data.forEach(n=>{e[n.thisId]={...n}});let r={};const i=function(n){e[n]&&(r[n]=e[n],e[n].children&&e[n].children.forEach(n=>{i(n)}))};i(t);const s=[["data",Object.values(r)]],c=s[0][1].map(n=>n.thisId);var a=[];for(const t in n)"data"!==t&&a.push([t,n[t]]);var o=a.map(n=>[n[0],n[1].filter(n=>c.includes(n.thisId))]);return Object.fromEntries(s.concat(o))}export{e as describeArc,d as parentFisheye,n as phisheye,c as radialLayout,u as readTree,o as rectangleLayout,f as subTree,h as unrooted};
1
+ import * as d3 from 'd3';
2
+
3
+ // Based on the archived d3 fisheye plugin, modernized & hardened.
4
+ // - Works in screen/pixel space (set xscale/yscale).
5
+ // - O(1) math with precomputed constants; avoids unnecessary sqrt.
6
+ // - Stable API: .radius(), .distortion(), .focus(), .scales()
7
+ // - Returns { x, y, z } where z ~= local magnification (clamped).
8
+ // - Adds small ergonomics: .setScales(), .focusFromEvent(), .clampZ()
9
+
10
+ const phisheye = {
11
+ circular: () => {
12
+ let radius = 200; // pixels
13
+ let distortion = 2; // dimensionless
14
+ let focus = [0, 0]; // [fx, fy] in pixels
15
+ let scales = {}; // { xscale, yscale }
16
+ let k0 = 0, k1 = 0; // precomputed factors
17
+ let radius2 = radius * radius;
18
+ let zClamp = 10; // max z (magnification) for stability
19
+
20
+ function ensureScales() {
21
+ if (!scales || typeof scales.xscale !== "function" || typeof scales.yscale !== "function") {
22
+ throw new Error("phisheye.circular: call .scales(xscale, yscale) before using the fisheye.");
23
+ }
24
+ }
25
+
26
+ function rescale() {
27
+ // Same functional form as the classic plugin:
28
+ // k = ((e^d) / (e^d - 1)) * R * (1 - exp(-d * r / R)) / r
29
+ // where d=distortion, R=radius, r=distance to focus.
30
+ const e = Math.exp(distortion);
31
+ k0 = (e / (e - 1)) * radius; // constant multiplier
32
+ k1 = distortion / radius; // exponent scale
33
+ radius2 = radius * radius;
34
+ return fisheye;
35
+ }
36
+
37
+ function fisheye(d) {
38
+ ensureScales();
39
+
40
+ const x0 = scales.xscale(d.x);
41
+ const y0 = scales.yscale(d.y);
42
+
43
+ const dx = x0 - focus[0];
44
+ const dy = y0 - focus[1];
45
+ const dd2 = dx * dx + dy * dy;
46
+
47
+ // At the focus or outside radius -> identity mapping, z ~ 1
48
+ if (dd2 === 0 || dd2 >= radius2) {
49
+ return { x: x0, y: y0, z: dd2 >= radius2 ? 1 : zClamp };
50
+ }
51
+
52
+ const dd = Math.sqrt(dd2);
53
+ // Classic mapping (with a slight blend for gentler core)
54
+ const k = ((k0 * (1 - Math.exp(-dd * k1))) / dd) * 0.75 + 0.25;
55
+
56
+ // New position
57
+ const x = focus[0] + dx * k;
58
+ const y = focus[1] + dy * k;
59
+
60
+ // Local magnification proxy (clamped)
61
+ const z = Math.min(k, zClamp);
62
+
63
+ return { x, y, z };
64
+ }
65
+
66
+ // --- Public API ---
67
+
68
+ fisheye.radius = function(_) {
69
+ if (!arguments.length) return radius;
70
+ radius = Math.max(0, +_);
71
+ return rescale();
72
+ };
73
+
74
+ fisheye.distortion = function(_) {
75
+ if (!arguments.length) return distortion;
76
+ distortion = Math.max(0, +_);
77
+ return rescale();
78
+ };
79
+
80
+ fisheye.focus = function(_) {
81
+ if (!arguments.length) return focus.slice();
82
+ if (!Array.isArray(_) || _.length !== 2) throw new Error("focus expects [x, y] in pixels.");
83
+ focus = [+_[0], +_[1]];
84
+ return fisheye;
85
+ };
86
+
87
+ fisheye.scales = function(xscale, yscale) {
88
+ if (!arguments.length) return scales;
89
+ scales = { xscale, yscale };
90
+ return fisheye;
91
+ };
92
+
93
+ // Convenience alias
94
+ fisheye.setScales = fisheye.scales;
95
+
96
+ // Clamp maximum z (magnification) returned; defaults to 10
97
+ fisheye.clampZ = function(_) {
98
+ if (!arguments.length) return zClamp;
99
+ zClamp = Math.max(1, +_);
100
+ return fisheye;
101
+ };
102
+
103
+ // Convenience: set focus from a pointer event relative to an HTMLElement/SVG
104
+ // Example: svg.on("pointermove", (e) => fe.focusFromEvent(e, svg.node()))
105
+ fisheye.focusFromEvent = function(event, element) {
106
+ const rect = element.getBoundingClientRect();
107
+ const fx = event.clientX - rect.left;
108
+ const fy = event.clientY - rect.top;
109
+ return fisheye.focus([fx, fy]);
110
+ };
111
+
112
+ return rescale();
113
+ }
114
+ };
115
+
116
+ // src/radial/polarToCartesian.js
117
+ function polarToCartesian (cx, cy, r, t) {
118
+ return { x: cx + r * Math.cos(t), y: cy - r * Math.sin(t) };
119
+ }
120
+
121
+ /**
122
+ * Draw the shortest arc between startAngle and endAngle (radians), CCW.
123
+ * If the CW path is shorter, swap start/end so the CCW path is still shortest.
124
+ * Works with Y-inverted screen coords (polarToCartesian already inverts Y).
125
+ */
126
+ function describeArc(cx, cy, radius, startAngle, endAngle) {
127
+ const TAU = Math.PI * 2;
128
+ const norm = (t) => ((t % TAU) + TAU) % TAU;
129
+ let a0 = norm(startAngle);
130
+ let a1 = norm(endAngle);
131
+
132
+ // CCW and CW spans
133
+ const ccw = (a1 - a0 + TAU) % TAU;
134
+ const cw = (a0 - a1 + TAU) % TAU;
135
+
136
+ // Ensure we always take the shorter span *in CCW* by swapping if needed
137
+ if (cw < ccw) {
138
+ const tmp = a0; a0 = a1; a1 = tmp;
139
+ }
140
+
141
+ const delta = (a1 - a0 + TAU) % TAU; // now the shorter CCW span
142
+ if (delta < 1e-9) {
143
+ const p = polarToCartesian(cx, cy, radius, a0);
144
+ return `M ${p.x} ${p.y}`; // degenerate span → no arc
145
+ }
146
+
147
+ const largeArcFlag = delta > Math.PI ? 1 : 0; // should be 0 for “shortest”, but keep for safety
148
+ const sweepFlag = 0; // CCW
149
+
150
+ const p0 = polarToCartesian(cx, cy, radius, a0);
151
+ const p1 = polarToCartesian(cx, cy, radius, a1);
152
+
153
+ return `M ${p0.x} ${p0.y} A ${radius} ${radius} 0 ${largeArcFlag} ${sweepFlag} ${p1.x} ${p1.y}`;
154
+ }
155
+
156
+ /**
157
+ * Recursive function for pre-order traversal of tree (returns array)
158
+ */
159
+ function preorder(node, list = []) {
160
+ list.push(node);
161
+ for (let i = 0; i < (node.children?.length || 0); i++) {
162
+ list = preorder(node.children[i], list);
163
+ }
164
+ return list;
165
+ }
166
+
167
+ /**
168
+ * Convert parsed Newick tree from readTree() into data
169
+ * frame.
170
+ * this is akin to a "phylo" object in R.
171
+ */
172
+
173
+ function fortify (tree, sort = true) {
174
+ var df = [];
175
+
176
+ for (const node of preorder(tree)) {
177
+ if (node.parent === null) {
178
+ df.push({
179
+ 'parentId': null,
180
+ 'parentLabel': null,
181
+ 'thisId': node.id,
182
+ 'thisLabel': node.label,
183
+ 'children': node.children.map(x => x.id),
184
+ 'branchLength': 0.,
185
+ 'isTip': false,
186
+ 'x': node.x,
187
+ 'y': node.y,
188
+ 'angle': node.angle
189
+ });
190
+ }
191
+ else {
192
+ df.push({
193
+ 'parentId': node.parent.id,
194
+ 'parentLabel': node.parent.label,
195
+ 'thisId': node.id,
196
+ 'thisLabel': node.label,
197
+ 'children': node.children.map(x => x.id),
198
+ 'branchLength': node.branchLength,
199
+ 'isTip': (node.children.length == 0),
200
+ 'x': node.x,
201
+ 'y': node.y,
202
+ 'angle': node.angle
203
+ });
204
+ }
205
+ }
206
+
207
+ if (sort) {
208
+ df = df.sort(function (a, b) {
209
+ return a.thisId - b.thisId;
210
+ });
211
+ }
212
+ return (df);
213
+ }
214
+
215
+ /**
216
+ * Compute per-node polar coordinates for radial layout:
217
+ * - Tip angles: evenly spaced 0..2π in tip DFS order
218
+ * - Internal angles: circular mean of child angles
219
+ * - Radii: cumulative branch length from root
220
+ * - x,y: cartesian projection
221
+ *
222
+ * Returns the fortified array with added {angle, r, x, y}.
223
+ */
224
+ function radialData(node) {
225
+ const TAU = Math.PI * 2;
226
+ const norm = (t) => ((t % TAU) + TAU) % TAU;
227
+
228
+ const pd = fortify(node, /*sort*/ true);
229
+ const byId = new Map(pd.map(d => [d.thisId, d]));
230
+ const kids = new Map(pd.map(d => [d.thisId, d.children || []]));
231
+
232
+ // Find root id
233
+ let root = null;
234
+ for (const d of pd) {
235
+ if (d.parentId == null) { root = d.thisId; break; }
236
+ }
237
+
238
+ // Collect tip ids in DFS left->right order to preserve input ordering
239
+ const tipIds = [];
240
+ (function dfs(id) {
241
+ const c = kids.get(id) || [];
242
+ if (c.length === 0) {
243
+ tipIds.push(id);
244
+ return;
245
+ }
246
+ for (const ch of c) dfs(ch);
247
+ })(root);
248
+
249
+ // Assign tip angles evenly spaced 0..2π
250
+ const N = Math.max(1, tipIds.length);
251
+ const angle = new Map();
252
+ tipIds.forEach((id, i) => {
253
+ angle.set(id, (i / N) * TAU);
254
+ });
255
+
256
+ // Internal node angles: circular mean of child angles (post-order)
257
+ (function setInternalAngles(id) {
258
+ const c = kids.get(id) || [];
259
+ for (const ch of c) setInternalAngles(ch);
260
+ if (c.length > 0) {
261
+ let sx = 0, sy = 0;
262
+ for (const ch of c) {
263
+ const th = angle.get(ch);
264
+ sx += Math.cos(th);
265
+ sy += Math.sin(th);
266
+ }
267
+ angle.set(id, norm(Math.atan2(sy, sx)));
268
+ }
269
+ })(root);
270
+
271
+ // Radii: cumulative branch lengths from root (root r=0)
272
+ const radius = new Map();
273
+ radius.set(root, 0);
274
+ (function setR(id) {
275
+ const c = kids.get(id) || [];
276
+ const r0 = radius.get(id) || 0;
277
+ for (const ch of c) {
278
+ const child = byId.get(ch);
279
+ const bl = child?.branchLength ?? 0;
280
+ radius.set(ch, r0 + bl);
281
+ setR(ch);
282
+ }
283
+ })(root);
284
+
285
+ // Enrich pd rows with angle, r, x, y
286
+ for (const d of pd) {
287
+ const th = angle.get(d.thisId) ?? 0;
288
+ const r = radius.get(d.thisId) ?? 0;
289
+ d.angle = th;
290
+ d.r = r;
291
+ d.x = r * Math.cos(th);
292
+ d.y = r * Math.sin(th);
293
+ }
294
+
295
+ return pd;
296
+ }
297
+
298
+ /**
299
+ * Per-edge radial segments (for highlighting and drawing).
300
+ * For each non-root node, draw a radial line from the parent radius to the child radius
301
+ * at the CHILD'S angle.
302
+ *
303
+ * Output: [{ parentId, childId, x0, y0, x1, y1, isTip }]
304
+ */
305
+ function getRadii(node) {
306
+ const data = radialData(node);
307
+ const byId = new Map(data.map(d => [d.thisId, d]));
308
+ const root = data.find(d => d.parentId == null)?.thisId;
309
+
310
+ const segments = [];
311
+ for (const d of data) {
312
+ if (d.thisId === root) continue;
313
+ const parent = byId.get(d.parentId);
314
+ if (!parent) continue;
315
+
316
+ const theta = d.angle;
317
+ const r0 = parent.r;
318
+ const r1 = d.r;
319
+
320
+ segments.push({
321
+ parentId: parent.thisId,
322
+ childId: d.thisId,
323
+ x0: r0 * Math.cos(theta),
324
+ y0: r0 * Math.sin(theta),
325
+ x1: r1 * Math.cos(theta),
326
+ y1: r1 * Math.sin(theta),
327
+ isTip: !!d.isTip
328
+ });
329
+ }
330
+ return segments;
331
+ }
332
+
333
+ /**
334
+ * Build arc descriptors for each internal parent:
335
+ * - One arc per internal node at radius = parent.r
336
+ * - Start/end angles choose the *shortest* wrap-aware span covering the children
337
+ * - Skips degenerate spans (delta ~ 0)
338
+ */
339
+ function getArcs(pd) {
340
+ const TAU = Math.PI * 2;
341
+ const norm = (t) => ((t % TAU) + TAU) % TAU;
342
+ const EPS = 1e-6;
343
+
344
+ // Quick lookups
345
+ new Map(pd.map(d => [d.thisId, d]));
346
+ const childrenByParent = new Map();
347
+ let root = null;
348
+
349
+ for (const d of pd) {
350
+ if (d.parentId == null) root = d.thisId;
351
+ if (!childrenByParent.has(d.parentId)) childrenByParent.set(d.parentId, []);
352
+ childrenByParent.get(d.parentId).push(d);
353
+ }
354
+
355
+ const arcs = [];
356
+
357
+ for (const parent of pd) {
358
+ const pid = parent.thisId;
359
+ if (pid === root) continue; // no arc above root
360
+ const kids = childrenByParent.get(pid) || [];
361
+ if (kids.length < 2) continue; // need at least two children
362
+
363
+ // Collect & sort child angles
364
+ const A = kids.map(k => norm(k.angle)).sort((a, b) => a - b);
365
+ const aMin = A[0], aMax = A[A.length - 1];
366
+
367
+ // Two candidate spans: direct (aMin -> aMax) and wrapped (aMax -> aMin across 2π)
368
+ const direct = aMax - aMin;
369
+ const wrapped = TAU - direct;
370
+
371
+ // Choose the shorter span. We'll draw **CCW** (sweepFlag = 0) in describeArc.
372
+ let start, end, span;
373
+ if (direct <= wrapped) {
374
+ start = aMin;
375
+ end = aMax;
376
+ span = direct;
377
+ } else {
378
+ // wrapped is shorter: go CCW from aMax up through 2π to aMin
379
+ start = aMax;
380
+ end = aMin;
381
+ span = wrapped;
382
+ }
383
+
384
+ if (span < EPS || !isFinite(parent.r) || parent.r <= 0) continue;
385
+
386
+ arcs.push({
387
+ start,
388
+ end,
389
+ radius: parent.r,
390
+ thisId: pid,
391
+ parentId: parent.parentId
392
+ });
393
+ }
394
+
395
+ return arcs;
396
+ }
397
+
398
+ /**
399
+ * Simple wrapper for radial layout:
400
+ * - data: per-node { angle, r, x, y, ... }
401
+ * - radii: per-edge radial spokes (parent.r → child.r)
402
+ * - arcs: per-internal-node arcs spanning its children at parent radius
403
+ */
404
+ function radialLayout(node) {
405
+ const data = {};
406
+ data.data = radialData(node);
407
+ data.radii = getRadii(node);
408
+ data.arcs = getArcs(data.data);
409
+ return data;
410
+ }
411
+
412
+ /**
413
+ * Iterable mean
414
+ * Poached from https://github.com/d3/d3-array/blob/master/src/mean.js
415
+ * (Other array means buggered up the tree)
416
+ */
417
+
418
+ function mean (values, valueof) {
419
+ let count = 0;
420
+ let sum = 0;
421
+ {
422
+ for (let value of values) {
423
+ if (value != null && (value = +value) >= value) {
424
+ ++count, sum += value;
425
+ }
426
+ }
427
+ }
428
+ if (count) return sum / count;
429
+ }
430
+
431
+ /**
432
+ * Rectangle layout: compute per-node x0,x1 and y0=y1
433
+ * - Tip y is assigned by input order (preserves ladderize/order)
434
+ * - Internal node y is mean of child y's
435
+ * - x1 accumulates branch lengths from root
436
+ */
437
+
438
+ function getHorizontal(node) {
439
+ const pd = fortify(node);
440
+
441
+ // Fast lookup from id -> pd index
442
+ const idIndex = new Map(pd.map((d, i) => [d.thisId, i]));
443
+
444
+ // 1) Leaf order from the INPUT TREE (respects your child order / ladderize)
445
+ const leafIds = [];
446
+ (function dfs(n) {
447
+ if (!n.children || n.children.length === 0) { leafIds.push(n.id); return; }
448
+ n.children.forEach(dfs);
449
+ })(node);
450
+
451
+ // Map each leaf id to a vertical slot (1..N)
452
+ const tipSlot = new Map(leafIds.map((id, i) => [id, i + 1]));
453
+
454
+ // 2) Set Y for tips directly from that order; internal node Y via children mean
455
+ (function setY(n) {
456
+ const i = idIndex.get(n.id);
457
+ if (!n.children || n.children.length === 0) {
458
+ const y = tipSlot.get(n.id);
459
+ pd[i].y0 = y; pd[i].y1 = y;
460
+ return y;
461
+ }
462
+ const ys = n.children.map(setY);
463
+ const y = mean(ys);
464
+ pd[i].y0 = y; pd[i].y1 = y;
465
+ return y;
466
+ })(node);
467
+
468
+ // 3) Set X by accumulating branch lengths down the tree
469
+ (function setX(n, xParent) {
470
+ const i = idIndex.get(n.id);
471
+ const bl = pd[i].branchLength ?? 0;
472
+ const x0 = xParent ?? 0;
473
+ const x1 = x0 + bl;
474
+ pd[i].x0 = x0; pd[i].x1 = x1;
475
+ if (n.children && n.children.length) n.children.forEach(c => setX(c, x1));
476
+ })(node, 0);
477
+
478
+ // Clean up: remove fields not needed downstream without triggering no-unused-vars
479
+ return pd.map((row) => {
480
+ const { y: _y, x: _x, angle: _angle, ...item } = row;
481
+ return item;
482
+ });
483
+ }
484
+
485
+ function getVertical(node) {
486
+ const data = getHorizontal(node);
487
+
488
+ // Group rows by parentId (children that share a parent)
489
+ const byParent = new Map();
490
+ for (const row of data) {
491
+ if (row.parentId == null) continue;
492
+ const a = byParent.get(row.parentId);
493
+ if (a) a.push(row); else byParent.set(row.parentId, [row]);
494
+ }
495
+
496
+ const verticals = [];
497
+ for (const [parentId, kids] of byParent.entries()) {
498
+ if (!kids.length) continue;
499
+ // Works for binary and multifurcations:
500
+ const yvals = kids.map(d => d.y0);
501
+ const y0 = Math.min(...yvals);
502
+ const y1 = Math.max(...yvals);
503
+ // All children share the same junction x (their x0)
504
+ const x = kids[0].x0;
505
+
506
+ verticals.push({
507
+ parentId,
508
+ x0: x,
509
+ x1: x,
510
+ y0,
511
+ y1,
512
+ heights: y1 - y0
513
+ });
514
+ }
515
+
516
+ return verticals;
517
+ }
518
+
519
+ /**
520
+ * Build per-child vertical segments for a rectangular tree:
521
+ * For each non-root node (child), draw a vertical from (parent.x, child.y) to (parent.x, parent.y).
522
+ * This yields exactly one vertical per edge (child->parent), making highlighting trivial.
523
+ *
524
+ * Returns an array of:
525
+ * {
526
+ * parentId: number,
527
+ * childId: number,
528
+ * x: number, // x of the parent junction
529
+ * y0: number, // min(child.y, parent.y)
530
+ * y1: number, // max(child.y, parent.y)
531
+ * }
532
+ */
533
+ function getChildVerticals(node) {
534
+ const data = getHorizontal(node); // has parentId, thisId, x0,x1,y0=y1
535
+
536
+ // Build a quick index to access parent's y by id
537
+ const byId = new Map(data.map(d => [d.thisId, d]));
538
+
539
+ const childVerticals = [];
540
+
541
+ for (const d of data) {
542
+ if (d.parentId == null) continue;
543
+ const parent = byId.get(d.parentId);
544
+ if (!parent) continue;
545
+
546
+ const x = d.x0; // child’s vertical sits at parent.x == child.x0
547
+ const yc = d.y0; // child y
548
+ const yp = parent.y0; // parent y
549
+ const y0 = Math.min(yc, yp);
550
+ const y1 = Math.max(yc, yp);
551
+
552
+ childVerticals.push({
553
+ parentId: d.parentId,
554
+ childId: d.thisId,
555
+ x,
556
+ y0,
557
+ y1
558
+ });
559
+ }
560
+
561
+ return childVerticals;
562
+ }
563
+
564
+ /**
565
+ * Rectangle layout wrapper.
566
+ * Returns:
567
+ * - data: per-node rows (x0,x1,y0=y1,...)
568
+ * - vertical_lines: single spanning vertical per parent (baseline draw)
569
+ * - child_vertical_lines: one vertical per edge (for highlighting)
570
+ * - horizontal_lines: per-edge child horizontals (x0->x1 at y), with labels & tip flags
571
+ */
572
+ function rectangleLayout(node) {
573
+ const data = getHorizontal(node); // per-node
574
+ const vertical_lines = getVertical(node); // parent spans
575
+ const child_vertical_lines = getChildVerticals(node); // per-edge verticals
576
+
577
+ // IMPORTANT: include y0 & y1, and carry isTip/labels for the renderer
578
+ new Map(data.map(d => [d.thisId, d]));
579
+ const horizontal_lines = data
580
+ .filter(d => d.parentId != null)
581
+ .map(d => ({
582
+ parentId: d.parentId,
583
+ childId: d.thisId,
584
+ thisId: d.thisId,
585
+ thisLabel: d.thisLabel,
586
+ isTip: d.isTip,
587
+ x0: d.x0,
588
+ x1: d.x1,
589
+ y0: d.y0,
590
+ y1: d.y0
591
+ }));
592
+
593
+ return { data, vertical_lines, child_vertical_lines, horizontal_lines };
594
+ }
595
+
596
+ /**
597
+ * Convert parsed Newick tree from fortify() into data frame of edges
598
+ * this is akin to a "phylo" object in R, where thisID and parentId
599
+ * are the $edge slot. I think.
600
+ */
601
+
602
+ function edges(df, rectangular = false) {
603
+ const rows = [...df].sort((a, b) => a.thisId - b.thisId);
604
+ const byId = new Map(rows.map((r) => [r.thisId, r]));
605
+ const result = [];
606
+
607
+ for (const row of rows) {
608
+ if (row.parentId == null) continue;
609
+ const parent = byId.get(row.parentId);
610
+ if (!parent) continue;
611
+
612
+ if (rectangular) {
613
+ result.push({ x1: row.x, y1: row.y, id1: row.thisId, x2: parent.x, y2: row.y, id2: undefined });
614
+ result.push({ x1: parent.x, y1: row.y, id1: undefined, x2: parent.x, y2: parent.y, id2: row.parentId });
615
+ } else {
616
+ result.push({ x1: row.x, y1: row.y, id1: row.thisId, x2: parent.x, y2: parent.y, id2: row.parentId });
617
+ }
618
+ }
619
+ return result;
620
+ }
621
+
622
+ /**
623
+ * Recursive function for breadth-first search of a tree
624
+ * the root node is visited first.
625
+ */
626
+
627
+ function levelorder(root) {
628
+ const queue = [root], result = [];
629
+ while (queue.length) {
630
+ const curnode = queue.shift(); // <- FIFO
631
+ result.push(curnode);
632
+ for (const child of curnode.children) queue.push(child);
633
+ }
634
+ return result;
635
+ }
636
+
637
+
638
+ /**
639
+ * Count the number of tips that descend from this node
640
+ */
641
+
642
+ function numTips(thisnode) {
643
+ var result = 0;
644
+ for (const node of levelorder(thisnode)) {
645
+ if (node.children.length == 0) result++;
646
+ }
647
+ return (result);
648
+ }
649
+
650
+ /**
651
+ * Equal-angle layout for unrooted trees.
652
+ * - Precomputes ntips in O(n) to avoid repeated subtree counts
653
+ * - Uses angles in "π units" (0..2) to match existing API
654
+ * - Populates x,y positions from branchLength and angle
655
+ */
656
+
657
+ function annotateTipCounts(root) {
658
+ (function post(n) {
659
+ if (!n.children || n.children.length === 0) {
660
+ n.ntips = 1; return 1;
661
+ }
662
+ let sum = 0;
663
+ for (const c of n.children) sum += post(c);
664
+ n.ntips = sum;
665
+ return sum;
666
+ })(root);
667
+ return root;
668
+ }
669
+
670
+ function equalAngleLayout(node) {
671
+ if (node.parent === null) {
672
+ annotateTipCounts(node);
673
+ node.start = 0.; // guarantees no arcs overlap 0
674
+ node.end = 2.; // *π
675
+ node.angle = 0.; // irrelevant at root
676
+ node.ntips = numTips(node); // safe (already computed), left for compatibility
677
+ node.x = 0;
678
+ node.y = 0;
679
+ }
680
+
681
+ let lastStart = node.start;
682
+
683
+ for (let i = 0; i < node.children.length; i++) {
684
+ const child = node.children[i];
685
+ const arc = (node.end - node.start) * (child.ntips / node.ntips);
686
+
687
+ child.start = lastStart;
688
+ child.end = lastStart + arc;
689
+
690
+ // bisect the arc in π-units
691
+ child.angle = child.start + (child.end - child.start) / 2.;
692
+ lastStart = child.end;
693
+
694
+ // map to coordinates (convert π-units to radians by multiplying by Math.PI)
695
+ const theta = child.angle * Math.PI;
696
+ const bl = (child.branchLength ?? 0);
697
+ child.x = node.x + bl * Math.sin(theta);
698
+ child.y = node.y + bl * Math.cos(theta);
699
+
700
+ equalAngleLayout(child);
701
+ }
702
+
703
+ return node;
704
+ }
705
+
706
+ /**
707
+ * Simple wrapper function for equalAngleLayout()
708
+ */
709
+
710
+ function unrooted (node) {
711
+ var data = {};
712
+ // use the Felsenstein equal angle layout algorithm
713
+ var eq = fortify(equalAngleLayout(node));
714
+ data.data = eq;
715
+ // make the edges dataset
716
+ data.edges = edges(eq);
717
+
718
+ return data;
719
+ }
720
+
721
+ function makeIndexById(rows, key = "thisId") {
722
+ return new Map(rows.map(d => [d[key], d]));
723
+ }
724
+ function parentFisheye(d, data) {
725
+ const byId = makeIndexById(data);
726
+ const parent = byId.get(d.parentId);
727
+ return parent ? { px: parent.fisheye.x, py: parent.fisheye.y } : null;
728
+ }
729
+
730
+ /**
731
+ * Parse a Newick tree string into a doubly-linked list of JS Objects.
732
+ * Assigns labels, branch lengths, and node IDs (tips before internals if input emits them that way).
733
+ *
734
+ * Notes / limitations:
735
+ * - Quoted labels and NHX annotations are not fully supported.
736
+ * - Branch lengths in scientific notation are supported (parseFloat).
737
+ */
738
+
739
+ function readTree(text) {
740
+ // Remove all whitespace (space, tabs, newlines)
741
+ text = String(text).replace(/\s+/g, '');
742
+
743
+ const tokens = text.split(/(;|\(|\)|,)/);
744
+ const root = { parent: null, children: [] };
745
+ let curnode = root;
746
+ let nodeId = 0;
747
+
748
+ for (const token of tokens) {
749
+ if (!token || token === ';') continue;
750
+
751
+ if (token === '(') {
752
+ const child = { parent: curnode, children: [] };
753
+ curnode.children.push(child);
754
+ curnode = child; // descend
755
+ } else if (token === ',') {
756
+ // back to parent, then create sibling
757
+ curnode = curnode.parent;
758
+ const child = { parent: curnode, children: [] };
759
+ curnode.children.push(child);
760
+ curnode = child;
761
+ } else if (token === ')') {
762
+ // ascend one level
763
+ curnode = curnode.parent;
764
+ if (curnode === null) break;
765
+ } else {
766
+ // label/branch-length chunk (e.g., "A:0.01" or "A")
767
+ const nodeinfo = token.split(':');
768
+ if (nodeinfo.length === 1) {
769
+ if (token.startsWith(':')) {
770
+ curnode.label = '';
771
+ curnode.branchLength = parseFloat(nodeinfo[0]);
772
+ } else {
773
+ curnode.label = nodeinfo[0];
774
+ curnode.branchLength = null;
775
+ }
776
+ } else if (nodeinfo.length === 2) {
777
+ curnode.label = nodeinfo[0];
778
+ curnode.branchLength = parseFloat(nodeinfo[1]);
779
+ } else {
780
+ console.warn(token, "Unhandled token with multiple ':' characters");
781
+ curnode.label = nodeinfo[0] || '';
782
+ curnode.branchLength = parseFloat(nodeinfo[nodeinfo.length - 1]);
783
+ }
784
+ curnode.id = nodeId++; // assign then increment
785
+ }
786
+ }
787
+
788
+ // Ensure root has an id if not assigned during parsing
789
+ if (root.id == null) root.id = nodeId;
790
+
791
+ return root;
792
+ }
793
+
794
+ /**
795
+ * Subset a tree given a node - i.e. the node of interests and all the descendents
796
+ */
797
+
798
+ function subTree (tree, node) {
799
+ // Thanks Richard Challis!
800
+ let fullTree = {};
801
+ tree.data.forEach(obj => {
802
+ fullTree[obj.thisId] = { ...obj };
803
+ });
804
+
805
+ let subTree = {};
806
+ const getDescendants = function (rootNodeId) {
807
+ if (fullTree[rootNodeId]) {
808
+ subTree[rootNodeId] = fullTree[rootNodeId];
809
+ if (fullTree[rootNodeId].children) {
810
+ fullTree[rootNodeId].children.forEach(childNodeId => {
811
+ getDescendants(childNodeId);
812
+ });
813
+ }
814
+ }
815
+ };
816
+ // call the recursive function
817
+ getDescendants(node);
818
+
819
+ // in each of the functions, data contains the children key
820
+ const data = [["data", Object.values(subTree)]];
821
+
822
+ const nodes = data[0][1].map(d => d.thisId);
823
+
824
+ var res = [];
825
+ // in all keys except data, push to new array
826
+ for (const node in tree) {
827
+ if (node === "data") continue;
828
+ res.push([node, tree[node]]);
829
+ }
830
+
831
+ var filtered = res.map(d => [
832
+ d[0],
833
+ d[1].filter(d => nodes.includes(d.thisId))
834
+ ]);
835
+
836
+ return Object.fromEntries(data.concat(filtered));
837
+ }
838
+
839
+ function drawPhylogeny(
840
+ treeText,
841
+ {
842
+ layout = "rect", // "rect" or "radial"
843
+ width = 800,
844
+ height = 800,
845
+ margin = { top: 20, right: 300, bottom: 20, left: 50 },
846
+ radialMargin = 80,
847
+ strokeWidth = 1,
848
+ radialMode = "outer" // or "align"
849
+ } = {}
850
+ ) {
851
+ if (layout === "rect") {
852
+ // RECTANGULAR LAYOUT
853
+ const tree_df = rectangleLayout(readTree(treeText));
854
+ const horizontal = tree_df.horizontal_lines;
855
+ const vertical = tree_df.vertical_lines;
856
+ const tips = horizontal.filter((d) => d.isTip);
857
+
858
+ const maxY = d3.max(horizontal, (d) => d.y1);
859
+ const minY = d3.min(horizontal, (d) => d.y1);
860
+ const maxX = d3.max(horizontal, (d) => d.x1);
861
+
862
+ const yScale = d3
863
+ .scaleLinear()
864
+ .domain([minY - 1, maxY + 1])
865
+ .range([margin.top, height - margin.bottom]);
866
+
867
+ const xScale = d3
868
+ .scaleLinear()
869
+ .domain([0, maxX])
870
+ .range([margin.left, width - margin.right]);
871
+
872
+ const svg = d3
873
+ .create("svg")
874
+ .attr("width", width)
875
+ .attr("height", height)
876
+ .attr("font-family", "sans-serif")
877
+ .attr("font-size", 10);
878
+
879
+ const group = svg.append("g");
880
+
881
+ group
882
+ .selectAll(".hline")
883
+ .data(horizontal)
884
+ .join("line")
885
+ .attr("x1", (d) => xScale(d.x0))
886
+ .attr("y1", (d) => yScale(d.y0))
887
+ .attr("x2", (d) => xScale(d.x1))
888
+ .attr("y2", (d) => yScale(d.y1))
889
+ .attr("stroke", "#555")
890
+ .attr("stroke-width", strokeWidth);
891
+
892
+ group
893
+ .selectAll(".vline")
894
+ .data(vertical)
895
+ .join("line")
896
+ .attr("x1", (d) => xScale(d.x0))
897
+ .attr("y1", (d) => yScale(d.y0))
898
+ .attr("x2", (d) => xScale(d.x1))
899
+ .attr("y2", (d) => yScale(d.y1))
900
+ .attr("stroke", "#555")
901
+ .attr("stroke-width", strokeWidth);
902
+
903
+ group
904
+ .selectAll(".tip-dot")
905
+ .data(tips)
906
+ .join("circle")
907
+ .attr("cx", (d) => xScale(d.x1))
908
+ .attr("cy", (d) => yScale(d.y1))
909
+ .attr("r", 2)
910
+ .attr("fill", "black");
911
+
912
+ svg
913
+ .append("g")
914
+ .selectAll("text")
915
+ .data(tips)
916
+ .join("text")
917
+ .attr("x", (d) => xScale(d.x1) + 4)
918
+ .attr("y", (d) => yScale(d.y1))
919
+ .attr("dy", "0.32em")
920
+ .attr("font-size", 10)
921
+ .text((d) => d.thisLabel?.replace(/_/g, " ") ?? "");
922
+
923
+ return svg.node();
924
+ } else if (layout === "radial") {
925
+ const parsedTree = readTree(treeText);
926
+ const rad = radialLayout(parsedTree);
927
+
928
+ // ===== MODE / DEBUG =====
929
+ const TIP_MODE = radialMode; // "align" (shorten to original tips) or "outer" (project to one circle)
930
+ const isOuter = TIP_MODE === "outer";
931
+
932
+ // visuals (0 = let spokes reach the dots)
933
+ const DOT_R = 3;
934
+ const END_CAP = 0;
935
+
936
+ // ===== SCALES / BOUNDS =====
937
+ const maxRadius = d3.max(rad.data, (d) => d.r) ?? 0;
938
+ const scaleRadial = maxRadius + 2 * radialMargin;
939
+ const w = width,
940
+ h = height;
941
+ const centerX = w / 2,
942
+ centerY = h / 2;
943
+
944
+ const xScaleRadial = d3
945
+ .scaleLinear()
946
+ .domain([-scaleRadial, scaleRadial])
947
+ .range([0, w]);
948
+ const yScaleRadial = d3
949
+ .scaleLinear()
950
+ .domain([-scaleRadial, scaleRadial])
951
+ .range([h, 0]);
952
+ const radiusPx = (r) => r * (w / (2 * scaleRadial));
953
+
954
+ // ===== INDEXES / HELPERS =====
955
+ const byId = new Map(rad.data.map((d) => [d.thisId, d]));
956
+ const tips = rad.data.filter((d) => d.isTip);
957
+ const tipMaxR = tips.length ? d3.max(tips, (d) => d.r) : 0;
958
+
959
+ // Robust child-id extractor (handles multiple shapes)
960
+ function childIdOf(spoke) {
961
+ // prefer explicit child id fields; fall back to thisId; last-ditch id1 (seen in some edge shapes)
962
+ return spoke.childId ?? spoke.thisId ?? spoke.id1 ?? null;
963
+ }
964
+
965
+ // Shorten the *screen-space* end of a spoke by END_CAP px
966
+ function shortenSpokePx(x0, y0, x1, y1) {
967
+ const X0 = xScaleRadial(x0),
968
+ Y0 = yScaleRadial(y0);
969
+ const X1 = xScaleRadial(x1),
970
+ Y1 = yScaleRadial(y1);
971
+ const dx = X1 - X0,
972
+ dy = Y1 - Y0;
973
+ const len = Math.hypot(dx, dy) || 1;
974
+ const t = Math.max(0, (len - END_CAP) / len);
975
+ return { X0, Y0, X1s: X0 + dx * t, Y1s: Y0 + dy * t, len };
976
+ }
977
+
978
+ // ===== SVG ROOT =====
979
+ const svg = d3
980
+ .create("svg")
981
+ .attr("width", w)
982
+ .attr("height", h)
983
+ .attr("font-family", "sans-serif")
984
+ .attr("font-size", 10);
985
+
986
+ const group = svg.append("g");
987
+
988
+ // ===== ARCS (parent circles) =====
989
+ group
990
+ .append("g")
991
+ .attr("class", "phylo_arcs")
992
+ .selectAll("path")
993
+ .data(rad.arcs)
994
+ .join("path")
995
+ .attr("d", (d) =>
996
+ describeArc(
997
+ centerX,
998
+ centerY,
999
+ Math.max(0, radiusPx(d.radius)),
1000
+ d.start,
1001
+ d.end
1002
+ )
1003
+ )
1004
+ .attr("fill", "none")
1005
+ .attr("stroke", "#777")
1006
+ .attr("stroke-width", strokeWidth);
1007
+
1008
+ // ===== RADII (spokes) =====
1009
+ group
1010
+ .append("g")
1011
+ .attr("class", "phylo_radii")
1012
+ .selectAll("line")
1013
+ .data(rad.radii)
1014
+ .join("line")
1015
+ .each(function(s, _) {
1016
+ // parent end (data space)
1017
+ const x0 = s.x0,
1018
+ y0 = s.y0;
1019
+
1020
+ // child end (data space), shape-agnostic
1021
+ const cid = childIdOf(s);
1022
+ const node = cid != null ? byId.get(cid) : undefined;
1023
+ const isTipSpoke = !!(node && node.isTip);
1024
+
1025
+ // default to the original child endpoint from the spoke record
1026
+ let x1 = s.x1,
1027
+ y1 = s.y1;
1028
+
1029
+ // In "outer" mode, project only *tip* spokes to the common circle
1030
+ if (isOuter && isTipSpoke) {
1031
+ x1 = tipMaxR * Math.cos(node.angle);
1032
+ y1 = tipMaxR * Math.sin(node.angle);
1033
+ }
1034
+
1035
+ // Shorten in screen space so the spoke doesn’t pierce the dot (END_CAP can be 0)
1036
+ const { X0, Y0, X1s, Y1s} = shortenSpokePx(x0, y0, x1, y1);
1037
+
1038
+ d3.select(this)
1039
+ .attr("x1", X0)
1040
+ .attr("y1", Y0)
1041
+ .attr("x2", X1s)
1042
+ .attr("y2", Y1s)
1043
+ .attr("stroke", "#777")
1044
+ .attr("stroke-width", strokeWidth);
1045
+ });
1046
+
1047
+ // ===== TIP DOTS =====
1048
+ group
1049
+ .append("g")
1050
+ .attr("class", "phylo_tip_dots")
1051
+ .selectAll("circle")
1052
+ .data(tips)
1053
+ .join("circle")
1054
+ .each(function(d, _) {
1055
+ // dot at original tip (align) or projected circle (outer)
1056
+ const x = isOuter ? tipMaxR * Math.cos(d.angle) : d.x;
1057
+ const y = isOuter ? tipMaxR * Math.sin(d.angle) : d.y;
1058
+
1059
+ d3.select(this)
1060
+ .attr("cx", xScaleRadial(x))
1061
+ .attr("cy", yScaleRadial(y))
1062
+ .attr("r", DOT_R)
1063
+ .attr("fill", "black")
1064
+ .attr("stroke", "black")
1065
+ .attr("stroke-width", 1.5);
1066
+ });
1067
+
1068
+ // ===== LABELS (unchanged) =====
1069
+ // Labels — make them follow the tip position used by the current mode
1070
+ group
1071
+ .append("g")
1072
+ .attr("class", "phylo_labels")
1073
+ .selectAll("g.label")
1074
+ .data(tips) // <— bind only tip nodes
1075
+ .join("g")
1076
+ .attr("class", "label")
1077
+ .attr("transform", (d) => {
1078
+ // same tip position rule as dots/spokes:
1079
+ // - "outer": snap to common ring (tipMaxR)
1080
+ // - otherwise (e.g. "align"/"phylo"): true tip radius
1081
+ const r = isOuter ? tipMaxR : d.r;
1082
+ const x = r * Math.cos(d.angle);
1083
+ const y = r * Math.sin(d.angle);
1084
+ return `translate(${xScaleRadial(x)},${yScaleRadial(y)})`;
1085
+ })
1086
+ .each(function(d) {
1087
+ // rotate so text reads outward; flip when on the left side
1088
+ let angle = (-d.angle * 180) / Math.PI;
1089
+ let xoff = 10; // radial padding for text (px)
1090
+ let anchor = "start";
1091
+ if (d.angle > Math.PI / 2 && d.angle < (3 * Math.PI) / 2) {
1092
+ angle += 180;
1093
+ xoff *= -1;
1094
+ anchor = "end";
1095
+ }
1096
+ d3.select(this)
1097
+ .append("g")
1098
+ .attr("transform", `rotate(${angle})`)
1099
+ .append("text")
1100
+ .attr("x", xoff)
1101
+ .attr("alignment-baseline", "middle")
1102
+ .attr("text-anchor", anchor)
1103
+ .attr("font-size", 10)
1104
+ .attr("fill", "black")
1105
+ .text((d) => d.thisLabel?.replace(/_/g, " ") ?? "");
1106
+ });
1107
+
1108
+ return svg.node();
1109
+ } else if (layout === "unrooted") {
1110
+ // UNROOTED LAYOUT
1111
+ const parsedTree = readTree(treeText);
1112
+ const unrootedPhylo = unrooted(parsedTree);
1113
+
1114
+ const w = width;
1115
+ const h = height;
1116
+
1117
+ // Get spatial extent
1118
+ const xExtent = d3.extent(unrootedPhylo.data, (d) => d.x);
1119
+ const yExtent = d3.extent(unrootedPhylo.data, (d) => d.y);
1120
+
1121
+ // Find maximum absolute distance from center (0,0)
1122
+ const maxX = Math.max(Math.abs(xExtent[0]), Math.abs(xExtent[1]));
1123
+ const maxY = Math.max(Math.abs(yExtent[0]), Math.abs(yExtent[1]));
1124
+ const maxRadius = Math.max(maxX, maxY);
1125
+
1126
+ // Add some margin
1127
+ const scaleUnroot = maxRadius + 2 * radialMargin;
1128
+
1129
+ const xScaleUnroot = d3
1130
+ .scaleLinear()
1131
+ .domain([-scaleUnroot, scaleUnroot])
1132
+ .range([0, w]);
1133
+
1134
+ const yScaleUnroot = d3
1135
+ .scaleLinear()
1136
+ .domain([-scaleUnroot, scaleUnroot])
1137
+ .range([h, 0]);
1138
+
1139
+ const svg = d3
1140
+ .create("svg")
1141
+ .attr("width", w)
1142
+ .attr("height", h)
1143
+ .attr("font-family", "sans-serif")
1144
+ .attr("font-size", 10);
1145
+
1146
+ const group = svg.append("g");
1147
+
1148
+ // Edges
1149
+ group
1150
+ .append("g")
1151
+ .attr("class", "phylo_lines")
1152
+ .selectAll("line")
1153
+ .data(unrootedPhylo.edges)
1154
+ .join("line")
1155
+ .attr("x1", (d) => xScaleUnroot(d.x1))
1156
+ .attr("y1", (d) => yScaleUnroot(d.y1))
1157
+ .attr("x2", (d) => xScaleUnroot(d.x2))
1158
+ .attr("y2", (d) => yScaleUnroot(d.y2))
1159
+ .attr("stroke-width", strokeWidth)
1160
+ .attr("stroke", "#777");
1161
+
1162
+ // Nodes
1163
+ group
1164
+ .append("g")
1165
+ .attr("class", "phylo_points")
1166
+ .selectAll("circle")
1167
+ .data(unrootedPhylo.data)
1168
+ .join("circle")
1169
+ .attr("class", "dot")
1170
+ .attr("r", (d) => (d.isTip ? 4 : 0))
1171
+ .attr("cx", (d) => xScaleUnroot(d.x))
1172
+ .attr("cy", (d) => yScaleUnroot(d.y))
1173
+ .attr("stroke", "black")
1174
+ .attr("stroke-width", 2)
1175
+ .attr("fill", (d) => (d.isTip ? "black" : "white"));
1176
+
1177
+ // Tip labels
1178
+ const tipEdges = new Map();
1179
+ const nodesById = new Map(unrootedPhylo.data.map((d) => [d.thisId, d]));
1180
+
1181
+ unrootedPhylo.edges.forEach((edge) => {
1182
+ const tipNode = nodesById.get(edge.id1);
1183
+ if (tipNode?.isTip) {
1184
+ tipEdges.set(edge.id1, edge);
1185
+ }
1186
+ });
1187
+
1188
+ group
1189
+ .append("g")
1190
+ .attr("class", "phylo_labels")
1191
+ .selectAll("g")
1192
+ .data(unrootedPhylo.data.filter((d) => d.isTip))
1193
+ .join("g")
1194
+ .attr("transform", (d) => {
1195
+ const x = xScaleUnroot(d.x);
1196
+ const y = yScaleUnroot(d.y);
1197
+ return `translate(${x},${y})`;
1198
+ })
1199
+ .each(function(d) {
1200
+ const edge = tipEdges.get(d.thisId);
1201
+ if (!edge) {
1202
+ console.warn(
1203
+ "No incoming edge found for tip node:",
1204
+ d.thisId,
1205
+ d.thisLabel
1206
+ );
1207
+ return;
1208
+ }
1209
+
1210
+ // Compute angle of the incoming edge (screen coords)
1211
+ const x1 = xScaleUnroot(edge.x1);
1212
+ const y1 = yScaleUnroot(edge.y1);
1213
+ const x2 = xScaleUnroot(edge.x2);
1214
+ const y2 = yScaleUnroot(edge.y2);
1215
+
1216
+ const dx = x2 - x1;
1217
+ const dy = y2 - y1;
1218
+ let angle = (Math.atan2(dy, dx) * 180) / Math.PI;
1219
+
1220
+ // Flip label if upside down
1221
+ let xOffset = -10;
1222
+ let anchor = "end";
1223
+ if (angle > 90 || angle < -90) {
1224
+ angle += 180;
1225
+ anchor = "start";
1226
+ xOffset = 10;
1227
+ }
1228
+
1229
+ // Draw label rotated along branch direction
1230
+ d3.select(this)
1231
+ .append("g")
1232
+ .attr("transform", `rotate(${angle})`)
1233
+ .append("text")
1234
+ .attr("x", xOffset)
1235
+ .attr("alignment-baseline", "middle")
1236
+ .attr("text-anchor", anchor)
1237
+ .attr("font-size", 10)
1238
+ .attr("fill", "black")
1239
+ .text(d.thisLabel?.replace(/_/g, " ") ?? "");
1240
+ });
1241
+
1242
+ return svg.node();
1243
+ } else {
1244
+ throw new Error("Unsupported layout type. Use 'rect' or 'radial'.");
1245
+ }
1246
+ }
1247
+
1248
+ export { describeArc, drawPhylogeny, parentFisheye, phisheye, radialLayout, readTree, rectangleLayout, subTree, unrooted };
2
1249
  //# sourceMappingURL=index.js.map