mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 08:47:23 +00:00
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.
154 lines
5.0 KiB
TypeScript
154 lines
5.0 KiB
TypeScript
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;
|
|
}
|