Repository navigation
refactor(platform): cross-platform primitives + migrate ~50 call-sites (iOS crash fix) - #249
Conversation
…50 call-sites
Adds `@scf/core/utils/platform/*` — a set of Metro platform-extension
primitives that replace scattered `Platform.OS === 'web'` branches and
unguarded `window.*` / `document.*` / `localStorage` access throughout
feature code. The original symptom that prompted this audit was an iOS
ErrorBoundary crash from `window.addEventListener is not a function`
in profile screens (`window` exists on RN as the global object, so
`typeof window === 'undefined'` guards silently failed).
## New primitives (each as .ts shared shape + .web.ts + .native.ts)
- `openExternalLink(url, { inApp? })` — `window.open` / `Linking.openURL`
(plus optional `expo-web-browser` in-app browser on native).
- `useUnsavedChangesPrompt(isDirty)` — replaces the 4× duplicated
`beforeunload` `useEffect` block in profile screens. Native attaches
`navigation.addListener('beforeRemove', ...)` for a native Alert.
- `confirmDialog({ title, message, destructive? })` — promise-wrapped
`window.confirm` / `Alert.alert` (so native no longer silently
no-ops).
- `kvStorage` (localStorage / AsyncStorage) + `sessionKvStorage`
(sessionStorage / in-memory Map) — async key/value with consistent
shape across both platforms.
- `downloadFile({ url, filename })` — anchor-click trick on web,
`Linking.openURL` on native.
- `pickFile({ accept, multiple? })` — hidden file-input on web,
`expo-document-picker` on native; returns a uniform `PickedFile[]`.
- `getCanonicalUrl(path)` — `${origin}${path}` on web, `undefined` on
native (SEO is a web-only concept).
- `setDocumentTitle(title)` — `document.title =` on web, no-op on
native (use `navigation.setOptions({ title })`).
- `reloadPage()` — `window.location.reload()` on web, no-op on native
(callers should `queryClient.invalidateQueries` for parity).
## Migrations (~50 files)
- 12× `window.open` → `openExternalLink` (profile certifications,
discover modals/hover cards, privacy, news, admin background checks,
oauth consent).
- 4× `beforeunload` `useEffect` blocks → `useUnsavedChangesPrompt`
(profile education/experience/general/skills + `useSaveStatus`).
- `window.confirm` in TasksDetail + DeveloperPortal → `confirmDialog`.
- `window.location.href` in AccountSwitcher + admin cms → `router.push`
/ `reloadPage`; oauth ConsentScreen → `openExternalLink`.
- `localStorage` / `sessionStorage` direct access in MapStateProvider,
ProfileCompletion, useCompletionNudges, oauth/passthrough,
feedbackStorage, UniversalThemeProvider → `kvStorage` /
`sessionKvStorage`.
- File-download anchor tricks in payments + ConnectionsList →
`downloadFile`.
- File-picker `<input type=file>` + `document.getElementById().click()`
in profile certifications → `pickFile`.
- Canonical-URL builders in `apps/scaffald/(public)/jobs/[slug]` and
IPIP share results → `getCanonicalUrl`.
- `document.title` writes in `usePageTitle` web branch + JobSeoHead →
`setDocumentTitle`.
## Platform-extension splits (companion to packages/ui PR)
- `useUserLocation` split into shared `.ts` shape + existing `.native.ts`
+ new `.web.ts` (was a single `.ts` doing runtime branching).
- `packages/ui` submodule bump to include the parallel
`useSidebarState` and `useAccessibilityInfo` splits (see Scaffald/ui#3).
## Other clean-ups
- Removes `hooks/useSafeToast.ts` — was a defensive wrapper around an
old beyond-ui toast bug (string-matching error messages). Sole
consumer (`profile-general-left`) now uses `useToast` directly.
- Collapses `publicProfileUrl.openPublicProfileInNewTab` into a thin
wrapper around `openExternalLink`.
## Guardrail
- New `scripts/check-platform-leakage.sh` + `pnpm lint:platform` flags
browser-DOM/BOM API use outside platform-extension files. Wired into
`pnpm lint:affected`. 5 surviving call-sites are annotated with
`// platform-allow: <reason>` (web-only debug flags, web-only map
pins, etc.) — see the script for the allow-list rules.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
The root package.json defines `build` as `pnpm locales:validate && nx run-many -t build --exclude=@scaffald/ui-docs`. Nx's @nx/js auto-discovery picks up that script and adds a `build` target on the root `scaffald` project itself. When `nx run-many -t build` runs, it sees the root project as a candidate, invokes its `build` target (which calls `pnpm build` again), and recurses without bound — each pass forks a new `pnpm` + `sh` + `nx run-many` + `run-executor` quartet. A single `pnpm prepush` ballooned to 260+ processes within three minutes during this branch's push attempt. Fix by excluding the root project from the recursive invocations: - `affected:build`: `--exclude=scaffald` - `build`: `--exclude=@scaffald/ui-docs,scaffald` - `prepush`: `--exclude=scaffald` on the affected-build leg and `--exclude=...,scaffald` on the test leg The root project never had a useful build artifact — its `build` script is an orchestrator, not a build target — so excluding it from the run-many sweep is the right thing regardless of the fork bomb fix. Co-Authored-By: Claude Opus 4.7 <[email protected]>
The bottom toolbar's floating glass buttons conflicted with the bottom tab navigator. Desktop search/sort via PageHeader is unchanged. Co-Authored-By: Claude Opus 4.7 <[email protected]>
`apps/web/.next/` (91MB build cache) and `apps/web/next-env.d.ts` (auto-regenerated by every `next build`) were leaking into `git status` after `pnpm prepush` ran. Neither has ever been tracked. Add both to the root `.gitignore` so they stop tripping `gh pr create`'s uncommitted-changes warning. `next-env.d.ts` is regenerated on demand by Next.js so ignoring it costs nothing. Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2f38d5252f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| consentUrl.searchParams.set('code_challenge_method', pendingAuth.code_challenge_method) | ||
|
|
||
| window.location.href = consentUrl.toString() | ||
| openExternalLink(consentUrl.toString()) |
There was a problem hiding this comment.
Keep pending OAuth continuation in same tab
continueOAuthFlowIfPending() is called during app bootstrap from a useEffect (see apps/scaffald/app/index.tsx), not from a direct user gesture. Switching this redirect to openExternalLink() means web now uses window.open(..., '_blank'), which popup blockers can deny in that context; the function still returns true, so bootstrap skips normal routing and the user can be left on the wrong screen instead of being navigated to /oauth/consent. This redirect should use same-tab navigation (location.href/location.assign) rather than the external-link primitive.
Useful? React with 👍 / 👎.
| // Redirect to client app | ||
| if (result.redirect_url) { | ||
| window.location.href = result.redirect_url | ||
| openExternalLink(result.redirect_url) |
There was a problem hiding this comment.
Use same-tab redirect after OAuth consent completion
After grantConsent resolves, this now calls openExternalLink(result.redirect_url), which opens a new tab on web instead of replacing the current authorization tab and may be popup-blocked after the async boundary. OAuth authorization flows expect the current user-agent context to be redirected to the client callback URL; opening a separate tab can leave the consent tab stranded and break client-side completion logic. Use a same-tab redirect API here (and in the deny branch) instead of openExternalLink.
Useful? React with 👍 / 👎.
Summary
@scf/core/utils/platform/*— a set of Metro platform-extension primitives (.web.ts/.native.tsresolved at build time) that replace scatteredPlatform.OS === 'web'branches and unguarded browser-API access in feature code.scf-coreandapps/scaffaldonto the new primitives. Net delta is negative (LOC removed > LOC added in feature code).pnpm lint:platformas a guardrail to prevent regression.nx/pnpmfork-bomb inprepushthat surfaced while validating this branch.apps/web/.next/andapps/web/next-env.d.tsto.gitignore.Why this exists
The original symptom was an iOS
ErrorBoundarycrash in the profile screens:Root cause: on React Native iOS,
windowexists as the global object — so the common defensive guardif (typeof window === 'undefined') returnsilently fails, and the next line crashes when it tries to call a DOM API likewindow.addEventListener. The same pattern was duplicated across four profile files plususeSaveStatus.Rather than just adding
Platform.OS !== 'web'checks at each call-site, we built a small set of cross-platform primitives that own the divergence once, so feature code never sees a runtime branch.Commits
95c13d40f2f38d5252nx run-many -t build(cherry-pickable)4555fd56e2fc5fabcaapps/webNew primitives
Each is a Metro platform extension: shared
.ts(types + a throwing default for static analysis),.web.ts(browser impl),.native.ts(iOS/Android impl).openExternalLink(url, { inApp? })window.openLinking.openURL(+ optionalexpo-web-browser)useUnsavedChangesPrompt(isDirty)beforeunloadlistenernavigation.addListener('beforeRemove', …)→ AlertconfirmDialog({ title, message, destructive? })window.confirmwrapped in a PromiseAlert.alertresolving the promisekvStoragelocalStorage(async wrapper)AsyncStoragesessionKvStoragesessionStorage(sync)Map(process-lifetime)downloadFile({ url, filename })<a download>clickLinking.openURLpickFile({ accept, multiple? })<input type=file>expo-document-pickergetCanonicalUrl(path)${origin}${path}undefinedsetDocumentTitle(title)document.title =navigation.setOptions)reloadPage()window.location.reload()queryClient.invalidateQueries)Migrations
Cat A —
window.open(12 sites): profile certifications, discover hover cards / preview modals, privacy dashboard, news widgets, admin background-check viewer, oauth consent. All now route throughopenExternalLink— includingapps/scaffald/.../dashboard/news/index.tsxwhich previously had its ownPlatform.OS === 'web' ? window.open : WebBrowser.openBrowserAsyncladder.Cat B —
beforeunload(4 sites):useSaveStatus,profile-education-left,profile-experience-left,profile-general-left. Each 12-lineuseEffectblock collapses touseUnsavedChangesPrompt(isDirty).useSaveStatus.tswas the worst offender — completely unguarded, would crash on iOS any time the skills page mounted.Cat C — confirms:
TaskDetailScreenandDeveloperPortalmigrated toconfirmDialog. Both now show a real Alert on native instead of silently no-opping the destructive action.Cat D — navigation/reload:
AccountSwitcher'sPlatform.OS === 'web' ? window.location.href : router.replacebranch collapses torouter.replace + reloadPage. PrivacyDashboard / office-ccpa-dashboard retry buttons usereloadPage. OAuthConsentScreenredirects viaopenExternalLink. The admin CMS project page now usesrouter.pushinstead ofwindow.location.href.Cat E — storage:
MapStateProvider,feedbackStorage,UniversalThemeProviderall migrated tokvStorage.ProfileCompletion/useCompletionNudges/oauth/passthroughmigrated tosessionKvStorage.useSidebarState(in @scaffald/ui — see companion PR) split into.web.ts(sync localStorage) +.native.ts(async AsyncStorage hydrate).Cat F — file IO: payments transaction export, connections CSV export migrated to
downloadFile. Profile-certifications file pickers +CertificationProofCard's inline<input type=file>migrated topickFile.Cat G — SEO:
apps/scaffald/(public)/jobs/[slug]canonical URL viagetCanonicalUrl.JobSeoHeadandusePageTitle's web branch viasetDocumentTitle. IPIPShareResultsshare URL viagetCanonicalUrl.Misc cleanups:
hooks/useSafeToast.ts— defensive wrapper that string-matched error messages to catch a now-fixed beyond-ui bug. Sole consumer migrated touseToastdirectly.publicProfileUrl.openPublicProfileInNewTabcollapses into a thin wrapper aroundopenExternalLink.discover/hooks/useUserLocation: pre-existing.ts+.native.tspair → proper shared.tsshape +.web.ts+.native.ts.api-keys+ Stripe settings clipboard usage to existingcopyToClipboardutility.Companion: fork-bomb fix in
prepushWhile running
pnpm prepushto validate this branch, the script ran away to 260+ processes in 3 minutes. Root cause:nx's @nx/js auto-discovery promotes every npm script to an nx target. The rootpackage.jsonhas abuildscript that itself invokesnx run-many -t build, so whennx run-manyincludes the root project, it executespnpm build→ which recurses. Fixed by excluding the rootscaffaldproject fromaffected:build,build, andprepush. Independent commit, cherry-pickable:2f38d5252.Communities mobile toolbar removal
4555fd56e— drops the floating glass search/sort toolbar (CommunitiesBottomToolbar) fromCommunitiesHubPage. The toolbar was visually conflicting with the bottom tab navigator on mobile. Desktop search/sort viaPageHeaderis unchanged..gitignore additions
2fc5fabca— adds**/.next/and**/next-env.d.tsto the root.gitignore. The 91MB Next.js build cache was leaking intogit statusafterpnpm prepushrannext build, trippinggh pr create's uncommitted-changes warning.next-env.d.tsis auto-regenerated on every build, so ignoring it costs nothing.Guardrail
New script
scripts/check-platform-leakage.sh(wired in viapnpm lint:platform, also added topnpm lint:affected) scans for browser-DOM/BOM usage in shared code. The allow-list captures the platform-primitive module itself, declared cross-platform utility shims (clipboard.ts,clearAuthStorage.ts, etc.), and any line annotated// platform-allow: <reason>. Final state: ✅ clean.Test plan
pnpm -F @scf/core exec tsc --noEmit— cleanpnpm -F @scaffald/ui exec tsc --noEmit— cleanpnpm -F scaffald exec tsc --noEmit— cleanpnpm -F @scf/core lint/pnpm -F scaffald lint— pass (11 pre-existing warnings unchanged)pnpm lint:platform— cleanpnpm prepush— completes without fork bomb (stamps HEAD as expected)LinkinguseResponsive,useToast,Popover,Sheetetc. unaffected (no edits to those primitives)🤖 Generated with Claude Code