Skip to content

buidangminh23/design-pro-max / skills/apple/.vendor/swiftui-expert-skill

swiftui-expert-skill

Verified

Use when writing, reviewing, or refactoring SwiftUI code for iOS or macOS, including state and `@Observable` data flow, view composition, resizable layouts, safe areas, display scale, performance, lists, environment, localization, animation, Liquid Glass, and API migration. Also use for iPhone Duo, foldable, or large-display layouts (`NavigationSplitView` on large displays, iPhone tab sidebar, two-column reflow, foldable grids, `ArrangementView`, `ReservedRegion`), hinge effects, vertical bars, `@State` initialization or synthesized-property diagnostics, `@ContentBuilder` ambiguity, `reorderable` drag/drop, custom `AsyncImage` `URLSession`, swipe actions outside List, item-bound `alert`/`confirmationDialog`, `ToolbarOverflowMenu`, `AnimatableValues`, Document APIs (`Document`/`DocumentReader`), and Instruments `.trace` capture or analysis.

FileKindSize
LICENSEother1.1 KB
SKILL.mdskill md11.4 KB
UPSTREAM.jsonconfig12.1 KB
references/accessibility-patterns.mdmarkdown5.9 KB
references/animation-advanced.mdmarkdown11.2 KB
references/animation-basics.mdmarkdown6.7 KB
references/animation-transitions.mdmarkdown7.9 KB
references/charts-accessibility.mdmarkdown6.1 KB
references/charts.mdmarkdown16.8 KB
references/document-apps.mdmarkdown11.1 KB
references/environment-patterns.mdmarkdown7.1 KB
references/focus-patterns.mdmarkdown8.7 KB
references/image-optimization.mdmarkdown10.4 KB
references/iphone-duo.mdmarkdown7.4 KB
references/latest-apis.mdmarkdown24.8 KB
references/layout-best-practices.mdmarkdown20.6 KB
references/liquid-glass.mdmarkdown12.4 KB
references/list-patterns.mdmarkdown20.5 KB
references/localization.mdmarkdown9.7 KB
references/macos-scenes.mdmarkdown9.5 KB
references/macos-views.mdmarkdown10.8 KB
references/macos-window-styling.mdmarkdown8.6 KB
references/modifier-patterns.mdmarkdown2.5 KB
references/performance-patterns.mdmarkdown11.7 KB
references/previews.mdmarkdown8.1 KB
references/scroll-patterns.mdmarkdown10.6 KB
references/sheet-navigation-patterns.mdmarkdown15.0 KB
references/soft-deprecation.mdmarkdown2.9 KB
references/state-management.mdmarkdown21.5 KB
references/styled-text-editing.mdmarkdown8.7 KB
references/text-patterns.mdmarkdown1.6 KB
references/toolbar-patterns.mdmarkdown9.9 KB
references/trace-analysis.mdmarkdown14.1 KB
references/trace-recording.mdmarkdown5.8 KB
references/view-structure.mdmarkdown28.3 KB
references/webkit-integration.mdmarkdown9.5 KB
scripts/analyze_trace.pyscript9.9 KB
scripts/instruments_parser/__init__.pyscript69 B
scripts/instruments_parser/causes.pyscript5.9 KB
scripts/instruments_parser/correlate.pyscript6.2 KB
scripts/instruments_parser/events.pyscript10.6 KB
scripts/instruments_parser/hangs.pyscript3.4 KB
scripts/instruments_parser/hitches.pyscript4.5 KB
scripts/instruments_parser/summary.pyscript9.1 KB
scripts/instruments_parser/swiftui.pyscript6.6 KB
scripts/instruments_parser/time_profiler.pyscript4.3 KB
scripts/instruments_parser/xctrace.pyscript3.5 KB
scripts/instruments_parser/xml_utils.pyscript7.4 KB
scripts/record_trace.pyscript10.6 KB

scripts/instruments_parser/causes.py

View on GitHub
"""SwiftUI cause-graph lane (`swiftui-causes` schema).

Instruments emits one row per edge in SwiftUI's dependency graph: every time
a source node (a state change, user defaults observer, system event, etc.)
propagates to a destination node (a body evaluation, layout, creation), a
row is written with both endpoints as metadata values.

This lane aggregates those edges two ways:

- **By source node** — which attribute graph nodes are driving the most
  updates overall. The canonical "why is my app thrashing?" view; a
  `UserDefaultObserver.send()` showing up with 11k outgoing edges is a
  feedback storm.
- **By destination node** — which views/modifiers receive the most
  invalidations, and from whom. Use this to trace a hot view back to the
  source that keeps poking it.

The analyzer's main lane (`swiftui`) tells you *what* updates are
expensive; this lane tells you *why* they keep happening.
"""
from __future__ import annotations

from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

from . import xctrace, xml_utils

SCHEMA = "swiftui-causes"

# Metadata nodes render as space-separated field dumps ("A gray icon n/a n/a").
# We aggregate on the full fmt string so callers can spot specific edges like
# "@AppStorage TextStyleModifier.fontOption", but also expose the short head
# ("@AppStorage", "Creation of App", ...) for coarser grouping.


def analyze(
    trace_path: Path,
    toc_schemas: frozenset[str],
    top_n: int = 10,
    top_k_per_node: int = 5,
    window: tuple[int, int] | None = None,
    run: int = 1,
) -> dict[str, Any]:
    if SCHEMA not in toc_schemas:
        return {
            "lane": "swiftui-causes",
            "available": False,
            "notes": [
                "SwiftUI causes data not present (requires SwiftUI template on a real device).",
            ],
        }

    xml_bytes = xctrace.export_schema(trace_path, SCHEMA, run=run)
    stream = xml_utils.RowStream(xml_bytes)

    source_edges: Counter[str] = Counter()
    destination_edges: Counter[str] = Counter()
    fanout: dict[str, Counter[str]] = defaultdict(Counter)
    fanin: dict[str, Counter[str]] = defaultdict(Counter)
    label_counts: Counter[str] = Counter()
    total_edges = 0

    for row in stream:
        time_el = xml_utils.first_present(row, "timestamp", "time")
        if time_el is not None:
            t_ns = xml_utils.int_text(stream.resolve(time_el))
            if t_ns is not None and not xml_utils.in_window(t_ns, window):
                continue

        src = _fmt(row, stream, "source-node")
        dst = _fmt(row, stream, "destination-node")
        if not src or not dst:
            continue

        source_edges[src] += 1
        destination_edges[dst] += 1
        fanout[src][dst] += 1
        fanin[dst][src] += 1

        label = _fmt(row, stream, "label")
        if label:
            label_counts[label] += 1

        total_edges += 1

    top_sources = [
        {
            "source": src,
            "edges": count,
            "top_destinations": [
                {"destination": d, "edges": c}
                for d, c in fanout[src].most_common(top_k_per_node)
            ],
        }
        for src, count in source_edges.most_common(top_n)
    ]

    top_destinations = [
        {
            "destination": dst,
            "edges": count,
            "top_sources": [
                {"source": s, "edges": c}
                for s, c in fanin[dst].most_common(top_k_per_node)
            ],
        }
        for dst, count in destination_edges.most_common(top_n)
    ]

    return {
        "lane": "swiftui-causes",
        "available": True,
        "schema_used": SCHEMA,
        "metrics": {
            "total_edges": total_edges,
            "unique_sources": len(source_edges),
            "unique_destinations": len(destination_edges),
            "top_labels": dict(label_counts.most_common(top_n)),
        },
        "top_sources": top_sources,
        "top_destinations": top_destinations,
        "notes": [],
    }


def fanin_for(
    trace_path: Path,
    toc_schemas: frozenset[str],
    destination_contains: str,
    top_k: int = 10,
    window: tuple[int, int] | None = None,
    run: int = 1,
) -> dict[str, Any]:
    """Return the top source nodes feeding any destination whose fmt string
    contains `destination_contains` (case-insensitive substring).

    Used when the agent has a suspect view from the `swiftui` lane and wants
    to know *who keeps invalidating it*. Does a full pass over the causes
    schema each time — cheap enough at typical trace sizes.
    """
    if SCHEMA not in toc_schemas:
        return {"available": False, "matches": []}

    needle = destination_contains.lower()
    xml_bytes = xctrace.export_schema(trace_path, SCHEMA, run=run)
    stream = xml_utils.RowStream(xml_bytes)

    matches: dict[str, Counter[str]] = defaultdict(Counter)
    totals: Counter[str] = Counter()

    for row in stream:
        time_el = xml_utils.first_present(row, "timestamp", "time")
        if time_el is not None:
            t_ns = xml_utils.int_text(stream.resolve(time_el))
            if t_ns is not None and not xml_utils.in_window(t_ns, window):
                continue

        dst = _fmt(row, stream, "destination-node")
        if not dst or needle not in dst.lower():
            continue
        src = _fmt(row, stream, "source-node")
        if not src:
            continue

        matches[dst][src] += 1
        totals[dst] += 1

    out = []
    for dst, count in totals.most_common(top_k):
        out.append({
            "destination": dst,
            "total_incoming_edges": count,
            "top_sources": [
                {"source": s, "edges": c}
                for s, c in matches[dst].most_common(top_k)
            ],
        })
    return {"available": True, "matches": out}


def _fmt(row, stream, key: str) -> str | None:
    el = row.get(key)
    if el is None:
        return None
    resolved = stream.resolve(el)
    return resolved.get("fmt") or xml_utils.str_text(resolved)
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall