Add capacitor skill for native iOS/Android builds

Provides the cross-platform primitives needed to wrap the mkstack web app
as a native iOS and Android binary using Capacitor, modeled on how Ditto
integrates the framework.

Each helper works unconditionally on every platform \u2014 native builds
use the real Capacitor plugin, web falls back to an equivalent browser
API:

- haptics: impactLight/Medium/Heavy, notificationSuccess/Warning/Error,
  selectionChanged \u2014 taptic engine on native, navigator.vibrate() on
  web, silent no-op where neither exists
- downloadTextFile / openUrl \u2014 @capacitor/filesystem and native
  share sheet on native, <a download> and window.open on web
- secureStorage + useSecureLocalStorage \u2014 iOS Keychain / Android
  KeyStore adapter with automatic migration of existing plaintext values
  from localStorage on first native read, plus an async-aware React hook
  that exposes a 'ready' flag
- DeepLinkHandler \u2014 listens for Capacitor appUrlOpen and forwards
  into React Router navigation
- bootstrapNative() \u2014 hides the iOS keyboard accessory bar and keeps
  the system-bar icon style in sync with the active CSS theme via
  MutationObserver on both the <html> class and the theme-vars style
  element; detects dark background from theme class or computed body
  luminance
- safe-area CSS utilities \u2014 .safe-area-top/-bottom/-left/-right
  padding classes plus .safe-area-inset-top/-bottom positional variants,
  preferring --safe-area-inset-* CSS vars (injected by the SystemBars
  plugin on Android) over env(safe-area-inset-*) so Chromium <140 on
  Android Just Works
- capacitor.config.ts template \u2014 preconfigured with androidScheme
  https, ios contentInset never, SystemBars insetsHandling css; placeholder
  appId / appName / scheme ready to be customized
- patch-cap-config.mjs \u2014 post-cap-sync hook that restores
  packageClassList entries for local (non-SPM) native plugin classes so
  they get registered at startup

SKILL.md documents the full setup sequence: install the nine
@capacitor/* + capacitor-secure-storage-plugin packages, copy files
into src/, paste the CSS snippet into index.css, edit capacitor.config.ts
identity fields, add viewport-fit=cover, wire bootstrapNative() into
main.tsx and DeepLinkHandler into AppRouter, npx cap add android / ios,
build, sync, run. Also covers common follow-ups (custom plugins, icons,
splash, push, deep-link verification, credential manager integration)
and troubleshooting (safe-area zero on Android, navigation no-op, keychain
orphaning, keyboard accessory bar timing, custom theme detection).

Validated: all files staged into src/ + deps installed \u2014 npm run
test passes with only the 6 pre-existing baseline errors (template
FIXMEs + missing index.html manifest/meta), then cleanly reverted.
This commit is contained in:
Alex Gleason committed 2026-04-26 19:48:23 -05:00
1 parent 0b220f250a
commit f927a00dcf
10 files changed
+1108

No files matched your search

+346
View File
@@ -0,0 +1,346 @@
---
name: capacitor
description: Wrap the mkstack web app as a native iOS and Android application using Capacitor. Provides haptics, native file downloads / share sheet, OS-level secure storage (Keychain / KeyStore), deep-link routing, status-bar theme sync, and safe-area CSS utilities.
---
# Capacitor Native Wrapper
This skill turns the web app into a native iOS and Android binary using
[Capacitor](https://capacitorjs.com/) — no Swift or Kotlin required for the
basics. The React UI runs unchanged inside a native WebView; this skill
provides the cross-platform primitives that let the app feel native:
haptics, OS-level secure storage, a working file download, the share sheet,
deep-link routing, safe-area handling, and automatic status-bar theming.
**This functionality is not included in the project by default.** When the
user wants to ship the app to the App Store or Google Play (or build an
`.apk` / `.ipa`), follow the setup instructions below.
## What This Skill Provides
| Capability | Web behavior | Native behavior |
|---|---|---|
| **Haptics** (`impactLight`, `notificationSuccess`, `selectionChanged`, …) | `navigator.vibrate()` (Android browsers) | Taptic engine / Android haptics |
| **`downloadTextFile(filename, content)`** | `<a download>` click | Writes to app Documents directory |
| **`openUrl(url)`** | `window.open(url, '_blank')` | Presents the native share sheet |
| **`secureStorage` / `useSecureLocalStorage`** | `localStorage` | iOS Keychain / Android KeyStore, auto-migrates existing plaintext values |
| **`<DeepLinkHandler />`** | no-op | Forwards OS `appUrlOpen` events into React Router |
| **`bootstrapNative()`** | no-op | Hides iOS keyboard accessory bar; syncs system-bar icon style with theme |
| **Safe-area CSS utilities** | `env(safe-area-inset-*)` fallback | `var(--safe-area-inset-*)` injected by `SystemBars` plugin (Android) + iOS notch support |
Everything is SSR-safe and web-safe — each helper does the right thing on
every platform, so you can import and call them unconditionally from shared
components.
## Files Provided by This Skill
Copy each file from `.agents/skills/capacitor/files/` into its matching
location:
### Source files (copy into `src/`)
| Skill file | Copy to |
|---|---|
| `files/lib/haptics.ts` | `src/lib/haptics.ts` |
| `files/lib/downloadFile.ts` | `src/lib/downloadFile.ts` |
| `files/lib/secureStorage.ts` | `src/lib/secureStorage.ts` |
| `files/lib/nativeBootstrap.ts` | `src/lib/nativeBootstrap.ts` |
| `files/hooks/useSecureLocalStorage.ts` | `src/hooks/useSecureLocalStorage.ts` |
| `files/components/DeepLinkHandler.tsx` | `src/components/DeepLinkHandler.tsx` |
### Project-root files
| Skill file | Copy to |
|---|---|
| `files/capacitor.config.ts` | `capacitor.config.ts` (project root) — edit `appId`, `appName`, `scheme`, background colors |
| `files/scripts/patch-cap-config.mjs` | `scripts/patch-cap-config.mjs` — only needed if you add **local** (non-SPM) native plugin classes; otherwise skip |
### Snippets to merge
| Skill file | What to do |
|---|---|
| `files/safe-area.css` | Paste inside the `@layer utilities { … }` block of `src/index.css` |
## Setup Instructions
### 1. Install Dependencies
```bash
npm install @capacitor/core @capacitor/app @capacitor/filesystem \
@capacitor/haptics @capacitor/keyboard @capacitor/share \
capacitor-secure-storage-plugin
npm install -D @capacitor/cli @capacitor/android @capacitor/ios
```
Each package:
- **`@capacitor/core`** (runtime) — `Capacitor.isNativePlatform()`,
`Capacitor.getPlatform()`, `registerPlugin`, `SystemBars`
- **`@capacitor/cli`** (dev) — the `npx cap` command (`init`, `add`,
`sync`, `run`)
- **`@capacitor/android`** (dev) — the Android Studio project scaffolding
- **`@capacitor/ios`** (dev) — the Xcode project scaffolding
- **`@capacitor/app`** (runtime) — `appUrlOpen` event for deep links
- **`@capacitor/filesystem`** (runtime) — native file writes (used by
`downloadTextFile`)
- **`@capacitor/haptics`** (runtime) — taptic engine integration
- **`@capacitor/keyboard`** (runtime) — iOS keyboard accessory-bar control
- **`@capacitor/share`** (runtime) — native share sheet (used by `openUrl`)
- **`capacitor-secure-storage-plugin`** (runtime) — iOS Keychain / Android
KeyStore wrapper (used by `secureStorage`)
### 2. Copy the Skill Files
Copy every file listed in the tables above from
`.agents/skills/capacitor/files/` into its corresponding location.
Paste the contents of `files/safe-area.css` into the
`@layer utilities { … }` block of `src/index.css`.
### 3. Edit `capacitor.config.ts`
Open the copied `capacitor.config.ts` and fill in your app identity:
```ts
const config: CapacitorConfig = {
appId: 'com.example.myapp', // reverse-DNS identifier
appName: 'MyApp', // user-visible name
webDir: 'dist',
ios: {
scheme: 'MyApp', // custom URL scheme (myapp://)
backgroundColor: '#14161f',
contentInset: 'never',
},
android: {
backgroundColor: '#14161f',
allowMixedContent: false,
},
// ...
};
```
**Important:** `appId` cannot be changed after the app is published to
either store.
### 4. Update `index.html`
Ensure your viewport meta tag opts into safe-area insets — without
`viewport-fit=cover`, iOS will not expose `env(safe-area-inset-*)`:
```html
<meta name="viewport"
content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content" />
```
### 5. Wire `bootstrapNative()` into `src/main.tsx`
Call it **before** `createRoot(...).render(...)` so the system bars are
themed by the time the first React paint lands:
```tsx
// src/main.tsx
import { createRoot } from 'react-dom/client';
import { bootstrapNative } from '@/lib/nativeBootstrap';
import App from './App.tsx';
import './index.css';
bootstrapNative();
createRoot(document.getElementById('root')!).render(<App />);
```
### 6. Wire `<DeepLinkHandler />` into `AppRouter.tsx`
It must live **inside** `<BrowserRouter>` so `useNavigate()` works:
```tsx
// src/AppRouter.tsx
import { BrowserRouter } from 'react-router-dom';
import { DeepLinkHandler } from '@/components/DeepLinkHandler';
import { ScrollToTop } from '@/components/ScrollToTop';
export default function AppRouter() {
return (
<BrowserRouter>
<DeepLinkHandler />
<ScrollToTop />
{/* <Routes>…</Routes> */}
</BrowserRouter>
);
}
```
### 7. Add the Native Platforms
```bash
npx cap add android
npx cap add ios # macOS only
```
This creates `android/` and `ios/` directories at the project root. Commit
them — they contain project-specific config (signing keys excluded).
### 8. Build & Sync
```bash
npm run build # produces dist/
npx cap sync # copies dist/ into android/ and ios/
```
Add a convenience npm script so you can re-sync with one command:
```jsonc
// package.json
{
"scripts": {
"cap:sync": "npx cap sync"
}
}
```
If you later add **local** (non-SPM) native plugin classes to `android/` or
`ios/`, wire up the patch script:
```jsonc
{
"scripts": {
"cap:sync": "npx cap sync && node scripts/patch-cap-config.mjs"
}
}
```
### 9. Run on a Device or Emulator
```bash
npx cap open android # opens Android Studio
npx cap open ios # opens Xcode (macOS only)
```
Then hit **Run** in the IDE. For headless quick-iteration:
```bash
npx cap run android
npx cap run ios
```
## Using the APIs
### Haptics
```tsx
import { impactLight, notificationSuccess } from '@/lib/haptics';
<Button onClick={() => { impactLight(); onLike(); }}>Like</Button>
await submitForm();
notificationSuccess();
```
All haptics are fire-and-forget; calling them on unsupported platforms (or
when permission is denied) is a silent no-op.
### Native File Download / Share
```tsx
import { downloadTextFile, openUrl } from '@/lib/downloadFile';
// Save a text file — Documents on native, `<a download>` on web
await downloadTextFile('export.json', JSON.stringify(data, null, 2));
// Open a URL — new tab on web, share sheet on native
await openUrl('https://example.com/article');
```
### Secure Storage
```tsx
import { secureStorage } from '@/lib/secureStorage';
await secureStorage.setItem('nwc:active', connectionString);
const value = await secureStorage.getItem('nwc:active');
await secureStorage.removeItem('nwc:active');
```
Or the React hook:
```tsx
import { useSecureLocalStorage } from '@/hooks/useSecureLocalStorage';
function WalletSettings() {
const [conn, setConn, ready] = useSecureLocalStorage<string | null>(
'nwc:active',
null,
);
if (!ready) return <Spinner />;
return (
<Input
value={conn ?? ''}
onChange={(e) => setConn(e.target.value || null)}
/>
);
}
```
The hook has the same signature as `useLocalStorage` but returns a third
`ready` flag because native secure reads are async. While `!ready` you
should render a spinner or skip decisions that depend on the stored value.
### Safe-area CSS
```tsx
{/* sticky top bar that clears the notch */}
<header className="sticky top-0 safe-area-top bg-background">…</header>
{/* bottom nav that clears the home indicator */}
<nav className="fixed bottom-0 safe-area-bottom">…</nav>
{/* toast stack that sits below the status bar */}
<Toaster className="safe-area-inset-top" />
```
## Common Follow-ups
- **Custom native plugins** — If you build a local Swift/Kotlin Capacitor
plugin that is *not* shipped via Swift Package Manager, add its class
name to `LOCAL_PLUGINS` in `scripts/patch-cap-config.mjs` so
`packageClassList` in `capacitor.config.json` is restored after each
`npx cap sync`.
- **App icons** — Use any standard icon generator; Capacitor looks for
`android/app/src/main/res/mipmap-*/ic_launcher*.png` and
`ios/App/App/Assets.xcassets/AppIcon.appiconset/`.
- **Splash screen** — Add `@capacitor/splash-screen` and configure it
under `plugins.SplashScreen` in `capacitor.config.ts`.
- **Push notifications** — Add `@capacitor/push-notifications` (FCM on
Android, APNs on iOS). The web side can keep using Web Push.
- **Deep-link verification** — host an
`apple-app-site-association` file and an `assetlinks.json` file on your
domain so the OS will open verified `https://` links directly in your
app without the disambiguation prompt. See the
[`DeepLinkHandler.tsx`](./files/components/DeepLinkHandler.tsx) header
comment for the full checklist.
- **Store password manager integration** — for saving / autofilling a
Nostr `nsec` via iCloud Keychain or AndroidX Credential Manager, add
`@capgo/capacitor-autofill-save-password` and wrap it in a helper
analogous to `secureStorage` (see Ditto's `credentialManager.ts` for a
reference implementation).
## Troubleshooting
- **`env(safe-area-inset-top)` returns `0` on Android** — confirm the
`SystemBars` plugin is configured with `insetsHandling: 'css'` in
`capacitor.config.ts` (the skill's template already does this). That
injects `--safe-area-inset-*` CSS variables and the utilities in
`safe-area.css` prefer them over `env(…)`.
- **Deep links don't navigate** — make sure `<DeepLinkHandler />` is
**inside** `<BrowserRouter>`. It uses `useNavigate()` and will throw
silently if it's mounted outside.
- **`secureStorage` write succeeds but read returns `null`** — the
`capacitor-secure-storage-plugin` stores values per-bundle-id. Reinstalling
a debug build can rotate the keychain entitlement and orphan previous
entries. Clear storage or reinstall clean if this happens in dev.
- **iOS keyboard keeps showing the accessory bar** — `bootstrapNative()`
hides it, but only if called *before* any `<input>` is focused. Make
sure it's invoked at the top of `main.tsx`.
- **Status bar icons don't match theme on custom themes** — the
bootstrap watches `<html class="…">` and `<style id="theme-vars">` by
default. If your theme mechanism writes CSS variables to a different
element, edit `isBackgroundDark()` in `nativeBootstrap.ts` accordingly.
@@ -0,0 +1,40 @@
import type { CapacitorConfig } from '@capacitor/cli';
// ── Fill in your app identity before running `npx cap add android` / `ios`. ──
// The appId must be a reverse-DNS-style identifier (e.g. `com.example.myapp`)
// and cannot be changed later without re-registering the app with the stores.
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'MyApp',
webDir: 'dist',
server: {
androidScheme: 'https',
iosScheme: 'https',
},
android: {
// Disallow loading mixed-content (http:// inside https://).
allowMixedContent: false,
// Background color shown behind the web view before first paint.
// Usually your app's dark-theme background so the splash feels seamless.
backgroundColor: '#14161f',
},
ios: {
backgroundColor: '#14161f',
// `never` prevents WKWebView from inset-adjusting scroll content — the
// app handles safe-area insets itself in CSS via env(safe-area-inset-*).
contentInset: 'never',
// Custom URL scheme for deep-links (e.g. `myapp://…`) — match this
// in your Info.plist CFBundleURLSchemes.
scheme: 'MyApp',
},
plugins: {
SystemBars: {
// Inject --safe-area-inset-* CSS variables on Android to work around
// a Chromium bug (<140) where env(safe-area-inset-*) reports 0.
insetsHandling: 'css',
},
},
};
export default config;
@@ -0,0 +1,83 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Capacitor } from '@capacitor/core';
/**
* Forwards OS-level deep-link opens into the React Router navigation stack.
*
* When the OS launches your app via a URL (a `https://your-domain.com/post/123`
* universal link or a `myapp://post/123` custom-scheme link), Capacitor fires
* an `appUrlOpen` event. This component listens for it and calls
* `navigate(pathname + search + hash)` so the app lands on the intended
* in-app route instead of staying on whatever page it was on.
*
* Must be rendered **inside** a `<BrowserRouter>` (so `useNavigate` works).
* Safe to render unconditionally — on web it is a no-op.
*
* To enable deep links:
*
* **iOS (Universal Links):**
* 1. Add your domain under *Signing & Capabilities → Associated Domains*
* as `applinks:your-domain.com`
* 2. Host an `apple-app-site-association` file at
* `https://your-domain.com/.well-known/apple-app-site-association`
*
* **iOS (custom scheme):**
* 1. Set `ios.scheme` in `capacitor.config.ts`
* 2. Capacitor already registers the scheme in Info.plist's
* `CFBundleURLSchemes` during `npx cap sync`
*
* **Android (App Links):**
* 1. Declare an `<intent-filter android:autoVerify="true">` with your
* domain in `android/app/src/main/AndroidManifest.xml`
* 2. Host a `assetlinks.json` file at
* `https://your-domain.com/.well-known/assetlinks.json`
*
* **Android (custom scheme):**
* 1. Add an `<intent-filter>` with `<data android:scheme="myapp" />` in
* the manifest
*
* @example
* // In AppRouter.tsx, inside BrowserRouter:
* <BrowserRouter>
* <DeepLinkHandler />
* <ScrollToTop />
* <Routes>...</Routes>
* </BrowserRouter>
*/
export function DeepLinkHandler() {
const navigate = useNavigate();
useEffect(() => {
if (!Capacitor.isNativePlatform()) return;
let cleanup: (() => void) | undefined;
async function setup() {
const { App } = await import('@capacitor/app');
// Handle URLs opened while the app is already running
const listener = await App.addListener('appUrlOpen', (event) => {
try {
const url = new URL(event.url);
const path = url.pathname + url.search + url.hash;
if (path) {
navigate(path);
}
} catch {
// Invalid URL, ignore
}
});
cleanup = () => listener.remove();
}
setup();
return () => {
cleanup?.();
};
}, [navigate]);
return null;
}
@@ -0,0 +1,153 @@
import { useState, useEffect, useRef } from 'react';
import { Capacitor } from '@capacitor/core';
import { secureStorage } from '@/lib/secureStorage';
/**
* Hook for storing sensitive state that should not live in plaintext
* localStorage on native platforms.
*
* - On web: uses `localStorage` (identical to `useLocalStorage`).
* - On native (Capacitor iOS/Android): uses the native Keychain / KeyStore via
* `secureStorage`. Any existing plaintext value in localStorage for the same
* key is migrated on first read and the plaintext copy is removed.
*
* This is async under the hood, so the hook additionally exposes a `ready`
* flag indicating whether the initial load has completed. While `!ready`, the
* state is `defaultValue` and callers should avoid making decisions based on
* an "empty" state (e.g. do not persist a default back if the user has real
* data stored that hasn't been loaded yet).
*
* The return tuple is `[state, setValue, ready]`.
*
* @example
* const [connection, setConnection, ready] = useSecureLocalStorage<string | null>(
* 'nwc:active',
* null,
* );
* if (!ready) return <Spinner />;
* // ...
*/
export function useSecureLocalStorage<T>(
key: string,
defaultValue: T,
serializer?: {
serialize: (value: T) => string;
deserialize: (value: string) => T;
},
) {
const serialize = serializer?.serialize || JSON.stringify;
const deserialize = serializer?.deserialize || JSON.parse;
const isNative = Capacitor.isNativePlatform();
// On web we can read synchronously during initialization (same behavior as
// useLocalStorage). On native we must wait for the async read, so we start
// with defaultValue and flip `ready` once loaded.
const [state, setState] = useState<T>(() => {
if (isNative) return defaultValue;
try {
const item = localStorage.getItem(key);
return item ? deserialize(item) : defaultValue;
} catch (error) {
console.warn(`Failed to load ${key} from localStorage:`, error);
return defaultValue;
}
});
const [ready, setReady] = useState<boolean>(!isNative);
// Track the most-recently-requested key so stale async reads don't clobber
// state after the caller swapped to a different key.
const currentKeyRef = useRef(key);
currentKeyRef.current = key;
useEffect(() => {
let cancelled = false;
async function load() {
try {
if (isNative) {
// Check secureStorage first (handles migration from plaintext
// localStorage internally per secureStorage.getItem).
const item = await secureStorage.getItem(key);
if (cancelled || currentKeyRef.current !== key) return;
setState(item ? deserialize(item) : defaultValue);
} else {
const item = localStorage.getItem(key);
if (cancelled || currentKeyRef.current !== key) return;
setState(item ? deserialize(item) : defaultValue);
}
} catch (error) {
if (!cancelled) {
console.warn(`Failed to load ${key} from secure storage:`, error);
setState(defaultValue);
}
} finally {
if (!cancelled) setReady(true);
}
}
setReady(false);
load();
return () => {
cancelled = true;
};
// defaultValue and deserialize are intentionally excluded — we only want to
// re-read when the key identity changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, isNative]);
const setValue = (value: T | ((prev: T) => T)) => {
const persist = (next: T) => {
try {
const serialized = serialize(next);
if (isNative) {
// Fire-and-forget; errors are logged but shouldn't block the caller.
void secureStorage.setItem(key, serialized).catch((error) => {
console.warn(`Failed to save ${key} to secure storage:`, error);
});
} else {
localStorage.setItem(key, serialized);
}
} catch (error) {
console.warn(`Failed to serialize ${key}:`, error);
}
};
if (value instanceof Function) {
setState((prev) => {
const next = (value as (p: T) => T)(prev);
if (next === prev) return prev;
persist(next);
return next;
});
} else {
setState((prev) => {
if (value === prev) return prev;
persist(value);
return value;
});
}
};
// Sync with cross-tab changes on web. Native secure storage has no
// cross-tab concept.
useEffect(() => {
if (isNative) return;
const handleStorageChange = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
try {
setState(deserialize(e.newValue));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [key, isNative, deserialize]);
return [state, setValue, ready] as const;
}
@@ -0,0 +1,60 @@
import { Capacitor } from '@capacitor/core';
/**
* Download a text file to the user's device.
*
* On the web this uses the classic `<a download>` trick.
* On native (Android & iOS) the file is saved to the app's Documents
* directory, which is visible in the iOS Files app and Android's
* app-scoped documents. No permissions are required.
*
* @example
* await downloadTextFile('backup.json', JSON.stringify(data));
*/
export async function downloadTextFile(filename: string, content: string): Promise<void> {
if (Capacitor.isNativePlatform()) {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem');
// Write straight to Documents — visible in the iOS Files app and
// Android's app-scoped documents. No storage permissions needed.
// NOTE: encoding is required — without it Capacitor expects base64 data
// and will throw for plain-text strings.
await Filesystem.writeFile({
path: filename,
data: content,
directory: Directory.Documents,
encoding: Encoding.UTF8,
});
} else {
// Web: use the anchor-click download pattern
const blob = new Blob([content], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
}
/**
* Open a URL in a new browser tab, or present the native share sheet on Capacitor.
*
* The programmatic `<a target="_blank">` click pattern doesn't work inside
* WKWebView on iOS. On native platforms this presents the share sheet instead,
* letting the user open, save, or share the resource.
*
* @example
* <Button onClick={() => openUrl('https://example.com')}>Visit site</Button>
*/
export async function openUrl(url: string): Promise<void> {
if (Capacitor.isNativePlatform()) {
const { Share } = await import('@capacitor/share');
await Share.share({ url });
} else {
window.open(url, '_blank', 'noopener,noreferrer');
}
}
@@ -0,0 +1,125 @@
import { Capacitor } from '@capacitor/core';
/**
* Centralized haptic feedback utility.
*
* On native (iOS/Android) it uses @capacitor/haptics for true taptic engine
* feedback. On web it falls back to navigator.vibrate() which works on
* Android browsers but is a silent no-op elsewhere.
*
* Each helper is fire-and-forget: errors are swallowed (logged as warnings)
* so calling haptics from UI handlers never disrupts user actions.
*
* @example
* import { impactLight, notificationSuccess } from '@/lib/haptics';
*
* <Button onClick={() => { impactLight(); doThing(); }}>Tap me</Button>
*/
type ImpactStyle = 'Heavy' | 'Medium' | 'Light';
type NotificationType = 'Success' | 'Warning' | 'Error';
// Lazy-loaded Haptics plugin — only imported on native to avoid bundling
// the plugin in web builds where it isn't useful.
let hapticsPromise: Promise<typeof import('@capacitor/haptics')> | null = null;
function getHaptics() {
if (!hapticsPromise) {
hapticsPromise = import('@capacitor/haptics');
}
return hapticsPromise;
}
// ── Helpers ──────────────────────────────────────────────────────────────────
async function nativeImpact(style: ImpactStyle) {
const { Haptics, ImpactStyle } = await getHaptics();
await Haptics.impact({ style: ImpactStyle[style] });
}
async function nativeNotification(type: NotificationType) {
const { Haptics, NotificationType } = await getHaptics();
await Haptics.notification({ type: NotificationType[type] });
}
async function nativeSelectionChanged() {
const { Haptics } = await getHaptics();
await Haptics.selectionChanged();
}
function vibrate(ms: number) {
try {
navigator.vibrate?.(ms);
} catch {
/* Vibration API not available */
}
}
// ── Public API ───────────────────────────────────────────────────────────────
function warnHapticError(label: string, err: unknown) {
console.warn(`[haptics] ${label} failed:`, err);
}
/** Light tap — reactions, reposts, bookmarks, share. */
export function impactLight(): void {
if (Capacitor.isNativePlatform()) {
nativeImpact('Light').catch((e) => warnHapticError('impactLight', e));
} else {
vibrate(10);
}
}
/** Medium tap — zap button press, pull-to-refresh threshold, follow. */
export function impactMedium(): void {
if (Capacitor.isNativePlatform()) {
nativeImpact('Medium').catch((e) => warnHapticError('impactMedium', e));
} else {
vibrate(20);
}
}
/** Heavy tap — game button press, destructive confirmation. */
export function impactHeavy(): void {
if (Capacitor.isNativePlatform()) {
nativeImpact('Heavy').catch((e) => warnHapticError('impactHeavy', e));
} else {
vibrate(30);
}
}
/** Success notification — zap payment success, post published. */
export function notificationSuccess(): void {
if (Capacitor.isNativePlatform()) {
nativeNotification('Success').catch((e) => warnHapticError('notificationSuccess', e));
} else {
vibrate(15);
}
}
/** Warning notification. */
export function notificationWarning(): void {
if (Capacitor.isNativePlatform()) {
nativeNotification('Warning').catch((e) => warnHapticError('notificationWarning', e));
} else {
vibrate(20);
}
}
/** Error notification. */
export function notificationError(): void {
if (Capacitor.isNativePlatform()) {
nativeNotification('Error').catch((e) => warnHapticError('notificationError', e));
} else {
vibrate(30);
}
}
/** Selection changed — toggle switches, tab taps, picker changes. */
export function selectionChanged(): void {
if (Capacitor.isNativePlatform()) {
nativeSelectionChanged().catch((e) => warnHapticError('selectionChanged', e));
} else {
vibrate(5);
}
}
@@ -0,0 +1,121 @@
import { Capacitor, SystemBars, SystemBarsStyle } from '@capacitor/core';
/**
* One-time Capacitor-native bootstrap: configures system chrome to match
* the active CSS theme and hides the iOS keyboard accessory bar.
*
* Call this from `src/main.tsx` **before** `createRoot(...).render(...)`.
* On web this is a no-op.
*
* What it does on native:
*
* 1. Hides the iOS keyboard accessory bar (the prev/next/done toolbar above
* the keyboard) — most apps don't need it and it steals screen space.
*
* 2. Keeps the native system bar icon style (clock, battery, etc.) in sync
* with the active CSS theme. When the app is on a dark background, icons
* are rendered light; on a light background, dark. This is re-applied
* whenever:
* - the `class` on `<html>` changes (light / dark / any custom theme
* that toggles a class, e.g. your AppProvider)
* - the contents of `<style id="theme-vars">` change (custom themes
* that set CSS variables without toggling a class)
*
* Uses `SystemBars` (exposed by the Capacitor-core plugin registry). On
* Android 16+ (API 36) setBackgroundColor on the bars no longer works — the
* bars are transparent and the web content renders behind them. Your app
* should draw its own safe-area backgrounds in CSS. Only icon style matters
* here.
*
* @example
* // src/main.tsx
* import { bootstrapNative } from '@/lib/nativeBootstrap';
* bootstrapNative();
* createRoot(document.getElementById('root')!).render(<App />);
*/
export function bootstrapNative(): void {
if (!Capacitor.isNativePlatform()) return;
// iOS-only: hide the keyboard accessory bar.
if (Capacitor.getPlatform() === 'ios') {
import('@capacitor/keyboard').then(({ Keyboard }) => {
Keyboard.setAccessoryBarVisible({ isVisible: false }).catch(() => {});
}).catch(() => {});
}
/**
* SystemBarsStyle.Dark = light/white icons (use on dark backgrounds)
* SystemBarsStyle.Light = dark/black icons (use on light backgrounds)
*/
function updateStatusBar() {
const isDark = isBackgroundDark();
SystemBars.setStyle({
style: isDark ? SystemBarsStyle.Dark : SystemBarsStyle.Light,
}).catch(() => {});
}
// Apply immediately. The theme class is usually set synchronously by the
// AppProvider useLayoutEffect before the first React paint, but we still
// try early in case it's already set.
updateStatusBar();
// Re-apply whenever the theme class changes on <html>.
const classObserver = new MutationObserver(() => updateStatusBar());
classObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
// Re-apply whenever the injected <style id="theme-vars"> content changes
// (covers custom themes that change CSS variables without changing the
// class).
const styleObserver = new MutationObserver(() => updateStatusBar());
const observeThemeVars = () => {
const el = document.getElementById('theme-vars');
if (el) {
styleObserver.observe(el, {
characterData: true,
childList: true,
subtree: true,
});
}
};
observeThemeVars();
// The style element may not exist yet — watch <head> for it to appear.
const headObserver = new MutationObserver(() => observeThemeVars());
headObserver.observe(document.head, { childList: true });
}
/**
* Detect whether the current app background is "dark" for the purposes of
* choosing status-bar icon color.
*
* Strategy (first match wins):
* 1. If `<html>` has class `dark`, return true.
* 2. If `<html>` has class `light`, return false.
* 3. Parse the computed `background-color` of `<body>` and compare its
* perceived luminance against 0.5.
*
* Steps 1 and 2 cover the default mkstack theme system. Step 3 covers
* custom themes that don't toggle the `light`/`dark` class on `<html>`.
*/
function isBackgroundDark(): boolean {
const cl = document.documentElement.classList;
if (cl.contains('dark')) return true;
if (cl.contains('light')) return false;
const bg = getComputedStyle(document.body).backgroundColor;
const rgb = parseRgb(bg);
if (!rgb) return false;
// Perceived luminance (ITU-R BT.709).
const [r, g, b] = rgb.map((c) => c / 255);
const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return lum < 0.5;
}
function parseRgb(color: string): [number, number, number] | null {
const m = color.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
if (!m) return null;
return [Number(m[1]), Number(m[2]), Number(m[3])];
}
@@ -0,0 +1,71 @@
import { Capacitor } from '@capacitor/core';
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';
/**
* Storage adapter that uses native secure storage (iOS Keychain / Android
* KeyStore) on Capacitor builds and falls back to localStorage on web.
*
* API is async-compatible with the Web Storage interface (`getItem`,
* `setItem`, `removeItem`) — each method returns a Promise.
*
* On the first native read, if a key is not found in secure storage but
* exists in localStorage, it is automatically migrated to secure storage
* and the plaintext localStorage copy is removed. This means shipping a
* Capacitor build of an app that previously wrote to localStorage will
* transparently upgrade existing users' secrets to the Keychain/KeyStore
* the first time the app reads them.
*
* Use this for any sensitive state you don't want in plaintext on device:
* - NWC (Nostr Wallet Connect) connection strings
* - Device-specific push notification keys
* - Encryption passphrases / derived keys
* - Any cached credential you'd otherwise have to re-prompt for
*
* @example
* await secureStorage.setItem('nwc:active', 'nostr+walletconnect://…');
* const conn = await secureStorage.getItem('nwc:active');
*/
export const secureStorage = {
async getItem(key: string): Promise<string | null> {
if (!Capacitor.isNativePlatform()) {
return localStorage.getItem(key);
}
try {
const { value } = await SecureStoragePlugin.get({ key });
return value;
} catch {
// Key not found in secure storage — check localStorage for migration.
const legacy = localStorage.getItem(key);
if (legacy !== null) {
// Migrate to secure storage and remove the plaintext copy.
await SecureStoragePlugin.set({ key, value: legacy });
localStorage.removeItem(key);
return legacy;
}
return null;
}
},
async setItem(key: string, value: string): Promise<void> {
if (!Capacitor.isNativePlatform()) {
localStorage.setItem(key, value);
return;
}
await SecureStoragePlugin.set({ key, value });
},
async removeItem(key: string): Promise<void> {
if (!Capacitor.isNativePlatform()) {
localStorage.removeItem(key);
return;
}
try {
await SecureStoragePlugin.remove({ key });
} catch {
// Key didn't exist — ignore.
}
},
};
@@ -0,0 +1,53 @@
/* ─────────────────────────────────────────────────────────────────────────
* Safe-area inset utilities
*
* Append this block inside the `@layer utilities { … }` section of your
* `src/index.css` file (or import this file from your main stylesheet).
*
* Uses var(--safe-area-inset-*, …) as the outer wrapper so that
* Capacitor's SystemBars plugin (which injects --safe-area-inset-* CSS
* variables on Android to work around a Chromium <140 bug where
* env(safe-area-inset-*) reports 0) takes precedence when available. The
* inner env(safe-area-inset-*, 0px) is the standard fallback for iOS and
* for modern web browsers.
*
* Usage examples:
*
* <header className="sticky top-0 safe-area-top bg-background">…</header>
* <nav className="fixed bottom-0 safe-area-bottom">…</nav>
* <Toaster className="safe-area-inset-top" />
*
* Don't forget the matching viewport meta in index.html:
*
* <meta name="viewport" content="width=device-width, initial-scale=1,
* viewport-fit=cover, interactive-widget=resizes-content" />
*
* Without `viewport-fit=cover`, iOS won't expose the safe-area insets.
* ───────────────────────────────────────────────────────────────────────── */
.safe-area-top {
padding-top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px));
}
.safe-area-bottom {
padding-bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
}
.safe-area-left {
padding-left: var(--safe-area-inset-left, env(safe-area-inset-left, 0px));
}
.safe-area-right {
padding-right: var(--safe-area-inset-right, env(safe-area-inset-right, 0px));
}
/* Positional variants — apply the inset as `top` / `bottom` rather than padding.
Use these for absolutely/fixed-positioned overlays (e.g. a toast stack that
hugs the top of the screen). */
.safe-area-inset-top {
top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px));
}
.safe-area-inset-bottom {
bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
}
@@ -0,0 +1,56 @@
#!/usr/bin/env node
/**
* Patch capacitor.config.json to include local (non-SPM) plugin classes.
*
* `npx cap sync` regenerates the `packageClassList` array from SPM packages
* only, so local plugins compiled directly into the app binary (like a
* custom SandboxPlugin) are not included. This script appends them after
* sync so the Capacitor bridge eagerly registers them at startup.
*
* Usage: node scripts/patch-cap-config.mjs
* Typically run after `npx cap sync` (wire it into an npm script, e.g.:
* "cap:sync": "npx cap sync && node scripts/patch-cap-config.mjs"
* ).
*
* Edit the LOCAL_PLUGINS array below to match the class names of any
* custom native plugins you've added to your android/ios projects.
*/
import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';
/** Local plugin class names to ensure are registered. */
const LOCAL_PLUGINS = [
// 'MyCustomPlugin',
];
const platforms = ['ios/App/App', 'android/app/src/main/assets'];
for (const platform of platforms) {
const configPath = resolve(platform, 'capacitor.config.json');
let config;
try {
config = JSON.parse(readFileSync(configPath, 'utf-8'));
} catch {
// Platform may not exist or config not yet generated — skip.
continue;
}
const classList = new Set(config.packageClassList ?? []);
let changed = false;
for (const plugin of LOCAL_PLUGINS) {
if (!classList.has(plugin)) {
classList.add(plugin);
changed = true;
}
}
if (changed) {
config.packageClassList = [...classList];
writeFileSync(configPath, JSON.stringify(config, null, '\t') + '\n');
console.log(`Patched ${configPath}: added ${LOCAL_PLUGINS.join(', ')}`);
}
}