phylotree 2.1.7 → 2.2.0

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/phylotree.js CHANGED
@@ -8274,6 +8274,16 @@
8274
8274
  /**
8275
8275
  * Get the tips of the tree
8276
8276
  * @returns {Array} Nodes in the current ``phylotree``.
8277
+ * @example
8278
+ * // Get all leaf nodes from a tree
8279
+ * const tree = new Phylotree("((A:0.1,B:0.2):0.05,C:0.3);");
8280
+ * const tips = tree.getTips();
8281
+ * console.log(tips.map(tip => tip.data.name)); // ["A", "B", "C"]
8282
+ *
8283
+ * @example
8284
+ * // Count the number of taxa in the tree
8285
+ * const numTaxa = tree.getTips().length;
8286
+ * console.log(`Tree has ${numTaxa} taxa`);
8277
8287
  */
8278
8288
  function getTips() {
8279
8289
  // get all nodes that have no nodes
@@ -8316,6 +8326,18 @@
8316
8326
  *
8317
8327
  * @param {String} name Name of the desired node.
8318
8328
  * @returns {Node} Desired node.
8329
+ * @example
8330
+ * // Find a specific node by name
8331
+ * const tree = new Phylotree("((A:0.1,B:0.2):0.05,C:0.3);");
8332
+ * const nodeA = tree.getNodeByName("A");
8333
+ * console.log(nodeA.data.name); // "A"
8334
+ *
8335
+ * @example
8336
+ * // Check if a node exists and get its branch length
8337
+ * const nodeB = tree.getNodeByName("B");
8338
+ * if (nodeB) {
8339
+ * console.log(`Node B has branch length: ${nodeB.data.attribute}`);
8340
+ * }
8319
8341
  */
8320
8342
  function getNodeByName(name) {
8321
8343
  return ___namespace.filter(this.nodes.descendants(), d => {
@@ -8329,6 +8351,21 @@
8329
8351
  *
8330
8352
  * @param {Object} attributes An object whose keys are the names of nodes
8331
8353
  * to modify, and whose values are the new attributes to add.
8354
+ * @example
8355
+ * // Add species information to nodes
8356
+ * const tree = new Phylotree(newick);
8357
+ * tree.assignAttributes({
8358
+ * "Human": { species: "Homo sapiens", host: "human" },
8359
+ * "Chimp": { species: "Pan troglodytes", host: "chimpanzee" }
8360
+ * });
8361
+ *
8362
+ * @example
8363
+ * // Add selection categories for visualization
8364
+ * tree.assignAttributes({
8365
+ * "foreground_1": { category: "foreground", color: "red" },
8366
+ * "foreground_2": { category: "foreground", color: "red" },
8367
+ * "background_1": { category: "background", color: "blue" }
8368
+ * });
8332
8369
  */
8333
8370
  function assignAttributes(attributes) {
8334
8371
  //return nodes;
@@ -8396,6 +8433,22 @@
8396
8433
  * @param {Boolean} terminal Whether to include terminal nodes.
8397
8434
  * @param {Boolean} internal Whther to include internal nodes.
8398
8435
  * @returns {Array} An array of selected nodes.
8436
+ * @example
8437
+ * // Select all descendants of an internal node
8438
+ * const tree = new Phylotree("(((A,B)AB,(C,D)CD)ABCD,E);");
8439
+ * const internalNode = tree.getNodeByName("ABCD");
8440
+ * const allDescendants = tree.selectAllDescendants(internalNode, true, true);
8441
+ * console.log(allDescendants.map(n => n.data.name)); // ["AB", "A", "B", "CD", "C", "D"]
8442
+ *
8443
+ * @example
8444
+ * // Select only terminal descendants (tips in a clade)
8445
+ * const cladeTips = tree.selectAllDescendants(internalNode, true, false);
8446
+ * console.log(cladeTips.map(n => n.data.name)); // ["A", "B", "C", "D"]
8447
+ *
8448
+ * @example
8449
+ * // Select only internal descendants
8450
+ * const cladeInternals = tree.selectAllDescendants(internalNode, false, true);
8451
+ * console.log(cladeInternals.map(n => n.data.name)); // ["AB", "CD"]
8399
8452
  */
8400
8453
  function selectAllDescendants$1(node, terminal, internal) {
8401
8454
 
@@ -8447,6 +8500,29 @@
8447
8500
  * @param {String} nwk_str - A string representing a phylogenetic tree in Newick format.
8448
8501
  * @param {Object} bootstrap_values.
8449
8502
  * @returns {Object} An object with keys ``json`` and ``error``.
8503
+ * @example
8504
+ * // Parse a simple Newick tree with branch lengths
8505
+ * const newick = "((A:0.1,B:0.2):0.05,C:0.3);";
8506
+ * const result = newickParser(newick);
8507
+ * if (result.error) {
8508
+ * console.error("Parse error:", result.error);
8509
+ * } else {
8510
+ * console.log("Parsed tree:", result.json);
8511
+ * }
8512
+ *
8513
+ * @example
8514
+ * // Parse tree with tagged branches
8515
+ * const taggedNewick = "((A:0.1,B{Foreground}:0.2){Foreground}:0.05,C:0.3);";
8516
+ * const result = newickParser(taggedNewick);
8517
+ * // Tagged branches will have annotation properties
8518
+ *
8519
+ * @example
8520
+ * // Parse tree with custom delimiters
8521
+ * const nhxNewick = "((A:0.1,B:0.2[&&NHX:S=species1:D=Y]):0.05,C:0.3);";
8522
+ * const result = newickParser(nhxNewick, {
8523
+ * left_delimiter: '[',
8524
+ * right_delimiter: ']'
8525
+ * });
8450
8526
  */
8451
8527
 
8452
8528
  function newickParser(nwk_str, options={}) {
@@ -8663,6 +8739,25 @@
8663
8739
  * what label is written (optional).
8664
8740
  * @param {Node} node - start at this node (default == root)
8665
8741
  * @returns {String} newick - Phylogenetic tree serialized as a Newick string.
8742
+ * @example
8743
+ * // Export tree to basic Newick format
8744
+ * const tree = new Phylotree(newick);
8745
+ * const exportedNewick = tree.getNewick();
8746
+ * console.log(exportedNewick); // "((A:0.1,B:0.2):0.05,C:0.3);"
8747
+ *
8748
+ * @example
8749
+ * // Export with custom node annotations
8750
+ * const annotatedNewick = tree.getNewick(function(node) {
8751
+ * if (node.data.selected) {
8752
+ * return "{SELECTED}";
8753
+ * }
8754
+ * return "";
8755
+ * });
8756
+ *
8757
+ * @example
8758
+ * // Export a subtree starting from a specific node
8759
+ * const nodeOfInterest = tree.getNodeByName("A");
8760
+ * const subtreeNewick = tree.getNewick(null, nodeOfInterest);
8666
8761
  */
8667
8762
 
8668
8763
 
@@ -8713,6 +8808,54 @@
8713
8808
  return element_array.join("")+";";
8714
8809
  }
8715
8810
 
8811
+ /**
8812
+ * Generate Newick string with selection tags.
8813
+ *
8814
+ * @param {Object} options - Configuration options.
8815
+ * @param {string} [options.tag='Foreground'] - Tag name for selected nodes (single selection mode).
8816
+ * @param {boolean} [options.multiSet=false] - Use multi-set mode tags (uses set names as tags).
8817
+ * @returns {string} Tagged Newick string.
8818
+ * @example
8819
+ * // Basic tagged output (uses selection state)
8820
+ * const tagged = tree.getTaggedNewick();
8821
+ * // Returns: "((A{Foreground}:0.1,B:0.2):0.05,C{Foreground}:0.3);"
8822
+ *
8823
+ * @example
8824
+ * // Custom tag name
8825
+ * const tagged = tree.getTaggedNewick({ tag: 'TEST' });
8826
+ * // Returns: "((A{TEST}:0.1,B:0.2):0.05,C{TEST}:0.3);"
8827
+ *
8828
+ * @example
8829
+ * // Multi-set mode (uses set names as tags)
8830
+ * const tagged = tree.getTaggedNewick({ multiSet: true });
8831
+ * // Returns: "((A{TEST}:0.1,B{REFERENCE}):0.2,C{TEST}:0.3);"
8832
+ */
8833
+ function getTaggedNewick(options = {}) {
8834
+ const tag = options.tag || 'Foreground';
8835
+ const multiSet = options.multiSet || false;
8836
+
8837
+ // Get selection attribute name from display if available
8838
+ const selectionAttr = this.display
8839
+ ? this.display.selection_attribute_name
8840
+ : 'selected';
8841
+
8842
+ // Get selection sets from display if in multi-set mode
8843
+ this.display ? this.display._selectionSets : null;
8844
+
8845
+ const annotator = (node) => {
8846
+ if (multiSet && node._selectionSet) {
8847
+ // Multi-set mode: use set name as tag
8848
+ return `{${node._selectionSet}}`;
8849
+ } else if (node[selectionAttr]) {
8850
+ // Single selection mode: use configured tag
8851
+ return `{${tag}}`;
8852
+ }
8853
+ return '';
8854
+ };
8855
+
8856
+ return this.getNewick(annotator);
8857
+ }
8858
+
8716
8859
  function parseAnnotations (buf) {
8717
8860
 
8718
8861
  let str = buf;
@@ -9234,6 +9377,23 @@
9234
9377
  *
9235
9378
  * @param {Function} attr Empty if getting, or new branch length accessor if setting.
9236
9379
  * @returns {Object} The branch length accessor if getting, or the current this if setting.
9380
+ * @example
9381
+ * // Set a custom branch length accessor
9382
+ * const tree = new Phylotree(newick);
9383
+ * tree.setBranchLength(function(node) {
9384
+ * // Use a transformed branch length
9385
+ * return Math.log(node.data.attribute + 1);
9386
+ * });
9387
+ *
9388
+ * @example
9389
+ * // Set all branch lengths to 1 (equal branch lengths)
9390
+ * tree.setBranchLength(function(node) {
9391
+ * return 1;
9392
+ * });
9393
+ *
9394
+ * @example
9395
+ * // Get the current branch length accessor
9396
+ * const currentAccessor = tree.setBranchLength();
9237
9397
  */
9238
9398
  function setBranchLength(attr) {
9239
9399
  if (!arguments.length) return this.branch_length_accessor;
@@ -9242,7 +9402,19 @@
9242
9402
  }
9243
9403
 
9244
9404
  /**
9245
- * Normalizes branch lengths
9405
+ * Normalizes branch lengths to range [0,1]
9406
+ * @returns {Phylotree} The current phylotree instance
9407
+ * @example
9408
+ * // Normalize all branch lengths to 0-1 range
9409
+ * const tree = new Phylotree(newick);
9410
+ * tree.normalizeBranchLengths();
9411
+ * // Now all branch lengths are between 0 and 1
9412
+ *
9413
+ * @example
9414
+ * // Useful for comparing trees with different scales
9415
+ * const tree1 = new Phylotree(newick1).normalizeBranchLengths();
9416
+ * const tree2 = new Phylotree(newick2).normalizeBranchLengths();
9417
+ * // Both trees now have comparable branch length scales
9246
9418
  */
9247
9419
  function normalize(attr) {
9248
9420
 
@@ -9276,9 +9448,29 @@
9276
9448
 
9277
9449
 
9278
9450
  /**
9279
- * Scales branch lengths
9451
+ * Scales branch lengths using a custom transformation function
9280
9452
  *
9281
- * @param {Function} function that scales the branches
9453
+ * @param {Function} scale_by Function that transforms each branch length
9454
+ * @returns {Phylotree} The current phylotree instance
9455
+ * @example
9456
+ * // Scale all branch lengths by a constant factor
9457
+ * const tree = new Phylotree(newick);
9458
+ * tree.scaleBranchLengths(function(length) {
9459
+ * return length * 2; // Double all branch lengths
9460
+ * });
9461
+ *
9462
+ * @example
9463
+ * // Apply logarithmic transformation
9464
+ * tree.scaleBranchLengths(function(length) {
9465
+ * return Math.log10(length + 1);
9466
+ * });
9467
+ *
9468
+ * @example
9469
+ * // Convert to time units (assuming substitutions per site)
9470
+ * const mutationRate = 1e-8;
9471
+ * tree.scaleBranchLengths(function(length) {
9472
+ * return length / mutationRate; // Convert to years
9473
+ * });
9282
9474
  */
9283
9475
  function scale(scale_by) {
9284
9476
 
@@ -9316,6 +9508,23 @@
9316
9508
  the specified fraction
9317
9509
 
9318
9510
  * @returns {Phylotree} The current ``phylotree``.
9511
+ * @example
9512
+ * // Reroot tree on a specific node
9513
+ * const tree = new Phylotree("((A:0.1,B:0.2):0.05,(C:0.3,D:0.1):0.08);");
9514
+ * const nodeC = tree.getNodeByName("C");
9515
+ * tree.reroot(nodeC);
9516
+ * // Tree is now rooted on the branch leading to C
9517
+ *
9518
+ * @example
9519
+ * // Reroot with custom branch length partitioning
9520
+ * const nodeA = tree.getNodeByName("A");
9521
+ * tree.reroot(nodeA, 0.3); // 30% of branch length goes to new root
9522
+ *
9523
+ * @example
9524
+ * // Reroot on midpoint of tree (balance tree)
9525
+ * const tips = tree.getTips();
9526
+ * const midpoint = tree.computeMidpoint();
9527
+ * tree.reroot(midpoint);
9319
9528
  */
9320
9529
  function reroot(node, fraction) {
9321
9530
 
@@ -9453,6 +9662,11 @@
9453
9662
  select(rendered_tree.container).node().appendChild(rendered_tree.show());
9454
9663
  select(this.display.container).dispatch('reroot');
9455
9664
 
9665
+ // Emit rerooted event via new event system
9666
+ if (rendered_tree.emit) {
9667
+ rendered_tree.emit('rerooted', this.nodes);
9668
+ }
9669
+
9456
9670
  }
9457
9671
 
9458
9672
  return this;
@@ -9797,8 +10011,12 @@
9797
10011
  .append("text")
9798
10012
  .classed(this.css_classes["node_text"], true)
9799
10013
  .merge(labels)
9800
- .on("click", d=> {
9801
- this.handle_node_click(node, d);
10014
+ .on("click", (event, d) => {
10015
+ this.emit('nodeClick', node, event);
10016
+ this.handle_node_click(node, event);
10017
+ })
10018
+ .on("mouseenter", (event) => {
10019
+ this.emit('nodeHover', node, event);
9802
10020
  })
9803
10021
  .attr("dy", d => {
9804
10022
  return this.shown_font_size * 0.33;
@@ -9939,8 +10157,12 @@
9939
10157
  .attr("r", d => {
9940
10158
  return Math.min(this.shown_font_size * 0.75, radius);
9941
10159
  })
9942
- .on("click", d => {
9943
- this.handle_node_click(node, d);
10160
+ .on("click", (event, d) => {
10161
+ this.emit('nodeClick', node, event);
10162
+ this.handle_node_click(node, event);
10163
+ })
10164
+ .on("mouseenter", (event) => {
10165
+ this.emit('nodeHover', node, event);
9944
10166
  });
9945
10167
  } else {
9946
10168
  circles.remove();
@@ -10251,9 +10473,15 @@
10251
10473
  .attr("class", d => {
10252
10474
  return this.reclassEdge(d);
10253
10475
  })
10254
- .on("click", d => {
10255
- this.modifySelection([edge.target], this.selection_attribute_name);
10256
- this.update();
10476
+ .on("click", (event, d) => {
10477
+ this.emit('branchClick', edge, event);
10478
+ // Check for multi-set selection mode
10479
+ if (this.options["selection-mode"] === "multi-set" && this._activeSetName) {
10480
+ this.handleMultiSetClick(edge.target);
10481
+ } else {
10482
+ this.modifySelection([edge.target], this.selection_attribute_name);
10483
+ this.update();
10484
+ }
10257
10485
  });
10258
10486
 
10259
10487
  let new_branch_path = this.draw_branch([edge.source, edge.target]);
@@ -10307,6 +10535,12 @@
10307
10535
  class_var += " " + css_classes["selected-branch"];
10308
10536
  }
10309
10537
 
10538
+ // Multi-set selection mode: add set-specific class
10539
+ if (edge.target && edge.target._selectionSet) {
10540
+ const safeName = edge.target._selectionSet.replace(/[^a-zA-Z0-9-_]/g, '_');
10541
+ class_var += " phylotree-set-branch-" + safeName;
10542
+ }
10543
+
10310
10544
  return class_var;
10311
10545
 
10312
10546
  }
@@ -10414,6 +10648,10 @@
10414
10648
  }
10415
10649
 
10416
10650
  this.placenodes();
10651
+
10652
+ // Emit collapsed event with node and current collapsed state
10653
+ this.emit('collapsed', node, node.collapsed);
10654
+
10417
10655
  return this;
10418
10656
  }
10419
10657
 
@@ -10466,7 +10704,13 @@
10466
10704
  svg = svg.transition(100);
10467
10705
  }
10468
10706
 
10469
- svg.attr("height", sizes[0]).attr("width", sizes[1]);
10707
+ if (this.options["responsive"]) {
10708
+ // Responsive mode: update viewBox
10709
+ svg.attr("viewBox", `0 0 ${sizes[1]} ${sizes[0]}`);
10710
+ } else {
10711
+ // Fixed mode: update width/height
10712
+ svg.attr("height", sizes[0]).attr("width", sizes[1]);
10713
+ }
10470
10714
 
10471
10715
  }
10472
10716
 
@@ -10573,7 +10817,7 @@
10573
10817
  menu_object = select(container)
10574
10818
  .append("div")
10575
10819
  .attr("id", d3_layout_phylotree_context_menu_id)
10576
- .attr("class", "dropdown-menu")
10820
+ .attr("class", "phylotree-context-menu dropdown-menu")
10577
10821
  .attr("role", "menu");
10578
10822
  }
10579
10823
 
@@ -10596,7 +10840,7 @@
10596
10840
  if (options["collapsible"]) {
10597
10841
  menu_object
10598
10842
  .append("a")
10599
- .attr("class", "dropdown-item")
10843
+ .attr("class", "phylotree-menu-item dropdown-item")
10600
10844
  .attr("tabindex", "-1")
10601
10845
  .text(isNodeCollapsed(node) ? "Expand Subtree" : "Collapse Subtree")
10602
10846
  .on("click", d => {
@@ -10604,10 +10848,10 @@
10604
10848
  this.toggleCollapse(node).update();
10605
10849
  });
10606
10850
  if (options["selectable"]) {
10607
- menu_object.append("div").attr("class", "dropdown-divider");
10851
+ menu_object.append("div").attr("class", "phylotree-menu-divider dropdown-divider");
10608
10852
  menu_object
10609
10853
  .append("h6")
10610
- .attr("class", "dropdown-header")
10854
+ .attr("class", "phylotree-menu-header dropdown-header")
10611
10855
  .text("Toggle selection");
10612
10856
  }
10613
10857
  }
@@ -10615,7 +10859,7 @@
10615
10859
  if (options["selectable"]) {
10616
10860
  menu_object
10617
10861
  .append("a")
10618
- .attr("class", "dropdown-item")
10862
+ .attr("class", "phylotree-menu-item dropdown-item")
10619
10863
  .attr("tabindex", "-1")
10620
10864
  .text("All descendant branches")
10621
10865
  .on("click", function(d) {
@@ -10627,7 +10871,7 @@
10627
10871
 
10628
10872
  menu_object
10629
10873
  .append("a")
10630
- .attr("class", "dropdown-item")
10874
+ .attr("class", "phylotree-menu-item dropdown-item")
10631
10875
  .attr("tabindex", "-1")
10632
10876
  .text("All terminal branches")
10633
10877
  .on("click", function(d) {
@@ -10639,7 +10883,7 @@
10639
10883
 
10640
10884
  menu_object
10641
10885
  .append("a")
10642
- .attr("class", "dropdown-item")
10886
+ .attr("class", "phylotree-menu-item dropdown-item")
10643
10887
  .attr("tabindex", "-1")
10644
10888
  .text("All internal branches")
10645
10889
  .on("click", function(d) {
@@ -10655,7 +10899,7 @@
10655
10899
  if (options["selectable"]) {
10656
10900
  menu_object
10657
10901
  .append("a")
10658
- .attr("class", "dropdown-item")
10902
+ .attr("class", "phylotree-menu-item dropdown-item")
10659
10903
  .attr("tabindex", "-1")
10660
10904
  .text("Incident branch")
10661
10905
  .on("click", function(d) {
@@ -10665,7 +10909,7 @@
10665
10909
 
10666
10910
  menu_object
10667
10911
  .append("a")
10668
- .attr("class", "dropdown-item")
10912
+ .attr("class", "phylotree-menu-item dropdown-item")
10669
10913
  .attr("tabindex", "-1")
10670
10914
  .text("Path to root")
10671
10915
  .on("click", d => {
@@ -10674,14 +10918,14 @@
10674
10918
  });
10675
10919
 
10676
10920
  if (options["reroot"] || options["hide"]) {
10677
- menu_object.append("div").attr("class", "dropdown-divider");
10921
+ menu_object.append("div").attr("class", "phylotree-menu-divider dropdown-divider");
10678
10922
  }
10679
10923
  }
10680
10924
 
10681
10925
  if (options["reroot"]) {
10682
10926
  menu_object
10683
10927
  .append("a")
10684
- .attr("class", "dropdown-item")
10928
+ .attr("class", "phylotree-menu-item dropdown-item")
10685
10929
  .attr("tabindex", "-1")
10686
10930
  .text("Reroot on this node")
10687
10931
  .on("click", d => {
@@ -10694,7 +10938,7 @@
10694
10938
  if (options["hide"]) {
10695
10939
  menu_object
10696
10940
  .append("a")
10697
- .attr("class", "dropdown-item")
10941
+ .attr("class", "phylotree-menu-item dropdown-item")
10698
10942
  .attr("tabindex", "-1")
10699
10943
  .text("Hide this " + (isLeafNode(node) ? "node" : "subtree"))
10700
10944
  .on("click", d => {
@@ -10709,7 +10953,7 @@
10709
10953
  if (hasHiddenNodes(node)) {
10710
10954
  menu_object
10711
10955
  .append("a")
10712
- .attr("class", "dropdown-item")
10956
+ .attr("class", "phylotree-menu-item dropdown-item")
10713
10957
  .attr("tabindex", "-1")
10714
10958
  .text("Show all descendant nodes")
10715
10959
  .on("click", function(d) {
@@ -10748,13 +10992,13 @@
10748
10992
  ];
10749
10993
 
10750
10994
  if (___namespace.some(show_divider_options)) {
10751
- menu_object.append("div").attr("class", "dropdown-divider");
10995
+ menu_object.append("div").attr("class", "phylotree-menu-divider dropdown-divider");
10752
10996
  }
10753
10997
 
10754
10998
  has_user_elements.forEach(function(d) {
10755
10999
  menu_object
10756
11000
  .append("a")
10757
- .attr("class", "dropdown-item")
11001
+ .attr("class", "phylotree-menu-item dropdown-item")
10758
11002
  .attr("tabindex", "-1")
10759
11003
  .text((d[0])(node)) // eslint-disable-line
10760
11004
  .on("click", ___namespace.partial(d[1], node));
@@ -10944,8 +11188,14 @@
10944
11188
  }
10945
11189
  }
10946
11190
 
10947
- if (this._selectionCallback && attr != "tag") {
10948
- this._selectionCallback(this.getSelection());
11191
+ if (attr != "tag") {
11192
+ const selection = this.getSelection();
11193
+ // Call legacy callback for backward compatibility
11194
+ if (this._selectionCallback) {
11195
+ this._selectionCallback(selection);
11196
+ }
11197
+ // Emit event for new event system
11198
+ this.emit('selectionChange', selection);
10949
11199
  }
10950
11200
 
10951
11201
  this.refresh();
@@ -11008,6 +11258,65 @@
11008
11258
  return this;
11009
11259
  }
11010
11260
 
11261
+ /**
11262
+ * Select nodes by their names.
11263
+ *
11264
+ * @param {string[]} names - Array of node names to select.
11265
+ * @returns {this} For chaining.
11266
+ * @example
11267
+ * tree.selectNodes(['HUMAN', 'CHIMP', 'GORILLA']);
11268
+ */
11269
+ function selectNodes(names) {
11270
+ if (!names || !Array.isArray(names) || names.length === 0) {
11271
+ return this;
11272
+ }
11273
+
11274
+ const nodesToSelect = this.phylotree.nodes.descendants()
11275
+ .filter(node => names.includes(node.data.name));
11276
+
11277
+ if (nodesToSelect.length > 0) {
11278
+ this.modifySelection(nodesToSelect, this.selection_attribute_name, false, false, 'true');
11279
+ }
11280
+
11281
+ return this;
11282
+ }
11283
+
11284
+ /**
11285
+ * Deselect nodes by their names.
11286
+ *
11287
+ * @param {string[]} names - Array of node names to deselect.
11288
+ * @returns {this} For chaining.
11289
+ * @example
11290
+ * tree.deselectNodes(['HUMAN']);
11291
+ */
11292
+ function deselectNodes(names) {
11293
+ if (!names || !Array.isArray(names) || names.length === 0) {
11294
+ return this;
11295
+ }
11296
+
11297
+ const nodesToDeselect = this.phylotree.nodes.descendants()
11298
+ .filter(node => names.includes(node.data.name));
11299
+
11300
+ if (nodesToDeselect.length > 0) {
11301
+ this.modifySelection(nodesToDeselect, this.selection_attribute_name, false, false, 'false');
11302
+ }
11303
+
11304
+ return this;
11305
+ }
11306
+
11307
+ /**
11308
+ * Clear all current selection.
11309
+ *
11310
+ * @returns {this} For chaining.
11311
+ * @example
11312
+ * tree.clearSelection();
11313
+ */
11314
+ function clearSelection() {
11315
+ const allNodes = this.phylotree.nodes.descendants();
11316
+ this.modifySelection(allNodes, this.selection_attribute_name, false, false, 'false');
11317
+ return this;
11318
+ }
11319
+
11011
11320
  var menus = /*#__PURE__*/Object.freeze({
11012
11321
  __proto__: null,
11013
11322
  nodeDropdownMenu: nodeDropdownMenu,
@@ -11015,7 +11324,357 @@
11015
11324
  modifySelection: modifySelection,
11016
11325
  getSelection: getSelection,
11017
11326
  selectAllDescendants: selectAllDescendants,
11018
- selectionCallback: selectionCallback
11327
+ selectionCallback: selectionCallback,
11328
+ selectNodes: selectNodes,
11329
+ deselectNodes: deselectNodes,
11330
+ clearSelection: clearSelection
11331
+ });
11332
+
11333
+ /**
11334
+ * Event emitter mixin for phylotree TreeRender
11335
+ * Provides on/off/emit pattern for tree events
11336
+ * @module render/event-emitter
11337
+ */
11338
+
11339
+ /**
11340
+ * Register an event listener
11341
+ * @param {string} eventName - Event name (nodeClick, branchClick, nodeHover,
11342
+ * contextMenu, rendered, selectionChange, collapsed, rerooted)
11343
+ * @param {Function} callback - Handler function
11344
+ * @returns {this} For chaining
11345
+ * @example
11346
+ * tree.on('nodeClick', (node, event) => console.log(node.data.name));
11347
+ * tree.on('selectionChange', (selectedNodes) => updatePanel(selectedNodes));
11348
+ */
11349
+ function on(eventName, callback) {
11350
+ if (!this._eventListeners) {
11351
+ this._eventListeners = {};
11352
+ }
11353
+ if (!this._eventListeners[eventName]) {
11354
+ this._eventListeners[eventName] = [];
11355
+ }
11356
+ this._eventListeners[eventName].push(callback);
11357
+ return this;
11358
+ }
11359
+
11360
+ /**
11361
+ * Remove an event listener
11362
+ * @param {string} eventName - Event name
11363
+ * @param {Function} callback - Handler to remove (must be same reference)
11364
+ * @returns {this} For chaining
11365
+ * @example
11366
+ * const handler = (node) => console.log(node);
11367
+ * tree.on('nodeClick', handler);
11368
+ * tree.off('nodeClick', handler);
11369
+ */
11370
+ function off(eventName, callback) {
11371
+ if (this._eventListeners && this._eventListeners[eventName]) {
11372
+ this._eventListeners[eventName] = this._eventListeners[eventName]
11373
+ .filter(cb => cb !== callback);
11374
+ }
11375
+ return this;
11376
+ }
11377
+
11378
+ /**
11379
+ * Emit an event to all registered listeners
11380
+ * @param {string} eventName - Event name
11381
+ * @param {...*} args - Arguments to pass to listeners
11382
+ * @returns {this} For chaining
11383
+ * @private
11384
+ */
11385
+ function emit(eventName, ...args) {
11386
+ if (this._eventListeners && this._eventListeners[eventName]) {
11387
+ this._eventListeners[eventName].forEach(callback => {
11388
+ try {
11389
+ callback.apply(this, args);
11390
+ } catch (e) {
11391
+ console.error(`Error in ${eventName} event handler:`, e);
11392
+ }
11393
+ });
11394
+ }
11395
+ return this;
11396
+ }
11397
+
11398
+ var eventEmitter = /*#__PURE__*/Object.freeze({
11399
+ __proto__: null,
11400
+ on: on,
11401
+ off: off,
11402
+ emit: emit
11403
+ });
11404
+
11405
+ /**
11406
+ * Multi-set selection management for phylotree
11407
+ * @module render/selection-sets
11408
+ */
11409
+
11410
+ /**
11411
+ * Initialize multi-set selection mode.
11412
+ * Called automatically during render when selection-mode is 'multi-set'.
11413
+ *
11414
+ * @param {Array<{name: string, color: string}>} sets - Array of selection set definitions.
11415
+ * @private
11416
+ */
11417
+ function initializeSelectionSets(sets) {
11418
+ this._selectionSets = {};
11419
+ this._activeSetName = null;
11420
+
11421
+ sets.forEach(set => {
11422
+ this._selectionSets[set.name] = {
11423
+ name: set.name,
11424
+ color: set.color,
11425
+ members: new Set()
11426
+ };
11427
+ });
11428
+
11429
+ // Set first set as active by default
11430
+ if (sets.length > 0) {
11431
+ this._activeSetName = sets[0].name;
11432
+ }
11433
+
11434
+ // Inject CSS for set colors
11435
+ this._injectSetStyles(sets);
11436
+ }
11437
+
11438
+ /**
11439
+ * Inject dynamic CSS styles for selection set colors.
11440
+ *
11441
+ * @param {Array<{name: string, color: string}>} sets - Array of selection set definitions.
11442
+ * @private
11443
+ */
11444
+ function _injectSetStyles(sets) {
11445
+ const styleId = 'phylotree-selection-set-styles';
11446
+ let styleEl = document.getElementById(styleId);
11447
+
11448
+ if (!styleEl) {
11449
+ styleEl = document.createElement('style');
11450
+ styleEl.id = styleId;
11451
+ document.head.appendChild(styleEl);
11452
+ }
11453
+
11454
+ const css = sets.map(set => {
11455
+ const safeName = set.name.replace(/[^a-zA-Z0-9-_]/g, '_');
11456
+ return `
11457
+ .phylotree-set-${safeName} path.branch {
11458
+ stroke: ${set.color} !important;
11459
+ }
11460
+ .phylotree-set-${safeName} .node circle {
11461
+ fill: ${set.color} !important;
11462
+ }
11463
+ .phylotree-set-branch-${safeName} {
11464
+ stroke: ${set.color} !important;
11465
+ }
11466
+ `;
11467
+ }).join('\n');
11468
+
11469
+ styleEl.textContent = css;
11470
+ }
11471
+
11472
+ /**
11473
+ * Set the active selection set. Clicks will add nodes to this set.
11474
+ *
11475
+ * @param {string} name - Name of the set to activate.
11476
+ * @returns {this} For chaining.
11477
+ * @example
11478
+ * tree.setActiveSet('foreground');
11479
+ */
11480
+ function setActiveSet(name) {
11481
+ if (this._selectionSets && this._selectionSets[name]) {
11482
+ this._activeSetName = name;
11483
+ } else {
11484
+ console.warn(`Selection set '${name}' not found`);
11485
+ }
11486
+ return this;
11487
+ }
11488
+
11489
+ /**
11490
+ * Get the currently active selection set name.
11491
+ *
11492
+ * @returns {string|null} Active set name or null if not in multi-set mode.
11493
+ * @example
11494
+ * const activeSet = tree.getActiveSet(); // 'foreground'
11495
+ */
11496
+ function getActiveSet() {
11497
+ return this._activeSetName;
11498
+ }
11499
+
11500
+ /**
11501
+ * Get all members (nodes) of a selection set.
11502
+ *
11503
+ * @param {string} setName - Name of the selection set.
11504
+ * @returns {Node[]} Array of nodes in the set.
11505
+ * @example
11506
+ * const foregroundNodes = tree.getSetMembers('foreground');
11507
+ */
11508
+ function getSetMembers(setName) {
11509
+ if (!this._selectionSets || !this._selectionSets[setName]) {
11510
+ return [];
11511
+ }
11512
+
11513
+ const memberNames = this._selectionSets[setName].members;
11514
+ return this.phylotree.nodes.descendants()
11515
+ .filter(node => memberNames.has(node.data.name));
11516
+ }
11517
+
11518
+ /**
11519
+ * Add a node to a selection set.
11520
+ *
11521
+ * @param {Node|string} node - Node object or node name.
11522
+ * @param {string} setName - Target set name.
11523
+ * @returns {this} For chaining.
11524
+ * @example
11525
+ * tree.addToSet('HUMAN', 'foreground');
11526
+ * tree.addToSet(nodeObject, 'background');
11527
+ */
11528
+ function addToSet(node, setName) {
11529
+ if (!this._selectionSets || !this._selectionSets[setName]) {
11530
+ console.warn(`Selection set '${setName}' not found`);
11531
+ return this;
11532
+ }
11533
+
11534
+ const nodeName = typeof node === 'string' ? node : node.data.name;
11535
+ const nodeObj = typeof node === 'string'
11536
+ ? this.phylotree.getNodeByName(node)
11537
+ : node;
11538
+
11539
+ if (nodeObj) {
11540
+ // Remove from all other sets (mutually exclusive)
11541
+ Object.keys(this._selectionSets).forEach(otherSet => {
11542
+ this._selectionSets[otherSet].members.delete(nodeName);
11543
+ });
11544
+
11545
+ this._selectionSets[setName].members.add(nodeName);
11546
+ nodeObj._selectionSet = setName;
11547
+
11548
+ this.emit('setChange', {
11549
+ action: 'add',
11550
+ set: setName,
11551
+ node: nodeObj,
11552
+ allSets: this._getSetsSummary()
11553
+ });
11554
+
11555
+ this.refresh();
11556
+ this.update();
11557
+ }
11558
+
11559
+ return this;
11560
+ }
11561
+
11562
+ /**
11563
+ * Remove a node from a selection set.
11564
+ *
11565
+ * @param {Node|string} node - Node object or node name.
11566
+ * @param {string} setName - Target set name.
11567
+ * @returns {this} For chaining.
11568
+ * @example
11569
+ * tree.removeFromSet('HUMAN', 'foreground');
11570
+ */
11571
+ function removeFromSet(node, setName) {
11572
+ if (!this._selectionSets || !this._selectionSets[setName]) {
11573
+ return this;
11574
+ }
11575
+
11576
+ const nodeName = typeof node === 'string' ? node : node.data.name;
11577
+ const nodeObj = typeof node === 'string'
11578
+ ? this.phylotree.getNodeByName(node)
11579
+ : node;
11580
+
11581
+ if (this._selectionSets[setName].members.has(nodeName)) {
11582
+ this._selectionSets[setName].members.delete(nodeName);
11583
+ if (nodeObj) {
11584
+ delete nodeObj._selectionSet;
11585
+ }
11586
+
11587
+ this.emit('setChange', {
11588
+ action: 'remove',
11589
+ set: setName,
11590
+ node: nodeObj,
11591
+ allSets: this._getSetsSummary()
11592
+ });
11593
+
11594
+ this.refresh();
11595
+ this.update();
11596
+ }
11597
+
11598
+ return this;
11599
+ }
11600
+
11601
+ /**
11602
+ * Get a summary of all sets and their members.
11603
+ *
11604
+ * @returns {Object} Object with set names as keys and arrays of node names as values.
11605
+ * @private
11606
+ */
11607
+ function _getSetsSummary() {
11608
+ const summary = {};
11609
+ if (this._selectionSets) {
11610
+ Object.keys(this._selectionSets).forEach(setName => {
11611
+ summary[setName] = Array.from(this._selectionSets[setName].members);
11612
+ });
11613
+ }
11614
+ return summary;
11615
+ }
11616
+
11617
+ /**
11618
+ * Handle click in multi-set mode.
11619
+ * Adds the clicked node to the active set.
11620
+ *
11621
+ * @param {Node} node - The clicked node.
11622
+ * @private
11623
+ */
11624
+ function handleMultiSetClick(node) {
11625
+ if (!this._activeSetName || !this._selectionSets) {
11626
+ return;
11627
+ }
11628
+
11629
+ node.data.name;
11630
+ const currentSet = node._selectionSet;
11631
+
11632
+ if (currentSet === this._activeSetName) {
11633
+ // Already in active set, remove it
11634
+ this.removeFromSet(node, this._activeSetName);
11635
+ } else {
11636
+ // Add to active set (removes from other sets automatically)
11637
+ this.addToSet(node, this._activeSetName);
11638
+ }
11639
+ }
11640
+
11641
+ /**
11642
+ * Check if a node belongs to a specific set.
11643
+ *
11644
+ * @param {Node} node - The node to check.
11645
+ * @param {string} setName - The set name to check.
11646
+ * @returns {boolean} True if node is in the set.
11647
+ */
11648
+ function isInSet(node, setName) {
11649
+ if (!this._selectionSets || !this._selectionSets[setName]) {
11650
+ return false;
11651
+ }
11652
+ return this._selectionSets[setName].members.has(node.data.name);
11653
+ }
11654
+
11655
+ /**
11656
+ * Get the set name a node belongs to.
11657
+ *
11658
+ * @param {Node} node - The node to check.
11659
+ * @returns {string|null} The set name or null if not in any set.
11660
+ */
11661
+ function getNodeSet(node) {
11662
+ return node._selectionSet || null;
11663
+ }
11664
+
11665
+ var selectionSets = /*#__PURE__*/Object.freeze({
11666
+ __proto__: null,
11667
+ initializeSelectionSets: initializeSelectionSets,
11668
+ _injectSetStyles: _injectSetStyles,
11669
+ setActiveSet: setActiveSet,
11670
+ getActiveSet: getActiveSet,
11671
+ getSetMembers: getSetMembers,
11672
+ addToSet: addToSet,
11673
+ removeFromSet: removeFromSet,
11674
+ _getSetsSummary: _getSetsSummary,
11675
+ handleMultiSetClick: handleMultiSetClick,
11676
+ isInSet: isInSet,
11677
+ getNodeSet: getNodeSet
11019
11678
  });
11020
11679
 
11021
11680
  // replacement for d3.functor
@@ -11038,6 +11697,7 @@
11038
11697
  this._nodeLabel = this.defNodeLabel;
11039
11698
  this.svg = null;
11040
11699
  this._selectionCallback = null;
11700
+ this._eventListeners = {};
11041
11701
  this.scales = [1, 1];
11042
11702
  this.size = [1, 1];
11043
11703
  this.fixed_width = [14, 30];
@@ -11106,7 +11766,13 @@
11106
11766
  "show-labels": true,
11107
11767
  "node-styler": null,
11108
11768
  "edge-styler": null,
11109
- "node-span": null
11769
+ "node-span": null,
11770
+ "responsive": false,
11771
+ "preserve-aspect-ratio": "xMidYMid meet",
11772
+ "selection-mode": "single",
11773
+ "selection-sets": [],
11774
+ "initial-selection": [],
11775
+ "initial-sets": {}
11110
11776
  };
11111
11777
 
11112
11778
  this.ensure_size_is_in_px = function(value) {
@@ -11148,6 +11814,37 @@
11148
11814
  this.initializeEdgeLabels();
11149
11815
  this.update();
11150
11816
  d3PhylotreeAddEventListener();
11817
+
11818
+ // Initialize multi-set selection if configured
11819
+ if (this.options["selection-mode"] === "multi-set" &&
11820
+ this.options["selection-sets"].length > 0) {
11821
+ this.initializeSelectionSets(this.options["selection-sets"]);
11822
+ }
11823
+
11824
+ // Apply initial selection if configured
11825
+ this.applyInitialSelection();
11826
+ }
11827
+
11828
+ /**
11829
+ * Apply initial selection from render options.
11830
+ * @private
11831
+ */
11832
+ applyInitialSelection() {
11833
+ // Single selection mode
11834
+ if (this.options["initial-selection"] &&
11835
+ this.options["initial-selection"].length > 0) {
11836
+ this.selectNodes(this.options["initial-selection"]);
11837
+ }
11838
+
11839
+ // Multi-set mode
11840
+ if (this.options["selection-mode"] === "multi-set" &&
11841
+ this.options["initial-sets"]) {
11842
+ Object.entries(this.options["initial-sets"]).forEach(([setName, nodeNames]) => {
11843
+ nodeNames.forEach(nodeName => {
11844
+ this.addToSet(nodeName, setName);
11845
+ });
11846
+ });
11847
+ }
11151
11848
  }
11152
11849
 
11153
11850
  pad_height() {
@@ -11215,9 +11912,22 @@
11215
11912
  .select("svg")
11216
11913
  .remove();
11217
11914
 
11218
- this.svg = create$1("svg")
11219
- .attr("width", this.width)
11220
- .attr("height", this.height);
11915
+ this.svg = create$1("svg");
11916
+
11917
+ if (this.options["responsive"]) {
11918
+ // Responsive mode: use viewBox for scaling
11919
+ this.svg
11920
+ .attr("viewBox", `0 0 ${this.width} ${this.height}`)
11921
+ .attr("preserveAspectRatio", this.options["preserve-aspect-ratio"])
11922
+ .style("width", "100%")
11923
+ .style("height", "auto")
11924
+ .style("max-width", "100%");
11925
+ } else {
11926
+ // Fixed mode: explicit width/height
11927
+ this.svg
11928
+ .attr("width", this.width)
11929
+ .attr("height", this.height);
11930
+ }
11221
11931
 
11222
11932
  this.set_size([this.height, this.width]);
11223
11933
 
@@ -11454,6 +12164,9 @@
11454
12164
  this.svg.call(zoom$1);
11455
12165
  }
11456
12166
 
12167
+ // Emit rendered event
12168
+ this.emit('rendered');
12169
+
11457
12170
  return this;
11458
12171
  }
11459
12172
 
@@ -12364,6 +13077,8 @@
12364
13077
  ___namespace.extend(TreeRender.prototype, events);
12365
13078
  ___namespace.extend(TreeRender.prototype, menus);
12366
13079
  ___namespace.extend(TreeRender.prototype, opt);
13080
+ ___namespace.extend(TreeRender.prototype, eventEmitter);
13081
+ ___namespace.extend(TreeRender.prototype, selectionSets);
12367
13082
 
12368
13083
  function resortChildren(comparator, start_node, filter) {
12369
13084
  // ascending
@@ -12422,6 +13137,28 @@
12422
13137
  * - boostrap_values
12423
13138
  * - type - format type
12424
13139
  * @returns {Phylotree} phylotree - itself, following the builder pattern.
13140
+ * @example
13141
+ * // Create a simple phylotree from a Newick string
13142
+ * const newick = "((A:0.1,B:0.2):0.05,C:0.3)";
13143
+ * const tree = new Phylotree(newick);
13144
+ *
13145
+ * @example
13146
+ * // Create a phylotree with options
13147
+ * const tree = new Phylotree(newick, {
13148
+ * bootstrap_values: true,
13149
+ * type: "newick"
13150
+ * });
13151
+ *
13152
+ * @example
13153
+ * // Create from hierarchical JSON
13154
+ * const jsonTree = {
13155
+ * name: "root",
13156
+ * children: [
13157
+ * { name: "A", length: 0.1 },
13158
+ * { name: "B", length: 0.2 }
13159
+ * ]
13160
+ * };
13161
+ * const tree = new Phylotree(jsonTree);
12425
13162
  */
12426
13163
  let Phylotree = class {
12427
13164
  constructor(nwk, options = {}) {
@@ -12551,7 +13288,7 @@
12551
13288
  return JSON.stringify(node_array);
12552
13289
  }
12553
13290
 
12554
- /*
13291
+ /**
12555
13292
  * Traverse the tree in a prescribed order, and compute a value at each node.
12556
13293
  *
12557
13294
  * @param {Function} callback A function to be called on each node.
@@ -12560,6 +13297,31 @@
12560
13297
  * @param {Function} backtrack ; if provided, then at each node n, backtrack (n) will be called,
12561
13298
  and if it returns TRUE, traversal will NOT continue past into this
12562
13299
  node and its children
13300
+ * @example
13301
+ * // Count all nodes in the tree
13302
+ * let nodeCount = 0;
13303
+ * tree.traverse_and_compute(function(node) {
13304
+ * nodeCount++;
13305
+ * });
13306
+ * console.log(`Tree has ${nodeCount} nodes`);
13307
+ *
13308
+ * @example
13309
+ * // Find maximum depth in post-order traversal
13310
+ * tree.traverse_and_compute(function(node) {
13311
+ * if (!node.children) {
13312
+ * node.depth = 0;
13313
+ * } else {
13314
+ * node.depth = Math.max(...node.children.map(c => c.depth)) + 1;
13315
+ * }
13316
+ * }, "post-order");
13317
+ *
13318
+ * @example
13319
+ * // Add custom attributes to leaf nodes only
13320
+ * tree.traverse_and_compute(function(node) {
13321
+ * if (!node.children) {
13322
+ * node.data.isLeaf = true;
13323
+ * }
13324
+ * });
12563
13325
  */
12564
13326
  traverse_and_compute(callback, traversal_type, root_node, backtrack) {
12565
13327
  traversal_type = traversal_type || "post-order";
@@ -12604,7 +13366,42 @@
12604
13366
  this.nodes = json;
12605
13367
  }
12606
13368
 
12607
- // Warning : Requires DOM!
13369
+ /**
13370
+ * Render the phylotree to a DOM element. Warning: Requires DOM!
13371
+ *
13372
+ * @param {Object} options - Rendering options including container, dimensions, and styling
13373
+ * @returns {TreeRender} The display object for further customization
13374
+ * @example
13375
+ * // Basic rendering to a div element
13376
+ * const tree = new Phylotree(newick);
13377
+ * tree.render({
13378
+ * container: "#tree-container",
13379
+ * width: 800,
13380
+ * height: 600
13381
+ * });
13382
+ *
13383
+ * @example
13384
+ * // Render with custom styling options
13385
+ * const display = tree.render({
13386
+ * container: d3.select("#my-tree"),
13387
+ * width: 1000,
13388
+ * height: 800,
13389
+ * 'left-right-spacing': 'fit-to-size',
13390
+ * 'top-bottom-spacing': 'fit-to-size',
13391
+ * 'show-scale': true,
13392
+ * selectable: true,
13393
+ * collapsible: true
13394
+ * });
13395
+ *
13396
+ * @example
13397
+ * // Render radial tree layout
13398
+ * tree.render({
13399
+ * container: "#radial-tree",
13400
+ * layout: "radial",
13401
+ * width: 600,
13402
+ * height: 600
13403
+ * });
13404
+ */
12608
13405
  render(options) {
12609
13406
  this.display = new TreeRender(this, options);
12610
13407
  return this.display;
@@ -12620,6 +13417,7 @@
12620
13417
  Phylotree.prototype.normalizeBranchLengths = normalize;
12621
13418
  Phylotree.prototype.scaleBranchLengths = scale;
12622
13419
  Phylotree.prototype.getNewick = getNewick;
13420
+ Phylotree.prototype.getTaggedNewick = getTaggedNewick;
12623
13421
  Phylotree.prototype.resortChildren = resortChildren;
12624
13422
  Phylotree.prototype.setBranchLength = setBranchLength;
12625
13423
  Phylotree.prototype.maxParsimony = maxParsimony;