Skip to content

Latest commit

 

History

History
380 lines (333 loc) · 16.8 KB

File metadata and controls

380 lines (333 loc) · 16.8 KB

ShareSpace Documentation

Comprehensive internal documentation for the ShareSpace mobile application (Expo React Native + Firebase). This complements the existing README.md by describing architecture, data design, feature flows, and suggested enhancements.


1. Project Overview

ShareSpace is a role-based social & mentorship platform connecting junior and senior university students. It enables knowledge sharing through posts, comments, role-targeted feeds, profile customization, and direct messaging.

Key idea: Seniors primarily create posts visible to juniors (and vice versa) enabling cross‑experience exchange while keeping role perspectives distinct.


2. Tech Stack

Layer Technology
Runtime Expo SDK 52 / React Native 0.76
Language JavaScript (ES6+)
State (Auth/User) Firebase Auth + custom UserContext
Backend Services Firebase (Authentication, Firestore, Storage)
Navigation @react-navigation/native + native stack + bottom tabs
UI Enhancements expo-linear-gradient, react-native-vector-icons, moti (animation)
Forms & Validation (potential) formik, yup (only partially leveraged)
Auth Provider Email/password + Google Sign-In (Expo Auth Session)
Fonts Poppins family (loaded at startup)

3. High-Level Architecture

App.js
 └─ UserProvider (UserContext)
     └─ NavigationContainer
         └─ Stack Navigator (Unauth vs Auth flows)
             ├─ Onboarding / Signin / Signup
             └─ MainTabs (bottom tabs)
                 ├─ HomeScreen (role-driven feed)
                 ├─ ExploreScreen (search + label filters)
                 ├─ MessagesScreen (chat list)
                 └─ ProfileScreen (self profile + posts)

Additional stack screens (pushed modally / navigated):
  - PostsScreen (create post)
  - CommentsScreen
  - ViewProfile (other user)
  - EditProfileScreen
  - StartChatScreen / ChatScreen
  - SettingsScreen / FeedbackScreen / NotificationsScreen

Core Context Provider

app/utils/UserContext.js attaches authenticated user + profile document fields (role, names, avatar, bio, username) for easy consumption across screens.

Navigation Separation

  • Unauthenticated: Onboarding → Sign In / Sign Up
  • Authenticated: Tab-based application + auxiliary stack screens

4. Feature Breakdown

Feature Description Key Files
Onboarding & Auth Email/password sign up & sign in; Google OAuth via Expo auth.js, onboarding/login screens
Role-Based Feeds Seniors see juniors' posts; juniors see seniors' posts HomeScreen.js, Firestore collection logic
Post Creation Rich text + multi-label tagging PostsScreen.js
Post Interaction Likes, comments (count summaries), label badges HomeScreen.js, CommentsScreen.js
Commenting Per-post subcollection with chronological ordering CommentsScreen.js
Explore & Search Text search (author/content) + multi-label filtering ExploreScreen.js
Profiles Self profile (editable) + posts list + avatar selection ProfileScreen.js, EditProfileScreen.js
View Other Profiles View posts & interact (like/comment) ViewProfile.js
Avatars Static curated set (local assets) assets/avatars/
Direct Messaging Real-time chat with read status + last message preview MessagesScreen.js, ChatScreen.js, StartChatScreen.js
Settings Logout, account deletion, feedback & bug reporting SettingsScreen.js, FeedbackScreen.js
Notifications (Placeholder) Screen scaffold exists; fetch logic not yet implemented NotificationsScreen.js
Feedback Opens mail composer (device dependent) FeedbackScreen.js
Theming & Fonts Global Poppins font injection after load App.js

5. Data Model (Firestore)

Naming pattern intentionally separates visibility by role. Current logic: a senior user posts into juniorsPosts (content aimed at juniors) and a junior user posts into seniorsPosts.

Collections

users (doc id = uid)
  firstName: string
  lastName: string
  role: 'junior' | 'senior'
  avatar: string (file name like "image 3.png")
  bio: string
  username: string

seniorsPosts (posts authored by juniors OR seniors? see note)
juniorsPosts (posts authored by seniors OR juniors? see note)
  post document:
    authorId: uid
    authorName: string
    content: string
    labels: string[]
    likedBy: string[] (uids) [optional; added over time]
    timestamp: Firestore serverTimestamp()

  subcollection: comments
    comment document:
      userId: uid
      authorName: string
      content: string
      timestamp: Date (or serverTimestamp locally set)

chats
  chat document:
    users: [uidA, uidB]
    userInfo: {
      [uid]: { firstName, lastName, avatar }
    }
    lastMessage: string (optional)
    lastMessageTimestamp: serverTimestamp()
    readStatus: { [uid]: boolean } (not consistently set on creation yet)
    createdAt: Date

  subcollection: messages
    message document:
      text: string
      senderId: uid
      senderName: string (currently not reliably stored; improvement needed)
      senderAvatar: string | null
      createdAt: serverTimestamp()

Observations / Inconsistencies

  • Role → Collection Mapping: In PostsScreen, collectionName = role === 'senior' ? 'juniorsPosts' : 'seniorsPosts'. This enforces cross-role visibility, but code comments and naming can be confusing. Consider renaming collections to postsForJuniors / postsForSeniors.
  • Chat Sender Name: senderName uses user.firstName / user.lastName but user from Firebase Auth does not include those properties—should leverage context profile.
  • Notifications: Placeholder only; no Firestore integration.

6. Authentication Flow

  1. App boots → fonts load → onAuthStateChanged fires.
  2. If user not signed in → show onboarding (first launch only) → Sign In / Sign Up.
  3. Email & password via Firebase Auth; Google Sign-In with Expo AuthSession → credential → signInWithCredential.
  4. Upon sign-in, user context fetches corresponding users/{uid} document. Missing doc → limited role resolution (some screens dependent on role).

Persisted State

  • AsyncStorage: key hasSeenOnboarding prevents re-showing onboarding.
  • Auth persistence configured via initializeAuth(... getReactNativePersistence(AsyncStorage)).

7. State & Data Fetch Strategy

Concern Mechanism
Auth User onAuthStateChanged (Firebase) in UserContext
Role Derived from user profile document (users/{uid})
Feed Posts Fetched on role change (HomeScreen, ExploreScreen) via getDocs (not real-time)
Likes Optimistic update + updateDoc
Comments Per-screen fetch (no real-time listener)
Chat List Real-time via onSnapshot on chats filtered by array-contains user id
Chat Messages Real-time listener on messages subcollection
Profile Posts Queried by authorId each time profile mounts

8. UI / UX Conventions

  • Color Motif: Warm orange (#e17d27 and variants) for brand accent.
  • Gradients: Soft top/bottom gradient backgrounds (orange-fade) used for cards & sections.
  • Typography: Poppins, with global override after font load.
  • Floating Action Button: Positioned near center-bottom for post creation (MainTabs).
  • Badges: Labels displayed as pills; grouping limited by wrapping container.
  • Animations: moti used in settings and profile edit transitions.

9. Known Gaps & Improvement Opportunities

Area Issue Suggested Action
Firestore Security No rules documented Add rules restricting reads/writes to authenticated users & proper role constraints
Hardcoded Firebase Config API keys inline Move to .env via expo config plugins or secure build env vars
Role ↔ Collection Naming Confusing semantics Rename collections or add abstraction layer (getTargetCollectionForRole(role))
Real-Time Feeds Feeds use one-time getDocs Replace with onSnapshot for live updates
Notification System Placeholder only Implement Firestore notifications subcollection + server functions or client triggers
Chat Sender Metadata Uses auth object fields not present Use UserContext.profile for senderName & senderAvatar
Error Handling Silent catches & console logs Centralize with toast/modal surface + logging service
Form Validation formik & yup imported but unused Implement validation for signup, profile, post forms
Input Sanitization Direct string writes Trim & limit lengths (bio, post content) server-side rules
Accessibility Limited a11y props Add accessible, accessibilityLabel, dynamic font scaling support
Performance N+1 comment count fetches (ViewProfile) Store commentCount and likeCount denormalized and increment via Cloud Functions
Offline Resilience No caching strategy Introduce Firestore persistence & optimistic queues
Testing No automated tests Add Jest + React Native Testing Library for core flows

10. Security & Privacy Considerations

  • Authentication: Relies on Firebase; ensure multi-factor or password policies if scaling.
  • Firestore Rules (Recommended): Limit post write to self; enforce correct target collection; restrict deletion and editing to authorId.
  • Data Exposure: Public user documents contain basic profile fields; ensure no sensitive info stored.
  • Email Feedback: Sends plain text; not suitable for sensitive reports.

Example (conceptual) snippet for rules (not yet in repo):

match /databases/{db}/documents {
  match /users/{uid} {
    allow read: if request.auth != null;
    allow create: if request.auth.uid == uid;
    allow update, delete: if request.auth.uid == uid;
  }
  match /{targetCollection}/{postId} where targetCollection in ['seniorsPosts','juniorsPosts'] {
    allow read: if request.auth != null;
    allow create: if request.auth != null && request.resource.data.authorId == request.auth.uid;
    allow update, delete: if resource.data.authorId == request.auth.uid;
  }
  match /chats/{chatId} {
    allow read, write: if request.auth.uid in resource.data.users;
  }
  match /chats/{chatId}/messages/{msgId} {
    allow read, write: if request.auth.uid in get(/databases/$(db)/documents/chats/$(chatId)).data.users;
  }
}

11. Build & Run

Prerequisites

  • Node.js LTS (≥ 18.x recommended)
  • Expo CLI (via npx – no global install required)
  • Firebase project configured with matching web app credentials

Install

npm install

Run (Development)

npm start       # or: npx expo start

Choose a platform (Expo Go, Android emulator, iOS simulator, or Web).

Environment (Future)

Create .env file (with expo-build-properties or react-native-dotenv) for:

FIREBASE_API_KEY=...
FIREBASE_AUTH_DOMAIN=...
FIREBASE_PROJECT_ID=...
...

Then refactor firebaseConfig.js to consume env variables.


12. Critical Flows (Sequence Summaries)

Post Creation

  1. User opens FAB → PostsScreen.
  2. Inputs content + selects labels.
  3. Determines target collection via role inversion.
  4. Writes Firestore doc (serverTimestamp).
  5. Returns to previous screen; manual refresh pulls new post.

Comment Addition

  1. Open post detail (CommentsScreen).
  2. Fetch existing comments ordered by timestamp.
  3. Add comment doc; reload entire list (no incremental append optimization yet).

Start Chat

  1. StartChatScreen queries opposite-role users.
  2. Checks existing chat via where('users','array-contains', uid) in memory.
  3. If absent, creates chat doc with users array and userInfo map.
  4. Navigates into ChatScreen setting up real-time listeners.

Like Toggle

  1. Locally compute updatedLikes.
  2. updateDoc on appropriate collection.
  3. Update local state map to avoid full refetch.

13. Error Handling Strategy (Current vs Suggested)

Current Limitation Suggested Enhancement
Console errors + Alert.alert Inconsistent user feedback Central toast component + error boundary
Silent Firestore permission errors not caught distinctly Harder debugging Pattern-match error.code for actionable messaging

14. Styling & Theming

  • Central brand color: #e17d27 (accents, labels, buttons).
  • Background neutrals: #fff5ea (soft cream), plain white surfaces for content.
  • Recommend future extraction of shared tokens (colors, spacing, fonts) into theme.js.

15. Deployment & Distribution (Future Roadmap)

Stage Action
QA Builds Use expo prebuild then EAS build channels
OTA Updates Leverage Expo Updates for minor JS changes
Versioning Increment semver + tag release notes
Monitoring Add Sentry for crash & performance tracing

16. Testing Roadmap (Proposed)

Test Type Scope
Unit Utility helpers (to be extracted), role-based collection resolver
Component Post card rendering, label filtering, chat message bubble alignment
Integration Auth → profile fetch, post → comment pipeline
E2E Detox: login → create post → like/comment → view profile

17. Performance Considerations

Concern Impact Mitigation
Multiple per-post comment count queries O(n * m) reads (profiles / view other) Denormalize counts + update via Cloud Function
No pagination in feeds Large downloads on growth Use limit() + infinite scroll + indexing
Uncached avatars Repeated require() fine (local), but dynamic expansion would need caching If migrated to remote storage, use caching layer

18. Internationalization

Currently hard-coded English strings. Future: extract copy to a locales/en.json and integrate expo-localization + i18n-js or react-intl.


19. Accessibility Checklist (Pending)

Item Status
Dynamic font scaling Not implemented
Color contrast baseline Adequate for most components; verify with WCAG AA
Screen reader labels Minimal; needs accessibilityLabel on icon-only buttons
Focus order (web) Implicit; ensure for cross-platform builds

20. Suggested Refactors (Prioritized)

  1. Abstract Firestore collection resolution: getPostCollectionForAuthorRole(role).
  2. Convert feed + comments to real-time listeners where beneficial.
  3. Introduce hooks/ directory for shared logic (e.g., useUserRole, usePosts, useChat(chatId)).
  4. Modularize repeated avatar mapping into constants/avatars.js.
  5. Add TypeScript (gradual) for reliability.
  6. Implement Firestore security rules & local emulator tests.
  7. Replace direct timestamp formatting with a util (formatDate(ts)).

21. Known Bugs / Edge Cases

Case Description
Missing profile doc If signup does not create a matching users doc, role-dependent screens stall
Chat sender name undefined Using user.firstName (undefined on auth object)
Duplicate SignUp file listing Directory listing shows duplicate Signupscreen.js (cleanup)
No optimistic comment append After adding comment entire list refetched
Notification logic absent UI suggests unread state but no backend integration

22. Maintenance Guidelines

Task Frequency Notes
Dependency audit Monthly Check for Expo SDK alignment
Firebase rules review Quarterly Update with new feature scopes
Performance profiling Pre-release Use why-did-you-render (web) / Hermes profiling
Crash & analytics review Weekly (after instrumentation) Add Sentry / Firebase Analytics

23. Glossary

Term Meaning
Role User classification: junior vs senior
Cross-role Feed Seniors view juniors' posts & vice versa
FAB Floating Action Button (create post)
Read Status Chat-level mapping of which users have unread messages

24. Quick Start (TL;DR)

npm install
npm start
# Sign up → choose role (ensure user doc exists) → explore feed → create post via + button

25. Future Enhancements (Ideation)

  • Mentorship pairing algorithm (matching juniors to seniors by interests / labels).
  • Push notifications for likes/comments/messages.
  • Media attachments (images) in posts (requires Firebase Storage integration UI).
  • Post moderation & reporting workflow.
  • Gamification (badges for engagement).

26. License & Ownership

Declared license: 0BSD in package.json (permissive). Ensure this aligns with intended project distribution; update if necessary.


27. Document Changelog

Version Date Notes
1.0 2025-10-09 Initial comprehensive internal documentation created

End of Documentation