phylotree 2.6.0 → 2.6.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.
@@ -1,116 +1,242 @@
1
1
  // Type definitions for phylotree
2
2
  // Project: https://github.com/veg/phylotree.js
3
+ //
4
+ // Every declaration here mirrors code in src/. Run `yarn typecheck` after
5
+ // changing this file; it compiles test/types/usage.ts against it.
3
6
 
4
- import { HierarchyNode, HierarchyLink } from 'd3-hierarchy';
7
+ import type * as d3 from 'd3';
5
8
 
6
9
  /**
7
- * Node data stored in the phylogenetic tree
10
+ * Node data stored in the phylogenetic tree (the `data` field of each node)
8
11
  */
9
12
  export interface PhylotreeNodeData {
10
13
  name: string;
14
+ /** Branch length as parsed from the input, as a string */
11
15
  attribute?: string;
16
+ /** Annotation parsed from `{...}` (or `[...]`) after the node name */
12
17
  annotation?: string;
18
+ /** Internal node label, kept when bootstrap values are parsed */
19
+ bootstrap_values?: string;
13
20
  [key: string]: any;
14
21
  }
15
22
 
16
23
  /**
17
- * A node in the phylogenetic tree (D3 hierarchy node with phylotree data)
24
+ * A node in the phylogenetic tree (D3 hierarchy node with phylotree state)
18
25
  */
19
- export type PhylotreeNode = HierarchyNode<PhylotreeNodeData> & {
26
+ export interface PhylotreeNode extends d3.HierarchyNode<PhylotreeNodeData> {
27
+ /** Default selection attribute; see `TreeRender.selectionLabel` */
20
28
  selected?: boolean;
21
29
  tag?: boolean;
22
30
  collapsed?: boolean;
23
31
  hidden?: boolean;
24
32
  notshown?: boolean;
33
+ /** Name of the selection set this node belongs to (multi-set mode) */
34
+ _selectionSet?: string;
25
35
  screen_x?: number;
26
36
  screen_y?: number;
27
37
  text_angle?: number;
28
38
  text_align?: string;
29
39
  angle?: number;
30
40
  radius?: number;
31
- };
41
+ }
32
42
 
33
43
  /**
34
44
  * A link/branch in the phylogenetic tree
35
45
  */
36
- export type PhylotreeLink = HierarchyLink<PhylotreeNodeData> & {
46
+ export interface PhylotreeLink extends d3.HierarchyLink<PhylotreeNodeData> {
37
47
  source: PhylotreeNode;
38
48
  target: PhylotreeNode;
39
- };
49
+ /** Default selection attribute, mirrored from `target` */
50
+ selected?: boolean;
51
+ tag?: boolean;
52
+ }
40
53
 
41
54
  /**
42
- * Options for rendering a phylogenetic tree
55
+ * Node styler: called with a selection of the node's `<g>` element.
56
+ */
57
+ export type NodeStyler = (
58
+ element: d3.Selection<SVGGElement, PhylotreeNode, null, undefined>,
59
+ node: PhylotreeNode
60
+ ) => void;
61
+
62
+ /**
63
+ * Edge styler: called with a selection of the branch's `<path>` element.
64
+ * `transition` is passed while the tree is being drawn, not on refresh.
65
+ */
66
+ export type EdgeStyler = (
67
+ element: d3.Selection<SVGPathElement, PhylotreeLink, null, undefined>,
68
+ link: PhylotreeLink,
69
+ transition?: boolean
70
+ ) => void;
71
+
72
+ /** Names accepted by `modifySelection` when `restricted-selectable` is on */
73
+ export type PredefinedSelector = 'all' | 'none' | 'all-leaf-nodes' | 'all-internal-nodes';
74
+
75
+ /** Keys of the CSS class map (see `css-classes` and `TreeRender.css`) */
76
+ export type CssClassKey =
77
+ | 'tree-container'
78
+ | 'tree-scale-bar'
79
+ | 'node'
80
+ | 'internal-node'
81
+ | 'tagged-node'
82
+ | 'selected-node'
83
+ | 'collapsed-node'
84
+ | 'root-node'
85
+ | 'branch'
86
+ | 'selected-branch'
87
+ | 'tagged-branch'
88
+ | 'tree-selection-brush'
89
+ | 'branch-tracer'
90
+ | 'clade'
91
+ | 'node_text';
92
+
93
+ /** A named, coloured selection set for `selection-mode: "multi-set"` */
94
+ export interface SelectionSetDefinition {
95
+ name: string;
96
+ color: string;
97
+ }
98
+
99
+ /**
100
+ * Options for rendering a phylogenetic tree (defaults in src/render/draw.js)
43
101
  */
44
102
  export interface RenderOptions {
45
103
  /** CSS selector or DOM element for the container */
46
104
  container?: string | HTMLElement;
47
- /** Width of the SVG in pixels */
105
+ /** Width of the SVG in pixels (default 800) */
48
106
  width?: number;
49
- /** Height of the SVG in pixels */
107
+ /** Height of the SVG in pixels (default 600) */
50
108
  height?: number;
51
- /** Enable zoom/pan behavior */
52
- zoom?: boolean;
53
- /** Tree layout: "left-to-right" or "right-to-left" */
109
+ /** Tree layout direction */
54
110
  layout?: 'left-to-right' | 'right-to-left';
55
- /** Use radial/circular layout */
56
- 'is-radial'?: boolean;
57
- /** Use unrooted (equal-angle) layout */
58
- 'is-unrooted'?: boolean;
59
- /** Align tip labels */
60
- 'align-tips'?: boolean;
61
- /** Show node labels */
62
- 'show-labels'?: boolean;
63
- /** Show scale bar */
64
- 'show-scale'?: boolean;
65
- /** Draw size bubbles on nodes */
66
- 'draw-size-bubbles'?: boolean;
111
+ /** Logger instance */
112
+ logger?: Console;
113
+ branches?: string;
114
+ /** Scale branches by length */
115
+ scaling?: boolean;
116
+ bootstrap?: boolean;
117
+ 'color-fill'?: boolean;
118
+ /** Font size for labels */
119
+ 'font-size'?: number;
67
120
  /** Show internal node names */
68
121
  'internal-names'?: boolean | ((node: PhylotreeNode) => boolean);
69
122
  /** Enable node selection */
70
123
  selectable?: boolean;
124
+ /** Only allow selection through the predefined selector names */
125
+ 'restricted-selectable'?: false | PredefinedSelector[];
71
126
  /** Enable collapsing of clades */
72
127
  collapsible?: boolean;
73
- /** Enable brushing for selection */
74
- brush?: boolean;
128
+ /** Horizontal spacing mode */
129
+ 'left-right-spacing'?: 'fixed-step' | 'fit-to-size';
130
+ /** Vertical spacing mode */
131
+ 'top-bottom-spacing'?: 'fixed-step' | 'fit-to-size';
75
132
  /** Left offset in pixels */
76
133
  'left-offset'?: number;
77
- /** Spacing mode for top-bottom */
78
- 'top-bottom-spacing'?: 'fixed-step' | 'fit';
79
- /** Spacing mode for left-right */
80
- 'left-right-spacing'?: 'fixed-step' | 'fit';
81
- /** Font size for labels */
82
- 'font-size'?: number;
83
- /** Maximum label width in characters */
84
- 'max-label-width'?: number;
85
- /** Bubble styler function */
134
+ /** Show scale bar (only top placement is implemented) */
135
+ 'show-scale'?: boolean | 'top';
136
+ /** Draw size bubbles on nodes */
137
+ 'draw-size-bubbles'?: boolean;
138
+ /** Bubble size for a node, used when `draw-size-bubbles` is on */
86
139
  'bubble-styler'?: (node: PhylotreeNode) => number;
87
- /** Restrict which nodes can be selected */
88
- 'restricted-selectable'?: string | ((link: PhylotreeLink) => boolean);
89
- /** Logger instance */
90
- logger?: Console;
140
+ 'binary-selectable'?: boolean;
141
+ /** Attributes cleared by binary selection */
142
+ 'attribute-list'?: string[];
143
+ /** Use radial/circular layout */
144
+ 'is-radial'?: boolean;
145
+ /** Use unrooted (equal-angle) layout */
146
+ 'is-unrooted'?: boolean;
147
+ 'max-radius'?: number;
148
+ 'annular-limit'?: number;
149
+ /** Compression applied to collapsed clades */
150
+ compression?: number;
151
+ /** Align tip labels */
152
+ 'align-tips'?: boolean;
153
+ 'maximum-per-node-spacing'?: number;
154
+ 'minimum-per-node-spacing'?: number;
155
+ 'maximum-per-level-spacing'?: number;
156
+ 'minimum-per-level-spacing'?: number;
157
+ /** Node circle radius accessor */
158
+ node_circle_size?: (node: PhylotreeNode) => number;
159
+ /** Force transitions on or off; null picks based on tree size */
160
+ transitions?: boolean | null;
161
+ /** Enable brushing for selection */
162
+ brush?: boolean;
163
+ /** Offer "reroot" in the node menu */
164
+ reroot?: boolean;
165
+ /** Offer "hide" in the node menu */
166
+ hide?: boolean;
167
+ 'label-nodes-with-name'?: boolean;
168
+ /** Enable zoom/pan behavior */
169
+ zoom?: boolean;
170
+ /** Show the node context menu */
171
+ 'show-menu'?: boolean;
172
+ /** Show node labels */
173
+ 'show-labels'?: boolean;
174
+ /** Node styler; same as `TreeRender.style_nodes` */
175
+ 'node-styler'?: NodeStyler | null;
176
+ /** Edge styler; same as `TreeRender.style_edges` */
177
+ 'edge-styler'?: EdgeStyler | null;
178
+ /** Vertical span of each node */
179
+ 'node-span'?: ((node: PhylotreeNode) => number) | null;
180
+ /** Scale the SVG with its container using a viewBox */
181
+ responsive?: boolean;
182
+ /** `preserveAspectRatio` used when `responsive` is on */
183
+ 'preserve-aspect-ratio'?: string;
184
+ /** Single selection or several named selection sets */
185
+ 'selection-mode'?: 'single' | 'multi-set';
186
+ /** Selection sets for multi-set mode */
187
+ 'selection-sets'?: SelectionSetDefinition[];
188
+ /** Names of nodes to select after the first render */
189
+ 'initial-selection'?: string[];
190
+ /** Set name to node names, applied after the first render (multi-set mode) */
191
+ 'initial-sets'?: { [setName: string]: string[] };
192
+ /** Override CSS class names */
193
+ 'css-classes'?: Partial<Record<CssClassKey, string>>;
91
194
  }
92
195
 
93
196
  /**
94
197
  * Options for parsing tree input
95
198
  */
96
199
  export interface ParseOptions {
97
- /** Enable bootstrap value parsing */
98
- bootstrap_values?: boolean;
99
- /** Format type: "newick", "phyloxml", "nexus" */
100
- type?: string | ((input: string, options: ParseOptions) => any);
200
+ /** A registered format name, or a custom parser function */
201
+ type?:
202
+ | 'nexml'
203
+ | 'phyloxml'
204
+ | 'nexus'
205
+ | 'nwk'
206
+ | 'nhx'
207
+ | 'beast'
208
+ | ((input: any, options: ParseOptions) => { json: object | null; error: string | null });
209
+ /** Newick annotation delimiters (default `{` and `}`) */
210
+ left_delimiter?: string;
211
+ right_delimiter?: string;
101
212
  /** Logger instance */
102
213
  logger?: Console;
103
214
  }
104
215
 
216
+ /** Branch length accessor; called with a second argument to set a length */
217
+ export type BranchLengthAccessor = (node: PhylotreeNode, new_length?: number) => number | undefined;
218
+
219
+ /** Result of the linear fit used by `fitRootToTip` */
220
+ export interface LinearFit {
221
+ intercept: number;
222
+ slope: number;
223
+ r2: number;
224
+ 'var (intercept)': number;
225
+ 'var (slope)': number;
226
+ }
227
+
105
228
  /**
106
- * The TreeRender class handles visualization of the tree
229
+ * The TreeRender class handles visualization of the tree.
230
+ *
231
+ * Type-only: the class is not exported at runtime, so create instances with
232
+ * `phylotree.render()` rather than `new TreeRender()` or `instanceof`.
107
233
  */
108
- export class TreeRender {
234
+ declare class TreeRender {
109
235
  /** The phylotree instance this renderer belongs to */
110
- phylotree: Phylotree;
236
+ phylotree: phylotree;
111
237
  /** The SVG element */
112
- svg: d3.Selection<SVGSVGElement, unknown, null, undefined>;
113
- /** Rendering options */
238
+ svg: d3.Selection<SVGSVGElement, undefined, null, undefined>;
239
+ /** Rendering options, merged with the defaults */
114
240
  options: RenderOptions;
115
241
  /** Current zoom transform */
116
242
  currentZoomTransform: d3.ZoomTransform | null;
@@ -119,66 +245,153 @@ export class TreeRender {
119
245
  /** Rightmost leaf x position */
120
246
  right_most_leaf: number;
121
247
  /** The container element */
122
- container: string | HTMLElement;
248
+ container: string | HTMLElement | undefined;
249
+ /** Width of the SVG in pixels */
250
+ width: number;
251
+ /** Height of the SVG in pixels */
252
+ height: number;
253
+ /** Links being drawn */
254
+ links: PhylotreeLink[];
255
+ /** Label font size */
256
+ font_size: number;
257
+ /** Scale bar font size */
258
+ scale_bar_font_size: number;
259
+ /** CSS class names in use */
260
+ css_classes: Record<CssClassKey, string>;
261
+ /** Selection attribute name; see `selectionLabel` */
262
+ selection_attribute_name: string;
263
+ /** Current node styler */
264
+ node_styler: NodeStyler | null | undefined;
265
+ /** Current edge styler */
266
+ edge_styler: EdgeStyler | null | undefined;
267
+ /** Vertical span of each node */
268
+ nodeSpan: (node: PhylotreeNode) => number;
269
+ /** Extra spacing between a node and the previous one */
270
+ separation: (node: PhylotreeNode, previous: PhylotreeNode) => number;
123
271
 
124
- constructor(phylotree: Phylotree, options?: RenderOptions);
272
+ constructor(phylotree: phylotree, options?: RenderOptions);
125
273
 
126
274
  /** Get the SVG element */
127
275
  show(): SVGSVGElement;
128
276
 
129
277
  /** Update the tree display */
130
- update(): this;
278
+ update(transitions?: boolean): this;
131
279
 
132
- /** Update layout coordinates */
133
- update_layout(tree: PhylotreeNode): this;
280
+ /** Re-run the layout and redraw */
281
+ update_layout(new_json: object, do_hierarchy?: boolean): void;
134
282
 
135
283
  /** Get/set radial mode */
136
- radial(value?: boolean): boolean | this;
284
+ radial(): boolean;
285
+ radial(value: boolean): this;
137
286
 
138
287
  /** Get/set unrooted (equal-angle) layout mode */
139
- unrooted(value?: boolean): boolean | this;
288
+ unrooted(): boolean;
289
+ unrooted(value: boolean): this;
140
290
 
141
291
  /** Get/set align tips mode */
142
- alignTips(value?: boolean): boolean | this;
292
+ alignTips(): boolean;
293
+ alignTips(value: boolean): this;
143
294
 
144
- /** Get/set selection label */
145
- selectionLabel(label?: string): string | this;
295
+ /** Get/set whether internal node names are shown */
296
+ internalNames(): boolean | ((node: PhylotreeNode) => boolean);
297
+ internalNames(value: boolean | ((node: PhylotreeNode) => boolean)): this;
146
298
 
147
- /** Get/set node label accessor */
148
- nodeLabel(accessor?: (node: PhylotreeNode) => string): ((node: PhylotreeNode) => string) | this;
299
+ /** Get/set the selection attribute name */
300
+ selectionLabel(): string;
301
+ selectionLabel(label: string): this;
302
+
303
+ /** Get/set node label accessor (a falsy value restores the default) */
304
+ nodeLabel(): (node: PhylotreeNode) => string;
305
+ nodeLabel(accessor: ((node: PhylotreeNode) => string) | null | undefined): this;
149
306
 
150
307
  /** Get/set node styler function */
151
- nodeStyler(styler?: (element: d3.Selection<any, PhylotreeNode, any, any>, node: PhylotreeNode) => void): this;
308
+ style_nodes(): NodeStyler | null | undefined;
309
+ style_nodes(styler: NodeStyler | null): this;
152
310
 
153
311
  /** Get/set edge styler function */
154
- edgeStyler(styler?: (element: d3.Selection<any, PhylotreeLink, any, any>, link: PhylotreeLink) => void): this;
312
+ style_edges(): EdgeStyler | null | undefined;
313
+ style_edges(styler: EdgeStyler): this;
314
+
315
+ /** Mark a node as collapsed (call `update()` to redraw) */
316
+ collapse_node(node: PhylotreeNode): void;
155
317
 
156
- /** Collapse a node */
157
- collapse_node(node: PhylotreeNode): this;
318
+ /** Collapse or expand a node and lay out the tree again */
319
+ toggleCollapse(node: PhylotreeNode): this;
158
320
 
159
- /** Modify selection based on a callback */
160
- modifySelection(callback: (link: PhylotreeLink, callback: (selected: boolean) => void) => boolean): this;
321
+ /**
322
+ * Modify the selection.
323
+ * @param node_selecter A predicate over links; an array of nodes to change;
324
+ * or, when `restricted-selectable` is set, a predefined selector name
325
+ * (any other value is then ignored and nothing is returned)
326
+ * @param attr Selection attribute to modify (default: `selectionLabel()`)
327
+ * @param place Whether to call `placenodes` afterwards
328
+ * @param skip_refresh Whether to skip the refresh
329
+ * @param mode For an array of nodes: toggle them, or set to true / false
330
+ */
331
+ modifySelection(
332
+ node_selecter: ((link: PhylotreeLink) => boolean) | PhylotreeNode[] | PredefinedSelector,
333
+ attr?: string,
334
+ place?: boolean,
335
+ skip_refresh?: boolean,
336
+ mode?: 'toggle' | 'true' | 'false'
337
+ ): this;
161
338
 
162
339
  /** Get selected nodes */
163
340
  getSelection(): PhylotreeNode[];
164
341
 
165
- /** Get selected branches */
166
- getSelectedBranches(): PhylotreeLink[];
342
+ /** Select nodes by name */
343
+ selectNodes(names: string[]): this;
344
+
345
+ /** Deselect nodes by name */
346
+ deselectNodes(names: string[]): this;
347
+
348
+ /** Clear the selection */
349
+ clearSelection(): this;
167
350
 
168
- /** Register event listener */
351
+ /**
352
+ * Register an event listener. Emitted events: nodeClick, nodeHover,
353
+ * branchClick, rendered, selectionChange, collapsed, rerooted, setChange.
354
+ */
169
355
  on(event: string, callback: (...args: any[]) => void): this;
170
356
 
357
+ /** Remove an event listener */
358
+ off(event: string, callback: (...args: any[]) => void): this;
359
+
171
360
  /** Emit an event */
172
361
  emit(event: string, ...args: any[]): this;
173
362
 
174
- /** Selection callback setter */
363
+ /** Get/set the selection callback */
364
+ selectionCallback(): ((selection: PhylotreeNode[]) => void) | null;
175
365
  selectionCallback(callback: (selection: PhylotreeNode[]) => void): this;
176
366
 
367
+ /** Make a set's members the target of node/branch clicks (multi-set mode) */
368
+ setActiveSet(name: string): this;
369
+
370
+ /** Name of the active selection set */
371
+ getActiveSet(): string | null | undefined;
372
+
373
+ /** Nodes in a selection set */
374
+ getSetMembers(setName: string): PhylotreeNode[];
375
+
376
+ /** Add a node (or node name) to a selection set, removing it from the others */
377
+ addToSet(node: PhylotreeNode | string, setName: string): this;
378
+
379
+ /** Remove a node (or node name) from a selection set */
380
+ removeFromSet(node: PhylotreeNode | string, setName: string): this;
381
+
382
+ /** Whether a node is in a selection set */
383
+ isInSet(node: PhylotreeNode, setName: string): boolean;
384
+
385
+ /** Name of the selection set a node belongs to */
386
+ getNodeSet(node: PhylotreeNode): string | null;
387
+
388
+ /** Set up selection sets (called by the constructor in multi-set mode) */
389
+ initializeSelectionSets(sets: SelectionSetDefinition[]): void;
390
+
177
391
  /**
178
392
  * Get or set spacing in the x-direction (horizontal spacing between nodes)
179
393
  * @param attr The new spacing value if setting
180
394
  * @param skip_render Whether to skip re-rendering after setting
181
- * @returns The current spacing_x value if getting, or the TreeRender instance if setting
182
395
  */
183
396
  spacing_x(): number;
184
397
  spacing_x(attr: number, skip_render?: boolean): this;
@@ -187,121 +400,89 @@ export class TreeRender {
187
400
  * Get or set spacing in the y-direction (vertical spacing between levels)
188
401
  * @param attr The new spacing value if setting
189
402
  * @param skip_render Whether to skip re-rendering after setting
190
- * @returns The current spacing_y value if getting, or the TreeRender instance if setting
191
403
  */
192
404
  spacing_y(): number;
193
405
  spacing_y(attr: number, skip_render?: boolean): this;
194
406
 
195
- /**
196
- * Get or set the font size for labels
197
- * @param attr The new font size if setting
198
- * @returns The current font size if getting, or the TreeRender instance if setting
199
- */
200
- font_size(): number;
201
- font_size(attr: number): this;
407
+ /** Get the node circle radius accessor, or set a constant radius */
408
+ node_circle_size(): (node: PhylotreeNode) => number;
409
+ node_circle_size(attr: number): this;
202
410
 
203
- /**
204
- * Get or set the scale bar font size
205
- * @param attr The new font size if setting
206
- * @returns The current scale bar font size if getting, or the TreeRender instance if setting
207
- */
208
- scale_bar_font_size(): number;
209
- scale_bar_font_size(attr: number): this;
411
+ /** Get or set this tree's CSS class names (kept across reroot) */
412
+ css(): Record<CssClassKey, string>;
413
+ css(opt: Partial<Record<CssClassKey, string>>): this;
210
414
 
211
- /**
212
- * Get or set the node circle size
213
- * @param attr The new circle size if setting
214
- * @param attr2 Optional second parameter
215
- * @returns The current node circle size if getting, or the TreeRender instance if setting
216
- */
217
- node_circle_size(): number;
218
- node_circle_size(attr: number, attr2?: number): this;
219
-
220
- /**
221
- * Get or set CSS classes
222
- * @param opt CSS class options
223
- * @returns The current CSS classes if getting, or the TreeRender instance if setting
224
- */
225
- css(): { [key: string]: string };
226
- css(opt: { [key: string]: string }): this;
227
-
228
- /**
229
- * Get or set transitions
230
- * @param arg Transition settings
231
- * @returns The current transition settings if getting, or the TreeRender instance if setting
232
- */
233
- transitions(): boolean | null;
234
- transitions(arg: boolean): this;
415
+ /** Whether transitions are used: `arg` if given, else the option, else size-based */
416
+ transitions(arg?: boolean): boolean;
235
417
 
236
- /**
237
- * Layout the tree
238
- * @param transitions Whether to use transitions
239
- * @returns The TreeRender instance
240
- */
418
+ /** Lay out the tree */
241
419
  layout(transitions?: boolean): this;
242
420
 
243
- /** Refresh the tree display */
421
+ /** Re-apply classes and the edge styler to the drawn edges */
244
422
  refresh(): this;
245
423
 
246
- /** Place nodes in the layout */
424
+ /** Compute node positions */
247
425
  placenodes(): this;
248
426
 
249
427
  /**
250
- * Set the separation function for node spacing
251
- * @param callback Function that returns additional spacing between nodes
252
- * @returns The TreeRender instance
428
+ * Set internal node selection from their children
429
+ * @param callback Called with an internal node's children; returns its selection state
430
+ * @param respect_existing Whether to keep existing internal selections
253
431
  */
254
- separation(callback: (node: PhylotreeNode, previous: PhylotreeNode) => number): this;
432
+ internalLabel(callback: (children: PhylotreeNode[]) => boolean, respect_existing?: boolean): void;
255
433
 
256
- /**
257
- * Set internal node labels based on children
258
- * @param callback Function that determines label based on children
259
- * @param respect_existing Whether to respect existing selections
260
- * @returns The TreeRender instance
261
- */
262
- internalLabel(callback: (children: PhylotreeNode[]) => boolean, respect_existing?: boolean): this;
434
+ /** Get or set the selection count handler */
435
+ countHandler(): (counts: { [attr: string]: number }) => void;
436
+ countHandler(callback: (counts: { [attr: string]: number }) => void): this;
263
437
 
264
- /**
265
- * Get or set the count handler callback
266
- * @param callback Function called with selection count
267
- * @returns The current handler if getting, or the TreeRender instance if setting
268
- */
269
- countHandler(): ((count: number) => void) | null;
270
- countHandler(callback: (count: number) => void): this;
438
+ /** Get or set the layout handler */
439
+ layoutHandler(): (tree: TreeRender) => void;
440
+ layoutHandler(callback: (tree: TreeRender) => void): this;
271
441
 
272
442
  /**
273
- * Update the selection key name
274
- * @param old_key The old key name
275
- * @param new_key The new key name
276
- * @returns The TreeRender instance
443
+ * Add an item to a node's context menu
444
+ * @param node The node
445
+ * @param name Returns the menu item label
446
+ * @param callback Called when the item is clicked
447
+ * @param condition Optional; the item is shown only if it returns true
277
448
  */
278
- updateKeyName(old_key: string, new_key: string | null): this;
449
+ addCustomMenu(
450
+ node: PhylotreeNode,
451
+ name: (node: PhylotreeNode) => string,
452
+ callback: (node: PhylotreeNode, ...args: any[]) => void,
453
+ condition?: (node: PhylotreeNode) => boolean
454
+ ): void;
279
455
 
280
456
  /**
281
- * Set the size of the tree display
282
- * @param attr Size as [width, height]
283
- * @returns The current size if getting, or the TreeRender instance if setting
457
+ * Get or set the size of the tree as `[height, width]`. Setting only
458
+ * changes dimensions whose spacing mode is not "fixed-step".
284
459
  */
285
460
  set_size(): [number, number];
286
461
  set_size(attr: [number, number]): this;
287
462
  }
288
463
 
464
+ export type { TreeRender };
465
+
289
466
  /**
290
- * Main Phylotree class for creating and manipulating phylogenetic trees
467
+ * Main phylotree class for creating and manipulating phylogenetic trees
291
468
  */
292
469
  export class phylotree {
293
- /** Hierarchical tree structure (D3 hierarchy) */
470
+ /** Root of the hierarchy (D3 hierarchy) */
294
471
  nodes: PhylotreeNode;
295
472
  /** Links between nodes */
296
473
  links: PhylotreeLink[];
297
474
  /** Parsed annotation tags */
298
475
  parsed_tags: string[];
299
476
  /** The tree renderer (set after calling render()) */
300
- display: TreeRender | null;
477
+ display?: TreeRender;
301
478
  /** Original Newick string */
302
479
  newick_string: string;
303
480
  /** Selection attribute name */
304
481
  selection_attribute_name: string;
482
+ /** Branch length accessor in use */
483
+ branch_length: BranchLengthAccessor;
484
+ /** Logger instance */
485
+ logger: Console;
305
486
 
306
487
  /**
307
488
  * Create a new phylogenetic tree
@@ -320,52 +501,58 @@ export class phylotree {
320
501
  /**
321
502
  * Traverse the tree and compute values at each node
322
503
  * @param callback Function called on each node
323
- * @param traversal_type "pre-order", "post-order", or "in-order"
504
+ * @param traversal_type "pre-order", "post-order" (default), or "in-order"
324
505
  * @param root_node Optional starting node
325
- * @param backtrack Optional function to stop traversal
506
+ * @param backtrack Optional; returning true skips a node and its subtree
326
507
  */
327
508
  traverse_and_compute(
328
509
  callback: (node: PhylotreeNode) => void,
329
510
  traversal_type?: 'pre-order' | 'post-order' | 'in-order',
330
- root_node?: PhylotreeNode,
511
+ root_node?: PhylotreeNode | null,
331
512
  backtrack?: (node: PhylotreeNode) => boolean
332
- ): void;
513
+ ): this;
333
514
 
334
- /** Export tree to JSON string */
335
- json(traversal_type?: string): string;
515
+ /** Export the nodes to a JSON string, in the given traversal order */
516
+ json(traversal_type?: 'pre-order' | 'post-order' | 'in-order'): string;
336
517
 
337
518
  /** Get parsed annotation tags */
338
519
  get_parsed_tags(): string[];
339
520
 
340
- /** Update tree from JSON */
341
- update(json: object): this;
521
+ /** Replace the hierarchy */
522
+ update(json: PhylotreeNode): void;
342
523
 
343
- /** Check if tree has branch lengths */
524
+ /** Check if every non-root node has a branch length */
344
525
  hasBranchLengths(): boolean;
345
526
 
346
527
  /** Get all branch lengths */
347
- getBranchLengths(): number[];
528
+ getBranchLengths(): Array<number | undefined>;
348
529
 
349
- /** Set branch length accessor */
350
- setBranchLength(accessor: (node: PhylotreeNode) => number): this;
530
+ /** Get or set the branch length accessor (a falsy value restores the default) */
531
+ setBranchLength(): BranchLengthAccessor;
532
+ setBranchLength(accessor: BranchLengthAccessor | null | undefined): this;
351
533
 
352
- /** Normalize branch lengths */
353
- normalizeBranchLengths(attr?: string): this;
534
+ /** Rescale branch lengths to [0, 1] */
535
+ normalizeBranchLengths(): this;
354
536
 
355
- /** Scale branch lengths by a factor */
356
- scaleBranchLengths(scale: number): this;
537
+ /** Transform every branch length with a function */
538
+ scaleBranchLengths(scale_by: (length: number) => number): this;
357
539
 
358
- /** Get branch name accessor */
359
- branchName(accessor?: (node: PhylotreeNode) => string): string | this;
540
+ /** Get or set the branch name accessor */
541
+ branchName(): ((node: PhylotreeNode) => string) | undefined;
542
+ branchName(accessor: (node: PhylotreeNode) => string): this;
360
543
 
361
- /** Get Newick representation of tree */
362
- getNewick(annotator?: (node: PhylotreeNode) => string): string;
544
+ /**
545
+ * Get Newick representation of the tree
546
+ * @param annotator Returns a label to write after each node name
547
+ * @param root Start at this node (default: the root)
548
+ */
549
+ getNewick(annotator?: ((node: PhylotreeNode) => string) | null, root?: PhylotreeNode): string;
363
550
 
364
- /** Get tagged Newick representation */
365
- getTaggedNewick(): string;
551
+ /** Get Newick with `{tag}` annotations on selected nodes (or set names) */
552
+ getTaggedNewick(options?: { tag?: string; multiSet?: boolean }): string;
366
553
 
367
- /** Find most recent common ancestor of nodes */
368
- mrca(nodes: (PhylotreeNode | string)[]): PhylotreeNode;
554
+ /** Find most recent common ancestor of nodes (given as nodes or names) */
555
+ mrca(nodes: Array<PhylotreeNode | string>): PhylotreeNode | undefined;
369
556
 
370
557
  /** Check if a node is a leaf */
371
558
  isLeafNode(node: PhylotreeNode): boolean;
@@ -379,44 +566,56 @@ export class phylotree {
379
566
  /** Get root node */
380
567
  getRootNode(): PhylotreeNode;
381
568
 
382
- /** Get all nodes */
383
- getNodes(): PhylotreeNode[];
569
+ /** Get the root of the hierarchy (same as getRootNode) */
570
+ getNodes(): PhylotreeNode;
384
571
 
385
572
  /** Get node by name */
386
573
  getNodeByName(name: string): PhylotreeNode | undefined;
387
574
 
388
- /** Select all descendants of a node */
575
+ /** Get the descendants of a node */
389
576
  selectAllDescendants(node: PhylotreeNode, terminal?: boolean, internal?: boolean): PhylotreeNode[];
390
577
 
391
- /** Reroot the tree at a node */
578
+ /** Reroot the tree on the branch above a node */
392
579
  reroot(node: PhylotreeNode, fraction?: number): this;
393
580
 
394
- /** Get path from a node to the root */
581
+ /** Get the path from a node to the root, starting with the node */
395
582
  pathToRoot(node: PhylotreeNode): PhylotreeNode[];
396
583
 
397
- /** Resort children of nodes */
584
+ /** Re-sort children of nodes */
398
585
  resortChildren(comparator: (a: PhylotreeNode, b: PhylotreeNode) => number): this;
399
586
 
400
- /** Graft a new node */
401
- graftANode(graftAt: PhylotreeNode, newChild: PhylotreeNode, newParent?: PhylotreeNode, lengths?: { new_child: number; new_parent: number }): void;
587
+ /**
588
+ * Graft a new leaf next to a node
589
+ * @param graftAt The node to graft next to
590
+ * @param newChild Name of the new leaf
591
+ * @param newParent Name of the new internal node
592
+ * @param lengths Branch lengths for `[graftAt, newChild, newParent]`
593
+ */
594
+ graftANode(graftAt: PhylotreeNode, newChild: string, newParent: string, lengths?: string[]): this;
595
+
596
+ /** Create a node stub for `addChild` */
597
+ createNode(name: string, lengths?: unknown[]): { data: { name: string; attribute: unknown }; parent: string };
402
598
 
403
- /** Add a child node */
404
- addChild(parent: PhylotreeNode, child: PhylotreeNode): void;
599
+ /** Add a child to a node; returns the parent */
600
+ addChild<T extends object>(parent: T, child: object): T;
405
601
 
406
- /** Delete a node */
407
- deleteANode(index: number): void;
602
+ /** Delete a node, given the node or its index in `nodes.descendants()` */
603
+ deleteANode(index: number | PhylotreeNode): this;
408
604
 
409
- /** Assign attributes to nodes */
410
- assignAttributes(attributes: object): this;
605
+ /** Store attributes in the `annotations` field of the nodes named by the keys */
606
+ assignAttributes(attributes: { [name: string]: unknown }): void;
411
607
 
412
- /** Get tip lengths for date extraction */
413
- getTipLengths(): { [name: string]: number };
608
+ /** Get tips and their branch lengths, longest first */
609
+ getTipLengths(): Array<{ name: string; length: number }>;
414
610
 
415
- /** Maximum parsimony ancestral state reconstruction */
416
- maxParsimony(attr: string, states: string[]): this;
611
+ /** Maximum parsimony reconstruction of a selection attribute; needs a rendered tree */
612
+ maxParsimony(respect_existing: boolean, attr_name: string): void;
417
613
 
418
- /** Clear internal node selections */
419
- clearInternalNodes(respect?: boolean): this;
614
+ /** Clear selection of internal nodes (unless `respect` is true) */
615
+ clearInternalNodes(respect?: boolean): void;
616
+
617
+ /** Rename (or, with a null new_key, delete) a key on every node */
618
+ updateKeyName(old_key: string, new_key: string | null): this;
420
619
  }
421
620
 
422
621
  // Utility functions
@@ -424,22 +623,32 @@ export class phylotree {
424
623
  /**
425
624
  * Parse a Newick format string
426
625
  */
427
- export function newickParser(newick: string, options?: ParseOptions): { json: object; error: string | null };
626
+ export function newickParser(
627
+ newick: string,
628
+ options?: { left_delimiter?: string; right_delimiter?: string }
629
+ ): { json: object | null; error: string | null };
428
630
 
429
631
  /**
430
- * Get Newick string from tree
632
+ * Get Newick string from a tree; must be called with a phylotree as `this`
633
+ * (prefer `tree.getNewick()`)
431
634
  */
432
- export function getNewick(tree: PhylotreeNode, annotator?: (node: PhylotreeNode) => string): string;
635
+ export function getNewick(
636
+ this: phylotree,
637
+ annotator?: ((node: PhylotreeNode) => string) | null,
638
+ root?: PhylotreeNode
639
+ ): string;
433
640
 
434
641
  /**
435
- * Compute pairwise distances between nodes
642
+ * Annotate nodes with path lengths for pairwise distance computations
643
+ * @returns The number of leaves
436
644
  */
437
- export function pairwise_distances(tree: phylotree): number[][];
645
+ export function pairwise_distances(tree: phylotree): number;
438
646
 
439
647
  /**
440
- * Compute pairwise distances between nodes (camelCase alias)
648
+ * Annotate nodes with path lengths for pairwise distance computations (camelCase alias)
649
+ * @returns The number of leaves
441
650
  */
442
- export function pairwiseDistances(tree: phylotree): number[][];
651
+ export function pairwiseDistances(tree: phylotree): number;
443
652
 
444
653
  /**
445
654
  * Compute Sackin's index (tree balance measure)
@@ -447,91 +656,110 @@ export function pairwiseDistances(tree: phylotree): number[][];
447
656
  export function sackin(tree: phylotree): number;
448
657
 
449
658
  /**
450
- * Find center of tree
659
+ * Find the center of the tree (minimises the sum of distances^power to the leaves)
451
660
  */
452
- export function centerOfTree(tree: phylotree): PhylotreeNode;
661
+ export function centerOfTree(tree: phylotree, power?: number): {
662
+ location: PhylotreeNode;
663
+ breakpoint: number;
664
+ distance: number;
665
+ };
453
666
 
454
667
  /**
455
- * Compute midpoint for rooting
668
+ * Compute the midpoint for rooting
456
669
  */
457
- export function computeMidpoint(tree: phylotree): { node: PhylotreeNode; fraction: number };
670
+ export function computeMidpoint(tree: phylotree): { location: PhylotreeNode; breakpoint: number };
458
671
 
459
672
  /**
460
- * Root to tip regression
673
+ * Store root-to-tip distances on the nodes; returns the tree
461
674
  */
462
- export function rootToTip(tree: phylotree, attr?: string): {
463
- slope: number;
464
- intercept: number;
465
- r2: number;
466
- data: Array<{ date: number; distance: number; name: string }>;
467
- };
675
+ export function rootToTip(tree: phylotree): phylotree;
468
676
 
469
677
  /**
470
- * Fit root to tip (find optimal root)
678
+ * Find the root that maximises the root-to-tip regression r2 (needs dates;
679
+ * see extractDates). `root` is 0 if the current root is best.
471
680
  */
472
- export function fitRootToTip(tree: phylotree, attr?: string): {
473
- node: PhylotreeNode;
474
- fraction: number;
475
- r2: number;
476
- };
681
+ export function fitRootToTip(tree: phylotree): { root: PhylotreeNode | 0; fit: LinearFit };
477
682
 
478
683
  /**
479
- * Extract dates from tip names
684
+ * Extract dates from nodes and store `date_value` / `decimal_date_value` in their data
480
685
  */
481
- export function extract_dates(tree: phylotree, pattern?: RegExp): { [name: string]: number };
686
+ export function extract_dates(
687
+ tree: phylotree,
688
+ date_getter?: (node: PhylotreeNode) => string | null,
689
+ date_converter?: (date: string) => Date | null
690
+ ): phylotree;
482
691
 
483
692
  /**
484
- * Extract dates from tip names (camelCase alias)
693
+ * Extract dates from nodes (camelCase alias)
485
694
  */
486
- export function extractDates(tree: phylotree, pattern?: RegExp): { [name: string]: number };
695
+ export function extractDates(
696
+ tree: phylotree,
697
+ date_getter?: (node: PhylotreeNode) => string | null,
698
+ date_converter?: (date: string) => Date | null
699
+ ): phylotree;
487
700
 
488
701
  /**
489
702
  * Cluster Picker algorithm
490
703
  */
491
- export function clusterPicker(tree: phylotree, options?: {
492
- bootstrap_threshold?: number;
493
- distance_threshold?: number;
494
- }): PhylotreeNode[][];
704
+ export function clusterPicker(
705
+ tree: phylotree,
706
+ bootstrap_threshold: number,
707
+ diameter_threshold: number,
708
+ root_node?: PhylotreeNode | null,
709
+ missing_bootstrap_value?: number
710
+ ): Array<{ root: PhylotreeNode; diameter: number; bootstrap: number; members: PhylotreeNode[] }>;
495
711
 
496
712
  /**
497
713
  * PhyloPart clustering algorithm
498
714
  */
499
- export function phylopart(tree: phylotree, options?: {
500
- bootstrap_threshold?: number;
501
- }): PhylotreeNode[][];
715
+ export function phylopart(
716
+ tree: phylotree,
717
+ bootstrap_threshold: number,
718
+ percentile_threshold: number,
719
+ missing_bootstrap_value?: number,
720
+ resolution?: number
721
+ ): Array<{ root: PhylotreeNode; median: number; bootstrap: number; members: PhylotreeNode[] }>;
502
722
 
503
723
  /**
504
- * Parse FASTA format
724
+ * Parse FASTA format into a map of sequence name to sequence
505
725
  */
506
- export function parseFasta(fasta: string): Array<{ name: string; seq: string }>;
726
+ export function parseFasta(fasta: string): { [name: string]: string };
507
727
 
508
728
  /**
509
729
  * Neighbor joining tree construction
730
+ * @param matrix The n x n distance matrix
731
+ * @param n The dimension of the matrix
732
+ * @param labels Row names (modified in place)
510
733
  */
511
- export function neighborJoining(matrix: number[][], labels: string[]): object;
734
+ export function neighborJoining(matrix: number[][], n: number, labels: string[]): phylotree | null;
512
735
 
513
736
  /**
514
- * Get distance matrix from sequences
737
+ * Pairwise (gap-masked) distances between aligned sequences
515
738
  */
516
- export function getDistanceMatrix(sequences: Array<{ name: string; seq: string }>): {
517
- matrix: number[][];
518
- labels: string[];
519
- };
739
+ export function getDistanceMatrix(sequences: { [name: string]: string }): { [name: string]: number[] };
520
740
 
521
741
  /**
522
- * Load annotations from NEXUS file
742
+ * Store `annotations.matrix[name]` in the `test` field of each tip's data
523
743
  */
524
- export function loadAnnotations(nexus: string): object;
744
+ export function loadAnnotations(
745
+ tree: phylotree,
746
+ label: string,
747
+ annotations: { matrix: { [name: string]: unknown } }
748
+ ): void;
525
749
 
526
750
  /**
527
- * Parse annotations from NEXUS
751
+ * Parse the DATA block of a NEXUS string ('' if there is none)
528
752
  */
529
- export function parseAnnotations(nexus: string): object;
753
+ export function parseAnnotations(nexus: string): '' | {
754
+ dimensions: { [key: string]: string };
755
+ format: { symbols: string[]; [key: string]: string | string[] };
756
+ matrix: { [name: string]: string[] };
757
+ };
530
758
 
531
759
  // Tree traversal functions
532
760
 
533
761
  /**
534
- * In-order traversal
762
+ * Level-order traversal (exported as inOrder)
535
763
  */
536
764
  export function inOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) => void, backtrack?: (node: PhylotreeNode) => boolean): void;
537
765
 
@@ -546,6 +774,10 @@ export function preOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) =>
546
774
  export function postOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) => void, backtrack?: (node: PhylotreeNode) => boolean): void;
547
775
 
548
776
  /**
549
- * Left-child right-sibling traversal
777
+ * Edge list of the multi-way tree encoded by a left-child right-sibling binary tree
550
778
  */
551
- export function leftChildRightSibling(node: PhylotreeNode, callback: (node: PhylotreeNode) => void): void;
779
+ export function leftChildRightSibling(root: PhylotreeNode): Array<{
780
+ source: PhylotreeNode | null | undefined;
781
+ target: PhylotreeNode;
782
+ name: string;
783
+ }>;