| 1 | import { randomId } from '../utils'; |
| 2 | import type Frame from './Frame'; |
| 3 | |
| 4 | export default class FrameGroup { |
| 5 | id: string; |
| 6 | rootFrame: Frame; |
| 7 | _frames: Frame[] = [] |
| 8 | |
| 9 | constructor(rootFrame: Frame) { |
| 10 | this.id = randomId() |
| 11 | this.rootFrame = rootFrame; |
| 12 | } |
| 13 | |
| 14 | addFrame(frame: Frame) { |
| 15 | if (frame.group) { |
| 16 | frame.group.removeFrame(frame); |
| 17 | } |
| 18 | this._frames.push(frame); |
| 19 | frame.group = this; |
| 20 | } |
| 21 | |
| 22 | removeFrame(frame: Frame) { |
| 23 | if (frame.group !== this) { |
| 24 | throw new Error("Frame not in group."); |
| 25 | } |
| 26 | |
| 27 | const index = this._frames.indexOf(frame); |
| 28 | if (index === -1) { |
| 29 | throw new Error("Frame not found in group."); |
| 30 | } |
| 31 | this._frames.splice(index, 1); |
| 32 | frame.group = null; |
| 33 | } |
| 34 | |
| 35 | get frames(): readonly Frame[] { |
| 36 | return this._frames; |
| 37 | } |
| 38 | |
| 39 | get exitFrames() { |
| 40 | // exit frames are frames inside this group that have children outside the group. |
| 41 | const exitFrames = [] |
| 42 | |
| 43 | for (const frame of this.frames) { |
| 44 | let isExit = false; |
| 45 | for (const child of frame.children) { |
| 46 | if (child.group != this) { |
| 47 | isExit = true; |
| 48 | break; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | if (isExit) { |
| 53 | exitFrames.push(frame); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | return exitFrames; |
| 58 | } |
| 59 | |
| 60 | get libraries() { |
| 61 | const libraries: string[] = []; |
| 62 | |
| 63 | for (const frame of this.frames) { |
| 64 | const library = frame.library |
| 65 | if (!library) { |
| 66 | continue |
| 67 | } |
| 68 | |
| 69 | if (!libraries.includes(library)) { |
| 70 | libraries.push(library); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | return libraries; |
| 75 | } |
| 76 | } |