Silence render-disposed spam, unbreak bundled skills, drop board wake

Three independently ugly bugs that all fed the same log flood:

* Electron's `WebFrameMain.send` writes every "Render frame was disposed"
  to stderr via `console.error`. When the worker fans a second
  agent-event past a reloading renderer, we produced thousands of
  identical lines and stalled the main loop on stderr I/O. Added a
  `mainFrame.detached` guard so the send is short-circuited before
  Electron's own catch block fires, and installed a targeted filter in
  `suppress-warnings.ts` (now actually imported from the entry point)
  so the specific `console.error("Error sending from webFrameMain:"…)`
  noise never reaches the terminal. Any other payload still surfaces.

* `dispatchAgentMessage` accepted the human-reader sentinel as a wake
  target when an agent replied to `__board__` — `wakeAgentIfPossible`
  then called `db.getAgent("__board__")`, threw, and the dispatcher
  kept repeating on every send. Strip `HUMAN_SENDER_ID` at
  `resolveMessageWakeTargets`, and keep a defense-in-depth guard in the
  heartbeat so a stray caller (future automation fan-out) cannot
  reintroduce the crash.

* Pi's skills loader rejects any SKILL.md whose frontmatter `name`
  diverges from its parent directory. The four bundled `my-writing-style`
  copies declared `name: writing-style-skill`, so every install emitted
  a warning and dropped the skill. They also lived as orphan gitlinks
  (mode 160000 without .gitmodules), and the global `*.md` gitignore
  hid every other SKILL.md from version control. Fixed the frontmatter
  to match the dir, converted the dangling submodules to plain trees,
  and allowlisted `builtin-skills/**/*.md` so a fresh clone carries the
  catalogue instead of silently losing it.
This commit is contained in:
ZacharyZhang-NY committed 2026-04-20 08:13:48 -04:00
1 parent 7a9a6779b0
commit e74dafcd36
287 files changed
+59858 -10

No files matched your search

@@ -0,0 +1,526 @@
---
name: app-icon-generator
description: Generates app icons in all required sizes for iOS, Android, and PWA from a single source image. Use when user asks to "generate app icons", "create ios icons", "android app icons", "favicon", or "pwa icons".
allowed-tools: [Read, Write, Bash, Glob]
---
# App Icon Generator
Generates app icons in all required sizes for iOS, Android, PWA, and web from a single source image.
## When to Use
- "Generate app icons for iOS"
- "Create Android app icons"
- "Generate all icon sizes"
- "Create favicon"
- "PWA icons"
- "App icon set"
## Instructions
### 1. Verify Source Image
Check for source icon file:
```bash
# Look for icon source
find . -name "*icon*.png" -o -name "*logo*.png"
```
**Source image requirements:**
- Minimum 1024x1024 pixels (recommended)
- Square (1:1 aspect ratio)
- PNG format with transparency (if needed)
- High quality, not compressed
- No text too close to edges (safe area: center 70%)
Present findings and ask for source if not found.
### 2. Check for Image Processing Tools
Verify available tools:
```bash
# Check for ImageMagick
which convert || echo "ImageMagick not found"
# Check for sharp-cli
which sharp || echo "sharp-cli not found"
# Check for sips (macOS)
which sips || echo "sips not found (macOS only)"
```
**Installation guide if needed:**
```bash
# macOS
brew install imagemagick
# Ubuntu/Debian
sudo apt-get install imagemagick
# Node.js (cross-platform, recommended)
npm install -g sharp-cli
```
### 3. Generate iOS Icons
**iOS requires multiple sizes:**
```bash
# iOS App Icons (all required sizes)
declare -a ios_sizes=(
"20" # iPhone Notification (2x, 3x)
"29" # iPhone Settings (2x, 3x)
"40" # iPhone Spotlight (2x, 3x)
"60" # iPhone App (2x, 3x)
"76" # iPad App (1x, 2x)
"83.5" # iPad Pro App (2x)
"1024" # App Store
)
# Generate using ImageMagick
for size in "${ios_sizes[@]}"; do
convert icon-source.png -resize ${size}x${size} "ios/icon-${size}.png"
# Generate 2x
size2x=$((size * 2))
convert icon-source.png -resize ${size2x}x${size2x} "ios/icon-${size}@2x.png"
# Generate 3x (for relevant sizes)
if [[ $size -eq 20 || $size -eq 29 || $size -eq 40 || $size -eq 60 ]]; then
size3x=$((size * 3))
convert icon-source.png -resize ${size3x}x${size3x} "ios/icon-${size}@3x.png"
fi
done
```
**Or using sharp-cli:**
```bash
# Generate all iOS sizes
sharp -i icon-source.png -o ios/icon-{size}.png \
resize 20 40 60 58 80 87 120 180 76 152 167 1024
```
**Contents.json for Xcode:**
```json
{
"images": [
{
"size": "20x20",
"idiom": "iphone",
"filename": "icon-40.png",
"scale": "2x"
},
{
"size": "20x20",
"idiom": "iphone",
"filename": "icon-60.png",
"scale": "3x"
},
{
"size": "29x29",
"idiom": "iphone",
"filename": "icon-58.png",
"scale": "2x"
},
{
"size": "29x29",
"idiom": "iphone",
"filename": "icon-87.png",
"scale": "3x"
},
{
"size": "40x40",
"idiom": "iphone",
"filename": "icon-80.png",
"scale": "2x"
},
{
"size": "40x40",
"idiom": "iphone",
"filename": "icon-120.png",
"scale": "3x"
},
{
"size": "60x60",
"idiom": "iphone",
"filename": "icon-120.png",
"scale": "2x"
},
{
"size": "60x60",
"idiom": "iphone",
"filename": "icon-180.png",
"scale": "3x"
},
{
"size": "1024x1024",
"idiom": "ios-marketing",
"filename": "icon-1024.png",
"scale": "1x"
}
],
"info": {
"version": 1,
"author": "xcode"
}
}
```
### 4. Generate Android Icons
**Android adaptive icons:**
Android uses adaptive icons with separate foreground and background layers.
```bash
# Android icon sizes (in dp)
# mdpi = 1x, hdpi = 1.5x, xhdpi = 2x, xxhdpi = 3x, xxxhdpi = 4x
# mipmap-mdpi (48x48)
convert icon-source.png -resize 48x48 android/mipmap-mdpi/ic_launcher.png
# mipmap-hdpi (72x72)
convert icon-source.png -resize 72x72 android/mipmap-hdpi/ic_launcher.png
# mipmap-xhdpi (96x96)
convert icon-source.png -resize 96x96 android/mipmap-xhdpi/ic_launcher.png
# mipmap-xxhdpi (144x144)
convert icon-source.png -resize 144x144 android/mipmap-xxhdpi/ic_launcher.png
# mipmap-xxxhdpi (192x192)
convert icon-source.png -resize 192x192 android/mipmap-xxxhdpi/ic_launcher.png
# Play Store (512x512)
convert icon-source.png -resize 512x512 android/playstore-icon.png
```
**Adaptive icon XML:**
```xml
<!-- res/mipmap-anydpi-v26/ic_launcher.xml -->
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
```
**Round icon variant:**
```bash
# Generate round icons (same sizes)
for size in 48 72 96 144 192; do
density=$(get_density $size) # mdpi, hdpi, etc.
convert icon-source.png -resize ${size}x${size} \
\( +clone -threshold -1 -negate -fill white -draw "circle $((size/2)),$((size/2)) $((size/2)),0" \) \
-alpha off -compose copy_opacity -composite \
"android/mipmap-${density}/ic_launcher_round.png"
done
```
### 5. Generate PWA Icons
**Progressive Web App icons:**
```bash
# PWA icon sizes
sharp -i icon-source.png -o pwa/icon-{size}.png \
resize 72 96 128 144 152 192 384 512
# Also generate maskable icons (with safe area)
# Maskable icons need 40% safe area
sharp -i icon-source.png -o pwa/icon-{size}-maskable.png \
resize 72 96 128 144 152 192 384 512 \
--extend top=10 bottom=10 left=10 right=10
```
**manifest.json:**
```json
{
"name": "My App",
"short_name": "App",
"icons": [
{
"src": "/icons/icon-72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "/icons/icon-96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "/icons/icon-128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "/icons/icon-144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "/icons/icon-152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "/icons/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icons/icon-384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "/icons/icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/icons/icon-192-maskable.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/icons/icon-512-maskable.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
```
### 6. Generate Favicons
**Web favicons (multiple sizes):**
```bash
# Standard sizes
convert icon-source.png -resize 16x16 favicon-16.png
convert icon-source.png -resize 32x32 favicon-32.png
convert icon-source.png -resize 48x48 favicon-48.png
# Create multi-size .ico file
convert favicon-16.png favicon-32.png favicon-48.png favicon.ico
# Apple touch icon
convert icon-source.png -resize 180x180 apple-touch-icon.png
# Microsoft tile
convert icon-source.png -resize 144x144 mstile-144.png
```
**HTML head tags:**
```html
<!-- Favicons -->
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="48x48" href="/favicon-48.png">
<link rel="shortcut icon" href="/favicon.ico">
<!-- Apple touch icon -->
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<!-- Android -->
<link rel="icon" type="image/png" sizes="192x192" href="/android-chrome-192.png">
<link rel="icon" type="image/png" sizes="512x512" href="/android-chrome-512.png">
<!-- Microsoft -->
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/mstile-144.png">
```
### 7. Generate React Native Icons
**For React Native apps:**
```bash
# iOS (place in ios/AppName/Images.xcassets/AppIcon.appiconset/)
# Same as iOS native above
# Android (place in android/app/src/main/res/)
# Same as Android native above
```
**Or use react-native-make:**
```bash
npx react-native set-icon --path icon-source.png
```
### 8. Generate Flutter Icons
**Using flutter_launcher_icons:**
```yaml
# pubspec.yaml
dev_dependencies:
flutter_launcher_icons: ^0.13.1
flutter_launcher_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon.png"
adaptive_icon_background: "#ffffff"
adaptive_icon_foreground: "assets/icon-foreground.png"
```
```bash
# Generate icons
flutter pub get
flutter pub run flutter_launcher_icons
```
### 9. Create Automated Script
**Complete icon generation script:**
```bash
#!/bin/bash
# generate-icons.sh
SOURCE_ICON="icon-source.png"
OUTPUT_DIR="generated-icons"
# Check if source exists
if [ ! -f "$SOURCE_ICON" ]; then
echo "Error: Source icon not found: $SOURCE_ICON"
exit 1
fi
# Create directories
mkdir -p "$OUTPUT_DIR"/{ios,android,pwa,web}
echo "🎨 Generating app icons..."
# iOS icons
echo "📱 iOS icons..."
for size in 40 60 58 87 80 120 180 76 152 167 1024; do
convert "$SOURCE_ICON" -resize ${size}x${size} \
"$OUTPUT_DIR/ios/icon-${size}.png"
echo " ✓ ${size}x${size}"
done
# Android icons
echo "🤖 Android icons..."
convert "$SOURCE_ICON" -resize 48x48 "$OUTPUT_DIR/android/mdpi.png"
convert "$SOURCE_ICON" -resize 72x72 "$OUTPUT_DIR/android/hdpi.png"
convert "$SOURCE_ICON" -resize 96x96 "$OUTPUT_DIR/android/xhdpi.png"
convert "$SOURCE_ICON" -resize 144x144 "$OUTPUT_DIR/android/xxhdpi.png"
convert "$SOURCE_ICON" -resize 192x192 "$OUTPUT_DIR/android/xxxhdpi.png"
convert "$SOURCE_ICON" -resize 512x512 "$OUTPUT_DIR/android/playstore.png"
echo " ✓ All densities generated"
# PWA icons
echo "🌐 PWA icons..."
for size in 72 96 128 144 152 192 384 512; do
convert "$SOURCE_ICON" -resize ${size}x${size} \
"$OUTPUT_DIR/pwa/icon-${size}.png"
echo " ✓ ${size}x${size}"
done
# Favicons
echo "🔖 Favicons..."
convert "$SOURCE_ICON" -resize 16x16 "$OUTPUT_DIR/web/favicon-16.png"
convert "$SOURCE_ICON" -resize 32x32 "$OUTPUT_DIR/web/favicon-32.png"
convert "$SOURCE_ICON" -resize 48x48 "$OUTPUT_DIR/web/favicon-48.png"
convert "$OUTPUT_DIR/web/favicon-"{16,32,48}.png "$OUTPUT_DIR/web/favicon.ico"
convert "$SOURCE_ICON" -resize 180x180 "$OUTPUT_DIR/web/apple-touch-icon.png"
echo " ✓ All favicons generated"
echo "✅ Icon generation complete!"
echo "📁 Icons saved to: $OUTPUT_DIR"
```
### 10. Provide Integration Instructions
**iOS (Xcode):**
1. Open Xcode project
2. Navigate to Assets.xcassets
3. Right-click → New App Icon
4. Drag generated icons to appropriate slots
**Android (Android Studio):**
1. Right-click res folder
2. New → Image Asset
3. Select generated icons
4. Configure adaptive icon layers
**Web:**
1. Copy icons to public/icons/ folder
2. Update manifest.json with icon paths
3. Add favicon links to index.html
**React Native:**
1. Copy iOS icons to `ios/AppName/Images.xcassets/AppIcon.appiconset/`
2. Copy Android icons to `android/app/src/main/res/mipmap-*/`
3. Update Contents.json for iOS
### Best Practices
**Design Guidelines:**
- Keep important content in center 80%
- Avoid thin lines (minimum 2px)
- Test on dark and light backgrounds
- Use simple, recognizable shapes
- Avoid text (too small on icons)
- Use bold colors for visibility
**Technical Guidelines:**
- Source: 1024x1024 minimum
- Format: PNG with transparency
- Color space: sRGB
- No compression on source
- Square aspect ratio
- Safe area for maskable: 40% padding
**Testing:**
- Test on actual devices
- Check all sizes render correctly
- Verify transparency works
- Test dark mode appearance
- Check adaptive icon animations (Android)
### Size Reference
**iOS:**
- 20pt (40x40, 60x60)
- 29pt (58x58, 87x87)
- 40pt (80x80, 120x120)
- 60pt (120x120, 180x180)
- 76pt (76x76, 152x152)
- 83.5pt (167x167)
- 1024x1024 (App Store)
**Android:**
- mdpi: 48x48
- hdpi: 72x72
- xhdpi: 96x96
- xxhdpi: 144x144
- xxxhdpi: 192x192
- Play Store: 512x512
**PWA:**
- 72x72, 96x96, 128x128
- 144x144, 152x152, 192x192
- 384x384, 512x512
**Web:**
- 16x16, 32x32 (favicon)
- 180x180 (Apple touch)
- 192x192, 512x512 (Android)
@@ -0,0 +1,647 @@
---
name: app-store-screenshots
description: Use when building App Store screenshot pages, generating exportable marketing screenshots for iOS apps, or creating programmatic screenshot generators with Next.js. Triggers on app store, screenshots, marketing assets, html-to-image, phone mockup.
---
# App Store Screenshots Generator
## Overview
Build a Next.js page that renders iOS App Store screenshots as **advertisements** (not UI showcases) and exports them via `html-to-image` at Apple's required resolutions. Screenshots are the single most important conversion asset on the App Store.
## Core Principle
**Screenshots are advertisements, not documentation.** Every screenshot sells one idea. If you're showing UI, you're doing it wrong — you're selling a *feeling*, an *outcome*, or killing a *pain point*.
## Step 1: Ask the User These Questions
Before writing ANY code, ask the user all of these. Do not proceed until you have answers:
### Required
1. **App screenshots** — "Where are your app screenshots? (PNG files of actual device captures)"
2. **App icon** — "Where is your app icon PNG?"
3. **Brand colors** — "What are your brand colors? (accent color, text color, background preference)"
4. **Font** — "What font does your app use? (or what font do you want for the screenshots?)"
5. **Feature list** — "List your app's features in priority order. What's the #1 thing your app does?"
6. **Number of slides** — "How many screenshots do you want? (Apple allows up to 10)"
7. **Style direction** — "What style do you want? Examples: warm/organic, dark/moody, clean/minimal, bold/colorful, gradient-heavy, flat. Share App Store screenshot references if you have any."
### Optional
8. **iPad screenshots** — "Do you also have iPad screenshots? If so, we'll generate iPad App Store screenshots too (recommended for universal apps)."
9. **Component assets** — "Do you have any UI element PNGs (cards, widgets, etc.) you want as floating decorations? If not, that's fine — we'll skip them."
10. **Localized screenshots** — "Do you want screenshots in multiple languages? This helps your listing rank in regional App Stores even if your app is English-only. If yes: which languages? (e.g. en, de, es, pt, ja, ar, he)"
11. **Theme preset system** — "Do you want one art direction, or reusable visual themes (for example: clean-light, dark-bold, warm-editorial) so you can swap screenshot looks quickly?"
12. **Additional instructions** — "Any specific requirements, constraints, or preferences?"
### Derived from answers (do NOT ask — decide yourself)
Based on the user's style direction, brand colors, and app aesthetic, decide:
- **Background style**: gradient direction, colors, whether light or dark base
- **Decorative elements**: blobs, glows, geometric shapes, or none — match the style
- **Dark vs light slides**: how many of each, which features suit dark treatment
- **Typography treatment**: weight, tracking, line height — match the brand personality
- **Color palette**: derive text colors, secondary colors, shadow tints from the brand colors
- **Theme preset names**: turn vague style requests into reusable theme ids the user can switch between
- **RTL behavior**: if any locale is RTL (`ar`, `he`, `fa`, `ur`), mirror layout intentionally instead of just translating the text
**IMPORTANT:** If the user gives additional instructions at any point during the process, follow them. User instructions always override skill defaults.
## Step 2: Set Up the Project
### Detect Package Manager
Check what's available, use this priority: **bun > pnpm > yarn > npm**
```bash
# Check in order
which bun && echo "use bun" || which pnpm && echo "use pnpm" || which yarn && echo "use yarn" || echo "use npm"
```
### Scaffold (if no existing Next.js project)
```bash
# With bun:
bunx create-next-app@latest . --typescript --tailwind --app --src-dir --no-eslint --import-alias "@/*"
bun add html-to-image
# With pnpm:
pnpx create-next-app@latest . --typescript --tailwind --app --src-dir --no-eslint --import-alias "@/*"
pnpm add html-to-image
# With yarn:
yarn create next-app . --typescript --tailwind --app --src-dir --no-eslint --import-alias "@/*"
yarn add html-to-image
# With npm:
npx create-next-app@latest . --typescript --tailwind --app --src-dir --no-eslint --import-alias "@/*"
npm install html-to-image
```
### Copy the Phone Mockup
The skill includes a pre-measured iPhone mockup at `mockup.png` (co-located with this SKILL.md). Copy it to the project's `public/` directory. The mockup file is in the same directory as this skill file. No iPad mockup is needed — the iPad frame is CSS-only.
### File Structure
```
project/
├── public/
│ ├── mockup.png # iPhone frame (included with skill)
│ ├── app-icon.png # User's app icon
│ ├── screenshots/ # iPhone app screenshots
│ │ ├── home.png
│ │ ├── feature-1.png
│ │ └── ...
│ └── screenshots-ipad/ # iPad app screenshots (optional)
│ ├── home.png
│ ├── feature-1.png
│ └── ...
├── src/app/
│ ├── layout.tsx # Font setup
│ └── page.tsx # The screenshot generator (single file)
└── package.json
```
**Note:** No iPad mockup PNG is needed — the iPad frame is rendered with CSS (see iPad Mockup Component below).
**Multi-language:** nest screenshots under a locale folder per language. The generator switches the `base` path; all slide image srcs stay identical.
```
└── screenshots/
├── en/
│ ├── home.png
│ ├── feature-1.png
│ └── ...
├── de/
│ └── ...
└── {locale}/
```
If iPad screenshots are localized too, mirror the same locale structure:
```
└── screenshots-ipad/
├── en/
├── de/
└── {locale}/
```
**The entire generator is a single `page.tsx` file.** No routing, no extra layouts, no API routes.
### Multi-language: Locale Tabs
Add a `LOCALES` array and locale tabs to the toolbar. Every slide src uses `base` — no hardcoded paths:
```tsx
const LOCALES = ["en", "de", "es"] as const; // use whatever langs were defined
type Locale = typeof LOCALES[number];
// In ScreenshotsPage:
const [locale, setLocale] = useState<Locale>("en");
const base = `/screenshots/${locale}`;
// Toolbar tabs:
{LOCALES.map(l => (
<button key={l} onClick={() => setLocale(l)}
style={{ fontWeight: locale === l ? 700 : 400 }}>
{l.toUpperCase()}
</button>
))}
// In every slide — unchanged between single and multi-language:
<Phone src={`${base}/home.png`} alt="Home" />
```
### Theme Presets + Locale Metadata
Add a small config layer so the user can switch theme and locale without rewriting slide components:
```tsx
const LOCALES = ["en", "de", "ar"] as const;
type Locale = typeof LOCALES[number];
const RTL_LOCALES = new Set<Locale>(["ar"]);
const THEMES = {
"clean-light": {
bg: "#F6F1EA",
fg: "#171717",
accent: "#5B7CFA",
muted: "#6B7280",
},
"dark-bold": {
bg: "#0B1020",
fg: "#F8FAFC",
accent: "#8B5CF6",
muted: "#94A3B8",
},
"warm-editorial": {
bg: "#F7E8DA",
fg: "#2B1D17",
accent: "#D97706",
muted: "#7C5A47",
},
} as const;
type ThemeId = keyof typeof THEMES;
const COPY_BY_LOCALE = {
en: { hero: "Build better habits" },
de: { hero: "Baue bessere Gewohnheiten auf" },
ar: { hero: "ابنِ عادات أفضل" },
} satisfies Record<Locale, { hero: string }>;
const [themeId, setThemeId] = useState<ThemeId>("clean-light");
const [locale, setLocale] = useState<Locale>("en");
const theme = THEMES[themeId];
const copy = COPY_BY_LOCALE[locale];
const isRtl = RTL_LOCALES.has(locale);
```
Use theme tokens everywhere instead of hardcoding colors. For RTL locales, set `dir={isRtl ? "rtl" : "ltr"}` on the screenshot canvas and mirror asymmetric layouts intentionally.
Support query params for automation:
```tsx
// ?locale=de&theme=dark-bold&device=ipad
```
### Font Setup
```tsx
// src/app/layout.tsx
import { YourFont } from "next/font/google"; // Use whatever font the user specified
const font = YourFont({ subsets: ["latin"] });
export default function Layout({ children }: { children: React.ReactNode }) {
return <html><body className={font.className}>{children}</body></html>;
}
```
## Step 3: Plan the Slides
### Screenshot Framework (Narrative Arc)
Adapt this framework to the user's requested slide count. Not all slots are required — pick what fits:
| Slot | Purpose | Notes |
|------|---------|-------|
| #1 | **Hero / Main Benefit** | App icon + tagline + home screen. This is the ONLY one most people see. |
| #2 | **Differentiator** | What makes this app unique vs competitors |
| #3 | **Ecosystem** | Widgets, extensions, watch — beyond the main app. Skip if N/A. |
| #4+ | **Core Features** | One feature per slide, most important first |
| 2nd to last | **Trust Signal** | Identity/craft — "made for people who [X]" |
| Last | **More Features** | Pills listing extras + coming soon. Skip if few features. |
**Rules:**
- Each slide sells ONE idea. Never two features on one slide.
- Vary layouts across slides — never repeat the same template structure.
- Include 1-2 contrast slides (inverted bg) for visual rhythm.
## Step 4: Write Copy FIRST
Get all headlines approved before building layouts. Bad copy ruins good design.
### The Iron Rules
1. **One idea per headline.** Never join two things with "and."
2. **Short, common words.** 1-2 syllables. No jargon unless it's domain-specific.
3. **3-5 words per line.** Must be readable at thumbnail size in the App Store.
4. **Line breaks are intentional.** Control where lines break with `<br />`.
### Three Approaches (pick one per slide)
| Type | What it does | Example |
|------|-------------|---------|
| **Paint a moment** | You picture yourself doing it | "Check your coffee without opening the app." |
| **State an outcome** | What your life looks like after | "A home for every coffee you buy." |
| **Kill a pain** | Name a problem and destroy it | "Never waste a great bag of coffee." |
### What NEVER Works
- **Feature lists as headlines**: "Log every item with tags, categories, and notes"
- **Two ideas joined by "and"**: "Track X and never miss Y"
- **Compound clauses**: "Save and customize X for every Y you own"
- **Vague aspirational**: "Every item, tracked"
- **Marketing buzzwords**: "AI-powered tips" (unless it's actually AI)
### Bad-to-Better Headline Examples
Use these patterns to rewrite weak copy before building any layout:
| Weak | Better | Why it wins |
|------|--------|-------------|
| Track habits and stay motivated | Keep your streak alive | one idea, faster to parse |
| Organize tasks with AI summaries and smart sorting | Turn notes into next steps | outcome-first, less jargon |
| Save recipes with tags, filters, and favorites | Find dinner fast | sells the user benefit, not the UI |
| Manage budgets and never miss payments | See where money goes | cleaner promise, no dual claim |
| AI-powered wellness support | Feel calmer tonight | concrete emotional outcome |
### Copy Process
1. Write 3 options per slide using the three approaches
2. Read each at arm's length — if you can't parse it in 1 second, it's too complex
3. Check: does each line have 3-5 words? If not, adjust line breaks
4. Present options to the user with reasoning for each
### Example Prompt Shapes
If the user gives a weak or underspecified request, reshape it internally into something like:
```text
Build App Store screenshots for my habit tracker.
The app helps people stay consistent with simple daily routines.
I want 6 slides, clean/minimal style, warm neutrals, and a calm premium feel.
```
```text
Generate App Store screenshots for my personal finance app.
The app's main strengths are fast expense capture, clear monthly trends, and shared budgets.
I want a sharp, modern style with high contrast and 7 slides.
```
```text
Create exportable App Store screenshots for my AI note-taking app.
The core value is turning messy voice notes into clean summaries and action items.
I want bold copy, dark backgrounds, and a polished tech-forward look.
```
The pattern is:
1. app category + core outcome
2. top features in priority order
3. desired slide count
4. style direction
### Localization Rules
- Do not literally translate headlines if the result becomes long or awkward.
- Re-write copy for the target market while keeping the same selling idea.
- Re-check line breaks per locale; German, French, and Portuguese often need shorter claims.
- For RTL languages, also reverse badge alignment, supporting decorations, and phone offsets when the composition depends on left/right weight.
### Reference Apps for Copy Style
- **Raycast** — specific, descriptive, one concrete value per slide
- **Turf** — ultra-simple action verbs, conversational
- **Mela / Notion** — warm, minimal, elegant
## Step 5: Build the Page
### Architecture
```
page.tsx
├── Constants (IPHONE_W/H, IPAD_W/H, SIZES, design tokens)
├── LOCALES / RTL_LOCALES / THEMES / COPY_BY_LOCALE
├── Phone component (mockup PNG with screen overlay)
├── IPad component (CSS-only frame with screen overlay)
├── Caption component (label + headline, accepts canvasW for scaling)
├── Decorative components (blobs, glows, shapes — based on style direction)
├── iPhoneSlide1..N components (one per slide)
├── iPadSlide1..N components (same designs, adjusted for iPad proportions)
├── IPHONE_SCREENSHOTS / IPAD_SCREENSHOTS arrays (registries)
├── ScreenshotPreview (ResizeObserver scaling + hover export)
└── ScreenshotsPage (grid + locale tabs + theme tabs + device toggle + export logic)
```
### Export Sizes (Apple Required, portrait)
#### iPhone
```typescript
const IPHONE_SIZES = [
{ label: '6.9"', w: 1320, h: 2868 },
{ label: '6.5"', w: 1284, h: 2778 },
{ label: '6.3"', w: 1206, h: 2622 },
{ label: '6.1"', w: 1125, h: 2436 },
] as const;
```
Design at the LARGEST size (1320x2868) and scale down for export.
#### iPad (Optional)
If the user provides iPad screenshots, also generate iPad App Store screenshots:
```typescript
const IPAD_SIZES = [
{ label: '13" iPad', w: 2064, h: 2752 },
{ label: '12.9" iPad Pro', w: 2048, h: 2732 },
] as const;
```
Design iPad slides at 2064x2752 and scale down. iPad screenshots are optional but recommended — they're required for iPad-only apps and improve listing quality for universal apps.
#### Device Toggle
When supporting both devices, add a toggle (iPhone / iPad) in the toolbar next to the size dropdown. The size dropdown should switch between iPhone and iPad sizes based on the selected device. Support a `?device=ipad` URL parameter for headless/automated capture workflows.
#### Theme + Locale Toggles
Place locale and theme selectors in the same toolbar as device + size. This turns the generator into a small control panel instead of a one-off page.
- `locale` switches screenshot folders and copy dictionaries
- `theme` switches design tokens only
- `device` switches iPhone/iPad slide registries
- `size` switches export resolution only
### Rendering Strategy
Each screenshot is designed at full resolution (1320x2868px). Two copies exist:
1. **Preview**: CSS `transform: scale()` via ResizeObserver to fit a grid card
2. **Export**: Offscreen at `position: absolute; left: -9999px` at true resolution
### Phone Mockup Component
The included `mockup.png` has these pre-measured values:
```typescript
const MK_W = 1022; // mockup image width
const MK_H = 2082; // mockup image height
const SC_L = (52 / MK_W) * 100; // screen left offset %
const SC_T = (46 / MK_H) * 100; // screen top offset %
const SC_W = (918 / MK_W) * 100; // screen width %
const SC_H = (1990 / MK_H) * 100; // screen height %
const SC_RX = (126 / 918) * 100; // border-radius x %
const SC_RY = (126 / 1990) * 100; // border-radius y %
```
```tsx
function Phone({ src, alt, style, className = "" }: {
src: string; alt: string; style?: React.CSSProperties; className?: string;
}) {
return (
<div className={`relative ${className}`}
style={{ aspectRatio: `${MK_W}/${MK_H}`, ...style }}>
<img src="/mockup.png" alt=""
className="block w-full h-full" draggable={false} />
<div className="absolute z-10 overflow-hidden"
style={{
left: `${SC_L}%`, top: `${SC_T}%`,
width: `${SC_W}%`, height: `${SC_H}%`,
borderRadius: `${SC_RX}% / ${SC_RY}%`,
}}>
<img src={src} alt={alt}
className="block w-full h-full object-cover object-top"
draggable={false} />
</div>
</div>
);
}
```
### iPad Mockup Component (CSS-Only)
Unlike the iPhone mockup which uses a pre-measured PNG frame, the iPad uses a **CSS-only frame**. This avoids needing a separate mockup asset and looks clean at any resolution.
**Critical dimension:** The frame aspect ratio must be `770/1000` so the inner screen area (92% width × 94.4% height) matches the 3:4 aspect ratio of iPad screenshots. Using incorrect proportions causes black bars or stretched screenshots.
```tsx
function IPad({ src, alt, style, className = "" }: {
src: string; alt: string; style?: React.CSSProperties; className?: string;
}) {
return (
<div className={`relative ${className}`}
style={{ aspectRatio: "770/1000", ...style }}>
<div style={{
width: "100%", height: "100%", borderRadius: "5% / 3.6%",
background: "linear-gradient(180deg, #2C2C2E 0%, #1C1C1E 100%)",
position: "relative", overflow: "hidden",
boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.1), 0 8px 40px rgba(0,0,0,0.6)",
}}>
{/* Front camera dot */}
<div style={{
position: "absolute", top: "1.2%", left: "50%",
transform: "translateX(-50%)", width: "0.9%", height: "0.65%",
borderRadius: "50%", background: "#111113",
border: "1px solid rgba(255,255,255,0.08)", zIndex: 20,
}} />
{/* Bezel edge highlight */}
<div style={{
position: "absolute", inset: 0, borderRadius: "5% / 3.6%",
border: "1px solid rgba(255,255,255,0.06)",
pointerEvents: "none", zIndex: 15,
}} />
{/* Screen area */}
<div style={{
position: "absolute", left: "4%", top: "2.8%",
width: "92%", height: "94.4%",
borderRadius: "2.2% / 1.6%", overflow: "hidden", background: "#000",
}}>
<img src={src} alt={alt}
style={{ display: "block", width: "100%", height: "100%",
objectFit: "cover", objectPosition: "top" }}
draggable={false} />
</div>
</div>
</div>
);
}
```
**iPad layout adjustments vs iPhone:**
- Use `width: "65-70%"` for iPad mockups (vs 82-86% for iPhone) — iPad is wider relative to its height
- Two-iPad layouts work the same as two-phone layouts but with adjusted widths
- Caption font sizes should scale from `canvasW` (which is 2064 for iPad vs 1320 for iPhone)
- Same slide designs/copy can be reused — just swap the Phone component for IPad and adjust positioning
### Typography (Resolution-Independent)
All sizing relative to canvas width W:
| Element | Size | Weight | Line Height |
|---------|------|--------|-------------|
| Category label | `W * 0.028` | 600 (semibold) | default |
| Headline | `W * 0.09` to `W * 0.1` | 700 (bold) | 1.0 |
| Hero headline | `W * 0.1` | 700 (bold) | 0.92 |
### Phone Placement Patterns
Vary across slides — NEVER use the same layout twice in a row:
**Centered phone** (hero, single-feature):
```
bottom: 0, width: "82-86%", translateX(-50%) translateY(12-14%)
```
**Two phones layered** (comparison):
```
Back: left: "-8%", width: "65%", rotate(-4deg), opacity: 0.55
Front: right: "-4%", width: "82%", translateY(10%)
```
**Phone + floating elements** (only if user provided component PNGs):
```
Cards should NOT block the phone's main content.
Position at edges, slight rotation (2-5deg), drop shadows.
If distracting, push partially off-screen or make smaller.
```
### "More Features" Slide (Optional)
Dark/contrast background with app icon, headline ("And so much more."), and feature pills. Can include a "Coming Soon" section with dimmer pills.
## Step 6: Export
### Why html-to-image, NOT html2canvas
`html2canvas` breaks on CSS filters, gradients, drop-shadow, backdrop-filter, and complex clipping. `html-to-image` uses native browser SVG serialization — handles all CSS faithfully.
### Export Implementation
```typescript
import { toPng } from "html-to-image";
// Before capture: move element on-screen
el.style.left = "0px";
el.style.opacity = "1";
el.style.zIndex = "-1";
const opts = { width: W, height: H, pixelRatio: 1, cacheBust: true };
// CRITICAL: Double-call trick — first warms up fonts/images, second produces clean output
await toPng(el, opts);
const dataUrl = await toPng(el, opts);
// After capture: move back off-screen
el.style.left = "-9999px";
el.style.opacity = "";
el.style.zIndex = "";
```
### Export Matrix
If the project supports multiple locales and themes, add bulk export helpers so the user can export everything in one pass:
```typescript
const jobs = LOCALES.flatMap(locale =>
ACTIVE_THEME_IDS.flatMap(themeId =>
ACTIVE_DEVICES.flatMap(device =>
getSlidesFor(device).map((slide, index) => ({
locale,
themeId,
device,
index,
slide,
})),
),
),
);
```
Name files so they sort cleanly and preserve metadata:
```text
01-hero-en-clean-light-iphone-1320x2868.png
01-hero-ar-dark-bold-ipad-2064x2752.png
```
At minimum, support:
1. export current slide
2. export all slides for current locale/device/theme
3. export all locales for current theme
4. export full matrix when the user explicitly asks for it
### Key Rules
- **Double-call trick**: First `toPng()` loads fonts/images lazily. Second produces clean output. Without this, exports are blank.
- **On-screen for capture**: Temporarily move to `left: 0` before calling `toPng`.
- **Offscreen container**: Use `position: absolute; left: -9999px` (not `fixed`).
- **Resizing**: Load data URL into Image, draw onto canvas at target size.
- 300ms delay between sequential exports.
- Set `fontFamily` on the offscreen container.
- **Numbered filenames**: Prefix exports with zero-padded index so they sort correctly: `01-hero-1320x2868.png`, `02-freshness-1320x2868.png`, etc. Use `String(index + 1).padStart(2, "0")`.
## Step 7: Final QA Gate
Before handing the page back to the user, review every slide against this checklist:
### Message Quality
- **One idea per slide**: if a headline sells two ideas, split it or simplify it
- **First slide is strongest**: the hero slide should communicate the main benefit immediately
- **Readable in one second**: if you cannot parse it instantly at arm's length, rewrite it
### Visual Quality
- **No repeated layouts in sequence**: adjacent slides should not feel templated
- **Decorative elements support the story**: they should add energy without covering the app UI
- **Visual rhythm exists**: include at least one contrast slide when the set is long enough
### Export Quality
- **No clipped text or assets** after scaling to the selected export size
- **Screenshots are correctly aligned** inside the phone or iPad frame
- **Filenames sort correctly** with zero-padded numeric prefixes
- **Theme tokens are applied consistently** across all slides in the same preset
- **Localized copy still fits** after translation, especially on long-word languages
- **RTL slides feel designed, not just flipped**
### Hand-off Behavior
When you present the finished work:
1. briefly explain the narrative arc across the slides
2. mention any slides that intentionally use contrast or different layout treatment
3. call out any assumptions you made about brand tone, copy, or missing assets
## Common Mistakes
| Mistake | Fix |
|---------|-----|
| All slides look the same | Vary phone position (center, left, right, two-phone, no-phone) |
| Decorative elements invisible | Increase size and opacity — better too visible than invisible |
| Copy is too complex | "One second at arm's length" test |
| Floating elements block the phone | Move off-screen edges or above the phone |
| Plain white/black background | Use gradients — even subtle ones add depth |
| Too cluttered | Remove floating elements, simplify to phone + caption |
| Too simple/empty | Add larger decorative elements, floating items at edges |
| Headlines use "and" | Split into two slides or pick one idea |
| No visual contrast across slides | Mix light and dark backgrounds |
| Export is blank | Use double-call trick; move element on-screen before capture |
@@ -0,0 +1,48 @@
---
name: icon-generator
description: Generate web UI/UX icon assets (favicon.ico, apple-touch-icon, PWA icons incl. maskable) and optionally Unreal Engine packaging icons (Windows .ico, macOS .iconset/.icns, Linux .png) from a single source SVG/PNG; use when you need correct multi-size icon files, safe-area guidance, manifests/head tags, or automation.
---
# Icon Generator
You generate icon asset bundles for **web UI/UX first** (favicons + PWA icons), and you can also generate **Unreal Engine packaging** icon assets when needed.
## Fast workflow
1. Pick target(s): Web UI/UX (favicon + PWA icons) and/or Unreal Engine packaging (optional).
2. Pick the source icon: prefer a **1024x1024 PNG** (square) or a clean **SVG**. If it's not square, choose whether to crop or pad (default: pad).
3. Generate the assets using [`scripts/generate_icons.py`](scripts/generate_icons.py).
Web/PWA sizes and safe-area rules: [`references/web-ui-ux.md`](references/web-ui-ux.md)
Unreal Engine formats and expectations: [`references/unreal-engine.md`](references/unreal-engine.md)
Full size tables: [`references/icon-sizes.md`](references/icon-sizes.md)
4. Verify output quality: ensure the `.ico` contains multiple sizes, and the 16/24/32 px variants are crisp.
## Quality rules (what "good" looks like)
- **Design for small sizes**: avoid thin strokes, tiny text, and busy details.
- **Prefer transparent backgrounds** for desktop icons unless you intentionally "plate" the icon.
- **Preview at 16px and 24px**. If it becomes muddy, create a simpler variant.
## Automation (recommended)
Run and customize the script:
- Script: [`scripts/generate_icons.py`](scripts/generate_icons.py)
- It supports:
- Web/PWA set: `favicon.ico`, `apple-touch-icon.png`, `icon-192.png`, `icon-512.png`, `icon-maskable-512.png`
- UE sets (optional): Windows `.ico`, macOS `.iconset`, Linux `.png`
If you need HTML `<head>` snippets, `manifest.webmanifest` examples, and maskable safe-area guidance, read:
- [`references/web-ui-ux.md`](references/web-ui-ux.md)
## Notes
- If your input is SVG and Python SVG rasterization is unavailable on your machine, export a 1024x1024 PNG first (e.g., Inkscape), then rerun the script using the PNG.
- Keep this SKILL.md lean; detailed size tables live in the reference files.
@@ -0,0 +1,39 @@
# Icon size tables
## Web UI/UX (favicons + PWA)
Minimal, modern set:
- `favicon.ico`: 16×16, 32×32 (optionally 48×48)
- `apple-touch-icon.png`: 180×180
- `icon-192.png`: 192×192
- `icon-512.png`: 512×512
- `icon-maskable-512.png`: 512×512 (opaque background + padding)
## Unreal Engine packaging (optional)
### Windows `.ico`
Recommended embedded sizes:
- 16, 24, 32, 48, 64, 128, 256
### macOS `.iconset` (source for `.icns`)
Common iconset sizes and filenames:
- `icon_16x16.png` (16)
- `icon_16x16@2x.png` (32)
- `icon_32x32.png` (32)
- `icon_32x32@2x.png` (64)
- `icon_128x128.png` (128)
- `icon_128x128@2x.png` (256)
- `icon_256x256.png` (256)
- `icon_256x256@2x.png` (512)
- `icon_512x512.png` (512)
- `icon_512x512@2x.png` (1024)
### Linux
- 256×256 PNG (common baseline)
- 512×512 PNG (nice to have)
@@ -0,0 +1,29 @@
# Unreal Engine packaging icons (optional target)
## What UE typically expects
- **Windows**: a multi-resolution `.ico` (commonly max 256×256)
- **macOS**: an `.icns` (UE may require `.icns` even if Apple has moved toward asset catalogs)
- **Linux**: usually a `.png` (commonly 256×256)
## What this skill generates
Using `--targets ue`, the script outputs:
- `ue/windows/icon.ico` (multi-size)
- `ue/mac/AppIcon.iconset/` (iconset PNGs)
- `ue/linux/icon-256.png`, `ue/linux/icon-512.png`
### Creating `.icns` (macOS)
Creating `.icns` is easiest on macOS with `iconutil`.
- Input: the `AppIcon.iconset/` folder
- Output: `AppIcon.icns`
If you’re not on macOS, keep the `.iconset` in source control and generate `.icns` on a Mac build machine.
## Quality reminder
Even if a single “master” PNG exists, small sizes often need a simplified design.
If your 16×16 looks mushy, create a simplified icon variant and regenerate.
@@ -0,0 +1,56 @@
# Web UI/UX icon set (favicon + PWA)
## Recommended minimal output set
This set covers modern browsers + iOS home screen + Android/PWA:
- `favicon.ico` (multi-size container): include 16×16 and 32×32 (optionally 48×48)
- `apple-touch-icon.png` (180×180)
- `icon-192.png` (192×192)
- `icon-512.png` (512×512)
- `icon-maskable-512.png` (512×512, **maskable**, opaque background, padded content)
This is intentionally “minimal but effective”. You can add more sizes if you have a specific requirement.
## HTML `<head>` snippet
Use this as a starting point:
- `<link rel="icon" href="/favicon.ico">`
- `<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">`
- `<link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png">`
- `<link rel="icon" type="image/png" sizes="512x512" href="/icon-512.png">`
- `<link rel="manifest" href="/manifest.webmanifest">` (if PWA)
## `manifest.webmanifest` example
Include both normal (“any”) and maskable icons:
```json
{
"name": "My App",
"short_name": "MyApp",
"display": "standalone",
"start_url": "/",
"icons": [
{ "src": "/icon-192.png", "type": "image/png", "sizes": "192x192", "purpose": "any" },
{ "src": "/icon-512.png", "type": "image/png", "sizes": "512x512", "purpose": "any" },
{ "src": "/icon-maskable-512.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" }
]
}
```
## Maskable safe area (practical rule)
Maskable icons can be cropped into different shapes by the OS/launcher.
- Keep important content inside the **center ~80%** of the image.
- Use an **opaque background** for the full 512×512.
In the generator script, this corresponds to `--maskable-scale 0.80` (default).
## Common failure modes
- You only provide a big 512×512 and let the browser scale down → looks blurry at 16×16.
- You use transparent background for iOS “Add to Home Screen” icons → iOS may render it with an ugly fill.
- Your maskable icon has no padding → the launcher crops off your logo.
@@ -0,0 +1,101 @@
---
name: ios-swift-development
description: >
Develop native iOS apps with Swift. Covers MVVM architecture, SwiftUI,
URLSession for networking, Combine for reactive programming, and Core Data
persistence.
---
# iOS Swift Development
## Table of Contents
- [Overview](#overview)
- [When to Use](#when-to-use)
- [Quick Start](#quick-start)
- [Reference Guides](#reference-guides)
- [Best Practices](#best-practices)
## Overview
Build high-performance native iOS applications using Swift with modern frameworks including SwiftUI, Combine, and async/await patterns.
## When to Use
- Creating native iOS applications with optimal performance
- Leveraging iOS-specific features and APIs
- Building apps that require tight hardware integration
- Using SwiftUI for declarative UI development
- Implementing complex animations and transitions
## Quick Start
Minimal working example:
```swift
import Foundation
import Combine
struct User: Codable, Identifiable {
let id: UUID
var name: String
var email: String
}
class UserViewModel: ObservableObject {
@Published var user: User?
@Published var isLoading = false
@Published var errorMessage: String?
private let networkService: NetworkService
init(networkService: NetworkService = .shared) {
self.networkService = networkService
}
@MainActor
func fetchUser(id: UUID) async {
isLoading = true
errorMessage = nil
// ... (see reference guides for full implementation)
```
## Reference Guides
Detailed implementations in the `references/` directory:
| Guide | Contents |
|---|---|
| [MVVM Architecture Setup](references/mvvm-architecture-setup.md) | MVVM Architecture Setup |
| [Network Service with URLSession](references/network-service-with-urlsession.md) | Network Service with URLSession |
| [SwiftUI Views](references/swiftui-views.md) | SwiftUI Views |
## Best Practices
### ✅ DO
- Use SwiftUI for modern UI development
- Implement MVVM architecture
- Use async/await patterns
- Store sensitive data in Keychain
- Handle errors gracefully
- Use @StateObject for ViewModels
- Validate API responses properly
- Implement Core Data for persistence
- Test on multiple iOS versions
- Use dependency injection
- Follow Swift style guidelines
### ❌ DON'T
- Store tokens in UserDefaults
- Make network calls on main thread
- Use deprecated UIKit patterns
- Ignore memory leaks
- Skip error handling
- Use force unwrapping (!)
- Store passwords in code
- Ignore accessibility
- Deploy untested code
- Use hardcoded API URLs
@@ -0,0 +1,60 @@
# MVVM Architecture Setup
## MVVM Architecture Setup
```swift
import Foundation
import Combine
struct User: Codable, Identifiable {
let id: UUID
var name: String
var email: String
}
class UserViewModel: ObservableObject {
@Published var user: User?
@Published var isLoading = false
@Published var errorMessage: String?
private let networkService: NetworkService
init(networkService: NetworkService = .shared) {
self.networkService = networkService
}
@MainActor
func fetchUser(id: UUID) async {
isLoading = true
errorMessage = nil
do {
user = try await networkService.fetch(User.self, from: "/users/\(id)")
} catch {
errorMessage = error.localizedDescription
}
isLoading = false
}
@MainActor
func updateUser(_ userData: User) async {
guard let user = user else { return }
do {
self.user = try await networkService.put(
User.self,
to: "/users/\(user.id)",
body: userData
)
} catch {
errorMessage = "Failed to update user"
}
}
func logout() {
user = nil
errorMessage = nil
}
}
```
@@ -0,0 +1,99 @@
# Network Service with URLSession
## Network Service with URLSession
```swift
class NetworkService {
static let shared = NetworkService()
private let session: URLSession
private let baseURL: URL
init(
session: URLSession = .shared,
baseURL: URL = URL(string: "https://api.example.com")!
) {
self.session = session
self.baseURL = baseURL
}
func fetch<T: Decodable>(
_: T.Type,
from endpoint: String
) async throws -> T {
let url = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: url)
request.addAuthHeader()
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return try decoder.decode(T.self, from: data)
}
func put<T: Decodable, Body: Encodable>(
_: T.Type,
to endpoint: String,
body: Body
) async throws -> T {
let url = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.addAuthHeader()
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
request.httpBody = try encoder.encode(body)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
}
private func validateResponse(_ response: URLResponse) throws {
guard let httpResponse = response as? HTTPURLResponse else {
throw NetworkError.invalidResponse
}
switch httpResponse.statusCode {
case 200...299:
return
case 401:
throw NetworkError.unauthorized
case 500...599:
throw NetworkError.serverError
default:
throw NetworkError.unknown
}
}
}
enum NetworkError: LocalizedError {
case invalidResponse
case unauthorized
case serverError
case unknown
var errorDescription: String? {
switch self {
case .invalidResponse: return "Invalid response"
case .unauthorized: return "Unauthorized"
case .serverError: return "Server error"
case .unknown: return "Unknown error"
}
}
}
extension URLRequest {
mutating func addAuthHeader() {
if let token = KeychainManager.shared.getToken() {
setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
}
}
```
@@ -0,0 +1,112 @@
# SwiftUI Views
## SwiftUI Views
```swift
struct ContentView: View {
@StateObject var userViewModel = UserViewModel()
var body: some View {
TabView {
HomeView()
.tabItem { Label("Home", systemImage: "house") }
ProfileView(viewModel: userViewModel)
.tabItem { Label("Profile", systemImage: "person") }
}
}
}
struct HomeView: View {
@State var items: [Item] = []
@State var loading = true
var body: some View {
NavigationView {
ZStack {
if loading {
ProgressView()
} else {
List(items) { item in
NavigationLink(destination: ItemDetailView(item: item)) {
VStack(alignment: .leading) {
Text(item.title).font(.headline)
Text(item.description).font(.subheadline).foregroundColor(.gray)
}
}
}
}
}
.navigationTitle("Items")
.task {
await loadItems()
}
}
}
private func loadItems() async {
do {
items = try await NetworkService.shared.fetch([Item].self, from: "/items")
} catch {
print("Error: \(error)")
}
loading = false
}
}
struct ItemDetailView: View {
let item: Item
@Environment(\.dismiss) var dismiss
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Text(item.title).font(.title2).fontWeight(.bold)
Text(item.description).font(.body)
Text("Price: $\(String(format: "%.2f", item.price))")
.font(.headline).foregroundColor(.blue)
Spacer()
}
.padding()
}
.navigationBarTitleDisplayMode(.inline)
}
}
struct ProfileView: View {
@ObservedObject var viewModel: UserViewModel
@State var isLoading = true
var body: some View {
NavigationView {
ZStack {
if viewModel.isLoading {
ProgressView()
} else if let user = viewModel.user {
VStack(spacing: 20) {
Text(user.name).font(.title).fontWeight(.bold)
Text(user.email).font(.subheadline)
Button("Logout") { viewModel.logout() }
.foregroundColor(.red)
Spacer()
}
.padding()
} else {
Text("No profile data")
}
}
.navigationTitle("Profile")
.task {
await viewModel.fetchUser(id: UUID())
}
}
}
}
struct Item: Codable, Identifiable {
let id: String
let title: String
let description: String
let price: Double
}
```
@@ -0,0 +1,261 @@
---
# ═══════════════════════════════════════════════════════════════════════════
# SKILL: Mobile Development
# Version: 2.0.0 | Updated: 2025-01
# ═══════════════════════════════════════════════════════════════════════════
name: mobile-development
description: iOS (Swift, SwiftUI), Android (Kotlin, Compose), cross-platform (Flutter, React Native), and game development (Unity, Unreal).
# ACTIVATION TRIGGERS
triggers:
- ios
- android
- flutter
- react native
- mobile
- swift
- kotlin
- unity
- game development
# SKILL PARAMETERS
parameters:
platform:
type: string
enum: [ios, android, cross-platform, games]
required: true
project_type:
type: string
required: false
description: Type of app (social, productivity, game, etc.)
# OUTPUT SPECIFICATION
outputs:
recommended_stack:
type: object
learning_path:
type: array
portfolio_projects:
type: array
# RELIABILITY
retry:
max_attempts: 3
backoff: exponential
# OBSERVABILITY
observability:
log_level: info
level: advanced
prerequisites:
- core-development
sasmp_version: "1.3.0"
bonded_agent: 01-core-paths
bond_type: PRIMARY_BOND
---
# Mobile Development Skill
## Quick Reference
| Platform | Language | Framework | Timeline | Job Market |
|----------|----------|-----------|----------|------------|
| **iOS** | Swift | SwiftUI | 6-9 mo | High |
| **Android** | Kotlin | Compose | 6-9 mo | High |
| **Cross-Platform** | Dart | Flutter | 4-6 mo | Growing |
| **Games** | C# | Unity | 12-24 mo | Moderate |
---
## Learning Paths
### iOS Development
```
[1] Swift Fundamentals (4-6 wk)
│ └─ Types, optionals, closures, protocols
│
▼
[2] SwiftUI (4-6 wk)
│ └─ Views, modifiers, state, binding
│
▼
[3] Navigation + Data (3-4 wk)
│ └─ NavigationStack, SwiftData/Core Data
│
▼
[4] Networking + Async (2-3 wk)
│ └─ URLSession, async/await, Combine
│
▼
[5] Testing + App Store (2 wk)
└─ XCTest, TestFlight, submission
```
**2025 Stack:** Swift 5.10 + SwiftUI + SwiftData + Xcode 16
---
### Android Development
```
[1] Kotlin Fundamentals (4-6 wk)
│ └─ Null safety, coroutines, data classes
│
▼
[2] Jetpack Compose (4-6 wk)
│ └─ Composables, state, effects
│
▼
[3] Architecture (3-4 wk)
│ └─ MVVM, Room, Navigation
│
▼
[4] Networking + DI (2-3 wk)
│ └─ Retrofit, Hilt, Flow
│
▼
[5] Testing + Play Store (2 wk)
└─ JUnit, Espresso, release
```
**2025 Stack:** Kotlin 2.0 + Jetpack Compose + Room + Hilt
---
### Flutter (Cross-Platform)
```
[1] Dart Fundamentals (2-3 wk)
│
▼
[2] Flutter Widgets (3-4 wk)
│
▼
[3] State Management (2-3 wk)
│ └─ Riverpod or Bloc
│
▼
[4] Backend Integration (2 wk)
│ └─ Firebase, REST APIs
│
▼
[5] Deploy to Both Stores (1 wk)
```
**2025 Stack:** Flutter 3.x + Dart 3.x + Riverpod + Firebase
---
### Game Development
```
[1] Game Basics (4-6 wk)
│ └─ Game loop, input handling
│
▼
[2] Unity/C# Fundamentals (6-8 wk)
│ └─ GameObjects, Components, Scripts
│
▼
[3] Physics + Graphics (4-6 wk)
│ └─ Rigidbody, colliders, shaders
│
▼
[4] Audio + Polish (2-4 wk)
│
▼
[5] Publish (ongoing)
└─ Steam, App Store, Play Store
```
**2025 Stack:** Unity 6 LTS + C# OR Unreal 5.4 + C++
---
## Platform Decision Tree
```
Which platform?
│
├─► Apple ecosystem only?
│ └─► iOS (Swift + SwiftUI)
│
├─► Android ecosystem only?
│ └─► Android (Kotlin + Compose)
│
├─► Both platforms?
│ ├─► Performance-critical? → Native for both
│ ├─► Budget/time limited? → Flutter
│ └─► Web developer background? → React Native
│
└─► Making games?
├─► 2D/3D indie → Unity
├─► AAA quality → Unreal
└─► Simple 2D → Godot
```
---
## Game Engine Comparison
| Engine | Market | Language | Learning | Best For |
|--------|--------|----------|----------|----------|
| **Unity** | 51% | C# | Medium | Indie, mobile, VR |
| **Unreal** | 31% | C++/BP | Hard | AAA, high-fidelity |
| **Godot** | 10% | GDScript | Easy | Indie, 2D |
---
## Troubleshooting
```
Native vs Cross-platform?
├─► Need platform-specific APIs (HealthKit, ARCore)? → Native
├─► Performance-critical (AR/VR, complex animations)? → Native
├─► Budget or time limited? → Flutter
├─► Team knows JavaScript? → React Native
└─► Starting from scratch? → Flutter (best DX)
Simulator works, device doesn't?
├─► Missing entitlements/capabilities?
├─► Different iOS/Android version?
├─► Network connectivity issues?
└─► Always test on real devices from day 1
App rejected by store?
├─► Read rejection reason carefully
├─► Check App Store Review Guidelines
├─► Most common: metadata issues, crashes, spam
└─► Appeal if unjustified
```
---
## Common Failure Modes
| Symptom | Root Cause | Recovery |
|---------|------------|----------|
| Slow UI | Too many recompositions | Profile, optimize state |
| Memory leaks | Not cleaning up resources | Use lifecycle-aware components |
| App rejected | Guidelines violation | Read guidelines BEFORE building |
| Game stutters | Draw call overhead | Object pooling, LOD, batching |
---
## Portfolio Projects
### Mobile (Progressive)
1. **Todo App** - CRUD basics
2. **Weather App** - API integration
3. **Chat App** - Real-time, auth
4. **Payment App** - Stripe, security
### Games
1. **2D Platformer** - Physics basics
2. **3D Runner** - 3D graphics, particles
3. **Multiplayer Game** - Networking
---
## Next Actions
Specify your target platform for a detailed learning plan.
@@ -0,0 +1,73 @@
# Mobile Development Guide for Cloudflare
## PWA on Cloudflare Pages
```json
// manifest.json
{
"name": "My PWA",
"short_name": "PWA",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#f38020",
"icons": [
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
]
}
```
## Service Worker with Cloudflare
```typescript
// sw.ts - Offline-first strategy
const CACHE_NAME = 'v1';
const OFFLINE_URL = '/offline.html';
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll([OFFLINE_URL, '/', '/styles.css']);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).catch(() => caches.match(OFFLINE_URL))
);
});
```
## Mobile API with Workers
```typescript
// Optimized for mobile clients
export default {
async fetch(request: Request, env: Env) {
const userAgent = request.headers.get('User-Agent') || '';
const isMobile = /Mobile|Android|iPhone/i.test(userAgent);
return Response.json({
data: await getData(env),
optimized: isMobile ? 'mobile' : 'desktop'
}, {
headers: {
'Cache-Control': isMobile ? 'max-age=300' : 'max-age=3600'
}
});
}
};
```
## Deployment
```bash
# Deploy to Cloudflare Pages
npx wrangler pages deploy dist --project-name=my-pwa
```
---
*Cloudflare Plugin - Mobile Development Skill*