SPB Git

Repository Public License

StorageMapView.swift 19.2 KB 322 lines swift

1// ORIX Clean — App/Sources/Features/StorageMap/StorageMapView.swift2// Description: Interactive treemap of the scanned tree: drill down, zoom, pan, hover details, search, selection for cleanup.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import AppKit5import ORIXCleanCore6import SwiftUI78struct StorageMapView: View {9    @Environment(AppModel.self) private var model10    @AppStorage("mapPalette") private var paletteName = MapPalette.orix.rawValue11    @AppStorage("sizeKind") private var sizeKindName = SizeKind.allocated.rawValue12    @AppStorage("showPackageContents") private var showPackages = false13    @State private var hover: TreemapCell?14    @State private var zoom: CGFloat = 115    @State private var zoomBase: CGFloat = 116    @State private var offset: CGSize = .zero17    @State private var dragBase: CGSize = .zero18    @State private var search = ""19    @State private var showList = true20    @Environment(\.accessibilityReduceMotion) private var reduceMotion2122    private var palette: MapPalette { MapPalette(rawValue: paletteName) ?? .orix }23    private var sizeKind: SizeKind { SizeKind(rawValue: sizeKindName) ?? .allocated }2425    var body: some View {26        if let tree = model.tree {27            VStack(spacing: 0) {28                header(tree)29                Divider()30                HSplitView {31                    map(tree).frame(minWidth: 420)32                    if showList { sideList(tree).frame(minWidth: 260, idealWidth: 320, maxWidth: 460) }33                }34                Divider()35                footer(tree)36            }37            .onChange(of: model.mapFocus) { resetView() }38        } else {39            EmptyState(symbol: "square.grid.3x3.square", title: L("No scan yet"),40                       message: L("Scan a folder or a volume to see where the space goes. Every block of the map is a real file or folder, sized by its measured size."),41                       actionTitle: L("Scan Home Folder")) { model.startScan(path: model.home) }42        }43    }4445    private func resetView() { zoom = 1; zoomBase = 1; offset = .zero; dragBase = .zero; hover = nil }4647    // MARK: Header (breadcrumb, search, controls)4849    private func header(_ tree: ScanTree) -> some View {50        HStack(spacing: ORIX.Space.s) {51            ScrollView(.horizontal, showsIndicators: false) {52                HStack(spacing: 2) {53                    ForEach(tree.ancestors(of: model.mapFocus) + [model.mapFocus], id: \.self) { i in54                        if i != 0 { Image(systemName: "chevron.right").font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true) }55                        Button(tree.displayName(of: i)) { withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { model.mapFocus = i } }56                            .buttonStyle(.plain).font(.callout.weight(i == model.mapFocus ? .semibold : .regular))57                            .foregroundStyle(i == model.mapFocus ? Color.primary : ORIX.Palette.textSecondary)58                            .padding(.horizontal, 4).padding(.vertical, 2)59                    }60                }61            }62            .accessibilityLabel(L("Location"))63            .frame(minWidth: 80)64            Spacer(minLength: 4)65            TextField(L("Search names"), text: $search).textFieldStyle(.roundedBorder).frame(minWidth: 110, idealWidth: 190, maxWidth: 190)66                .accessibilityIdentifier("map.search")67            Picker(L("Size"), selection: $sizeKindName) {68                Text(L("On disk")).tag(SizeKind.allocated.rawValue)69                Text(L("Content")).tag(SizeKind.logical.rawValue)70            }71            .pickerStyle(.segmented).labelsHidden().fixedSize()72            .help(L("On disk: blocks allocated. Content: length of the files."))73            Button { if model.mapFocus != 0, let t = model.tree { model.mapFocus = t[model.mapFocus].parent } } label: { Image(systemName: "arrow.up") }74                .disabled(model.mapFocus == 0).help(L("Enclosing folder")).keyboardShortcut(.upArrow, modifiers: .command)75                .accessibilityLabel(L("Enclosing folder"))76            Button { resetView() } label: { Image(systemName: "arrow.up.left.and.down.right.magnifyingglass") }77                .disabled(zoom == 1 && offset == .zero).help(L("Reset zoom")).accessibilityLabel(L("Reset zoom"))78            Toggle(isOn: $showList) { Image(systemName: "sidebar.right") }.toggleStyle(.button).help(L("Show the list")).accessibilityLabel(L("Show the list"))79        }80        .padding(.horizontal, ORIX.Space.m).padding(.vertical, ORIX.Space.s)81        .background(.bar)82    }8384    // MARK: Map8586    private func cells(_ tree: ScanTree, size: CGSize) -> [TreemapCell] {87        var o = TreemapOptions()88        o.sizeKind = sizeKind89        o.showPackageContents = showPackages90        o.visible = CGRect(origin: .zero, size: size)91        let virtual = CGRect(x: offset.width, y: offset.height, width: size.width * zoom, height: size.height * zoom)92        return Treemap.layout(tree: tree, root: model.mapFocus, in: virtual, options: o)93    }9495    private func map(_ tree: ScanTree) -> some View {96        GeometryReader { geo in97            let _ = model.treeVersion98            let size = geo.size99            let cells = cells(tree, size: size)100            let needle = search.lowercased()101            Canvas(opaque: true, rendersAsynchronously: false) { ctx, _ in102                ctx.fill(Path(CGRect(origin: .zero, size: size)), with: .color(ORIX.Palette.canvas))103                for cell in cells { draw(cell, tree: tree, in: &ctx, needle: needle) }104                if let h = hover {105                    ctx.stroke(Path(roundedRect: h.rect.insetBy(dx: 1, dy: 1), cornerRadius: 3), with: .color(.white), lineWidth: 2)106                    ctx.stroke(Path(roundedRect: h.rect.insetBy(dx: 2.5, dy: 2.5), cornerRadius: 2), with: .color(.black.opacity(0.55)), lineWidth: 1)107                }108                if let sel = model.mapSelection, let c = cells.first(where: { $0.node == sel && $0.aggregateCount == 0 }) {109                    ctx.stroke(Path(roundedRect: c.rect.insetBy(dx: 1.5, dy: 1.5), cornerRadius: 3), with: .color(ORIX.Palette.accent), style: StrokeStyle(lineWidth: 3, dash: [6, 3]))110                }111            }112            .contentShape(Rectangle())113            .onContinuousHover { phase in114                switch phase {115                case let .active(p): hover = hit(p, cells)116                case .ended: hover = nil117                }118            }119            .gesture(SpatialTapGesture(count: 2).onEnded { v in120                if let c = hit(v.location, cells), c.aggregateCount == 0 { open(c.node, tree) }121            })122            .simultaneousGesture(SpatialTapGesture().onEnded { v in123                if let c = hit(v.location, cells), c.aggregateCount == 0 { model.mapSelection = c.node } else { model.mapSelection = nil }124            })125            .gesture(MagnifyGesture().onChanged { v in126                let newZoom = min(12, max(1, zoomBase * v.magnification))127                let anchor = v.startLocation128                // Keep the point under the fingers fixed.129                let fx = (anchor.x - offset.width) / (size.width * zoom), fy = (anchor.y - offset.height) / (size.height * zoom)130                zoom = newZoom131                offset = clamp(CGSize(width: anchor.x - fx * size.width * zoom, height: anchor.y - fy * size.height * zoom), size)132            }.onEnded { _ in zoomBase = zoom; dragBase = offset })133            .simultaneousGesture(DragGesture(minimumDistance: 6).onChanged { v in134                guard zoom > 1 else { return }135                offset = clamp(CGSize(width: dragBase.width + v.translation.width, height: dragBase.height + v.translation.height), size)136            }.onEnded { _ in dragBase = offset })137            .contextMenu {138                if let sel = model.mapSelection ?? hover?.node, sel != 0 {139                    let path = tree.path(of: sel)140                    if tree[sel].flags.contains(.directory) { Button(L("Open in Map")) { open(sel, tree) } }141                    FileMenu(path: path)142                    Divider()143                    Button(model.isSelected(path) ? L("Remove from Cleanup Selection") : L("Add to Cleanup Selection")) {144                        if let item = model.item(forNode: sel) { model.toggle(item) }145                    }146                }147            }148            .accessibilityElement()149            .accessibilityLabel(L("Storage map of %@", tree.displayName(of: model.mapFocus)))150            .accessibilityValue(L("%d regions. Use the list next to the map to browse with VoiceOver.", cells.count))151            .accessibilityIdentifier("map.canvas")152        }153    }154155    private func clamp(_ o: CGSize, _ size: CGSize) -> CGSize {156        CGSize(width: min(0, max(size.width - size.width * zoom, o.width)), height: min(0, max(size.height - size.height * zoom, o.height)))157    }158159    private func open(_ node: Int32, _ tree: ScanTree) {160        var target = node161        if !tree[target].flags.contains(.directory) || tree[target].childCount == 0 { target = tree[target].parent }162        if target >= 0 { withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { model.mapFocus = target } }163    }164165    /// Deepest cell under the point. Cells are in parent-before-child order.166    private func hit(_ p: CGPoint, _ cells: [TreemapCell]) -> TreemapCell? {167        var best: TreemapCell?168        for c in cells where c.rect.contains(p) { if best == nil || c.depth >= best!.depth { best = c } }169        return best170    }171172    private func draw(_ cell: TreemapCell, tree: ScanTree, in ctx: inout GraphicsContext, needle: String) {173        let r = cell.rect174        guard r.width > 0.5, r.height > 0.5 else { return }175        let node = tree[cell.node]176        if !cell.isLeaf {177            // Folder frame with its name in the header strip.178            ctx.fill(Path(roundedRect: r, cornerRadius: 3), with: .color(ORIX.Palette.surfaceRaised.opacity(cell.depth % 2 == 0 ? 0.92 : 0.7)))179            ctx.stroke(Path(roundedRect: r.insetBy(dx: 0.5, dy: 0.5), cornerRadius: 3), with: .color(ORIX.Palette.hairline), lineWidth: 1)180            if r.height > 33, r.width > 46 {181                let text = Text(tree.name(of: cell.node)).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(Color.primary.opacity(0.8))182                let size = Text(ByteFormat.string(tree.size(of: cell.node, sizeKind))).font(.system(size: 9.5).monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)183                var clipped = ctx184                clipped.clip(to: Path(CGRect(x: r.minX + 4, y: r.minY, width: r.width - 8, height: 16)))185                let resolved = clipped.resolve(text)186                let w = resolved.measure(in: CGSize(width: 2000, height: 16)).width187                clipped.draw(resolved, at: CGPoint(x: r.minX + 5, y: r.minY + 8.5), anchor: .leading)188                if r.width > w + 80 { clipped.draw(size, at: CGPoint(x: r.maxX - 5, y: r.minY + 8.5), anchor: .trailing) }189            }190            return191        }192        var category: FileCategory = .other193        var isFolder = false194        if cell.aggregateCount > 0 {195            category = .other196        } else if node.flags.contains(.directory) {197            isFolder = true198            let ext = tree.fileExtension(of: cell.node)199            category = node.flags.contains(.package) ? (ext == "app" ? .application : FileCategory.of(extension: ext)) : .other200        } else {201            category = FileCategory.of(extension: tree.fileExtension(of: cell.node))202        }203        let base = palette.color(category)204        let shade = 1.0 - Double(min(cell.depth, 7)) * 0.035205        var color = Color(.sRGB, red: base.r * shade, green: base.g * shade, blue: base.b * shade, opacity: 1)206        if cell.aggregateCount > 0 { color = ORIX.Palette.textTertiary.opacity(0.45) }207        else if isFolder, !node.flags.contains(.package) { color = ORIX.Palette.accentSecondary.opacity(0.55) }208        let matches = !needle.isEmpty && cell.aggregateCount == 0 && tree.name(of: cell.node).lowercased().contains(needle)209        if !needle.isEmpty, !matches { color = color.opacity(0.22) }210        let inner = r.insetBy(dx: r.width > 4 ? 0.75 : 0, dy: r.height > 4 ? 0.75 : 0)211        let path = Path(roundedRect: inner, cornerRadius: min(3, inner.width / 4, inner.height / 4))212        ctx.fill(path, with: .color(color))213        if inner.width > 14, inner.height > 14 {214            // Soft top-left light for depth.215            ctx.fill(path, with: .linearGradient(Gradient(colors: [.white.opacity(0.18), .clear, .black.opacity(0.10)]),216                                                 startPoint: CGPoint(x: inner.minX, y: inner.minY), endPoint: CGPoint(x: inner.maxX, y: inner.maxY)))217        }218        if model.isSelected(cell.aggregateCount == 0 ? tree.path(of: cell.node) : "") {219            ctx.stroke(path, with: .color(.white), style: StrokeStyle(lineWidth: 2, dash: [4, 3]))220        }221        if inner.width > 54, inner.height > 26 {222            let name = cell.aggregateCount > 0 ? L("%d smaller items", cell.aggregateCount) : tree.name(of: cell.node)223            let bytes = cell.aggregateCount > 0 ? cell.aggregateSize : tree.size(of: cell.node, sizeKind)224            var clipped = ctx225            clipped.clip(to: Path(inner.insetBy(dx: 4, dy: 2)))226            let dark = palette == .colorblind && category == .application227            let fg: Color = dark ? .black.opacity(0.85) : .white228            clipped.draw(Text(name).font(.system(size: 10.5, weight: .medium)).foregroundStyle(fg), at: CGPoint(x: inner.minX + 5, y: inner.minY + 9), anchor: .leading)229            if inner.height > 38 {230                clipped.draw(Text(ByteFormat.string(bytes)).font(.system(size: 9.5).monospacedDigit()).foregroundStyle(fg.opacity(0.85)),231                             at: CGPoint(x: inner.minX + 5, y: inner.minY + 22), anchor: .leading)232            }233        }234    }235236    // MARK: Side list (accessible equivalent of the map)237238    private func sideList(_ tree: ScanTree) -> some View {239        let _ = model.treeVersion240        let needle = search.lowercased()241        let children: [Int32]242        if needle.isEmpty {243            children = tree.sortedChildren(of: model.mapFocus, by: sizeKind)244        } else {245            var f = FileFilter(); f.nameContains = needle; f.under = model.mapFocus; f.sizeKind = sizeKind; f.includePackageContents = showPackages246            children = TreeQuery.largestFiles(in: tree, filter: f, limit: 300).map(\.node)247        }248        let total = max(1, tree.size(of: model.mapFocus, sizeKind))249        return List(selection: Binding(get: { model.mapSelection }, set: { model.mapSelection = $0 })) {250            Section(needle.isEmpty ? L("%@ items in %@", ByteFormat.count(children.count), tree.displayName(of: model.mapFocus)) : L("%@ matches", ByteFormat.count(children.count))) {251                ForEach(children.prefix(600), id: \.self) { c in252                    let n = tree[c]253                    HStack(spacing: 8) {254                        Checkbox(isOn: model.isSelected(tree.path(of: c)), label: L("Select %@ for cleanup", tree.name(of: c))) {255                            if let item = model.item(forNode: c) { model.toggle(item) }256                        }257                        Image(systemName: n.flags.contains(.directory) ? (n.flags.contains(.package) ? "shippingbox" : "folder.fill") : "doc")258                            .foregroundStyle(n.flags.contains(.directory) ? ORIX.Palette.accentSecondary : ORIX.Palette.textSecondary).frame(width: 16).accessibilityHidden(true)259                        VStack(alignment: .leading, spacing: 2) {260                            Text(tree.name(of: c)).lineLimit(1).truncationMode(.middle)261                            ProportionBar(fraction: Double(tree.size(of: c, sizeKind)) / Double(total), height: 3)262                        }263                        Spacer(minLength: 4)264                        VStack(alignment: .trailing, spacing: 0) {265                            Text(ByteFormat.string(tree.size(of: c, sizeKind))).font(.callout.monospacedDigit())266                            if n.flags.contains(.unreadable) { Text(L("not readable")).font(.caption2).foregroundStyle(ORIX.Palette.review) }267                            else if n.flags.contains(.boundary) { Text(L("other volume")).font(.caption2).foregroundStyle(ORIX.Palette.textSecondary) }268                            else if n.flags.contains(.dataless) { Text(L("in iCloud")).font(.caption2).foregroundStyle(ORIX.Palette.textSecondary) }269                        }270                    }271                    .tag(c)272                    .contentShape(Rectangle())273                    .onTapGesture(count: 2) { open(c, tree) }274                    .contextMenu {275                        if n.flags.contains(.directory) { Button(L("Open in Map")) { open(c, tree) } }276                        FileMenu(path: tree.path(of: c))277                    }278                    .accessibilityElement(children: .combine)279                    .accessibilityAction(named: L("Open in Map")) { open(c, tree) }280                }281            }282        }283        .listStyle(.inset)284        .accessibilityIdentifier("map.list")285    }286287    // MARK: Footer (details of the hovered or selected region)288289    private func footer(_ tree: ScanTree) -> some View {290        let cell = hover291        let node = cell?.aggregateCount == 0 ? cell?.node : nil292        let shown = node ?? model.mapSelection293        return HStack(spacing: ORIX.Space.m) {294            if let cell, cell.aggregateCount > 0 {295                Text(L("%d smaller items in %@ · %@", cell.aggregateCount, tree.displayName(of: cell.node), ByteFormat.string(cell.aggregateSize))).font(.callout)296            } else if let i = shown {297                let n = tree[i]298                FileIcon(path: tree.path(of: i), size: 18)299                Text(tree.path(of: i).abbreviatingHome).font(.callout).lineLimit(1).truncationMode(.middle)300                Spacer()301                if n.flags.contains(.mayShareBlocks) { Label(L("may share blocks"), systemImage: "square.on.square.dashed").font(.caption).foregroundStyle(ORIX.Palette.textSecondary) }302                if n.flags.contains(.hardLinked) { Label(L("hard-linked"), systemImage: "link").font(.caption).foregroundStyle(ORIX.Palette.textSecondary) }303                if n.flags.contains(.sparse) { Label(L("sparse"), systemImage: "circle.dotted").font(.caption).foregroundStyle(ORIX.Palette.textSecondary) }304                if n.flags.contains(.directory) { Text(L("%@ files", ByteFormat.count(Int(n.fileCount)))).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary) }305                Text(L("%@ on disk · %@ content", ByteFormat.string(n.allocatedSize), ByteFormat.string(n.logicalSize))).font(.callout.monospacedDigit())306            } else {307                Text(L("Double-click a folder to open it. Pinch to zoom, drag to pan. Right-click for actions.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)308                Spacer()309                ForEach(FileCategory.allCases, id: \.self) { c in310                    HStack(spacing: 3) {311                        RoundedRectangle(cornerRadius: 2).fill(palette.swiftUIColor(c)).frame(width: 9, height: 9)312                        Text(c.title).font(.caption2).foregroundStyle(ORIX.Palette.textSecondary)313                    }314                }315            }316        }317        .padding(.horizontal, ORIX.Space.m).frame(height: 30)318        .background(.bar)319        .accessibilityIdentifier("map.footer")320    }321}322
Files main
Menu

Theme