| 1 | import { UnreachableCaseError } from "../utils"; |
| 2 | import Frame from "./Frame"; |
| 3 | import { SELF_TIME_FRAME_IDENTIFIER } from "./Frame"; |
| 4 | |
| 5 | export function deleteFrameFromTree(frame: Frame, options: {replaceWith: 'children'|'self_time'|'nothing'}) { |
| 6 | const {replaceWith} = options |
| 7 | const parent = frame.parent |
| 8 | if (!parent) { |
| 9 | throw new Error('Cannot delete the root frame') |
| 10 | } |
| 11 | |
| 12 | if (replaceWith == 'children') { |
| 13 | parent.addChildren(frame.children, {after: frame}) |
| 14 | } else if (replaceWith == 'self_time') { |
| 15 | parent.addChild( |
| 16 | new Frame({ |
| 17 | identifier: SELF_TIME_FRAME_IDENTIFIER, |
| 18 | time: frame.time, |
| 19 | }, parent.context), |
| 20 | {after: frame} |
| 21 | ) |
| 22 | } else if (replaceWith == 'nothing') { |
| 23 | parent.absorbedTime += frame.time |
| 24 | } else { |
| 25 | throw new UnreachableCaseError(replaceWith) |
| 26 | } |
| 27 | |
| 28 | frame.removeFromParent() |
| 29 | removeFrameFromGroups(frame, true) |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Combines two frames into one. The frames must have the same parent. |
| 34 | * |
| 35 | * @param frame The frame to remove. |
| 36 | * @param into The frame to combine into. |
| 37 | */ |
| 38 | export function combineFrames(frame: Frame, into: Frame): void { |
| 39 | if (frame.parent !== into.parent) { |
| 40 | throw new Error("Both frames must have the same parent."); |
| 41 | } |
| 42 | |
| 43 | into.absorbedTime += frame.absorbedTime; |
| 44 | into.time += frame.time; |
| 45 | |
| 46 | Object.entries(frame.attributes).forEach(([attribute, time]) => { |
| 47 | if (into.attributes[attribute] !== undefined) { |
| 48 | into.attributes[attribute] += time; |
| 49 | } else { |
| 50 | into.attributes[attribute] = time; |
| 51 | } |
| 52 | }); |
| 53 | |
| 54 | into.addChildren(frame.children); |
| 55 | frame.removeFromParent(); |
| 56 | removeFrameFromGroups(frame, false); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Removes a frame from any groups that it is a member of. Should be used when |
| 61 | * removing a frame from a tree, so groups don't keep references to removed frames. |
| 62 | * |
| 63 | * @param frame The frame to be removed from groups. |
| 64 | * @param recursive Whether to also remove all child frames from their groups. |
| 65 | */ |
| 66 | export function removeFrameFromGroups(frame: Frame, recursive: boolean): void { |
| 67 | if (recursive && frame.children) { |
| 68 | frame.children.forEach(child => { |
| 69 | removeFrameFromGroups(child, true); |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | if (frame.group) { |
| 74 | const group = frame.group; |
| 75 | group.removeFrame(frame); |
| 76 | |
| 77 | if (group.frames.length === 1) { |
| 78 | // A group with only one frame is meaningless; remove it entirely. |
| 79 | group.removeFrame(group.frames[0]); |
| 80 | } |
| 81 | } |
| 82 | } |