|
| 1 | +import type { NodeSnapshot, VisibleTree } from '../model' |
| 2 | + |
| 3 | +export type AssetPlan = { |
| 4 | + vectorRoots: Set<string> |
| 5 | +} |
| 6 | + |
| 7 | +export function planAssets(tree: VisibleTree): AssetPlan { |
| 8 | + const vectorRoots = new Set<string>() |
| 9 | + const skipped = new Set<string>() |
| 10 | + const vectorInfo = computeVectorInfo(tree) |
| 11 | + |
| 12 | + for (const id of tree.order) { |
| 13 | + if (skipped.has(id)) continue |
| 14 | + const node = tree.nodes.get(id) |
| 15 | + if (!node) continue |
| 16 | + |
| 17 | + const children = node.children |
| 18 | + .map((childId) => tree.nodes.get(childId)) |
| 19 | + .filter(Boolean) as NodeSnapshot[] |
| 20 | + |
| 21 | + const info = vectorInfo.get(id) |
| 22 | + const isVectorGroup = !!info && info.allVector && info.leafCount > 1 && node.children.length > 1 |
| 23 | + |
| 24 | + if (isVectorGroup) { |
| 25 | + vectorRoots.add(id) |
| 26 | + children.forEach((child) => skipDescendants(child.id, tree, skipped)) |
| 27 | + continue |
| 28 | + } |
| 29 | + |
| 30 | + if (node.assetKind === 'vector') { |
| 31 | + vectorRoots.add(id) |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + return { vectorRoots } |
| 36 | +} |
| 37 | + |
| 38 | +function computeVectorInfo( |
| 39 | + tree: VisibleTree |
| 40 | +): Map<string, { allVector: boolean; leafCount: number }> { |
| 41 | + const info = new Map<string, { allVector: boolean; leafCount: number }>() |
| 42 | + |
| 43 | + for (let i = tree.order.length - 1; i >= 0; i--) { |
| 44 | + const id = tree.order[i] |
| 45 | + const node = tree.nodes.get(id) |
| 46 | + if (!node) continue |
| 47 | + |
| 48 | + if (!node.children.length) { |
| 49 | + const isVector = node.assetKind === 'vector' |
| 50 | + info.set(id, { allVector: isVector, leafCount: isVector ? 1 : 0 }) |
| 51 | + continue |
| 52 | + } |
| 53 | + |
| 54 | + let allVector = true |
| 55 | + let leafCount = 0 |
| 56 | + for (const childId of node.children) { |
| 57 | + const childInfo = info.get(childId) |
| 58 | + if (!childInfo || !childInfo.allVector) { |
| 59 | + allVector = false |
| 60 | + } |
| 61 | + if (childInfo) leafCount += childInfo.leafCount |
| 62 | + } |
| 63 | + info.set(id, { allVector, leafCount }) |
| 64 | + } |
| 65 | + |
| 66 | + return info |
| 67 | +} |
| 68 | + |
| 69 | +function skipDescendants(id: string, tree: VisibleTree, skipped: Set<string>): void { |
| 70 | + const node = tree.nodes.get(id) |
| 71 | + if (!node) return |
| 72 | + if (skipped.has(id)) return |
| 73 | + skipped.add(id) |
| 74 | + node.children.forEach((childId) => skipDescendants(childId, tree, skipped)) |
| 75 | +} |
0 commit comments