@euphrasiologist/lwphylo 1.1.15 → 1.2.2

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