Skip to content

State & contexts

Francisca Portugal edited this page Oct 27, 2026 · 1 revision

The React context map, the planner's data shapes, and exactly what is persisted where. Status: current. Absorbs the old wiki State-variables-structure page, with the stale parts corrected.

Two storage systems coexist:

  • React context — in-memory state for the current tab;
  • localStorage — write-through persistence, device-local only.

There is no backend persistence for the planner today. PlannerState is designed but 🚧; see Planned endpoints.

The two trees

App
└── CombinedProvider                 root state for every page
    ├── SessionContext               who is signed in
    ├── ThemeContext                 dark-mode flag (currently forced off)
    ├── MajorContext                 course list for the picker
    ├── CourseContext                picked courses + picker UI
    ├── MultipleOptionsContext       drafts + selected draft
    └── ConflictsContext             conflict flags
        └── page
            ├── ScheduleContext          exchange/admin schedule previews
            ├── CollabSessionContext     collaborative sessions
            └── ExchangeRequestCommonContext  request-card state

Planner picker subtree:
    CoursePickerContext
    ClassSelectorContext

Admin subtree:
    AdminPaginationContext
    RequestFiltersContext

Providers are mounted where they are needed. The six root providers live in contexts/CombinedProvider.tsx; the rest are mounted by the owning page or component.

Root contexts

Context Value Persisted
SessionContext signedIn, user, isSessionLoading, forceScheduleRevalidation signedIn flag only; the session itself is the cookie
ThemeContext enabled, setEnabled dark-theme (but dark mode is disabled — see below)
MajorContext majors, setMajors no
CourseContext pickedCourses, coursesInfo, checkboxedCourses, choosingNewCourse, ucsModalOpen picked courses
MultipleOptionsContext multipleOptions, selectedOption + setters both, write-through
ConflictsContext conflictSeverity, tClassConflicts, hasSomeConflict no

useSession fetches /v1/auth/me with SWR and maps the canonical user onto the legacy field names (username, is_admin, eligible_exchange). forceScheduleRevalidation is the SWR mutate.

Feature-scoped contexts

Context Mounted by Holds
CoursePickerContext course picker coursesInfo, checkboxedCourses, selectedMajor, modal flags
ClassSelectorContext class selector selected/preview class, lock toggle, the CourseOption being edited
ScheduleContext Exchange page, admin preview original/exchange schedule, enrolled units, loading
CollabSessionContext CollaborativeSession session list + current session id
ExchangeRequestCommonContext request cards chosen request, hidden ids, selected options, preview open
AdminPaginationContext admin panel current page, total pages, page size
RequestFiltersContext admin panel activeCourse, activeCurricularYear, activeStates

CourseContext and CoursePickerContext duplicate coursesInfo, checkboxedCourses, choosingNewCourse and ucsModalOpen. That is legacy duplication, not a design pattern to copy.

PreviewContext is not a React context and is not mounted: it exports a module-level map and helpers, with no provider or consumer.

Planner shapes

type MultipleOptions = Array<Option>   // exactly 10 drafts

type Option = {
  id: number
  icon: string
  name: string                         // "Horário 1" … "Horário 10"
  course_options: Array<CourseOption>
}

type CourseOption = {
  course_id: number
  picked_class_id: number              // declared number, is null until a class is picked
  locked: boolean
  filteredTeachers: Array<number>
  hide: Array<lesson_type>
}
  • multipleOptions is the draft list. Position 0 is “Horário 1”, position 1 is “Horário 2”, … 9 is “Horário 10”. The defaults are created in api/storage.ts.
  • selectedOption is a plain index into multipleOptions, persisted separately. It is not an id.
  • Option.course_options holds one entry per picked course, in every draft. Adding a course appends a default CourseOption to all ten drafts; removing it removes it from all ten.
  • picked_class_id is the class (turma) chosen for that course in that draft. null means no class yet.
  • locked is per CourseOption in a draft — lock “BD” in Horário 2 without locking it in Horário 1. It is not global.
  • filteredTeachers is the teacher filter for that draft; hide is the set of lesson types to hide.
  • pickedCourses is the separate list of chosen courses shown by the picker. It is not derived from multipleOptions; the two must stay in sync.

On load, getPickedCoursesStorage() clears the picked list if every draft has no course options but the picked list is non-empty — a guard against a half-written storage state.

CourseInfo is occurrence-shaped

CourseInfo in @types/index.d.ts is not the backend Course:

CourseInfo Meaning
id occurrence id (the teaching instance)
course_unit_id abstract course-unit id
course course id
course_unit_year academic year
ects, hash, url occurrence fields
classes? embedded classes with slots and teachers

Do not map it onto the catalog Course shape. The glossary has the full trap table.

Storage keys

Key Written by Holds
niaefeup-tts.multiple-options StorageAPI / MultipleOptionsContext the 10 drafts
niaefeup-tts.selected-option StorageAPI / MultipleOptionsContext draft index (0–9)
niaefeup-tts.selected-major StorageAPI last picked course
niaefeup-tts.picked-courses StorageAPI picked course list
niaefeup-tts.info StorageAPI cached backend info (update is TODO)
niaefeup-tts.current-visit StorageAPI.storeCurrentVisit() { year, semester } of the visit
niaefeup-tts.show-exchange-alert.session StorageAPI whether the exchange alert was dismissed
niaefeup-tts.show-grid useShowGrid schedule grid visibility
sidebar-position SidebarProvider left / right
collab-sessions useCollabSessions known collaborative sessions
dark-theme useDarkMode dark-mode flag (currently ignored)
signedIn useSession display flag, not a credential
<key>.fetch-date StorageAPI.writeStorage when a value was written; null marks invalid

There are three localStorage helpers with subtly different behaviour: api/storage.ts, hooks/useLocalStorage.ts (effect-based write) and the inline hook in useShowGrid.tsx. Check which one owns a key before changing it.

Device-local vs backend

Data Where Cross-device?
Session / identity session cookie + DB Yes (log in)
Picked courses, drafts, class choices, locks, filters localStorage No — PlannerState is 🚧
Theme, active draft, draft names/icons localStorage No, by design
Catalog PostgreSQL Yes
Exchange requests PostgreSQL (demo seed only) No endpoints yet
Collaborative sessions localStorage + in-memory socket No server

When PlannerState lands, the split is intended to stay: picks and class choices go to the backend; theme, active draft, names/icons, locks, hidden lesson types and teacher filters stay device-local.

Known mismatches

  • course_id is ambiguous. CourseOption.course_id is created from course.id (an occurrence id), but courseHasClassPicked compares it with course.course_unit_id, and getCourseFilteredTeachersStorage(selectedOption, courseUnitId) treats it as a unit id. The field is used as both at different call sites. Do not “fix” one side without tracing all consumers.
  • filteredTeachers is declared Array<number> but starts as null in createDefaultCourseOption; it is overwritten with teacher ids when the course is added. The type is still inaccurate for the default object.
  • picked_class_id is declared number but is null before a class is picked.
  • CourseInfo is not the backend Course (see above).
  • Dark mode is disabled. useDarkMode always removes data-theme; the toggle is commented out in the header. The dark-theme key is written but has no visual effect.
  • CourseContext / CoursePickerContext duplicate fields, so a new field may need adding in both places.
  • signedIn in localStorage is display-only. Never treat it as auth.

Adding state

  1. Decide ownership. Page-local useState → owning subtree context → root context, in that order. Do not add to CombinedProvider unless more than one page needs it.
  2. Decide persistence. If it must survive a reload, write through StorageAPI or useLocalStorage; if it must survive a device, it needs a backend model — the planner does not have one yet.
  3. Pick a key. Reuse an existing key if the data belongs to it; otherwise namespace it niaefeup-tts.<thing>.
  4. Keep the setter and storage in sync. The multiple-options setters write on every update; a bare useState will not survive a refresh.
  5. Do not store credentials. The session is HttpOnly; localStorage is readable by any script on the origin.
  6. Update this page if you add a key or a provider.

See also


Last verified: 2026-10-27

Clone this wiki locally