Communitygithub.com

ComeOnOliver/skillshub

重构和审查 SwiftUI 视图文件,确保结构一致、依赖注入正确、并遵循 Observation 用法。当被要求清理 SwiftUI 视图的布局/顺序、安全处理视图模型(尽可能避免可选)、或标准化依赖项和 @Observable 状态的初始化与传递方式时使用。

skillshub 是什么?

该 AI 技能专注于重构和审查 SwiftUI 视图文件,以建立一致的结构、依赖注入和 Observation 使用模式。它提供了一套明确的指南,帮助开发者按照自上而下的顺序(环境、属性、状态、计算属性、初始化器、视图体、辅助函数)排列视图元素。技能强调采用模型-视图(MV)模式,主张视图应轻量且专注于状态表达,而业务逻辑应属于模型和服务。它指导如何安全地处理视图模型(尽量使其非可选),并通过 `init` 传递依赖。代码示例展示了如何拆分大型视图体、提取计算视图属性为子视图、以及为复杂部分创建专用的 `View` 结构体。该技能适用于任何需要人为参与的 SwiftUI 重构请求,支持通过 `@State`、`@Environment`、`@Query`、`task` 和 `onChange` 等进行轻量级编排,同时确保 Observation 使用正确,例如将根 `@Observable` 模型存储在 `@State` 中。当视图文件超过约 300 行时,它还提供了通过扩展和 `MARK` 注释进行组织的方法。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/dimillian/swiftui-view-refactor

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

SwiftUI 视图重构

概述

对 SwiftUI 视图应用一致的结构和依赖模式,重点关注顺序、模型-视图(MV)模式、谨慎的视图模型处理以及正确的 Observation 用法。

核心指南

1) 视图顺序(自上而下)

  • 环境
  • private/public let
  • @State / 其他存储属性
  • 计算型 var(非视图)
  • init
  • body
  • 计算型视图构建器 / 其他视图辅助方法
  • 辅助 / 异步函数

2) 优先使用 MV(模型-视图)模式

  • 默认采用 MV:视图是轻量级状态表达式;模型/服务拥有业务逻辑。
  • 推崇使用 @State、@Environment、@Query 以及 task/onChange 进行编排。
  • 通过 @Environment 注入服务和共享模型;保持视图小巧且可组合。
  • 将大型视图拆分为子视图,而不是引入视图模型。

3) 拆分大型 body 和视图属性

  • 如果 body 超过一屏长度或包含多个逻辑区块,将其拆分为更小的子视图。
  • 当大型计算视图属性(var header: some View { ... })携带状态或复杂分支时,将其提取为专用的 View 类型。
  • 将相关的子视图作为计算视图属性保留在同一文件中是可以的;仅在结构上有意义或为了复用时,才提取为独立的 View 结构体。
  • 优先传递小的输入(数据、绑定、回调),而不是复用整个父视图状态。

示例(提取一个区块):

var body: some View {
    VStack(alignment: .leading, spacing: 16) {
        HeaderSection(title: title, isPinned: isPinned)
        DetailsSection(details: details)
        ActionsSection(onSave: onSave, onCancel: onCancel)
    }
}

示例(长 body → 更短的 body + 同一文件内计算视图):

var body: some View {
    List {
        header
        filters
        results
        footer
    }
}

private var header: some View {
    VStack(alignment: .leading, spacing: 6) {
        Text(title).font(.title2)
        Text(subtitle).font(.subheadline)
    }
}

private var filters: some View {
    ScrollView(.horizontal, showsIndicators: false) {
        HStack {
            ForEach(filterOptions, id: \.self) { option in
                FilterChip(option: option, isSelected: option == selectedFilter)
                    .onTapGesture { selectedFilter = option }
            }
        }
    }
}

示例(提取复杂的计算视图):

private var header: some View {
    HeaderSection(title: title, subtitle: subtitle, status: status)
}

private struct HeaderSection: View {
    let title: String
    let subtitle: String?
    let status: Status

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(title).font(.headline)
            if let subtitle { Text(subtitle).font(.subheadline) }
            StatusBadge(status: status)
        }
    }
}

4) 视图模型处理(仅在已存在的情况下)

  • 除非请求或现有代码明确要求,否则不要引入视图模型。
  • 如果视图模型已存在,尽可能使其非可选。
  • 通过 init 将依赖项传递给视图,然后在视图的 init 中将其传递给视图模型。
  • 避免使用 bootstrapIfNeeded 模式。

示例(基于 Observation):

@State private var viewModel: SomeViewModel

init(dependency: Dependency) {
    _viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}

5) Observation 用法

  • 对于 @Observable 引用类型,将其作为 @State 存储在根视图中。
  • 根据需要显式传递可观测对象;除非必要,否则避免使用可选状态。

工作流程

  1. 按照排序规则重新排列视图。
  2. 优先使用 MV:使用 @State、@Environment、@Query、task 和 onChange 将轻量级编排移入视图。
  3. 如果存在视图模型,用非可选的 @State 视图模型替换可选的视图模型,并在 init 中通过传递来自视图的依赖项进行初始化。
  4. 确认 Observation 的使用:根 @Observable 视图模型使用 @State,没有冗余的包装器。
  5. 保持行为不变:除非被要求,否则不要更改布局或业务逻辑。

说明

  • 优先使用小而明确的辅助方法,而非大型条件语句块。
  • 将计算视图构建器放在 body 下方,将非视图的计算变量放在 init 上方。
  • 有关 MV 优先的指南和原理,请参阅 references/mv-patterns.md。

大型视图处理

  • 当 SwiftUI 视图文件超过约 300 行时,使用扩展来分组相关的辅助方法。将异步函数和辅助函数移动到专用的 private 扩展中,并用 // MARK: - 注释描述其用途(例如 // MARK: - Actions、// MARK: - Subviews、// MARK: - Helpers)。保持主 struct 专注于存储属性、init 和 body,当文件较长时,视图构建的计算变量也通过标记进行分组。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能