phylotree 2.5.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,114 +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
- /** Align tip labels */
58
- 'align-tips'?: boolean;
59
- /** Show node labels */
60
- 'show-labels'?: boolean;
61
- /** Show scale bar */
62
- 'show-scale'?: boolean;
63
- /** Draw size bubbles on nodes */
64
- '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;
65
120
  /** Show internal node names */
66
121
  'internal-names'?: boolean | ((node: PhylotreeNode) => boolean);
67
122
  /** Enable node selection */
68
123
  selectable?: boolean;
124
+ /** Only allow selection through the predefined selector names */
125
+ 'restricted-selectable'?: false | PredefinedSelector[];
69
126
  /** Enable collapsing of clades */
70
127
  collapsible?: boolean;
71
- /** Enable brushing for selection */
72
- 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';
73
132
  /** Left offset in pixels */
74
133
  'left-offset'?: number;
75
- /** Spacing mode for top-bottom */
76
- 'top-bottom-spacing'?: 'fixed-step' | 'fit';
77
- /** Spacing mode for left-right */
78
- 'left-right-spacing'?: 'fixed-step' | 'fit';
79
- /** Font size for labels */
80
- 'font-size'?: number;
81
- /** Maximum label width in characters */
82
- 'max-label-width'?: number;
83
- /** 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 */
84
139
  'bubble-styler'?: (node: PhylotreeNode) => number;
85
- /** Restrict which nodes can be selected */
86
- 'restricted-selectable'?: string | ((link: PhylotreeLink) => boolean);
87
- /** Logger instance */
88
- 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>>;
89
194
  }
90
195
 
91
196
  /**
92
197
  * Options for parsing tree input
93
198
  */
94
199
  export interface ParseOptions {
95
- /** Enable bootstrap value parsing */
96
- bootstrap_values?: boolean;
97
- /** Format type: "newick", "phyloxml", "nexus" */
98
- 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;
99
212
  /** Logger instance */
100
213
  logger?: Console;
101
214
  }
102
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
+
103
228
  /**
104
- * 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`.
105
233
  */
106
- export class TreeRender {
234
+ declare class TreeRender {
107
235
  /** The phylotree instance this renderer belongs to */
108
- phylotree: Phylotree;
236
+ phylotree: phylotree;
109
237
  /** The SVG element */
110
- svg: d3.Selection<SVGSVGElement, unknown, null, undefined>;
111
- /** Rendering options */
238
+ svg: d3.Selection<SVGSVGElement, undefined, null, undefined>;
239
+ /** Rendering options, merged with the defaults */
112
240
  options: RenderOptions;
113
241
  /** Current zoom transform */
114
242
  currentZoomTransform: d3.ZoomTransform | null;
@@ -117,63 +245,153 @@ export class TreeRender {
117
245
  /** Rightmost leaf x position */
118
246
  right_most_leaf: number;
119
247
  /** The container element */
120
- 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;
121
271
 
122
- constructor(phylotree: Phylotree, options?: RenderOptions);
272
+ constructor(phylotree: phylotree, options?: RenderOptions);
123
273
 
124
274
  /** Get the SVG element */
125
275
  show(): SVGSVGElement;
126
276
 
127
277
  /** Update the tree display */
128
- update(): this;
278
+ update(transitions?: boolean): this;
129
279
 
130
- /** Update layout coordinates */
131
- update_layout(tree: PhylotreeNode): this;
280
+ /** Re-run the layout and redraw */
281
+ update_layout(new_json: object, do_hierarchy?: boolean): void;
132
282
 
133
283
  /** Get/set radial mode */
134
- radial(value?: boolean): boolean | this;
284
+ radial(): boolean;
285
+ radial(value: boolean): this;
286
+
287
+ /** Get/set unrooted (equal-angle) layout mode */
288
+ unrooted(): boolean;
289
+ unrooted(value: boolean): this;
135
290
 
136
291
  /** Get/set align tips mode */
137
- alignTips(value?: boolean): boolean | this;
292
+ alignTips(): boolean;
293
+ alignTips(value: boolean): this;
138
294
 
139
- /** Get/set selection label */
140
- 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;
141
298
 
142
- /** Get/set node label accessor */
143
- 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;
144
306
 
145
307
  /** Get/set node styler function */
146
- 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;
147
310
 
148
311
  /** Get/set edge styler function */
149
- 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;
150
317
 
151
- /** Collapse a node */
152
- collapse_node(node: PhylotreeNode): this;
318
+ /** Collapse or expand a node and lay out the tree again */
319
+ toggleCollapse(node: PhylotreeNode): this;
153
320
 
154
- /** Modify selection based on a callback */
155
- 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;
156
338
 
157
339
  /** Get selected nodes */
158
340
  getSelection(): PhylotreeNode[];
159
341
 
160
- /** Get selected branches */
161
- getSelectedBranches(): PhylotreeLink[];
342
+ /** Select nodes by name */
343
+ selectNodes(names: string[]): this;
162
344
 
163
- /** Register event listener */
345
+ /** Deselect nodes by name */
346
+ deselectNodes(names: string[]): this;
347
+
348
+ /** Clear the selection */
349
+ clearSelection(): this;
350
+
351
+ /**
352
+ * Register an event listener. Emitted events: nodeClick, nodeHover,
353
+ * branchClick, rendered, selectionChange, collapsed, rerooted, setChange.
354
+ */
164
355
  on(event: string, callback: (...args: any[]) => void): this;
165
356
 
357
+ /** Remove an event listener */
358
+ off(event: string, callback: (...args: any[]) => void): this;
359
+
166
360
  /** Emit an event */
167
361
  emit(event: string, ...args: any[]): this;
168
362
 
169
- /** Selection callback setter */
363
+ /** Get/set the selection callback */
364
+ selectionCallback(): ((selection: PhylotreeNode[]) => void) | null;
170
365
  selectionCallback(callback: (selection: PhylotreeNode[]) => void): this;
171
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
+
172
391
  /**
173
392
  * Get or set spacing in the x-direction (horizontal spacing between nodes)
174
393
  * @param attr The new spacing value if setting
175
394
  * @param skip_render Whether to skip re-rendering after setting
176
- * @returns The current spacing_x value if getting, or the TreeRender instance if setting
177
395
  */
178
396
  spacing_x(): number;
179
397
  spacing_x(attr: number, skip_render?: boolean): this;
@@ -182,121 +400,89 @@ export class TreeRender {
182
400
  * Get or set spacing in the y-direction (vertical spacing between levels)
183
401
  * @param attr The new spacing value if setting
184
402
  * @param skip_render Whether to skip re-rendering after setting
185
- * @returns The current spacing_y value if getting, or the TreeRender instance if setting
186
403
  */
187
404
  spacing_y(): number;
188
405
  spacing_y(attr: number, skip_render?: boolean): this;
189
406
 
190
- /**
191
- * Get or set the font size for labels
192
- * @param attr The new font size if setting
193
- * @returns The current font size if getting, or the TreeRender instance if setting
194
- */
195
- font_size(): number;
196
- font_size(attr: number): this;
197
-
198
- /**
199
- * Get or set the scale bar font size
200
- * @param attr The new font size if setting
201
- * @returns The current scale bar font size if getting, or the TreeRender instance if setting
202
- */
203
- scale_bar_font_size(): number;
204
- scale_bar_font_size(attr: number): this;
205
-
206
- /**
207
- * Get or set the node circle size
208
- * @param attr The new circle size if setting
209
- * @param attr2 Optional second parameter
210
- * @returns The current node circle size if getting, or the TreeRender instance if setting
211
- */
212
- node_circle_size(): number;
213
- node_circle_size(attr: number, attr2?: 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;
214
410
 
215
- /**
216
- * Get or set CSS classes
217
- * @param opt CSS class options
218
- * @returns The current CSS classes if getting, or the TreeRender instance if setting
219
- */
220
- css(): { [key: string]: string };
221
- css(opt: { [key: string]: string }): 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;
222
414
 
223
- /**
224
- * Get or set transitions
225
- * @param arg Transition settings
226
- * @returns The current transition settings if getting, or the TreeRender instance if setting
227
- */
228
- transitions(): boolean | null;
229
- transitions(arg: boolean): this;
415
+ /** Whether transitions are used: `arg` if given, else the option, else size-based */
416
+ transitions(arg?: boolean): boolean;
230
417
 
231
- /**
232
- * Layout the tree
233
- * @param transitions Whether to use transitions
234
- * @returns The TreeRender instance
235
- */
418
+ /** Lay out the tree */
236
419
  layout(transitions?: boolean): this;
237
420
 
238
- /** Refresh the tree display */
421
+ /** Re-apply classes and the edge styler to the drawn edges */
239
422
  refresh(): this;
240
423
 
241
- /** Place nodes in the layout */
424
+ /** Compute node positions */
242
425
  placenodes(): this;
243
426
 
244
427
  /**
245
- * Set the separation function for node spacing
246
- * @param callback Function that returns additional spacing between nodes
247
- * @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
248
431
  */
249
- separation(callback: (node: PhylotreeNode, previous: PhylotreeNode) => number): this;
432
+ internalLabel(callback: (children: PhylotreeNode[]) => boolean, respect_existing?: boolean): void;
250
433
 
251
- /**
252
- * Set internal node labels based on children
253
- * @param callback Function that determines label based on children
254
- * @param respect_existing Whether to respect existing selections
255
- * @returns The TreeRender instance
256
- */
257
- 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;
258
437
 
259
- /**
260
- * Get or set the count handler callback
261
- * @param callback Function called with selection count
262
- * @returns The current handler if getting, or the TreeRender instance if setting
263
- */
264
- countHandler(): ((count: number) => void) | null;
265
- 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;
266
441
 
267
442
  /**
268
- * Update the selection key name
269
- * @param old_key The old key name
270
- * @param new_key The new key name
271
- * @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
272
448
  */
273
- 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;
274
455
 
275
456
  /**
276
- * Set the size of the tree display
277
- * @param attr Size as [width, height]
278
- * @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".
279
459
  */
280
460
  set_size(): [number, number];
281
461
  set_size(attr: [number, number]): this;
282
462
  }
283
463
 
464
+ export type { TreeRender };
465
+
284
466
  /**
285
- * Main Phylotree class for creating and manipulating phylogenetic trees
467
+ * Main phylotree class for creating and manipulating phylogenetic trees
286
468
  */
287
469
  export class phylotree {
288
- /** Hierarchical tree structure (D3 hierarchy) */
470
+ /** Root of the hierarchy (D3 hierarchy) */
289
471
  nodes: PhylotreeNode;
290
472
  /** Links between nodes */
291
473
  links: PhylotreeLink[];
292
474
  /** Parsed annotation tags */
293
475
  parsed_tags: string[];
294
476
  /** The tree renderer (set after calling render()) */
295
- display: TreeRender | null;
477
+ display?: TreeRender;
296
478
  /** Original Newick string */
297
479
  newick_string: string;
298
480
  /** Selection attribute name */
299
481
  selection_attribute_name: string;
482
+ /** Branch length accessor in use */
483
+ branch_length: BranchLengthAccessor;
484
+ /** Logger instance */
485
+ logger: Console;
300
486
 
301
487
  /**
302
488
  * Create a new phylogenetic tree
@@ -315,52 +501,58 @@ export class phylotree {
315
501
  /**
316
502
  * Traverse the tree and compute values at each node
317
503
  * @param callback Function called on each node
318
- * @param traversal_type "pre-order", "post-order", or "in-order"
504
+ * @param traversal_type "pre-order", "post-order" (default), or "in-order"
319
505
  * @param root_node Optional starting node
320
- * @param backtrack Optional function to stop traversal
506
+ * @param backtrack Optional; returning true skips a node and its subtree
321
507
  */
322
508
  traverse_and_compute(
323
509
  callback: (node: PhylotreeNode) => void,
324
510
  traversal_type?: 'pre-order' | 'post-order' | 'in-order',
325
- root_node?: PhylotreeNode,
511
+ root_node?: PhylotreeNode | null,
326
512
  backtrack?: (node: PhylotreeNode) => boolean
327
- ): void;
513
+ ): this;
328
514
 
329
- /** Export tree to JSON string */
330
- 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;
331
517
 
332
518
  /** Get parsed annotation tags */
333
519
  get_parsed_tags(): string[];
334
520
 
335
- /** Update tree from JSON */
336
- update(json: object): this;
521
+ /** Replace the hierarchy */
522
+ update(json: PhylotreeNode): void;
337
523
 
338
- /** Check if tree has branch lengths */
524
+ /** Check if every non-root node has a branch length */
339
525
  hasBranchLengths(): boolean;
340
526
 
341
527
  /** Get all branch lengths */
342
- getBranchLengths(): number[];
528
+ getBranchLengths(): Array<number | undefined>;
343
529
 
344
- /** Set branch length accessor */
345
- 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;
346
533
 
347
- /** Normalize branch lengths */
348
- normalizeBranchLengths(attr?: string): this;
534
+ /** Rescale branch lengths to [0, 1] */
535
+ normalizeBranchLengths(): this;
349
536
 
350
- /** Scale branch lengths by a factor */
351
- scaleBranchLengths(scale: number): this;
537
+ /** Transform every branch length with a function */
538
+ scaleBranchLengths(scale_by: (length: number) => number): this;
352
539
 
353
- /** Get branch name accessor */
354
- 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;
355
543
 
356
- /** Get Newick representation of tree */
357
- 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;
358
550
 
359
- /** Get tagged Newick representation */
360
- getTaggedNewick(): string;
551
+ /** Get Newick with `{tag}` annotations on selected nodes (or set names) */
552
+ getTaggedNewick(options?: { tag?: string; multiSet?: boolean }): string;
361
553
 
362
- /** Find most recent common ancestor of nodes */
363
- 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;
364
556
 
365
557
  /** Check if a node is a leaf */
366
558
  isLeafNode(node: PhylotreeNode): boolean;
@@ -374,44 +566,56 @@ export class phylotree {
374
566
  /** Get root node */
375
567
  getRootNode(): PhylotreeNode;
376
568
 
377
- /** Get all nodes */
378
- getNodes(): PhylotreeNode[];
569
+ /** Get the root of the hierarchy (same as getRootNode) */
570
+ getNodes(): PhylotreeNode;
379
571
 
380
572
  /** Get node by name */
381
573
  getNodeByName(name: string): PhylotreeNode | undefined;
382
574
 
383
- /** Select all descendants of a node */
575
+ /** Get the descendants of a node */
384
576
  selectAllDescendants(node: PhylotreeNode, terminal?: boolean, internal?: boolean): PhylotreeNode[];
385
577
 
386
- /** Reroot the tree at a node */
578
+ /** Reroot the tree on the branch above a node */
387
579
  reroot(node: PhylotreeNode, fraction?: number): this;
388
580
 
389
- /** Get path from a node to the root */
581
+ /** Get the path from a node to the root, starting with the node */
390
582
  pathToRoot(node: PhylotreeNode): PhylotreeNode[];
391
583
 
392
- /** Resort children of nodes */
584
+ /** Re-sort children of nodes */
393
585
  resortChildren(comparator: (a: PhylotreeNode, b: PhylotreeNode) => number): this;
394
586
 
395
- /** Graft a new node */
396
- 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;
397
595
 
398
- /** Add a child node */
399
- addChild(parent: PhylotreeNode, child: PhylotreeNode): void;
596
+ /** Create a node stub for `addChild` */
597
+ createNode(name: string, lengths?: unknown[]): { data: { name: string; attribute: unknown }; parent: string };
400
598
 
401
- /** Delete a node */
402
- deleteANode(index: number): void;
599
+ /** Add a child to a node; returns the parent */
600
+ addChild<T extends object>(parent: T, child: object): T;
403
601
 
404
- /** Assign attributes to nodes */
405
- assignAttributes(attributes: object): this;
602
+ /** Delete a node, given the node or its index in `nodes.descendants()` */
603
+ deleteANode(index: number | PhylotreeNode): this;
406
604
 
407
- /** Get tip lengths for date extraction */
408
- getTipLengths(): { [name: string]: number };
605
+ /** Store attributes in the `annotations` field of the nodes named by the keys */
606
+ assignAttributes(attributes: { [name: string]: unknown }): void;
409
607
 
410
- /** Maximum parsimony ancestral state reconstruction */
411
- maxParsimony(attr: string, states: string[]): this;
608
+ /** Get tips and their branch lengths, longest first */
609
+ getTipLengths(): Array<{ name: string; length: number }>;
412
610
 
413
- /** Clear internal node selections */
414
- clearInternalNodes(respect?: boolean): this;
611
+ /** Maximum parsimony reconstruction of a selection attribute; needs a rendered tree */
612
+ maxParsimony(respect_existing: boolean, attr_name: string): void;
613
+
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;
415
619
  }
416
620
 
417
621
  // Utility functions
@@ -419,22 +623,32 @@ export class phylotree {
419
623
  /**
420
624
  * Parse a Newick format string
421
625
  */
422
- 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 };
423
630
 
424
631
  /**
425
- * Get Newick string from tree
632
+ * Get Newick string from a tree; must be called with a phylotree as `this`
633
+ * (prefer `tree.getNewick()`)
426
634
  */
427
- 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;
428
640
 
429
641
  /**
430
- * Compute pairwise distances between nodes
642
+ * Annotate nodes with path lengths for pairwise distance computations
643
+ * @returns The number of leaves
431
644
  */
432
- export function pairwise_distances(tree: phylotree): number[][];
645
+ export function pairwise_distances(tree: phylotree): number;
433
646
 
434
647
  /**
435
- * 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
436
650
  */
437
- export function pairwiseDistances(tree: phylotree): number[][];
651
+ export function pairwiseDistances(tree: phylotree): number;
438
652
 
439
653
  /**
440
654
  * Compute Sackin's index (tree balance measure)
@@ -442,91 +656,110 @@ export function pairwiseDistances(tree: phylotree): number[][];
442
656
  export function sackin(tree: phylotree): number;
443
657
 
444
658
  /**
445
- * Find center of tree
659
+ * Find the center of the tree (minimises the sum of distances^power to the leaves)
446
660
  */
447
- export function centerOfTree(tree: phylotree): PhylotreeNode;
661
+ export function centerOfTree(tree: phylotree, power?: number): {
662
+ location: PhylotreeNode;
663
+ breakpoint: number;
664
+ distance: number;
665
+ };
448
666
 
449
667
  /**
450
- * Compute midpoint for rooting
668
+ * Compute the midpoint for rooting
451
669
  */
452
- export function computeMidpoint(tree: phylotree): { node: PhylotreeNode; fraction: number };
670
+ export function computeMidpoint(tree: phylotree): { location: PhylotreeNode; breakpoint: number };
453
671
 
454
672
  /**
455
- * Root to tip regression
673
+ * Store root-to-tip distances on the nodes; returns the tree
456
674
  */
457
- export function rootToTip(tree: phylotree, attr?: string): {
458
- slope: number;
459
- intercept: number;
460
- r2: number;
461
- data: Array<{ date: number; distance: number; name: string }>;
462
- };
675
+ export function rootToTip(tree: phylotree): phylotree;
463
676
 
464
677
  /**
465
- * 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.
466
680
  */
467
- export function fitRootToTip(tree: phylotree, attr?: string): {
468
- node: PhylotreeNode;
469
- fraction: number;
470
- r2: number;
471
- };
681
+ export function fitRootToTip(tree: phylotree): { root: PhylotreeNode | 0; fit: LinearFit };
472
682
 
473
683
  /**
474
- * Extract dates from tip names
684
+ * Extract dates from nodes and store `date_value` / `decimal_date_value` in their data
475
685
  */
476
- 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;
477
691
 
478
692
  /**
479
- * Extract dates from tip names (camelCase alias)
693
+ * Extract dates from nodes (camelCase alias)
480
694
  */
481
- 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;
482
700
 
483
701
  /**
484
702
  * Cluster Picker algorithm
485
703
  */
486
- export function clusterPicker(tree: phylotree, options?: {
487
- bootstrap_threshold?: number;
488
- distance_threshold?: number;
489
- }): 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[] }>;
490
711
 
491
712
  /**
492
713
  * PhyloPart clustering algorithm
493
714
  */
494
- export function phylopart(tree: phylotree, options?: {
495
- bootstrap_threshold?: number;
496
- }): 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[] }>;
497
722
 
498
723
  /**
499
- * Parse FASTA format
724
+ * Parse FASTA format into a map of sequence name to sequence
500
725
  */
501
- export function parseFasta(fasta: string): Array<{ name: string; seq: string }>;
726
+ export function parseFasta(fasta: string): { [name: string]: string };
502
727
 
503
728
  /**
504
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)
505
733
  */
506
- export function neighborJoining(matrix: number[][], labels: string[]): object;
734
+ export function neighborJoining(matrix: number[][], n: number, labels: string[]): phylotree | null;
507
735
 
508
736
  /**
509
- * Get distance matrix from sequences
737
+ * Pairwise (gap-masked) distances between aligned sequences
510
738
  */
511
- export function getDistanceMatrix(sequences: Array<{ name: string; seq: string }>): {
512
- matrix: number[][];
513
- labels: string[];
514
- };
739
+ export function getDistanceMatrix(sequences: { [name: string]: string }): { [name: string]: number[] };
515
740
 
516
741
  /**
517
- * Load annotations from NEXUS file
742
+ * Store `annotations.matrix[name]` in the `test` field of each tip's data
518
743
  */
519
- export function loadAnnotations(nexus: string): object;
744
+ export function loadAnnotations(
745
+ tree: phylotree,
746
+ label: string,
747
+ annotations: { matrix: { [name: string]: unknown } }
748
+ ): void;
520
749
 
521
750
  /**
522
- * Parse annotations from NEXUS
751
+ * Parse the DATA block of a NEXUS string ('' if there is none)
523
752
  */
524
- 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
+ };
525
758
 
526
759
  // Tree traversal functions
527
760
 
528
761
  /**
529
- * In-order traversal
762
+ * Level-order traversal (exported as inOrder)
530
763
  */
531
764
  export function inOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) => void, backtrack?: (node: PhylotreeNode) => boolean): void;
532
765
 
@@ -541,6 +774,10 @@ export function preOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) =>
541
774
  export function postOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) => void, backtrack?: (node: PhylotreeNode) => boolean): void;
542
775
 
543
776
  /**
544
- * Left-child right-sibling traversal
777
+ * Edge list of the multi-way tree encoded by a left-child right-sibling binary tree
545
778
  */
546
- 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
+ }>;