Skip to content
Repos

DevPlaceApp

Markdown 35.6 KB300 lines Opens in site

Directory Raw Download

DevPlaceIOS shell inventory

Source root: DevPlaceIOS/DevPlaceIOS/ (abbreviated R/). Citations are file:line. Scope: app entry, delegate, state, stores, push, request layer, util, navigation, shared UI utils, Main/LogIn/SignUp/Settings screens, Template, plist/entitlements/assets. Feed/Messages/Notifications/Post/Profile/CreatePost/Conversation screens and UI/Components/* are out of scope here (only the pieces this shell uses are described: BoxView, CharacterCounterView, styles).

Platform facts (from DevPlaceIOS.xcodeproj/project.pbxproj): iOS deployment target 26.0 (lines 211, 269), Swift 6.0 (311), bundle id wok.DevPlaceIOS (304), marketing version 1.1.0 (303), display name DevPlace (291), category public.app-category.social-networking (293), iPhone orientations portrait + landscape left/right (298), ITSAppUsesNonExemptEncryption = NO (292), launch screen auto-generated (296). Backend base URL https://devplace.net/ (DevPlaceSwiftSDK/Sources/DevPlaceSwiftSDK/DevPlace/DevPlaceBackend.swift:4); WebSocket URL replaces https:// with wss:// (DevPlaceSwiftSDK.swift:528-530).

1. App entry: R/DevPlaceIOSApp.swift

  • @main struct DevPlaceIOSApp: App (3-4). Adapts AppDelegate via @UIApplicationDelegateAdaptor (5). Holds @State appSettings = AppSettingsStore.shared (6).
  • init() (8-22), runs once at launch, fire-and-forget Tasks:
    1. api = .prod (10).
    2. If keychain has both email and password (12): api.logIn(email,password) then AppState.shared.loadFeed(api) sequentially in one Task (13-16). Errors from the Task are thrown and swallowed (Task result never observed): if login fails, the feed is NOT loaded.
    3. Else (17-20): AppState.shared.loadFeed(api) as anonymous.
  • Scene (24-29): WindowGroup { MainView().preferredColorScheme(appSettings.appearance.colorScheme) }. .system -> nil (follow OS), .light, .dark.
  • Default appearance is dark (AppSettingsStore.swift:71).

2. R/Push/AppDelegate.swift (the only AppDelegate)

final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate (4).

  • didFinishLaunchingWithOptions (5-11): sets UNUserNotificationCenter.current().delegate = self; returns true.
  • didRegisterForRemoteNotificationsWithDeviceToken (13-18): forwards to PushNotificationManager.shared.didRegisterForRemoteNotifications(deviceToken:).
  • didFailToRegisterForRemoteNotificationsWithError (20-25): forwards to manager (logs only).
  • didReceiveRemoteNotification(userInfo) async (27-33): awaits manager.handleRemoteNotification(userInfo), returns .newData.
  • willPresent notification (35-41): awaits handleRemoteNotification(userInfo of notification); returns [.banner, .badge, .sound] (foreground notifications are shown with banner, badge and sound).
  • didReceive response (43-48): awaits manager.handleNotificationTap(userInfo).

3. R/Push/PushNotificationManager.swift

@MainActor final class, singleton .shared, private init (5-9). State: api (default .prod, 11), deviceTokenHex: String? (12, in memory only, not persisted).

  • registerForPushNotifications(api) (14-19): store api; requestAuthorization(); UIApplication.shared.registerForRemoteNotifications(); sendDeviceTokenToBackend(). Called from MainView at launch when logged in (MainView.swift:130-135) and on login transition (136-141).
  • requestAuthorization (61-69): UNUserNotificationCenter.requestAuthorization(options: [.alert,.badge,.sound]); logs Push authorization granted: <bool> or Push authorization request failed: <error>. No in-app rationale UI.
  • didRegisterForRemoteNotifications(deviceToken) (33-39): hex = each byte %02x joined, lowercase; logs Registered for APNs with device token: <hex>; then sendDeviceTokenToBackend() in a Task.
  • didFailToRegisterForRemoteNotifications (41-43): logs Failed to register for APNs: <error>.
  • sendDeviceTokenToBackend (71-80): guard AppState.shared.isLoggedIn and hex non-nil, else silent return; api.registerPushDevice(deviceToken:); on error logs Failed to register push device with backend: <error>. SDK call: registerPushDevice(provider: .apns, deviceToken:, token:) (ProdDevPlaceApi.swift:289-295).
  • unregisterForPushNotifications(api) (21-31): if hex exists calls api.unregisterPushDevice; error logged Failed to unregister push device: <error>; then updateAppIconBadge(0). Prod unregisterPushDevice is a no-op after login+refresh check (297-305; backend has no unsubscribe endpoint, TODO).
  • handleRemoteNotification(userInfo) (49-52): logs Received push notification payload: <pretty JSON, sorted keys, or String(describing:)> (90-97), then AppState.loadUnreadCounts(api). Payload carries no badge number; counts are refetched on every push (TODO at 45-48).
  • handleNotificationTap(userInfo) (54-59): same refresh, then if conversationUid(in:) non-nil sets AppState.shared.pendingConversationUid.
  • conversationUid (99-108): reads userInfo["url"] string, URLComponents, requires path contains "messages", takes query item with_uid, non-empty.
  • updateAppIconBadge(count) (82-88): UNUserNotificationCenter.setBadgeCount(count); error logged Failed to set app icon badge count: <error>.
  • Entitlement aps-environment = development (R/DevPlaceIOS.entitlements:5-6). No UIBackgroundModes key in build settings or Info.plist.

4. R/AppState/*

AppState.swift (@Observable @MainActor final class, singleton)

Fields (12-24): token: AuthToken?, isLoggedIn = token != nil (14), currentUser: User?, feed: Feed?, unreadNotificationCount = 0, unreadMessageCount = 0, pendingConversationUid: String?.

  • isCurrentUser(id) (26-28): currentUser?.id == id.
  • loadFeed(api) (30-33): feed = api.feed() (first page) then loadUnreadCounts. Throws on feed failure.
  • loadUnreadCounts(api) (35-44): api.notificationCounts(); sets unreadNotificationCount = counts.notifications, unreadMessageCount = counts.messages; PushNotificationManager.updateAppIconBadge(unreadNotificationCount) (icon badge = notifications only, not messages); error logged Failed to load unread counts: <error>. When not logged in the prod call throws notLoggedIn and is swallowed.
  • loadUnreadNotificationCount (46-48): alias.
  • conversationUser(withUid, api) (50-57): api.messages(withUid:).otherUser; nil on error with log Failed to resolve conversation user for uid <uid>: <error>.
  • loadMoreFeed(api) (59-81): needs feed and nextCursor, else return. api.feed(before: cursor). Duplicates (by post.id) are dropped and logged load-more in feed returned duplicate post from backend: <id>. New Feed = existing posts + new posts; all other fields (currentTab, currentTopic, search, nextCursor, totalMembers, postsToday, totalProjects, totalGists, topAuthors) taken from the next page.
  • clear() (83-90): token, feed, currentUser = nil; both counts 0; pendingConversationUid nil.

AppState+Vote.swift

  • updatePostVoteInFeed(postId, vote, count) (4-44): replaces the matching post with data.stars = count, myVote = vote, all else identical; no-op if feed nil or post absent.
  • updateCommentVoteInFeed(commentId, vote) (46-52): applies recentComments.updatingVote to every post.
  • performVoteToggle(targetType,targetId,currentVote,api,apply) (58-73): newVote = currentVote == .up ? .none : .up; apply(newVote) optimistically; api.vote(..., vote: .up) (always sends .up, backend toggles); on error apply(currentVote) and log Double-tap vote failed: <error>. No user alert.

AppState+React.swift

  • updatePostReactionInFeed(postId, emoji) (4-12): post.replacingReactions(reactions.toggling(emoji)).
  • updateCommentReactionInFeed(commentId, emoji) (14-20).
  • performReactionToggle(targetType,targetId,emoji,api,apply) (25-39): apply() optimistic, api.react, on error apply() again (toggle back), log Reaction toggle failed: <error>. No alert.

5. R/Stores/*

AppSettingsStore (@Observable, singleton, UserDefaults.standard)

Every property writes to UserDefaults in didSet. Keys and defaults (init 69-79):

Key Type Default Notes
appearance String raw of system/light/dark dark (invalid or missing gives dark) 10, 70-71
showFeedAttachments Bool true 11, 72
showFeedComments Bool true 12, 73
showReportButtons Bool true 13, 74
recentEmojis [String] [] 14, 75; cap maxRecentEmojis = 30 (19)
draftPostTitle String "" 15, 76
draftPostMessage String "" 16, 77
draftReplyMessage String "" 17, 78
  • recordEmojiPick(emoji) (81-85): remove existing occurrence, insert at index 0, truncate to 30.
  • AppearanceMode titles (96-102): "System", "Light", "Dark"; allCases order system, light, dark. colorScheme: nil / .light / .dark.

UserSessionStore (@Observable, singleton)

  • Keychain via SwiftKeychainWrapper, serviceName: "DevPlace" (11). Keys "email" and "password" (13-14). Values are JSON-encoded (JSONEncoder of the String) then stored as Data (72-80), accessibility .whenUnlockedThisDeviceOnly, not synchronizable. Decode failure returns nil (58-70).
  • Setting nil removes the key (31, 51). Set failure logs Error: failed to store <key> in keychain.
  • The plaintext password is stored so the token can be silently re-obtained; there is no refresh token.

6. R/Request/**

DevPlaceApi protocol (API/DevPlaceApi.swift)

Methods (4-42): logIn, signUp, deleteAccount, feed(before), postDetail(slug), createPost, editPost, deletePost, deleteComment, editComment, createComment, profile(username?), follow/unfollow/block/unblock/mute/unmute(username), messages(withUid?), sendMessage, makeMessagesSocket(otherUserId), usersForMentioning(matching), notifications(before), openNotification(uid), notificationCounts, markNotificationRead(uid), markAllNotificationsRead, registerPushDevice, unregisterPushDevice, vote, submitPollChoice, react, reportReasons, report, uploadFile, uploadFromUrl, deleteAttachment. Convenience overloads feed(), notifications(), messages() pass nil (45-55).

Token refresh (refreshTokenIfNeeded, 65-72): if AppState.token exists and token.willExpireSoon then re-login with stored keychain credentials (logInWithStoredCredentials 57-63; silently returns if none stored) and log Refreshed token which was about to expire soon. willExpireSoon = expireTime.timeIntervalSinceNow < 3600 (SDK AuthToken.swift:15-18); token expireTime = now + expires_in seconds (AuthToken.CodingData.decoded). The log line prints even when no stored credentials exist and nothing was refreshed. Refresh happens before each request, never on a 401, with no lock (parallel requests can each re-login).

Environment (DevPlaceApi+Environment.swift): SwiftUI key \.api, default .prod (3-5, 7-11). Screens read @Environment(\.api); previews inject .mock.

ProdDevPlaceApi (API/ProdDevPlaceApi.swift)

Singleton .shared (11); logger = DevPlaceRequestLogger(), request = DevPlaceRequest(requestLogger:) (13-18, SDK client). DevPlaceApi.prod static accessor (4-8). Pattern for every authenticated method: guard AppState.shared.token else throw DevPlaceError.notLoggedIn ("Not logged in"); refreshTokenIfNeeded(); call SDK with the token captured BEFORE the refresh (so the first call after a refresh can use the stale token; methods that read the token after the refresh are feed, postDetail, profile, messagesWebSocketURL). No error mapping inside the API: errors propagate to view models, which map via AlertMessage (section 9).

Method SDK call Token handling AppState effect
logIn (20-24) getAuthToken(email,password) then getProfile(username:nil, token:).user none required sets token; sets currentUser via try? (profile failure leaves currentUser nil, login still succeeds)
signUp (26-28) signUp(username,email,password,confirmPassword,birthDate,acceptTerms) none none
deleteAccount (30-36) deleteAccount(username,password,token) needs token and currentUser.username else notLoggedIn; refresh after capture none (caller logs out)
feed (38-41) getFeed(before,token: optional) refresh, token optional (anonymous OK) none
postDetail (43-46) getPost(slug,token: optional) refresh, optional none
createPost (48-54) createPost(title,topic,content,attachments,pollQuestion,pollOptions,projectLink,token) required none
editPost (56-62) editPost(slug,title,topic,content,projectLink,token) required none
deletePost (64-70) deletePost(slug,token) required none
deleteComment (72-78) deleteComment(uid,token) required none
editComment (80-86) editComment(uid,content,token) required none
createComment (88-94) createComment(targetType,targetId,content,parentId,attachments,token) required none
vote (96-102) vote(targetType,targetId,vote,token) required none
submitPollChoice (104-110) submitPollChoice(pollId,optionId,token) required none
react (112-118) react(targetType,targetId,emoji,token) required none
reportReasons (120-122) getReportReasons() no token, no refresh none
report (124-130) report(targetType,targetId,reason,detail,token) required none
uploadFile (132-138) uploadFile(data,filename,mimeType,token) returns UploadResponse required none
uploadFromUrl (140-146) uploadFromUrl(url,filename,token) required none
deleteAttachment (148-154) deleteAttachment(uid,token) required none
follow/unfollow/block/unblock/mute/unmute (156-202) followUser/unfollowUser/blockUser/unblockUser/muteUser/unmuteUser(username,token) required none
messages (204-210) getMessages(withUid,token) required none
sendMessage (212-218) sendMessage(receiverId,content,attachments,token) required none
makeMessagesSocket (220-224) builds LiveMessagesSocket(receiverUid:) with a URL provider provider (226-239) checks token, refreshes, re-reads token, getMessagesWebSocketTicket(token), then messagesWebSocketURL(ticket: ticket.ticket); nil URL throws DevPlaceError.invalidUrl(ticket.ticket) none
usersForMentioning (241-247) searchMessageRecipients(q:token) required none
notifications (249-255) getNotifications(before,token) required none
openNotification (257-263) openNotification(uid,token) returns NotificationOpen (ok, redirect) required none
notificationCounts (265-271) getNotificationCounts(token) required none
markNotificationRead (273-279) markNotificationRead(uid,token) required none
markAllNotificationsRead (281-287) markAllNotificationsRead(token) required none
registerPushDevice (289-295) registerPushDevice(provider: .apns, deviceToken, token) required none
unregisterPushDevice (297-305) none (TODO, no backend endpoint) requires token, refresh none
profile (307-319) getProfile(username,token) refresh; with username: token optional; without (own profile): token required else notLoggedIn none

MockDevPlaceApi (API/MockDevPlaceApi.swift)

Singleton, DevPlaceApi.mock (4-12). mockDelay(d = 1s) sleeps (15-17). Every method sleeps then calls refreshTokenIfNeeded() (no-op unless token near expiry). Delays: logIn 1 s, signUp 1 s, feed 1 s, postDetail 1 s, uploadFile 1 s, uploadFromUrl 1 s, messages 0.3 s (115-119), notifications 0.5 s, profile 0.1 s (79-83), all others 0.2 s. logIn sets token type bearer, random UUID string, expiring in 3610 s, currentUser = Profile.mock.user (20-27). Returns: Feed.mock, PostDetail.mock, Profile.mock, messages withUid == nil ? .mockInbox : .mockConversation (118), notifications .mock, counts notifications 3, messages 1 (164), openNotification redirect = target URL of the matching mock notification else /posts/a-post-with-several-attachments#comment-c6 (151-158). usersForMentioning: empty query returns UserSearch.mock, else filters its results by case-insensitive username contains. reportReasons fixed list: hate "Hate speech or discriminatory content", violence "Realistic violence or threats", harassment "Harassment or bullying", spam "Spam or unwanted promotion", other "Something else". uploadFile echoes filename, url https://example.com/<filename>, size, isImage/isVideo/isAudio by mime prefix; uploadFromUrl returns filename = given or last path component or attachment, mime application/octet-stream, size 0. Socket: MockMessagesSocket.

Sockets (Socket/*)

  • MessagesSocket protocol (4-11): events: AsyncStream<ChatSocketEvent>, connect, disconnect, send(content, attachmentUids, clientId), sendTyping, sendRead(withUid).
  • MockMessagesSocket: all methods no-ops; disconnect finishes the stream.
  • LiveMessagesSocket (URLSessionWebSocketTask, URLSession(.default)):
    • connect() (23-29): idempotent; starts connection loop Task. disconnect() (31-37): inactive, cancel loop, cancel task with .goingAway.
    • Loop (58-89): backoffMs = 200. Each iteration: get URL from provider (fresh ticket every connect), open task, reset backoff to 200 on open, run receiveLoop. Errors logged Chat socket connection error: <error> only while active. After the loop ends while still active: yield .disconnected; delay = 200 ms if close code 4013, else current backoff then doubled up to a cap of 5000 ms (200, 400, 800, 1600, 3200, 5000, 5000...). Logs Chat socket reconnecting in <ms>ms (closeCode: <n>); sleeps.
    • Receive (91-105): text frames UTF-8 decoded, binary frames passed as is, to ChatSocketFrameDecoder.decode; undecodable logs Chat socket received unrecognized frame (107-113).
    • Send (39-56, 115-122): frames via ChatSocketFrameEncoder.send(receiverUid,content,attachmentUids,clientId), .typing(receiverUid), .read(withUid); sent as text frame; if no task the send is silently dropped; failure logged Chat socket send failed: <error>.
  • Logger.swift: DevPlaceRequestLogger.log(message) hops to MainActor and calls dlog (SDK request logging).

7. R/Util/*

  • DevPlaceError (DevPlaceError.swift): notLoggedIn -> "Not logged in"; invalidUrl(s) -> "Invalid URL: "; postNotEditable -> "This post cannot be edited" (8-17).
  • Logging.swift: dlog(String) prints only in DEBUG builds: "\n" + "<yyyy-MM-dd HH:mm:ss.SSS> \n<message>" (11-23); dlog(Error) logs "\(error)" (25-27). Release builds log nothing.
  • TextCharacterCounter.numberOfCharacters = text.utf16.count (UTF-16 code units, deliberately matching the web app; the backend counts differently, known bug) (1-5). Used by character counters; SignUp validation uses String.count (grapheme clusters) instead.

8. R/UI/Navigation/*

  • NotificationRoute (enum): .post(PostDestination), .conversation(User), .web(URL), .ownProfile (4-9).
  • PostDestination (struct, Hashable, Identifiable): slug: String, scrollToCommentId: String?, id = self (1-6).
  • SettingsDestination (enum Hashable): .profile (1-3).

9. R/UI/Util/AlertMessage.swift

Struct {isPresented, title, message, buttonText} (6-11). Factories:

  • .none(): not presented, empty strings (14-16).
  • .presentedError(message:): title "Error", button "OK" (18-20).
  • .presentedMessage(msg): empty title, button "OK" (71-73).
  • .presentedError(error) (22-69) mapping, in order:
    1. CancellationError: no alert (.none()).
    2. DevPlaceError: its message.
    3. KreeRequest.Error<DevPlaceApiError.CodingData>: .generalError(status, error1): error1 CancellationError gives no alert; error1 again a KreeRequest error .generalError(_, error3): if error3 is a KreeRequest error .apiError(status, error4) then d = error4.decoded; if d.isSpecific message = d.message else "(<status>) <d.message>"; other error3 cases use error3.localizedDescription; other error2 cases error2.localizedDescription; other error1 error1.localizedDescription. Non-generalError KreeRequest cases use dpApiError.description.
    4. Anything else: error.localizedDescription. Logs Error: <error> before presenting (67).
  • View extension alert(Binding<AlertMessage>) (76-90): native .alert(title, isPresented:) with one button labeled buttonText, role: .cancel, no action, message Text(message). Empty title renders a title-less alert.

10. Color and style tokens

Assets.xcassets (R/Assets.xcassets/*/Contents.json), components 0-1, alpha 1.0

Code refers to .BG_0/.BG_1/.BG_2/.FG_1/.FG_2 (underscored symbol names; asset folders are BG0/BG1/BG2/FG1/FG2; the symbol extension is Xcode generated, ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES, pbxproj 162/226; the exact generation rule for the underscore was not found in source) and .agStart/.agEnd/.AFG for assets AGStart/AGEnd/AFG.

Token (asset) Light Dark
BG0 sRGB (1.000,1.000,1.000) sRGB (0.000,0.000,0.000)
BG1 (card/field fill) P3 (0.954,0.941,1.000) P3 (0.029,0.016,0.071)
BG2 (screen background) P3 (0.913,0.880,1.000) P3 (0.096,0.064,0.181)
FG1 (primary text) P3 (0.029,0.016,0.071) P3 (0.953,0.934,0.980)
FG2 (secondary text) P3 (0.202,0.134,0.380) P3 (0.711,0.661,0.804)
AccentColor (global accent, pbxproj 283) P3 (0.930,0.456,0.272) same (single appearance)
AGStart (gradient start) P3 (0.930,0.449,0.302) same
AGEnd (gradient end) P3 (0.925,0.370,0.429) same
AFG (text on gradient) P3 (1.000,1.000,1.000) same

Display-P3 values; a C++ port must decide on P3 to sRGB conversion (document the choice).

App icon (AppIcon.appiconset/Contents.json)

Universal iOS 1024x1024, three slots: default DevPlace.png (file present), dark (luminosity dark) and tinted (luminosity tinted) entries with NO filename (images not supplied). Icon name AppIcon (pbxproj 282).

Info.plist / entitlements

  • R/Info.plist is an empty <dict/>; all keys come from build settings listed above. No privacy usage strings, no URL schemes, no UIBackgroundModes.
  • R/DevPlaceIOS.entitlements: only aps-environment = development.

Styles

  • ScreenStyleModifier / .screenStyle(bgColor: BG_2, fgColor: FG_1): full-bleed BG_2 background ignoring safe area, foreground style FG_1 (UI/Style/Screen/ScreenStyleModifier.swift:3-27).
  • AccentGradientButtonStyle (UI/Style/ButtonStyles/AccentGradientButtonStyle.swift): label semibold (13); padding 16 horizontal, 12 vertical (14-15); background shape RoundedRectangle radius 14 or Circle (34-39) filled with linear gradient agStart to agEnd, topLeading to bottomTrailing (19-24); background opacity 0.7 when pressed else 1 (25); shadow color accentColor at 0.5 opacity, radius 5 (26); label foreground AFG (28); scale 0.95 pressed else 1.0 (29). No explicit animation (implicit system press animation). Disabled uses SwiftUI default dimming.
  • FormButtonStyle (.form): label frame maxWidth infinity, leading alignment, rectangle content shape, foreground gray when pressed else FG_1 (FormButtonStyle.swift:3-13).
  • DevPlaceTextFieldStyle (.devPlace): wraps the field in BoxView(backgroundColor: BG_1, borderOpacity: 0.5, cornerSize: .big, paddingSize: .small) (DevPlaceTextFieldStyle.swift:3-16).
  • BoxView (UI/Components/BoxView.swift): content foreground FG_1, padding by size (none 0, small 10, normal 12, big 16), overlay strokeBorder of FG_2 at opacity (default 0.25) width 1, background rounded rect BG_2 default; radii small 10, normal 12, big 14 (3-56). A text field is thus: padding 10, radius 14, 1 pt border FG_2 at 0.5, fill BG_1.
  • CharacterCounterView (UI/Components/CharacterCounterView.swift): text "<count>/<max>" using locale formatted() for both numbers; font system size 12 * scale (@ScaledMetric, Dynamic Type), monospaced; text FG_2, count part red when count < min (if min given) or count > max, else FG_2 (10-23). Count via UTF-16.
  • MarkdownTheme.swift exists under UI/Style (out of scope).

11. MainView (R/UI/Screens/Main/MainView.swift)

Root view; TabView(selection:) with 4 Tabs (65-129), native iOS 26 tab bar (system styling; accent applies).

Tab (value) Label text SF Symbol Content Badge
postsFeed Posts (72) list.bullet.rectangle NavigationStack { FeedView(selectedPost: $feedPost, reselectSignal:) } none
messages Messages (84) bubble.left.and.bubble.right NavigationStack(path: $messagesPath [User]) { MessagesView() } .badge(unreadMessageCount) (89)
notifications Notifications (111) bell NavigationStack { NotificationsView(reselectSignal, onOpenPost, onOpenConversation, onOpenOwnProfile) } .badge(unreadNotificationCount) (116)
settings Settings (124) gear NavigationStack(path: $settingsPath [SettingsDestination]) { SettingsView() } none

(.badge(0) shows nothing on iOS.) Initial tab .postsFeed (10). State (10-16): selectedTab, feedPost: PostDestination?, messagesPath, settingsPath, feedReselectSignal: Bool, notificationsReselectSignal: Bool. Behavior:

  • Tab reselect (25-46): selecting the already-selected tab toggles feedReselectSignal (only if feedPost == nil) or notificationsReselectSignal; messages and settings: nothing. Screens react in onChange (e.g. FeedView.swift:61).
  • Notification callbacks (95-107): onOpenPost(destination) sets feedPost = destination; selectedTab = .postsFeed; onOpenConversation(user) sets messagesPath = [user]; selectedTab = .messages; onOpenOwnProfile sets settingsPath = [.profile]; selectedTab = .settings.
  • .task at appear (130-135): if logged in: registerForPushNotifications(api) then openPendingConversationIfNeeded().
  • onChange(isLoggedIn) (136-146): true: register push + open pending conversation; false: clear messagesPath and settingsPath.
  • onChange(pendingConversationUid) (147-152): non-nil: open pending conversation.
  • openPendingConversationIfNeeded (52-62): requires logged in and pending uid; sets pending nil; resolves conversationUser(withUid:); if found messagesPath = [user], selectedTab = .messages; silent no-op on failure.
  • onChange(selectedTab) (153-157) and onChange(scenePhase == .active) (158-163): loadUnreadCounts(api) (refetch on every tab switch and every foreground).
  • No loading/empty/error UI at this level.

12. LogInView (R/UI/Screens/LogIn/LogInView.swift, LogInView+ViewModel.swift)

Presented via fullScreenCover from Settings (SettingsView.swift:375-380). Wraps its own NavigationStack (193).

  • Title navigationBarTitle("Sign in") (199). Toolbar .navigation placement button, SF Symbol xmark, action dismiss() (201-207).
  • Background BG_2 ignoring safe area; foreground FG_1 (195-198).
  • Layout (216-229): ScrollView { VStack(spacing: 26) { textFields, logInButton, forgotPassword, createNewAccount }.padding() } (default 16 pt padding on all sides).
  • textFields (231-256): VStack(spacing: 10) of two fields, with .textInputAutocapitalization(.never), .autocorrectionDisabled(), .textFieldStyle(.devPlace), .disabled(isLoading):
    • TextField("Email"): placeholder Email; content type emailAddress; keyboard emailAddress; return key next moves focus to password.
    • SecureField("Password"): placeholder Password; content type password; return key go calls submit().
    • Prefilled from keychain email/password on ViewModel init (41-48).
  • logInButton (258-274): ZStack: ProgressView() (default spinner) opacity 1 when loading else 0; Button label Text("Sign in") frame maxWidth infinity, .accentGradient, .bold(), disabled when !canSubmit, opacity 0 while loading. canSubmit = !email.isEmpty && !password.isEmpty (350-352; no trimming, no format check).
  • submit() (276-279): clears focus then viewModel.logIn().
  • logIn() (354-373): writes email and password to keychain BEFORE the request (failed credentials persist and are reused at next launch); Task: isLoading = true (defer false); api.logIn(email,password); AppState.loadUnreadNotificationCount(api); dismiss.send() closes the cover. On error alertMessage = .presentedError(error) (title "Error", button "OK"). Login does NOT reload the feed; push registration is triggered by MainView observing isLoggedIn.
  • forgotPassword (281-288): Link to https://devplace.net/auth/forgot-password, text Forgot your password?, accent color.
  • createNewAccount (290-313): ViewThatFits picks the first that fits: HStack(spacing: 8) { text, link } else VStack(spacing: 2) { text, link }. text Don't have an account? medium weight, FG_2. link NavigationLink to SignUpView() with label Create new account bold, accent color.
  • No inline validation messages.

13. SignUpView (R/UI/Screens/SignUp/SignUpView.swift, SignUpView+ViewModel.swift)

Pushed inside LogIn's NavigationStack. Title Create account (39). Background BG_2 ignoring safe area, foreground FG_1 (35-38). Tapping anywhere (content shape rectangle) clears focus (31-34).

  • Layout (53-66): ScrollView { VStack(spacing: 26) { textFields, dateOfBirth, termsOfService, signUpButton }.padding() }.
  • textFields (68-139): VStack(spacing: 10); style .devPlace, no autocapitalization, autocorrect off, disabled while loading. Each field is VStack(alignment: .leading, spacing: 4) { input; counter.padding(.horizontal, 10) } (141-151, characterCounterHorizontalPadding = 10).
    1. Username: content type username; return next focuses email. Counter min 3 max 32.
    2. Email: content type emailAddress, keyboard emailAddress; next focuses password. Counter min 3 max 100.
    3. Password (SecureField): content type newPassword; next focuses confirm. Counter min 6 max 1024.
    4. Confirm password (SecureField): newPassword; return go calls submit(). Counter min 6 max 1024.
  • dateOfBirth (153-168): VStack(alignment: .leading, spacing: 8): DatePicker("Date of birth", selection: birthDate, in: ...Date.now, displayedComponents: .date) (default compact style), disabled while loading; footnote text Your date of birth is only used to confirm your age. It is not stored - only your age range is kept. in FG_2. Default birthDate = Date.now (ViewModel 236). Frame maxWidth infinity, leading.
  • termsOfService (170-187): VStack(alignment: .leading, spacing: 12): Link text Read the Terms of Service to https://devplace.net/docs/terms.html (accent); Toggle label I accept the Terms of Service in FG_2, tint accent, disabled while loading; default off.
  • signUpButton (189-205): same ZStack spinner/button pattern as login; text Create account, .accentGradient, bold, disabled unless canSubmit. canSubmit = username, email, password, confirmPassword all non-empty and tosAccepted (251-257).
  • signUp() (259-284): first validationError(); if present shows presentedError(message:) (title "Error", OK) and returns without a request. Else Task: isLoading = true; api.signUp(...) with birthDate and acceptTerms: tosAccepted; success succeeded.send(); failure presentedError(error).
  • Validation order and exact messages (286-316), lengths via String.count (grapheme clusters):
    1. username length outside 3...32: Username must be between 3 and 32 characters.
    2. username has a character that is not letter/number/-/_ (Swift isLetter/isNumber, Unicode aware): Username may only contain letters, numbers, hyphens, and underscores.
    3. email length outside 3...100: Email must be between 3 and 100 characters.
    4. email lacks @: Please enter a valid email address.
    5. password length outside 6...1024: Password must be between 6 and 1024 characters.
    6. password differs from confirm: The passwords do not match.
    7. terms not accepted: Please accept the Terms of Service to continue.
  • Success alert (41-47): title Account created, message Your account has been created. You can now sign in., button OK calls dismiss() (pops back to LogIn). No auto login. No client-side age check.

14. SettingsView (R/UI/Screens/Settings/SettingsView.swift, SettingsView+ViewModel.swift)

Root of the Settings tab. screenStyle() (BG_2 / FG_1, 355); navigationTitle("Settings") (356). navigationDestination(for: SettingsDestination): .profile shows ProfileView() (357-362).

  • Toolbar (363-374): only when logged out: .topBarTrailing button Sign in, .buttonStyle(.glassProminent) (iOS 26 prominent glass), opens fullScreenCover LogInView() (375-380).
  • Body (383-525): Form with .scrollContentBackground(.hidden); every section .listRowBackground(BG_1). Sections in order:
    1. (no header) when logged in: NavigationLink(value: .profile) with .buttonStyle(.form), Label("Profile", systemImage: "person"). When logged out the section is empty.
    2. (no header) Picker bound to appearance, label Label("Appearance", systemImage: "circle.lefthalf.filled"), options System/Light/Dark, tint accent. Applies instantly via root preferredColorScheme.
    3. header Posts Feed: Toggle Show one attachment per post (icon photo) bound to showFeedAttachments; Toggle Show recent comments (icon text.bubble) bound to showFeedComments; tint accent.
    4. header Violating Content: Toggle Show report buttons (icon flag) bound to showReportButtons.
    5. (logged in only) buttons with .form style:
      • Sign out (icon iphone.and.arrow.right.outward) opens alert titled Do you want to sign out?, buttons: system Cancel (role cancel) and destructive Sign out.
      • Delete account (icon trash) opens alert Do you want to permanently delete your account?, buttons Cancel and destructive Delete account; that opens a second alert titled Your account will be deleted. This cannot be undone! Do you want to proceed?, message Enter your password to confirm., containing SecureField("Password") (content type password), buttons Cancel (clears deleteAccountPassword) and destructive Delete account (copies and clears the password, then viewModel.deleteAccount(password:)). The error alert .alert($viewModel.alertMessage) is attached here (511).
    • Section headers and row metrics are native Form styling.
  • Final success alert (517-524): title Account deleted, message Your account has been permanently deleted., button OK.
  • logOut() (ViewModel 548-554): PushNotificationManager.unregisterForPushNotifications (backend no-op, badge 0), clear keychain email and password, AppState.clear(), try? loadFeed(api) (anonymous feed). MainView clears nav paths via the isLoggedIn observer.
  • deleteAccount(password) (556-564): api.deleteAccount(password) (SDK deleteAccount(username,password,token)), then logOut(), then accountDeletedConfirmationPresented = true; error sets alertMessage = presentedError(error).
  • Persistence: all toggles and the picker go through AppSettingsStore keys (section 5).

15. TemplateView (R/UI/Template/*)

Scaffold only, no UI, no strings: TemplateView reads @Environment(\.api) and creates TemplateViewContent(viewModel: .init(api:)); ViewModel is @Observable holding api (TemplateView.swift:1-26, TemplateView+ViewModel.swift:1-12). Convention for every screen: outer view injects api, private ...Content view owns @State viewModel, @ViewBuilder content(). A C++ port should mirror this as View + ViewModel pairs.

16. Gaps and notes for the port

  • Mock data payloads (Feed.mock, Profile.mock, ...) live in R/Model/Mocks/*, outside this scope.
  • Animations: the shell defines no explicit animation durations; only the button press scale 0.95 and opacity 0.7 (implicit SwiftUI animation) and system-provided tab/navigation/alert transitions.
  • System controls (tab bar, Form, DatePicker, alerts, glassProminent button) are iOS 26 native; exact pixel metrics for these are not in source and must be taken from screenshots of a real device.
  • Measurements: none; this document is static source reading.
717.0ms