feat: redesign day picker with expandable calendar, status markers & Playwright E2E testing

- Replace modal calendar with inline expandable calendar widget integrated into the day picker.
- Add status indicator dots (attended/absent/pending) to month calendar grid matching day picker.
- Disable and gray out weekend days in calendar when weekend schedule is turned off.
- Redesign extend bar with integrated handle that aligns with the palette.
- Remove start-to-end timing on Today screen's class time rail, showing only start time.
- Implement Playwright E2E and visual testing suite with multi-screen capture scripts.
- Add cascade DELETE endpoints for subjects and versioned recurring timetable entries.
This commit is contained in:
root
2026-09-05 08:58:51 +05:30
parent e6884a148b
commit 693cc1c0b6
39 changed files with 1350 additions and 129 deletions

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,71 @@
---
name: frontend-design
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
license: Complete terms in LICENSE.txt
---
# Frontend Design
Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified.
## Ground your designs in the subject matter
If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 811 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout.
## Design principles
For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option.
Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct.
Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content.
Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif.
Avoid these default typographic treatments; they are the commonest tells of a generated page:
- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color.
- Using all caps for labels.
- Adding unnecessary typographic labels above content.
Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence.
Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed.
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
## Process: plan, review against the brief, build, critique
For calibration, AI-generated design right now clusters around some traits:
1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell);
2. a near-black background with a single bright acid-green or vermilion accent;
3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns;
4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration;
5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text.
All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles.
- Color: describe the core base palette as 46 named hex values.
- Type: the typefaces and their roles.
- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified?
- Principles: the high-level guidance for what makes this page unique.
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan.
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections.
## Restraint and self-critique
Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
## More on writing in design
Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever.
Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job.

6
.gitignore vendored
View File

@@ -47,3 +47,9 @@ app-example
# Local College Kit API database
backend/data/
# Playwright & test artifacts
dist-web/
screenshots/
test-results/
playwright-report/

View File

@@ -2,7 +2,7 @@ import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect } from '@react-navigation/native';
import { useRouter } from 'expo-router';
import { useCallback, useState } from 'react';
import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
import { ActivityIndicator, Alert, Pressable, StyleSheet, View } from 'react-native';
import {
AppHeader,
@@ -11,6 +11,7 @@ import {
Button,
Card,
EmptyState,
IconButton,
InlineBanner,
ProgressBar,
Screen,
@@ -19,7 +20,7 @@ import {
colors,
spacing,
} from '@/components/ui';
import { attendanceMessage, attendanceTone, subjectToneFor } from '@/lib/design';
import { attendanceMessage, attendanceTone, subjectShortLabel, subjectToneFor } from '@/lib/design';
import { collegeApi } from '@/lib/api';
type Subject = Awaited<ReturnType<typeof collegeApi.attendanceSummary>>['subjects'][number];
@@ -54,7 +55,21 @@ export default function AttendanceScreen() {
});
return <Screen contentContainerStyle={styles.content}>
<AppHeader title="Attendance" />
<AppHeader
title="Attendance"
style={styles.header}
trailing={
<IconButton
icon="information-circle-outline"
label="Attendance calculation rules"
tone="ghost"
onPress={() => Alert.alert(
'Attendance rules',
'• Overall attendance is calculated from classes that were marked attended vs. total classes held.\n\n• Cancelled classes are automatically excluded from calculations.\n\n• Target threshold is 75%.'
)}
/>
}
/>
{loadError ? <InlineBanner title="Couldnt load attendance" message={loadError} tone="danger" action={<Button label="Retry" size="compact" variant="ghost" fullWidth={false} onPress={load} />} style={styles.firstBlock} /> : null}
{loading ? <Card tone="skySoft" style={[styles.loading, styles.firstBlock]}><ActivityIndicator color={colors.brand.cobalt} /><AppText variant="bodySmall" color={colors.neutral.textSecondary}>Calculating attendance</AppText></Card> : null}
@@ -106,7 +121,7 @@ export default function AttendanceScreen() {
accessibilityLabel={`${subject.name}, ${subject.percentage} percent attendance, ${subject.attended} of ${subject.total} classes attended`}
onPress={() => router.push(`/subjects/${subject.id}` as never)}
style={({ pressed }) => [styles.subject, pressed && styles.subjectPressed]}>
<SubjectBadge shortName={subject.shortName || subject.code.slice(0, 3)} tone={tone} />
<SubjectBadge shortName={subjectShortLabel(subject.name, subject.code, subject.shortName)} tone={tone} />
<View style={styles.subjectBody}>
<View style={styles.subjectTop}>
<View style={styles.subjectTitleWrap}>
@@ -136,9 +151,10 @@ function Stat({ value, label }: { value: number; label: string }) {
const styles = StyleSheet.create({
content: { paddingTop: spacing[1], paddingBottom: spacing[9] },
firstBlock: { marginTop: spacing[6] },
header: { paddingTop: spacing[2], minHeight: 0 },
firstBlock: { marginTop: spacing[4] },
loading: { minHeight: 144, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing[3] },
hero: { marginTop: spacing[6], flexDirection: 'row', alignItems: 'center', gap: spacing[6], borderRadius: 20 },
hero: { marginTop: spacing[3], flexDirection: 'row', alignItems: 'center', gap: spacing[6], borderRadius: 20, borderCurve: 'continuous' },
heroCopy: { flex: 1 },
heroMessage: { marginTop: spacing[2] },
heroStatus: { marginTop: spacing[4] },

View File

@@ -25,7 +25,17 @@ import {
spacing,
type WeekDay,
} from '@/components/ui';
import { addDays, currentMinutes, dateKey, formatDayHeading, mondayOfWeek, timeToMinutes } from '@/lib/date';
import {
addDays,
currentMinutes,
dateKey,
formatCurrentTime,
formatDayHeading,
formatHeaderDate,
formatMonthYear,
mondayOfWeek,
timeToMinutes,
} from '@/lib/date';
import { attendanceMessage, attendanceTone, subjectToneFor } from '@/lib/design';
import { collegeApi, type AttendanceStatus, type Profile, type Session } from '@/lib/api';
@@ -46,10 +56,11 @@ export default function TodayScreen() {
const [summary, setSummary] = useState<AttendanceSummary>(emptySummary);
const [weekendSchedule, setWeekendSchedule] = useState(false);
const [weekMarkers, setWeekMarkers] = useState<Record<string, DayMarker>>({});
const [monthMarkers, setMonthMarkers] = useState<Record<string, DayMarker>>({});
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [refresh, setRefresh] = useState(0);
const [calendarOpen, setCalendarOpen] = useState(false);
const [calendarExpanded, setCalendarExpanded] = useState(false);
const [addClassOpen, setAddClassOpen] = useState(false);
const [selectedClass, setSelectedClass] = useState<Session | null>(null);
@@ -111,12 +122,20 @@ export default function TodayScreen() {
.filter((date) => weekendSchedule || (date.getDay() !== 0 && date.getDay() !== 6))
.map((date) => ({ date, marker: weekMarkers[dateKey(date)] ?? 'none' }));
const calendarMonthKey = `${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth() + 1).padStart(2, '0')}`;
useEffect(() => {
collegeApi.attendanceMarkers(calendarMonthKey)
.then(({ markers }) => setMonthMarkers(markers))
.catch(() => setMonthMarkers({}));
}, [calendarMonthKey, refresh]);
const updateStatus = (session: Session, status: AttendanceStatus) => {
const previous = classes;
setClasses((items) => items.map((item) => item.id === session.id ? { ...item, status } : item));
collegeApi.markAttendance(session.id, status)
.then(() => {
if (Platform.OS !== 'web') void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
setRefresh((v) => v + 1);
})
.catch((error: Error) => {
setClasses(previous);
@@ -149,24 +168,63 @@ export default function TodayScreen() {
].sort((left, right) => left.start.localeCompare(right.start) || (left.type === 'recess' ? -1 : 1));
const activeTimelineIndex = isToday ? timelineItems.findIndex((item) => timeToMinutes(item.start) <= now && now < timeToMinutes(item.end)) : -1;
const insertionIndex = isToday ? (activeTimelineIndex >= 0 ? activeTimelineIndex : timelineItems.findIndex((item) => timeToMinutes(item.start) > now)) : -1;
const currentTimeLabel = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(new Date());
const currentTimeLabel = formatCurrentTime();
const pendingCount = classes.filter((item) => item.status === 'pending').length;
return <Screen scroll={false} contentContainerStyle={styles.content}>
<View style={styles.stickyHeader}>
<AppHeader title={new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'short', day: 'numeric' }).format(activeDate)} />
<View style={styles.dateActions}>
{!isToday ? <Button label="Today" variant="ghost" size="compact" fullWidth={false} onPress={() => setActiveDate(new Date())} /> : null}
<IconButton icon="calendar-outline" label="Open calendar" tone="sky" onPress={() => { setCalendarMonth(startOfMonth(activeDate)); setCalendarOpen(true); }} />
<View style={styles.headerRow}>
<AppHeader
title={formatHeaderDate(activeDate)}
style={styles.headerTitle}
/>
{profile?.name ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Open account profile"
onPress={() => router.push('/account' as never)}
style={({ pressed }) => [styles.avatar, pressed && styles.avatarPressed]}>
<AppText variant="label" color={colors.brand.cobalt}>{profile.initials || '?'}</AppText>
</Pressable>
) : null}
</View>
<View style={styles.pickerContainer}>
{calendarExpanded ? (
<InlineCalendarWidget
month={calendarMonth}
selectedDateKey={selectedDateKey}
todayKey={todayKey}
markers={monthMarkers}
allowWeekends={weekendSchedule}
onMonthChange={setCalendarMonth}
onSelect={(date) => {
setActiveDate(date);
setCalendarExpanded(false);
}}
/>
) : (
<WeekStrip days={visibleDays} selectedDateKey={selectedDateKey} todayDateKey={todayKey} onSelect={setActiveDate} style={styles.weekStrip} />
)}
<Pressable
accessibilityRole="button"
accessibilityLabel={calendarExpanded ? 'Collapse calendar' : 'Expand calendar'}
onPress={() => {
if (!calendarExpanded) {
setCalendarMonth(startOfMonth(activeDate));
}
setCalendarExpanded((v) => !v);
}}
style={({ pressed }) => [styles.extendBar, pressed && styles.extendBarPressed]}>
<View style={styles.extendHandle} />
</Pressable>
</View>
<WeekStrip days={visibleDays} selectedDateKey={selectedDateKey} todayDateKey={todayKey} onSelect={setActiveDate} />
{summary.total > 0 ? <InlineBanner title={insight.title} message={insight.message} tone={insightTone} style={styles.insight} /> : null}
<View style={styles.sectionHeader}>
<View style={styles.sectionCopy}>
<AppText variant="heading2">{isToday ? 'Todays classes' : `${new Intl.DateTimeFormat(undefined, { weekday: 'long' }).format(activeDate)}s classes`}</AppText>
<AppText variant="heading2">{isToday ? 'Todays classes' : `${formatDayHeading(activeDate).split(',')[0]}s classes`}</AppText>
<AppText variant="bodySmall" color={colors.neutral.textMuted} style={styles.sectionSubtitle}>
{classes.length ? `${classes.length} ${classes.length === 1 ? 'class' : 'classes'}${pendingCount ? ` · ${pendingCount} to mark` : ''}` : 'Your agenda for this date'}
</AppText>
@@ -190,7 +248,6 @@ export default function TodayScreen() {
<View style={styles.classRow}>
<View style={styles.timeRail}>
<AppText variant="label" style={styles.timeText}>{entry.start}</AppText>
<AppText variant="caption" color={colors.neutral.textMuted} style={styles.timeText}>{entry.end}</AppText>
{index < timelineItems.length - 1 ? <View style={styles.railLine} /> : null}
</View>
{entry.type === 'recess' ? <RecessCard timeRange={`${entry.start}${entry.end}`} isNow={isNow} style={styles.event} /> : <ScheduleEventCard
@@ -204,7 +261,7 @@ export default function TodayScreen() {
isNow={isNow}
style={styles.event}
topAction={<IconButton icon="ellipsis-horizontal" label={`Options for ${entry.item.title}`} tone="ghost" onPress={() => setSelectedClass(entry.item)} />}
footer={entry.item.status !== 'cancelled' ? <AttendanceActions tone={subjectToneFor(entry.item.subjectId || entry.item.code, entry.item.color)} onAttended={() => updateStatus(entry.item, 'attended')} onAbsent={() => updateStatus(entry.item, 'absent')} /> : null}
footer={entry.item.status !== 'cancelled' ? <AttendanceActions tone={subjectToneFor(entry.item.subjectId || entry.item.code, entry.item.color)} status={entry.item.status} onAttended={() => updateStatus(entry.item, 'attended')} onAbsent={() => updateStatus(entry.item, 'absent')} /> : null}
/>}
</View>
</View>;
@@ -228,54 +285,140 @@ export default function TodayScreen() {
</View>
</> : null}
</BottomSheet>
<CalendarSheet
visible={calendarOpen}
month={calendarMonth}
selectedDateKey={selectedDateKey}
todayKey={todayKey}
onMonthChange={setCalendarMonth}
onClose={() => setCalendarOpen(false)}
onSelect={(date) => { setActiveDate(date); setCalendarOpen(false); }}
/>
</Screen>;
}
function AttendanceActions({ tone, onAttended, onAbsent }: { tone: keyof typeof colors.subject; onAttended: () => void; onAbsent: () => void }) {
function AttendanceActions({ tone, status, onAttended, onAbsent }: { tone: keyof typeof colors.subject; status?: AttendanceStatus; onAttended: () => void; onAbsent: () => void }) {
const palette = colors.subject[tone];
const isAttended = status === 'attended';
const isAbsent = status === 'absent';
return <View style={styles.attendanceActions}>
<Pressable accessibilityRole="button" accessibilityLabel="Mark attended" onPress={onAttended} style={({ pressed }) => [styles.attendanceButton, { borderColor: palette.accent }, pressed && styles.actionPressed]}>
<Ionicons name="checkmark" size={18} color={palette.accent} />
<Pressable
accessibilityRole="button"
accessibilityLabel="Mark attended"
onPress={onAttended}
style={({ pressed }) => [
styles.attendanceButton,
{ borderColor: isAttended ? colors.semantic.success.solid : palette.accent },
isAttended && { backgroundColor: colors.semantic.success.solid },
pressed && styles.actionPressed,
]}>
<Ionicons name="checkmark" size={18} color={isAttended ? colors.neutral.surface : palette.accent} />
</Pressable>
<Pressable accessibilityRole="button" accessibilityLabel="Mark absent" onPress={onAbsent} style={({ pressed }) => [styles.attendanceButton, { borderColor: palette.accent }, pressed && styles.actionPressed]}>
<Ionicons name="close" size={18} color={palette.accent} />
<Pressable
accessibilityRole="button"
accessibilityLabel="Mark absent"
onPress={onAbsent}
style={({ pressed }) => [
styles.attendanceButton,
{ borderColor: isAbsent ? colors.semantic.danger.solid : palette.accent },
isAbsent && { backgroundColor: colors.semantic.danger.solid },
pressed && styles.actionPressed,
]}>
<Ionicons name="close" size={18} color={isAbsent ? colors.neutral.surface : palette.accent} />
</Pressable>
</View>;
}
function CalendarSheet({ visible, month, selectedDateKey, todayKey, onMonthChange, onClose, onSelect }: { visible: boolean; month: Date; selectedDateKey: string; todayKey: string; onMonthChange: (date: Date) => void; onClose: () => void; onSelect: (date: Date) => void }) {
const markerColorMap = {
none: 'transparent',
success: colors.semantic.success.solid,
warning: colors.semantic.warning.solid,
danger: colors.semantic.danger.solid,
neutral: colors.neutral.textMuted,
} as const;
function InlineCalendarWidget({
month,
selectedDateKey,
todayKey,
markers = {},
allowWeekends = false,
onMonthChange,
onSelect,
}: {
month: Date;
selectedDateKey: string;
todayKey: string;
markers?: Record<string, DayMarker>;
allowWeekends?: boolean;
onMonthChange: (date: Date) => void;
onSelect: (date: Date) => void;
}) {
const offset = (month.getDay() + 6) % 7;
const dates = Array.from({ length: offset + daysInMonth(month) }, (_, index) => index < offset ? null : index - offset + 1);
const weekdayLabels = Array.from({ length: 7 }, (_, index) => new Intl.DateTimeFormat(undefined, { weekday: 'narrow' }).format(addDays(mondayOfWeek(new Date()), index)));
return <BottomSheet visible={visible} title="Choose a date" onClose={onClose}>
<View style={styles.monthNavigation}>
<IconButton icon="chevron-back" label="Previous month" onPress={() => onMonthChange(new Date(month.getFullYear(), month.getMonth() - 1, 1))} />
<AppText variant="title">{new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' }).format(month)}</AppText>
<IconButton icon="chevron-forward" label="Next month" onPress={() => onMonthChange(new Date(month.getFullYear(), month.getMonth() + 1, 1))} />
const dates = Array.from({ length: offset + daysInMonth(month) }, (_, index) => (index < offset ? null : index - offset + 1));
const weekdayLabels = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
return (
<View style={styles.calendarWidget}>
<View style={styles.monthNavigation}>
<IconButton icon="chevron-back" label="Previous month" tone="ghost" onPress={() => onMonthChange(new Date(month.getFullYear(), month.getMonth() - 1, 1))} />
<AppText variant="title">{formatMonthYear(month)}</AppText>
<IconButton icon="chevron-forward" label="Next month" tone="ghost" onPress={() => onMonthChange(new Date(month.getFullYear(), month.getMonth() + 1, 1))} />
</View>
<View style={styles.calendarWeekdays}>
{weekdayLabels.map((label, index) => {
const isWeekendCol = index >= 5;
const disabledCol = isWeekendCol && !allowWeekends;
return (
<AppText
key={`${label}-${index}`}
variant="caption"
color={disabledCol ? colors.neutral.textDisabled : colors.neutral.textMuted}
style={[styles.calendarWeekday, disabledCol && styles.calendarDisabledText]}>
{label}
</AppText>
);
})}
</View>
<View style={styles.calendarGrid}>
{dates.map((day, index) => {
if (!day) return <View key={`empty-${index}`} style={styles.calendarCell} />;
const date = new Date(month.getFullYear(), month.getMonth(), day);
const key = dateKey(date);
const dayOfWeek = date.getDay();
const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
const isDisabled = isWeekend && !allowWeekends;
const selected = key === selectedDateKey;
const isToday = key === todayKey;
const marker = markers[key] ?? 'none';
return (
<Pressable
key={key}
accessibilityRole="button"
accessibilityLabel={formatDayHeading(date)}
accessibilityState={{ selected, disabled: isDisabled }}
disabled={isDisabled}
onPress={() => onSelect(date)}
style={({ pressed }) => [
styles.calendarCell,
selected && styles.calendarSelected,
isToday && !selected && styles.calendarToday,
isDisabled && styles.calendarCellDisabled,
pressed && !isDisabled && styles.actionPressed,
]}>
<AppText
variant="label"
color={selected ? colors.brand.ink : isDisabled ? colors.neutral.textDisabled : colors.neutral.textPrimary}
style={[styles.timeText, isDisabled && styles.calendarDisabledText]}>
{day}
</AppText>
<View style={styles.indicatorRow}>
<View
style={[
styles.dot,
isToday && !selected && styles.todayDot,
marker !== 'none' && !isDisabled && { backgroundColor: markerColorMap[marker] },
]}
/>
</View>
</Pressable>
);
})}
</View>
</View>
<View style={styles.calendarWeekdays}>{weekdayLabels.map((label, index) => <AppText key={`${label}-${index}`} variant="caption" color={colors.neutral.textMuted} style={styles.calendarWeekday}>{label}</AppText>)}</View>
<View style={styles.calendarGrid}>{dates.map((day, index) => {
if (!day) return <View key={`empty-${index}`} style={styles.calendarCell} />;
const date = new Date(month.getFullYear(), month.getMonth(), day);
const key = dateKey(date);
const selected = key === selectedDateKey;
const isToday = key === todayKey;
return <Pressable key={key} accessibilityRole="button" accessibilityLabel={formatDayHeading(date)} accessibilityState={{ selected }} onPress={() => onSelect(date)} style={[styles.calendarCell, selected && styles.calendarSelected, isToday && !selected && styles.calendarToday]}>
<AppText variant="label" color={selected ? colors.brand.ink : colors.neutral.textPrimary} style={styles.timeText}>{day}</AppText>
</Pressable>;
})}</View>
<Button label="Go to today" variant="secondary" onPress={() => onSelect(new Date())} leading={<Ionicons name="locate-outline" size={18} color={colors.brand.cobalt} />} style={styles.calendarButton} />
</BottomSheet>;
);
}
const styles = StyleSheet.create({
@@ -283,17 +426,62 @@ const styles = StyleSheet.create({
content: { paddingTop: spacing[1], paddingBottom: 0 },
stickyHeader: { flexShrink: 0 },
dateActions: { minHeight: 44, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', gap: spacing[1], marginBottom: spacing[3] },
insight: { marginTop: spacing[5] },
headerRow: { flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between', gap: spacing[2], marginBottom: spacing[3] },
headerTitle: { flex: 1, minHeight: 0 },
headerActions: { flexDirection: 'row', alignItems: 'center', gap: spacing[2], paddingTop: spacing[1] },
avatar: { width: 40, height: 40, borderRadius: radius.control, borderCurve: 'continuous', backgroundColor: colors.brand.cobaltSoft, alignItems: 'center', justifyContent: 'center' },
avatarPressed: { opacity: 0.78 },
pickerContainer: {
marginTop: spacing[1],
borderRadius: radius.feature,
borderCurve: 'continuous',
backgroundColor: colors.brand.skySoft,
overflow: 'hidden',
borderWidth: 1,
borderColor: '#E2F0FA',
},
weekStrip: {
width: '100%',
borderRadius: 0,
backgroundColor: 'transparent',
},
calendarWidget: {
backgroundColor: 'transparent',
paddingHorizontal: spacing[2],
paddingTop: spacing[3],
paddingBottom: spacing[1],
},
extendBar: {
height: 16,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
borderTopWidth: 1,
borderTopColor: '#E2EEF8',
},
extendHandle: {
width: 36,
height: 3.5,
borderRadius: 2,
backgroundColor: colors.neutral.textDisabled,
opacity: 0.7,
},
extendBarPressed: { opacity: 0.6 },
calendarCellDisabled: { opacity: 0.28 },
calendarDisabledText: { textDecorationLine: 'none' },
indicatorRow: { height: 5, marginTop: 1, justifyContent: 'center', alignItems: 'center' },
dot: { width: 4, height: 4, borderRadius: 2, backgroundColor: 'transparent' },
todayDot: { width: 4.5, height: 4.5, borderRadius: 2.5, backgroundColor: colors.brand.cobalt },
insight: { marginTop: spacing[4] },
sectionHeader: { marginTop: spacing[8], marginBottom: spacing[4], flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[4] },
sectionCopy: { flex: 1 },
sectionSubtitle: { marginTop: spacing[1] },
loading: { minHeight: 112, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing[3] },
timeline: { gap: spacing[2] },
classRow: { flexDirection: 'row', alignItems: 'stretch' },
timeRail: { width: 54, alignItems: 'flex-start', paddingTop: spacing[4], position: 'relative' },
timeText: { fontVariant: ['tabular-nums'] },
railLine: { position: 'absolute', top: 58, bottom: -10, left: 4, width: 1, backgroundColor: colors.neutral.divider },
timeRail: { width: 50, alignItems: 'flex-start', paddingTop: spacing[4], position: 'relative' },
timeText: { fontVariant: ['tabular-nums'], fontSize: 13, lineHeight: 17, fontWeight: '700', color: colors.neutral.textSecondary },
railLine: { position: 'absolute', top: 38, bottom: -10, left: 4, width: 1, backgroundColor: colors.neutral.divider },
classList: { flex: 1, minHeight: 0 },
classListContent: { paddingTop: spacing[4], paddingBottom: size.tabBar + spacing[6] },
event: { flex: 1, marginBottom: spacing[2] },
@@ -306,7 +494,7 @@ const styles = StyleSheet.create({
calendarWeekdays: { flexDirection: 'row', marginBottom: spacing[2] },
calendarWeekday: { width: '14.2857%', textAlign: 'center' },
calendarGrid: { flexDirection: 'row', flexWrap: 'wrap' },
calendarCell: { width: '14.2857%', aspectRatio: 1, alignItems: 'center', justifyContent: 'center', borderRadius: radius.control },
calendarCell: { width: '14.2857%', aspectRatio: 1, alignItems: 'center', justifyContent: 'center', borderRadius: radius.control, borderCurve: 'continuous' },
calendarSelected: { backgroundColor: colors.brand.coral },
calendarToday: { borderWidth: 2, borderColor: colors.brand.cobalt },
calendarButton: { marginTop: spacing[5] },

View File

@@ -1,12 +1,13 @@
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect, useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import { ActivityIndicator, Alert, StyleSheet, View } from 'react-native';
import { AddClassModal } from '@/components/add-class-modal';
import {
AppHeader,
AppText,
BottomSheet,
Button,
Card,
EmptyState,
@@ -20,7 +21,15 @@ import {
spacing,
type WeekDay,
} from '@/components/ui';
import { addDays, dateKey, formatDayHeading, mondayOfWeek } from '@/lib/date';
import {
addDays,
dateKey,
formatDayHeading,
formatMonthShortDay,
formatWeekdayLong,
formatYear,
mondayOfWeek,
} from '@/lib/date';
import { subjectToneFor } from '@/lib/design';
import { collegeApi } from '@/lib/api';
@@ -38,6 +47,7 @@ export default function TimetableScreen() {
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [addClassOpen, setAddClassOpen] = useState(false);
const [selectedTimetableClass, setSelectedTimetableClass] = useState<TimetableClass | null>(null);
const [refresh, setRefresh] = useState(0);
const selectedDateKey = dateKey(activeDate);
@@ -69,7 +79,7 @@ export default function TimetableScreen() {
useEffect(() => { load(); }, [load, refresh]);
const moveWeek = (amount: number) => setActiveDate(addDays(activeDate, amount * 7));
const weekday = new Intl.DateTimeFormat(undefined, { weekday: 'long' }).format(activeDate);
const weekday = formatWeekdayLong(activeDate);
const showRecess = recess.enabled && recess.start < recess.end;
const timelineItems = [
...schedule.map((item) => ({ type: 'class' as const, start: item.startTime, end: item.endTime, item })),
@@ -77,20 +87,20 @@ export default function TimetableScreen() {
].sort((left, right) => left.start.localeCompare(right.start) || (left.type === 'recess' ? -1 : 1));
return <Screen contentContainerStyle={styles.content}>
<AppHeader title="Timetable" />
<AppHeader title="Timetable" style={styles.header} />
<View style={styles.weekToolbar}>
<IconButton icon="chevron-back" label="Previous week" tone="ghost" onPress={() => moveWeek(-1)} />
<View style={styles.weekCopy}>
<AppText variant="label">Week of {new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' }).format(weekStart)}</AppText>
<AppText variant="caption" color={colors.neutral.textMuted}>{new Intl.DateTimeFormat(undefined, { year: 'numeric' }).format(activeDate)}</AppText>
<AppText variant="label">Week of {formatMonthShortDay(weekStart)}</AppText>
<AppText variant="caption" color={colors.neutral.textMuted}>{formatYear(activeDate)}</AppText>
</View>
<View style={styles.toolbarActions}>
{todayKey !== selectedDateKey ? <Button label="This week" variant="ghost" size="compact" fullWidth={false} onPress={() => setActiveDate(new Date())} /> : null}
<IconButton icon="chevron-forward" label="Next week" tone="ghost" onPress={() => moveWeek(1)} />
</View>
</View>
<WeekStrip days={weekDays} selectedDateKey={selectedDateKey} todayDateKey={todayKey} onSelect={setActiveDate} />
<WeekStrip days={weekDays} selectedDateKey={selectedDateKey} todayDateKey={todayKey} onSelect={setActiveDate} style={styles.weekStrip} />
<View style={styles.sectionHeader}>
<View style={styles.sectionCopy}>
@@ -119,6 +129,7 @@ export default function TimetableScreen() {
room={entry.item.room}
subjectTone={subjectToneFor(entry.item.subjectId, entry.item.color)}
style={styles.event}
topAction={<IconButton icon="ellipsis-horizontal" label={`Options for ${entry.item.subjectName}`} tone="ghost" onPress={() => setSelectedTimetableClass(entry.item)} />}
onPress={() => router.push(`/subjects/${entry.item.subjectId}` as never)}
/>}
</View>)}
@@ -139,14 +150,69 @@ export default function TimetableScreen() {
onClose={() => setAddClassOpen(false)}
onAdded={() => setRefresh((value) => value + 1)}
/>
<BottomSheet
visible={Boolean(selectedTimetableClass)}
title="Recurring class options"
onClose={() => setSelectedTimetableClass(null)}>
{selectedTimetableClass ? <>
<Card tone="skySoft" style={styles.selectedClassSummary}>
<AppText variant="title">{selectedTimetableClass.subjectName}</AppText>
<AppText variant="bodySmall" color={colors.neutral.textSecondary} style={styles.sectionSub}>
{selectedTimetableClass.code} · {selectedTimetableClass.startTime}{selectedTimetableClass.endTime} · {selectedTimetableClass.room}
</AppText>
</Card>
<View style={styles.sheetButtons}>
<Button
label="View subject"
variant="secondary"
onPress={() => {
const id = selectedTimetableClass.subjectId;
setSelectedTimetableClass(null);
router.push(`/subjects/${id}` as never);
}}
leading={<Ionicons name="book-outline" size={18} color={colors.brand.cobalt} />}
/>
<Button
label="Delete recurring class"
variant="ghost"
onPress={() => {
Alert.alert(
'Delete recurring class?',
'This will stop this class from repeating in future weeks. Past class records will be preserved.',
[
{ text: 'Keep', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: async () => {
try {
await collegeApi.deleteTimetableClass(selectedTimetableClass.id);
setSelectedTimetableClass(null);
setRefresh((v) => v + 1);
} catch (err) {
Alert.alert('Couldnt delete class', err instanceof Error ? err.message : 'Please try again.');
}
},
},
]
);
}}
leading={<Ionicons name="trash-outline" size={18} color={colors.semantic.danger.text} />}
/>
</View>
</> : null}
</BottomSheet>
</Screen>;
}
const styles = StyleSheet.create({
content: { paddingTop: spacing[1], paddingBottom: spacing[9] },
weekToolbar: { marginTop: spacing[6], marginBottom: spacing[3], flexDirection: 'row', alignItems: 'center', gap: spacing[2] },
header: { paddingTop: spacing[2], minHeight: 0 },
weekToolbar: { marginTop: spacing[3], marginBottom: spacing[3], flexDirection: 'row', alignItems: 'center', gap: spacing[2] },
weekCopy: { flex: 1, alignItems: 'center' },
toolbarActions: { flexDirection: 'row', alignItems: 'center' },
weekStrip: { marginTop: spacing[1] },
sectionHeader: { marginTop: spacing[8], marginBottom: spacing[4], flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[4] },
sectionCopy: { flex: 1 },
sectionSub: { marginTop: spacing[1] },
@@ -158,4 +224,6 @@ const styles = StyleSheet.create({
railLine: { position: 'absolute', top: 58, bottom: -10, left: 4, width: 1, backgroundColor: colors.neutral.divider },
event: { flex: 1, marginBottom: spacing[2] },
note: { marginTop: spacing[6] },
selectedClassSummary: { marginTop: spacing[2] },
sheetButtons: { gap: spacing[2], marginTop: spacing[5] },
});

View File

@@ -121,11 +121,11 @@ function Info({ icon, label, value }: { icon: keyof typeof Ionicons.glyphMap; la
}
const styles = StyleSheet.create({
content: { paddingBottom: spacing[9] },
content: { paddingTop: spacing[1], paddingBottom: spacing[9] },
loading: { minHeight: 220, alignItems: 'center', justifyContent: 'center', gap: spacing[3] },
error: { marginTop: spacing[6] },
profileHero: { marginTop: spacing[5], alignItems: 'center', borderRadius: radius.feature, backgroundColor: colors.brand.sky, padding: spacing[7] },
avatar: { width: 82, height: 82, borderRadius: 27, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.neutral.surface },
error: { marginTop: spacing[4] },
profileHero: { marginTop: spacing[3], alignItems: 'center', borderRadius: radius.feature, borderCurve: 'continuous', backgroundColor: colors.brand.sky, padding: spacing[7] },
avatar: { width: 82, height: 82, borderRadius: 27, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.neutral.surface },
avatarDot: { position: 'absolute', right: 2, top: 2, width: 14, height: 14, borderRadius: 7, backgroundColor: colors.brand.coral, borderWidth: 3, borderColor: colors.neutral.surface },
name: { marginTop: spacing[4], textAlign: 'center' },
college: { marginTop: spacing[1], textAlign: 'center' },
@@ -135,7 +135,7 @@ const styles = StyleSheet.create({
sectionTitle: { marginTop: spacing[8], marginBottom: spacing[3] },
details: { overflow: 'hidden' },
info: { minHeight: 78, flexDirection: 'row', alignItems: 'center', gap: spacing[3], paddingHorizontal: spacing[4], paddingVertical: spacing[3] },
infoIcon: { width: 40, height: 40, borderRadius: radius.control, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.brand.cobaltSoft },
infoIcon: { width: 40, height: 40, borderRadius: radius.control, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.brand.cobaltSoft },
infoCopy: { flex: 1 },
infoValue: { marginTop: spacing[1] },
divider: { height: 1, marginLeft: 68, marginRight: spacing[4], backgroundColor: colors.neutral.divider },

View File

@@ -142,7 +142,7 @@ export default function OnboardingScreen() {
const styles = StyleSheet.create({
content: { paddingTop: spacing[5], paddingBottom: spacing[9] },
brand: { flexDirection: 'row', alignItems: 'center', gap: spacing[3] },
logo: { width: 40, height: 40, borderRadius: radius.control, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.brand.cobalt },
logo: { width: 40, height: 40, borderRadius: radius.control, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.brand.cobalt },
progress: { flexDirection: 'row', gap: spacing[2], marginTop: spacing[8] },
progressSegment: { flex: 1, height: 5, borderRadius: radius.pill, backgroundColor: colors.neutral.divider },
progressActive: { backgroundColor: colors.brand.cobalt },

View File

@@ -1,4 +1,5 @@
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, StyleSheet, Switch, View } from 'react-native';
@@ -17,6 +18,7 @@ import {
import { collegeApi } from '@/lib/api';
export default function SettingsScreen() {
const router = useRouter();
const [name, setName] = useState('');
const [college, setCollege] = useState('');
const [programme, setProgramme] = useState('');
@@ -76,7 +78,7 @@ export default function SettingsScreen() {
};
return <Screen contentContainerStyle={styles.content}>
<AppHeader title="Settings" />
<AppHeader title="Settings" style={styles.header} />
{loading ? <View style={styles.loading}><ActivityIndicator color={colors.brand.cobalt} /><AppText variant="bodySmall" color={colors.neutral.textSecondary}>Loading settings</AppText></View> : null}
{loadError ? <InlineBanner title="Couldnt load settings" message={loadError} tone="danger" action={<Button label="Retry" variant="ghost" size="compact" fullWidth={false} onPress={load} />} style={styles.firstBlock} /> : null}
@@ -155,16 +157,27 @@ export default function SettingsScreen() {
</Card>
<Button label="Save settings" loading={saving} haptic="success" onPress={save} style={styles.save} />
<AppText variant="heading3" style={styles.sectionTitle}>Account</AppText>
<Card style={styles.card} padding={0}>
<Button
label="View full account profile"
variant="secondary"
onPress={() => router.push('/account' as never)}
leading={<Ionicons name="person-outline" size={18} color={colors.brand.cobalt} />}
/>
</Card>
</> : null}
</Screen>;
}
const styles = StyleSheet.create({
content: { paddingBottom: spacing[9] },
content: { paddingTop: spacing[1], paddingBottom: spacing[9] },
header: { paddingTop: spacing[2], minHeight: 0 },
loading: { minHeight: 240, alignItems: 'center', justifyContent: 'center', gap: spacing[3] },
firstBlock: { marginTop: spacing[6] },
intro: { marginTop: spacing[5], flexDirection: 'row', alignItems: 'center', gap: spacing[4] },
introIcon: { width: 48, height: 48, borderRadius: radius.card, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.neutral.surface },
firstBlock: { marginTop: spacing[4] },
intro: { marginTop: spacing[3], flexDirection: 'row', alignItems: 'center', gap: spacing[4] },
introIcon: { width: 48, height: 48, borderRadius: radius.card, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.neutral.surface },
introCopy: { flex: 1 },
introText: { marginTop: spacing[1] },
feedback: { marginTop: spacing[4] },
@@ -172,7 +185,7 @@ const styles = StyleSheet.create({
card: { padding: spacing[5] },
fields: { gap: spacing[4] },
settingHeading: { flexDirection: 'row', alignItems: 'center', gap: spacing[3] },
settingIcon: { width: 40, height: 40, borderRadius: radius.control, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.brand.cobaltSoft },
settingIcon: { width: 40, height: 40, borderRadius: radius.control, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.brand.cobaltSoft },
settingCopy: { flex: 1 },
settingSub: { marginTop: spacing[1] },
nestedField: { marginTop: spacing[5], marginLeft: 52 },

View File

@@ -1,7 +1,7 @@
import { Ionicons } from '@expo/vector-icons';
import { router, useLocalSearchParams } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import { ActivityIndicator, Alert, StyleSheet, View } from 'react-native';
import {
AppHeader,
@@ -94,6 +94,28 @@ export default function SubjectDetailsScreen() {
}
};
const deleteSubject = () => {
Alert.alert(
'Delete subject?',
`Are you sure you want to delete ${data?.name}? This will remove its timetable classes and attendance records.`,
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: async () => {
try {
await collegeApi.deleteSubject(subjectId);
router.back();
} catch (err) {
Alert.alert('Couldnt delete subject', err instanceof Error ? err.message : 'Please try again.');
}
},
},
]
);
};
if (loading && !data) return <Screen scroll={false} contentContainerStyle={styles.center}><ActivityIndicator color={colors.brand.cobalt} /><AppText variant="bodySmall" color={colors.neutral.textSecondary} style={styles.loadingText}>Loading subject</AppText></Screen>;
if (!data) return <Screen contentContainerStyle={styles.content}>
<AppHeader compact title="Subject details" leading={<IconButton icon="chevron-back" label="Go back" onPress={() => router.back()} />} />
@@ -141,6 +163,7 @@ export default function SubjectDetailsScreen() {
<FormField label="Default room or location" value={defaultRoom} onChangeText={setDefaultRoom} placeholder="e.g. B-204 or Lab 3" hint="Used automatically when you add a class." autoCapitalize="words" />
</View>
<Button label="Save changes" loading={saving} haptic="success" onPress={save} />
<Button label="Delete subject" variant="ghost" onPress={deleteSubject} leading={<Ionicons name="trash-outline" size={18} color={colors.semantic.danger.text} />} style={styles.deleteButton} />
</Card> : <>
<InlineBanner title={summaryCopy.title} message={summaryCopy.message} tone={summaryTone} style={styles.insight} />
<Card padding={0} style={styles.stats}>
@@ -182,13 +205,13 @@ function Stat({ value, label }: { value: number; label: string }) {
}
const styles = StyleSheet.create({
content: { paddingBottom: spacing[9] },
content: { paddingTop: spacing[1], paddingBottom: spacing[9] },
center: { alignItems: 'center', justifyContent: 'center' },
loadingText: { marginTop: spacing[3] },
error: { marginTop: spacing[6] },
hero: { marginTop: spacing[5], borderRadius: radius.feature, padding: spacing[6] },
error: { marginTop: spacing[4] },
hero: { marginTop: spacing[3], borderRadius: radius.feature, borderCurve: 'continuous', padding: spacing[6] },
heroIdentity: { flexDirection: 'row', alignItems: 'center', gap: spacing[4] },
badge: { width: 52, height: 52, borderRadius: 17 },
badge: { width: 52, height: 52, borderRadius: 17, borderCurve: 'continuous' },
heroCopy: { flex: 1 },
heroMeta: { marginTop: spacing[1] },
heroProgress: { marginTop: spacing[6], flexDirection: 'row', alignItems: 'flex-end', gap: spacing[5] },
@@ -197,6 +220,7 @@ const styles = StyleSheet.create({
editCard: { marginTop: spacing[4] },
formError: { marginTop: spacing[4] },
fields: { gap: spacing[4], marginVertical: spacing[5] },
deleteButton: { marginTop: spacing[3] },
insight: { marginTop: spacing[4] },
stats: { minHeight: 92, marginTop: spacing[3], flexDirection: 'row', alignItems: 'center' },
stat: { flex: 1, alignItems: 'center', paddingVertical: spacing[5] },

View File

@@ -95,7 +95,10 @@ function ensureSessions(date) {
const create = db.prepare('INSERT OR IGNORE INTO class_sessions (user_id, subject_id, timetable_class_id, class_date, start_time, end_time, room) VALUES (?, ?, ?, ?, ?, ?, ?)');
for (const item of templates) create.run(STUDENT_ID, item.subject_id, item.id, date, item.start_time, item.end_time, item.room);
}
function getSubject(id) { return db.prepare('SELECT id FROM subjects WHERE id = ? AND user_id = ?').get(id, STUDENT_ID); }
function getSubject(id) {
if (id === undefined || id === null || Number.isNaN(Number(id))) return null;
return db.prepare('SELECT id FROM subjects WHERE id = ? AND user_id = ?').get(Number(id), STUDENT_ID);
}
migrate();
const server = createServer(async (req, res) => {
@@ -130,6 +133,8 @@ const server = createServer(async (req, res) => {
const body = await readBody(req);
const { subjectId, date, startTime, endTime, room } = body;
if (!getSubject(subjectId) || !dateIsValid(date) || !/^\d\d:\d\d$/.test(startTime) || !/^\d\d:\d\d$/.test(endTime) || !room?.trim()) return error(res, 400, 'subjectId, date, startTime, endTime and room are required');
const existing = db.prepare('SELECT id FROM class_sessions WHERE user_id = ? AND subject_id = ? AND class_date = ? AND start_time = ? AND is_removed = 0').get(STUDENT_ID, subjectId, date, startTime);
if (existing) return json(res, 200, { id: existing.id });
const record = db.prepare('INSERT INTO class_sessions (user_id, subject_id, class_date, start_time, end_time, room, is_override) VALUES (?, ?, ?, ?, ?, ?, 1)').run(STUDENT_ID, subjectId, date, startTime, endTime, room.trim());
return json(res, 201, db.prepare('SELECT id FROM class_sessions WHERE id = ?').get(record.lastInsertRowid));
}
@@ -194,6 +199,15 @@ const server = createServer(async (req, res) => {
return json(res, 201, { id: Number(result.lastInsertRowid), effectiveFrom });
}
const timetableMatch = path.match(/^\/api\/v1\/timetable\/classes\/(\d+)$/);
if (req.method === 'DELETE' && timetableMatch) {
const id = Number(timetableMatch[1]);
const existing = db.prepare('SELECT * FROM timetable_classes WHERE id = ? AND user_id = ? AND active = 1').get(id, STUDENT_ID);
if (!existing) return error(res, 404, 'Timetable class not found');
const earliestFutureDate = nextDateKey(localDateKey());
db.prepare('UPDATE timetable_classes SET active = 0, effective_to = ? WHERE id = ?').run(previousDateKey(earliestFutureDate), id);
db.prepare('DELETE FROM class_sessions WHERE timetable_class_id = ? AND class_date >= ? AND is_override = 0').run(id, earliestFutureDate);
return json(res, 200, { id, deleted: true });
}
if (req.method === 'PATCH' && timetableMatch) {
const body = await readBody(req); const id = Number(timetableMatch[1]);
const existing = db.prepare('SELECT * FROM timetable_classes WHERE id = ? AND user_id = ? AND active = 1').get(id, STUDENT_ID);
@@ -222,7 +236,7 @@ const server = createServer(async (req, res) => {
const sessions = db.prepare(`SELECT cs.id, cs.class_date AS date, cs.start_time AS time, cs.end_time AS endTime, cs.room,
COALESCE(a.status, 'pending') AS status FROM class_sessions cs LEFT JOIN attendance a ON a.session_id = cs.id
WHERE cs.subject_id = ? AND cs.user_id = ? ORDER BY cs.class_date DESC, cs.start_time DESC`).all(id, STUDENT_ID);
const eligible = sessions.filter((session) => session.status !== 'cancelled');
const eligible = sessions.filter((session) => session.status === 'attended' || session.status === 'absent');
const attended = eligible.filter((session) => session.status === 'attended').length;
return json(res, 200, { ...subject, summary: { total: eligible.length, attended, absent: eligible.filter((session) => session.status === 'absent').length, percentage: eligible.length ? Math.round(attended / eligible.length * 100) : 0 }, sessions });
}
@@ -235,14 +249,77 @@ const server = createServer(async (req, res) => {
return json(res, 200, { id });
} catch { return error(res, 409, 'A subject with that code already exists'); }
}
if (req.method === 'DELETE' && subjectMatch) {
const id = Number(subjectMatch[1]);
const existing = getSubject(id);
if (!existing) return error(res, 404, 'Subject not found');
// Cascade delete subject's attendance, sessions, and timetable classes
const sessions = db.prepare('SELECT id FROM class_sessions WHERE subject_id = ? AND user_id = ?').all(id, STUDENT_ID);
for (const sess of sessions) {
db.prepare('DELETE FROM attendance WHERE session_id = ?').run(sess.id);
}
db.prepare('DELETE FROM class_sessions WHERE subject_id = ? AND user_id = ?').run(id, STUDENT_ID);
db.prepare('DELETE FROM timetable_classes WHERE subject_id = ? AND user_id = ?').run(id, STUDENT_ID);
db.prepare('DELETE FROM subjects WHERE id = ? AND user_id = ?').run(id, STUDENT_ID);
return json(res, 200, { id, deleted: true });
}
if (req.method === 'GET' && path === '/api/v1/attendance/summary') {
const rows = db.prepare(`SELECT s.id, s.name, s.code, s.color,
COUNT(cs.id) AS total, SUM(CASE WHEN a.status = 'attended' THEN 1 ELSE 0 END) AS attended,
const rows = db.prepare(`SELECT s.id, s.name, s.code, s.short_name AS shortName, s.color,
SUM(CASE WHEN cs.id IS NOT NULL AND a.status IN ('attended', 'absent') THEN 1 ELSE 0 END) AS total,
SUM(CASE WHEN a.status = 'attended' THEN 1 ELSE 0 END) AS attended,
SUM(CASE WHEN a.status = 'absent' THEN 1 ELSE 0 END) AS absent,
SUM(CASE WHEN a.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM subjects s LEFT JOIN class_sessions cs ON cs.subject_id = s.id LEFT JOIN attendance a ON a.session_id = cs.id
FROM subjects s
LEFT JOIN class_sessions cs ON cs.subject_id = s.id AND cs.is_removed = 0
LEFT JOIN attendance a ON a.session_id = cs.id
WHERE s.user_id = ? GROUP BY s.id ORDER BY s.name`).all(STUDENT_ID);
return json(res, 200, { subjects: rows.map(r => ({ ...r, total: Number(r.total) - Number(r.cancelled), percentage: Number(r.total) - Number(r.cancelled) ? Math.round(Number(r.attended) / (Number(r.total) - Number(r.cancelled)) * 100) : 0 })) });
return json(res, 200, {
subjects: rows.map(r => {
const tot = Number(r.total);
const att = Number(r.attended);
return {
id: r.id,
name: r.name,
code: r.code,
shortName: r.shortName,
color: r.color,
total: tot,
attended: att,
absent: Number(r.absent),
cancelled: Number(r.cancelled),
percentage: tot > 0 ? Math.round((att / tot) * 100) : 0,
};
}),
});
}
if (req.method === 'GET' && path === '/api/v1/attendance/markers') {
const month = url.searchParams.get('month'); // Expect YYYY-MM
if (!month || !/^\d{4}-\d{2}$/.test(month)) return error(res, 400, 'month must be YYYY-MM');
const start = `${month}-01`;
const [yearStr, monthStr] = month.split('-');
const days = new Date(Number(yearStr), Number(monthStr), 0).getDate();
const end = `${month}-${String(days).padStart(2, '0')}`;
const sessions = db.prepare(`SELECT cs.class_date AS date, COALESCE(a.status, 'pending') AS status
FROM class_sessions cs
LEFT JOIN attendance a ON a.session_id = cs.id
WHERE cs.user_id = ? AND cs.class_date >= ? AND cs.class_date <= ? AND cs.is_removed = 0`).all(STUDENT_ID, start, end);
const byDate = {};
for (const row of sessions) {
if (!byDate[row.date]) byDate[row.date] = [];
byDate[row.date].push(row.status);
}
const today = localDateKey();
const markers = {};
for (const [date, statuses] of Object.entries(byDate)) {
if (date > today) continue;
const held = statuses.filter((s) => s !== 'cancelled');
if (!held.length) continue;
if (held.every((s) => s === 'attended')) markers[date] = 'success';
else if (held.some((s) => s === 'absent')) markers[date] = 'danger';
else if (held.some((s) => s === 'pending')) markers[date] = 'warning';
else markers[date] = 'neutral';
}
return json(res, 200, { markers });
}
return error(res, 404, 'Route not found');
} catch (err) { console.error(err); return error(res, 400, err.message || 'Bad request'); }

View File

@@ -13,7 +13,7 @@ import {
radius,
spacing,
} from '@/components/ui';
import { dateFromKey, formatDayHeading, timeToMinutes } from '@/lib/date';
import { dateFromKey, formatDayHeading, formatWeekdayLong, timeToMinutes } from '@/lib/date';
import { subjectToneFor } from '@/lib/design';
import { collegeApi, type Subject } from '@/lib/api';
@@ -112,7 +112,7 @@ export function AddClassModal({ visible, onClose, onAdded, date, regular = false
const title = regular ? 'Add recurring class' : 'Add a class';
const context = regular
? `Repeats on ${new Intl.DateTimeFormat(undefined, { weekday: 'long' }).format(dateFromKey(date))}. Recurring changes begin in the future.`
? `Repeats on ${formatWeekdayLong(dateFromKey(date))}. Recurring changes begin in the future.`
: `One-off class for ${formatDayHeading(dateFromKey(date))}.`;
return <BottomSheet
@@ -167,7 +167,7 @@ const styles = StyleSheet.create({
loading: { minHeight: 180, alignItems: 'center', justifyContent: 'center', gap: spacing[3] },
sectionLabel: { marginTop: spacing[6], marginBottom: spacing[3] },
subjects: { gap: spacing[2] },
subject: { minHeight: 58, flexDirection: 'row', alignItems: 'center', gap: spacing[3], paddingHorizontal: spacing[3], paddingVertical: spacing[2], borderRadius: radius.card, borderWidth: 1, borderColor: colors.neutral.border, backgroundColor: colors.neutral.surface },
subject: { minHeight: 58, flexDirection: 'row', alignItems: 'center', gap: spacing[3], paddingHorizontal: spacing[3], paddingVertical: spacing[2], borderRadius: radius.card, borderCurve: 'continuous', borderWidth: 1, borderColor: colors.neutral.border, backgroundColor: colors.neutral.surface },
pressed: { opacity: 0.76 },
subjectCopy: { flex: 1 },
radio: { width: 20, height: 20, borderRadius: 10, borderWidth: 2, borderColor: colors.neutral.border, alignItems: 'center', justifyContent: 'center' },

View File

@@ -1,7 +1,7 @@
import type { ReactNode } from 'react';
import { StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { AppText } from './app-text';
import { colors, size, spacing } from './tokens';
import { colors, radius, size, spacing } from './tokens';
type Props = {
title: string;
@@ -9,33 +9,46 @@ type Props = {
subtitle?: string;
leading?: ReactNode;
trailing?: ReactNode;
avatar?: { initials: string; onPress: () => void };
compact?: boolean;
style?: StyleProp<ViewStyle>;
};
export function AppHeader({ title, context, subtitle, leading, trailing, compact = false, style }: Props) {
export function AppHeader({ title, context, subtitle, leading, trailing, avatar, compact = false, style }: Props) {
if (compact) return <View style={[styles.compact, style]}>
<View style={styles.side}>{leading}</View>
<AppText variant="title" numberOfLines={1} style={styles.compactTitle}>{title}</AppText>
<View style={[styles.side, styles.trailing]}>{trailing}</View>
</View>;
const resolvedTrailing = trailing ?? (avatar ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Open account profile"
onPress={avatar.onPress}
style={({ pressed }) => [styles.avatar, pressed && styles.avatarPressed]}>
<AppText variant="label" color={colors.brand.cobalt}>{avatar.initials || '?'}</AppText>
</Pressable>
) : null);
return <View style={[styles.root, style]}>
<View style={styles.copy}>
{context ? <AppText variant="bodySmall" color={colors.neutral.textMuted}>{context}</AppText> : null}
<AppText variant="heading1" style={context ? styles.titleWithContext : undefined}>{title}</AppText>
{subtitle ? <AppText variant="bodySmall" color={colors.neutral.textSecondary} style={styles.subtitle}>{subtitle}</AppText> : null}
</View>
{trailing ? <View style={styles.rootTrailing}>{trailing}</View> : null}
{resolvedTrailing ? <View style={styles.rootTrailing}>{resolvedTrailing}</View> : null}
</View>;
}
const styles = StyleSheet.create({
root: { minHeight: 76, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[5], paddingTop: spacing[6] },
root: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[5], paddingTop: spacing[4] },
copy: { flex: 1 },
titleWithContext: { marginTop: spacing[1] },
subtitle: { marginTop: spacing[1] },
rootTrailing: { alignSelf: 'flex-start', paddingTop: spacing[1] },
avatar: { width: 40, height: 40, borderRadius: radius.control, borderCurve: 'continuous', backgroundColor: colors.brand.cobaltSoft, alignItems: 'center', justifyContent: 'center' },
avatarPressed: { opacity: 0.78 },
compact: { height: 56, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
side: { width: size.touchTargetMin, minHeight: size.touchTargetMin, justifyContent: 'center' },
trailing: { alignItems: 'flex-end' },

View File

@@ -39,7 +39,7 @@ const styles = StyleSheet.create({
overlay: { flex: 1, justifyContent: 'flex-end', backgroundColor: colors.neutral.scrim },
backdrop: { ...StyleSheet.absoluteFillObject },
keyboard: { width: '100%', maxHeight: '92%' },
sheet: { borderTopLeftRadius: radius.sheet, borderTopRightRadius: radius.sheet, backgroundColor: colors.neutral.surface, paddingHorizontal: spacing[6], paddingTop: spacing[3], ...shadow.floating },
sheet: { borderTopLeftRadius: radius.sheet, borderTopRightRadius: radius.sheet, borderCurve: 'continuous', backgroundColor: colors.neutral.surface, paddingHorizontal: spacing[6], paddingTop: spacing[3], ...shadow.floating },
handle: { width: 36, height: 4, alignSelf: 'center', borderRadius: radius.pill, backgroundColor: colors.neutral.border },
header: { minHeight: 60, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[4] },
body: { paddingBottom: spacing[5] },

View File

@@ -47,10 +47,10 @@ export function BottomTabBar({ state, descriptors, navigation, insets }: BottomT
}
const styles = StyleSheet.create({
floatingArea: { position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: spacing[5], paddingTop: spacing[3], backgroundColor: 'transparent' },
bar: { minHeight: size.touchTargetMin + spacing[3], flexDirection: 'row', alignItems: 'center', gap: spacing[1], padding: spacing[2], borderRadius: radius.sheet, borderWidth: 1, borderColor: colors.neutral.border, backgroundColor: colors.neutral.surface, ...shadow.floating },
tab: { minHeight: size.touchTargetMin, flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1, borderRadius: radius.pill, paddingHorizontal: spacing[2] },
tabActive: { flexDirection: 'row', flexGrow: 1.28, gap: spacing[2], backgroundColor: colors.brand.cobalt, paddingHorizontal: spacing[4] },
label: { textAlign: 'center' },
floatingArea: { position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: spacing[4], paddingTop: spacing[3], backgroundColor: 'transparent' },
bar: { minHeight: size.touchTargetMin + spacing[3], flexDirection: 'row', alignItems: 'center', gap: 2, padding: spacing[2], borderRadius: radius.sheet, borderCurve: 'continuous', borderWidth: 1, borderColor: colors.neutral.border, backgroundColor: colors.neutral.surface, ...shadow.floating },
tab: { minHeight: size.touchTargetMin, flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2, borderRadius: radius.pill, borderCurve: 'continuous', paddingHorizontal: spacing[1] },
tabActive: { flexDirection: 'row', flexGrow: 1.15, gap: spacing[1] + 2, backgroundColor: colors.brand.cobalt, paddingHorizontal: spacing[3] },
label: { textAlign: 'center', flexShrink: 0 },
pressed: { opacity: 0.76 },
});

View File

@@ -50,8 +50,8 @@ export function Button({ label, onPress, variant = 'primary', size: buttonSize =
}
const styles = StyleSheet.create({
base: { minHeight: size.control, paddingHorizontal: spacing[5], borderRadius: 14, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing[2] },
compact: { minHeight: 40, paddingHorizontal: spacing[4], borderRadius: 12 },
base: { minHeight: size.control, paddingHorizontal: spacing[5], borderRadius: 14, borderCurve: 'continuous', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing[2] },
compact: { minHeight: 40, paddingHorizontal: spacing[4], borderRadius: 12, borderCurve: 'continuous' },
fullWidth: { alignSelf: 'stretch' },
pressed: { transform: [{ scale: motion.pressedScale }] },
disabled: { backgroundColor: colors.neutral.surfaceSubtle, borderColor: colors.neutral.surfaceSubtle },

View File

@@ -19,5 +19,5 @@ export function Card({ children, tone = 'surface', padding = spacing[5], style,
}
const styles = StyleSheet.create({
base: { borderRadius: radius.card },
base: { borderRadius: radius.card, borderCurve: 'continuous' },
});

View File

@@ -35,7 +35,7 @@ export function FormField({ label, hint, error, containerStyle, editable = true,
const styles = StyleSheet.create({
label: { marginBottom: spacing[2] },
inputWrap: { minHeight: size.control, flexDirection: 'row', alignItems: 'center', borderRadius: radius.control, borderWidth: 1, borderColor: colors.neutral.border, backgroundColor: colors.neutral.surface, paddingHorizontal: spacing[4] },
inputWrap: { minHeight: size.control, flexDirection: 'row', alignItems: 'center', borderRadius: radius.control, borderCurve: 'continuous', borderWidth: 1, borderColor: colors.neutral.border, backgroundColor: colors.neutral.surface, paddingHorizontal: spacing[4] },
inputFocused: { borderColor: colors.brand.cobalt, borderWidth: 2, paddingHorizontal: spacing[3] + 1 },
inputError: { borderColor: colors.semantic.danger.solid, borderWidth: 2, paddingHorizontal: spacing[3] + 1 },
inputDisabled: { backgroundColor: colors.neutral.surfaceSubtle },

View File

@@ -29,7 +29,7 @@ export function IconButton({ icon, label, onPress, tone = 'soft', disabled = fal
}
const styles = StyleSheet.create({
base: { width: size.touchTargetMin, height: size.touchTargetMin, borderRadius: radius.control, alignItems: 'center', justifyContent: 'center' },
base: { width: size.touchTargetMin, height: size.touchTargetMin, borderRadius: radius.control, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center' },
disabled: { opacity: 0.48 },
pressed: { transform: [{ scale: motion.pressedScale }] },
});

View File

@@ -28,7 +28,7 @@ export function InlineBanner({ title, message, tone = 'neutral', action, style }
}
const styles = StyleSheet.create({
banner: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing[3], borderRadius: radius.card, padding: spacing[4] },
banner: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing[3], borderRadius: radius.card, borderCurve: 'continuous', padding: spacing[4] },
copy: { flex: 1 },
message: { marginTop: spacing[1] },
action: { alignSelf: 'center' },

View File

@@ -27,8 +27,8 @@ export function RecessCard({ timeRange, isNow = false, style }: Props) {
}
const styles = StyleSheet.create({
card: { minHeight: 96, flexDirection: 'row', alignItems: 'center', gap: spacing[4], borderRadius: radius.feature, padding: spacing[5], backgroundColor: colors.neutral.surfaceSubtle, borderWidth: 1, borderColor: colors.neutral.divider },
icon: { width: 40, height: 40, borderRadius: radius.control, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.neutral.surface },
card: { minHeight: 96, flexDirection: 'row', alignItems: 'center', gap: spacing[4], borderRadius: radius.feature, borderCurve: 'continuous', padding: spacing[5], backgroundColor: colors.neutral.surfaceSubtle, borderWidth: 1, borderColor: colors.neutral.divider },
icon: { width: 40, height: 40, borderRadius: radius.control, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', backgroundColor: colors.neutral.surface },
copy: { flex: 1 },
heading: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[3] },
now: { borderRadius: radius.pill, backgroundColor: colors.brand.coral, paddingHorizontal: spacing[3], paddingVertical: 3 },

View File

@@ -26,6 +26,7 @@ export function ScheduleEventCard({ title, timeRange, subjectTone, room, kind, c
const subject = colors.subject[subjectTone];
const cancelled = state === 'cancelled';
const absent = state === 'absent';
const attended = state === 'attended';
const backgroundColor = cancelled ? colors.neutral.surfaceSubtle : absent ? colors.semantic.danger.soft : subject.surface;
const foreground = cancelled ? colors.neutral.textMuted : absent ? colors.semantic.danger.text : subject.accent;
const content = <>
@@ -42,7 +43,23 @@ export function ScheduleEventCard({ title, timeRange, subjectTone, room, kind, c
<Ionicons name="school-outline" size={14} color={foreground} />
<AppText variant="label" color={foreground}>{classType}</AppText>
</View>
{isNow ? <View style={styles.now}><AppText variant="caption" color={colors.brand.ink}>Now</AppText></View> : cancelled ? <AppText variant="label" color={colors.neutral.textMuted}>Cancelled</AppText> : <ParticipantStack accent={foreground} />}
{isNow ? (
<View style={styles.now}><AppText variant="caption" color={colors.brand.ink}>Now</AppText></View>
) : cancelled ? (
<AppText variant="label" color={colors.neutral.textMuted}>Cancelled</AppText>
) : attended ? (
<View style={styles.statusConfirmed}>
<Ionicons name="checkmark-circle" size={15} color={colors.semantic.success.solid} />
<AppText variant="label" color={colors.semantic.success.text}>Attended</AppText>
</View>
) : absent ? (
<View style={styles.statusConfirmed}>
<Ionicons name="close-circle" size={15} color={colors.semantic.danger.solid} />
<AppText variant="label" color={colors.semantic.danger.text}>Absent</AppText>
</View>
) : (
<ParticipantStack accent={foreground} />
)}
</View>
{footer ? <View style={styles.footer}>{footer}</View> : null}
</>;
@@ -62,7 +79,7 @@ function ParticipantStack({ accent }: { accent: string }) {
}
const styles = StyleSheet.create({
card: { minHeight: 116, overflow: 'hidden', borderRadius: radius.feature, padding: spacing[5] },
card: { minHeight: 116, overflow: 'hidden', borderRadius: radius.feature, borderCurve: 'continuous', padding: spacing[5] },
titleRow: { minHeight: 40, flexDirection: 'row', alignItems: 'flex-start', gap: spacing[2] },
title: { flex: 1, paddingTop: spacing[1] },
topAction: { marginRight: -spacing[3], marginTop: -spacing[3] },
@@ -72,6 +89,7 @@ const styles = StyleSheet.create({
bottomRow: { minHeight: 30, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing[3], marginTop: spacing[3] },
typeRow: { flexDirection: 'row', alignItems: 'center', gap: spacing[2] },
now: { borderRadius: radius.pill, backgroundColor: colors.brand.coral, paddingHorizontal: spacing[3], paddingVertical: 3 },
statusConfirmed: { flexDirection: 'row', alignItems: 'center', gap: 4 },
participants: { flexDirection: 'row', alignItems: 'center' },
avatar: { width: 24, height: 24, alignItems: 'center', justifyContent: 'center', borderRadius: radius.pill, borderWidth: 2, borderColor: colors.neutral.surface },
more: { marginLeft: spacing[2] },

View File

@@ -20,6 +20,7 @@ export function Screen({ children, scroll = true, edges = ['top'], style, conten
<ScrollView
testID={testID}
style={styles.scroll}
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={[styles.content, { paddingHorizontal: responsiveGutter }, contentContainerStyle, { paddingBottom: size.tabBar + spacing[6] }]}
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="handled">

View File

@@ -13,7 +13,7 @@ export function SubjectBadge({ shortName, tone, size = 'medium', style }: Props)
}
const styles = StyleSheet.create({
base: { alignItems: 'center', justifyContent: 'center', borderRadius: radius.control },
base: { alignItems: 'center', justifyContent: 'center', borderRadius: radius.control, borderCurve: 'continuous' },
small: { minWidth: 32, height: 32, paddingHorizontal: 6 },
medium: { minWidth: 44, height: 44, paddingHorizontal: 8, borderRadius: 14 },
medium: { minWidth: 44, height: 44, paddingHorizontal: 8, borderRadius: 14, borderCurve: 'continuous' },
});

View File

@@ -2,6 +2,7 @@ import * as Haptics from 'expo-haptics';
import { Platform, Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { AppText } from './app-text';
import { colors, radius, spacing } from './tokens';
import { formatDayHeading, formatWeekdayShort } from '@/lib/date';
export type WeekDay = { date: Date; disabled?: boolean; marker?: 'none' | 'success' | 'warning' | 'danger' | 'neutral' };
type Props = {
@@ -23,8 +24,8 @@ export function WeekStrip({ days, selectedDateKey, onSelect, todayDateKey, style
const key = dateKey(date);
const selected = key === selectedDateKey;
const today = key === todayDateKey;
const weekday = new Intl.DateTimeFormat(undefined, { weekday: 'narrow' }).format(date);
const fullDate = new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric' }).format(date);
const weekday = formatWeekdayShort(date).slice(0, 3).toLowerCase();
const fullDate = formatDayHeading(date);
return <Pressable
key={key}
accessibilityRole="button"
@@ -33,7 +34,7 @@ export function WeekStrip({ days, selectedDateKey, onSelect, todayDateKey, style
disabled={disabled}
onPress={() => { if (Platform.OS !== 'web') void Haptics.selectionAsync(); onSelect(date); }}
style={({ pressed }) => [styles.day, selected && styles.selected, disabled && styles.disabled, pressed && !disabled && styles.pressed]}>
<AppText variant="caption" color={selected ? colors.brand.ink : colors.neutral.textSecondary}>{weekday}</AppText>
<AppText variant="caption" color={selected ? colors.brand.ink : colors.neutral.textMuted} style={styles.weekday}>{weekday}</AppText>
<AppText variant="title" color={selected ? colors.brand.ink : colors.neutral.textPrimary} style={styles.number}>{date.getDate()}</AppText>
<View style={styles.indicatorRow}>
<View style={[styles.dot, today && !selected && styles.todayDot, marker !== 'none' && { backgroundColor: markerColor[marker] }]} />
@@ -44,13 +45,14 @@ export function WeekStrip({ days, selectedDateKey, onSelect, todayDateKey, style
}
const styles = StyleSheet.create({
strip: { flexDirection: 'row', gap: spacing[1], padding: spacing[2], borderRadius: radius.feature, backgroundColor: colors.brand.sky },
day: { flex: 1, minHeight: 60, alignItems: 'center', justifyContent: 'center', borderRadius: radius.control, paddingVertical: spacing[1] },
strip: { flexDirection: 'row', gap: spacing[1], padding: spacing[2], borderRadius: radius.feature, borderCurve: 'continuous', backgroundColor: colors.brand.skySoft },
day: { flex: 1, minHeight: 64, alignItems: 'center', justifyContent: 'center', borderRadius: radius.control, borderCurve: 'continuous', paddingVertical: spacing[2] },
selected: { backgroundColor: colors.brand.coral },
disabled: { opacity: 0.42 },
pressed: { opacity: 0.78 },
number: { marginTop: 1, fontVariant: ['tabular-nums'] },
indicatorRow: { height: 5, marginTop: 2, justifyContent: 'center' },
weekday: { fontSize: 11, lineHeight: 14, fontWeight: '600' },
number: { fontSize: 18, lineHeight: 22, fontWeight: '800', marginTop: 2, fontVariant: ['tabular-nums'] },
indicatorRow: { height: 6, marginTop: 3, justifyContent: 'center' },
dot: { width: 4, height: 4, borderRadius: 2, backgroundColor: 'transparent' },
todayDot: { width: 6, height: 6, borderRadius: 3, backgroundColor: colors.brand.cobalt },
todayDot: { width: 5, height: 5, borderRadius: 2.5, backgroundColor: colors.brand.cobalt },
});

70
e2e/app.spec.ts Normal file
View File

@@ -0,0 +1,70 @@
import { test, expect } from '@playwright/test';
test.describe('College Kit E2E & Visual Verification', () => {
test.beforeEach(async ({ page }) => {
// Ensure profile is setup so we are on the main tabs
await page.request.put('http://localhost:4000/api/v1/profile', {
data: {
name: 'Sam Taylor',
college: 'Northbridge University',
programme: 'B.Tech Computer Science',
semester: 'Semester 3',
},
});
});
test('Today screen loads with date, week strip, and classes', async ({ page }) => {
await page.goto('/');
await expect(page.locator('text=Todays classes')).toBeVisible();
await expect(page.locator('text=Timetable')).toBeVisible();
await expect(page.locator('text=Attendance')).toBeVisible();
await expect(page.locator('text=Settings')).toBeVisible();
});
test('Navigation between all bottom tabs works smoothly', async ({ page }) => {
await page.goto('/');
// Navigate to Timetable
await page.locator('text=Timetable').click();
await expect(page.locator('text=Week of')).toBeVisible();
// Navigate to Attendance
await page.getByRole('button', { name: 'Attendance' }).click();
await expect(page.locator('text=By subject')).toBeVisible();
await expect(page.locator('text=Classes held')).toBeVisible();
// Navigate to Settings
await page.getByRole('button', { name: 'Settings' }).click();
await expect(page.locator('text=Shape your class day')).toBeVisible();
await expect(page.locator('text=Default class length')).toBeVisible();
// Navigate back to Today
await page.getByRole('button', { name: 'Today' }).click();
await expect(page.locator('text=classes').first()).toBeVisible();
});
test('Account screen displays profile information correctly', async ({ page }) => {
await page.goto('/account');
await expect(page.locator('text=Sam Taylor')).toBeVisible();
await expect(page.getByText('Northbridge University').first()).toBeVisible();
await expect(page.locator('text=B.Tech Computer Science')).toBeVisible();
});
test('Subject Details screen loads subject metrics', async ({ page }) => {
// Get subjects list
const subjectsRes = await page.request.get('http://localhost:4000/api/v1/subjects');
const subjects = await subjectsRes.json();
if (subjects.length > 0) {
await page.goto(`/subjects/${subjects[0].id}`);
await expect(page.locator('text=Subject details')).toBeVisible();
await expect(page.locator('text=Recent classes')).toBeVisible();
}
});
test('Settings can be updated and saved', async ({ page }) => {
await page.goto('/settings');
await expect(page.locator('text=Save settings')).toBeVisible();
await page.locator('text=Save settings').click();
await expect(page.locator('text=Settings saved')).toBeVisible();
});
});

View File

@@ -25,12 +25,15 @@ export const collegeApi = {
createSubject(data: { name: string; code: string; shortName?: string; color?: string; classType?: string; defaultRoom?: string }) { return request<{ id: number }>('/subjects', { method: 'POST', body: JSON.stringify(data) }); },
subject(id: number) { return request<{ id: number; name: string; code: string; shortName: string; color: string; classType: string; defaultRoom: string; summary: { total: number; attended: number; absent: number; percentage: number }; sessions: Array<{ id: number; date: string; time: string; endTime: string; room: string; status: AttendanceStatus }> }>(`/subjects/${id}`); },
updateSubject(id: number, data: { name: string; code: string; shortName: string; color?: string; classType?: string; defaultRoom?: string }) { return request<{ id: number }>(`/subjects/${id}`, { method: 'PATCH', body: JSON.stringify(data) }); },
deleteSubject(id: number) { return request<{ id: number; deleted: boolean }>(`/subjects/${id}`, { method: 'DELETE' }); },
schedule(date: string) { return request<{ date: string; sessions: Session[] }>(`/schedule?date=${date}`); },
markAttendance(id: number, status: AttendanceStatus) { return request<{ id: number; status: AttendanceStatus }>(`/schedule/${id}/attendance`, { method: 'PUT', body: JSON.stringify({ status }) }); },
removeClass(id: number) { return request<{ id: number; deleted: boolean }>(`/schedule/${id}`, { method: 'DELETE' }); },
addOneOffClass(data: { subjectId: number; date: string; startTime: string; endTime: string; room: string }) { return request<{ id: number }>('/schedule', { method: 'POST', body: JSON.stringify(data) }); },
attendanceSummary() { return request<{ subjects: Array<{ id: number; name: string; code: string; shortName?: string; color: string; total: number; attended: number; absent: number; cancelled: number; percentage: number }> }>('/attendance/summary'); },
attendanceMarkers(month: string) { return request<{ markers: Record<string, 'success' | 'warning' | 'danger' | 'neutral'> }>(`/attendance/markers?month=${month}`); },
timetable(date: string) { return request<{ date: string; classes: Array<{ id: number; weekday: number; startTime: string; endTime: string; room: string; subjectId: number; subjectName: string; code: string; color: string; classType: string; effectiveFrom: string; effectiveTo: string | null }> }>(`/timetable/classes?date=${date}`); },
updateTimetableClass(id: number, data: { subjectId?: number; weekday?: number; startTime?: string; endTime?: string; room?: string; effectiveFrom?: string }) { return request<{ id: number; replacesId: number; effectiveFrom: string }>(`/timetable/classes/${id}`, { method: 'PATCH', body: JSON.stringify(data) }); },
deleteTimetableClass(id: number) { return request<{ id: number; deleted: boolean }>(`/timetable/classes/${id}`, { method: 'DELETE' }); },
addTimetableClass(data: { subjectId: number; weekday: number; startTime: string; endTime: string; room: string; effectiveFrom?: string }) { return request<{ id: number }>('/timetable/classes', { method: 'POST', body: JSON.stringify(data) }); },
};

View File

@@ -1,3 +1,17 @@
// Pre-instantiated Intl formatters hoisted to module scope (per js-hoist-intl best practice)
const dayHeadingFormatter = new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
const monthDayFormatter = new Intl.DateTimeFormat(undefined, { month: 'long', day: 'numeric' });
const sessionDateFormatter = new Intl.DateTimeFormat(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
const weekdayNarrowFormatter = new Intl.DateTimeFormat(undefined, { weekday: 'narrow' });
const weekdayLongFormatter = new Intl.DateTimeFormat(undefined, { weekday: 'long' });
const monthYearFormatter = new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' });
const monthShortDayFormatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
const yearFormatter = new Intl.DateTimeFormat(undefined, { year: 'numeric' });
const timeShortFormatter = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' });
const headerDateFormatter = new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'short', day: 'numeric' });
const weekdayShortFormatter = new Intl.DateTimeFormat(undefined, { weekday: 'short' });
export const dateKey = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
export const addDays = (date: Date, amount: number) => {
@@ -10,11 +24,27 @@ export const mondayOfWeek = (date: Date) => addDays(date, -((date.getDay() + 6)
export const dateFromKey = (value: string) => new Date(`${value}T12:00:00`);
export const formatDayHeading = (date: Date) => new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric' }).format(date);
export const formatDayHeading = (date: Date) => dayHeadingFormatter.format(date);
export const formatMonthDay = (date: Date) => new Intl.DateTimeFormat(undefined, { month: 'long', day: 'numeric' }).format(date);
export const formatMonthDay = (date: Date) => monthDayFormatter.format(date);
export const formatSessionDate = (value: string) => new Intl.DateTimeFormat(undefined, { weekday: 'short', month: 'short', day: 'numeric' }).format(dateFromKey(value));
export const formatSessionDate = (value: string) => sessionDateFormatter.format(dateFromKey(value));
export const formatWeekdayNarrow = (date: Date) => weekdayNarrowFormatter.format(date);
export const formatWeekdayShort = (date: Date) => weekdayShortFormatter.format(date);
export const formatWeekdayLong = (date: Date) => weekdayLongFormatter.format(date);
export const formatMonthYear = (date: Date) => monthYearFormatter.format(date);
export const formatMonthShortDay = (date: Date) => monthShortDayFormatter.format(date);
export const formatYear = (date: Date) => yearFormatter.format(date);
export const formatCurrentTime = (date = new Date()) => timeShortFormatter.format(date);
export const formatHeaderDate = (date: Date) => headerDateFormatter.format(date);
export const currentMinutes = () => {
const now = new Date();

View File

@@ -16,6 +16,15 @@ export function subjectToneFor(identity: string | number, savedColor?: string):
return matched ?? subjectTones[hash(identity) % subjectTones.length];
}
export function subjectShortLabel(name: string, code: string, shortName?: string): string {
if (shortName && shortName.trim()) return shortName.trim().slice(0, 5);
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length >= 2) {
return parts.map((w) => w[0]).join('').toUpperCase().slice(0, 4);
}
return code.trim().slice(0, 4);
}
export function attendanceTone(percentage: number, total: number, threshold = 75): SemanticTone {
if (!total) return 'neutral';
if (percentage >= threshold) return 'success';

65
package-lock.json generated
View File

@@ -37,9 +37,11 @@
"react-native-worklets": "0.5.1"
},
"devDependencies": {
"@playwright/test": "^1.62.1",
"@types/react": "~19.1.0",
"eslint": "^9.25.0",
"eslint-config-expo": "~10.0.0",
"playwright": "^1.62.1",
"typescript": "~5.9.2"
}
},
@@ -2423,6 +2425,22 @@
"node": ">=12.4.0"
}
},
"node_modules/@playwright/test": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz",
"integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.62.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@radix-ui/primitive": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.7.tgz",
@@ -9527,6 +9545,53 @@
"node": ">= 6"
}
},
"node_modules/playwright": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
"integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.62.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
"integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/plist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",

View File

@@ -9,7 +9,9 @@
"ios": "expo start --ios",
"web": "expo start --web",
"lint": "expo lint",
"api": "node backend/server.mjs"
"api": "node backend/server.mjs",
"test:e2e": "playwright test",
"test:visual": "node scripts/capture-all.mjs"
},
"dependencies": {
"@expo-google-fonts/manrope": "^0.4.2",
@@ -41,9 +43,11 @@
"react-native-worklets": "0.5.1"
},
"devDependencies": {
"@playwright/test": "^1.62.1",
"@types/react": "~19.1.0",
"eslint": "^9.25.0",
"eslint-config-expo": "~10.0.0",
"playwright": "^1.62.1",
"typescript": "~5.9.2"
},
"private": true

28
playwright.config.ts Normal file
View File

@@ -0,0 +1,28 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
timeout: 30000,
use: {
baseURL: 'http://127.0.0.1:3000',
trace: 'on-first-retry',
},
projects: [
{
name: 'Mobile Chrome',
use: { ...devices['Pixel 5'] },
},
],
webServer: [
{
command: 'node backend/server.mjs',
port: 4000,
reuseExistingServer: !process.env.CI,
},
{
command: 'node scripts/serve-dist.mjs',
port: 3000,
reuseExistingServer: !process.env.CI,
},
],
});

118
scripts/capture-all.mjs Normal file
View File

@@ -0,0 +1,118 @@
import { chromium } from 'playwright';
import { mkdirSync } from 'node:fs';
const OUT_DIR = './screenshots';
mkdirSync(OUT_DIR, { recursive: true });
async function run() {
// Update profile
await fetch('http://localhost:4000/api/v1/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Sam Taylor',
college: 'Northbridge University',
programme: 'B.Tech Computer Science',
semester: 'Semester 3',
}),
});
// Get subjects or create if not present
let subjects = await fetch('http://localhost:4000/api/v1/subjects').then(r => r.json());
if (!subjects.length) {
await fetch('http://localhost:4000/api/v1/subjects', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Data Structures & Algorithms',
code: 'CS201',
shortName: 'DSA',
classType: 'Theory',
defaultRoom: 'Hall 101',
color: '#0559FA',
}),
});
await fetch('http://localhost:4000/api/v1/subjects', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Database Management Systems',
code: 'CS202',
shortName: 'DBMS',
classType: 'Lab',
defaultRoom: 'Lab 3',
color: '#9B4BA4',
}),
});
subjects = await fetch('http://localhost:4000/api/v1/subjects').then(r => r.json());
}
const now = new Date();
const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
// Add one-off class for today
await fetch('http://localhost:4000/api/v1/schedule', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
subjectId: subjects[0].id,
date: dateStr,
startTime: '09:00',
endTime: '10:00',
room: 'Hall 101',
}),
}).catch(() => {});
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
isMobile: true,
hasTouch: true,
});
const page = await context.newPage();
console.log('Capturing Today...');
await page.goto('http://127.0.0.1:3000/');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/01-today.png` });
console.log('Capturing Timetable...');
await page.goto('http://127.0.0.1:3000/timetable');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/02-timetable.png` });
console.log('Capturing Attendance...');
await page.goto('http://127.0.0.1:3000/attendance');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/03-attendance.png` });
console.log('Capturing Settings...');
await page.goto('http://127.0.0.1:3000/settings');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/04-settings.png` });
console.log('Capturing Account...');
await page.goto('http://127.0.0.1:3000/account');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/05-account.png` });
console.log('Capturing Subject Details...');
await page.goto(`http://127.0.0.1:3000/subjects/${subjects[0].id}`);
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/06-subject-details.png` });
console.log('Capturing Onboarding...');
await page.goto('http://127.0.0.1:3000/onboarding');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/07-onboarding.png` });
await browser.close();
console.log('All screenshots captured successfully!');
}
run().catch((err) => {
console.error(err);
process.exit(1);
});

View File

@@ -0,0 +1,23 @@
import { chromium } from 'playwright';
async function captureFriday() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
isMobile: true,
});
const page = await context.newPage();
await page.goto('http://127.0.0.1:3000/');
await page.waitForTimeout(2000);
// Click on the Friday date card (date number 4)
const fridayCell = page.locator('text=fri').locator('..');
if (await fridayCell.isVisible()) {
await fridayCell.click();
await page.waitForTimeout(1000);
}
await page.screenshot({ path: './screenshots/01-today-friday.png' });
await browser.close();
}
captureFriday().catch(console.error);

53
scripts/serve-dist.mjs Normal file
View File

@@ -0,0 +1,53 @@
import { createServer } from 'node:http';
import { readFileSync, existsSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';
const PORT = 3000;
const DIST = join(process.cwd(), 'dist-web');
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml',
'.ttf': 'font/ttf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
const server = createServer((req, res) => {
const url = new URL(req.url || '/', `http://localhost:${PORT}`);
let pathname = decodeURIComponent(url.pathname);
if (pathname === '/') pathname = '/index.html';
let filePath = join(DIST, pathname);
if (!existsSync(filePath) || statSync(filePath).isDirectory()) {
if (existsSync(join(DIST, `${pathname}.html`))) {
filePath = join(DIST, `${pathname}.html`);
} else if (existsSync(join(filePath, 'index.html'))) {
filePath = join(filePath, 'index.html');
} else {
filePath = join(DIST, 'index.html');
}
}
const ext = extname(filePath);
const contentType = MIME[ext] || 'application/octet-stream';
try {
const data = readFileSync(filePath);
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
} catch (err) {
res.writeHead(404);
res.end('Not found');
}
});
server.listen(PORT, '127.0.0.1', () => {
console.log(`Static server running at http://127.0.0.1:${PORT}`);
});

View File

@@ -0,0 +1,66 @@
import { chromium } from 'playwright';
import { mkdirSync } from 'node:fs';
const OUT_DIR = './screenshots';
mkdirSync(OUT_DIR, { recursive: true });
async function capture() {
const browser = await chromium.launch({ headless: true });
// iPhone 14 dimensions & scale
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
isMobile: true,
hasTouch: true,
});
const page = await context.newPage();
console.log('Navigating to Today screen...');
await page.goto('http://127.0.0.1:3000/');
await page.waitForTimeout(2000);
await page.screenshot({ path: `${OUT_DIR}/01-today.png`, fullPage: false });
console.log('Navigating to Timetable...');
const timetableTab = page.locator('text=Timetable');
if (await timetableTab.isVisible()) {
await timetableTab.click();
await page.waitForTimeout(1500);
await page.screenshot({ path: `${OUT_DIR}/02-timetable.png`, fullPage: false });
}
console.log('Navigating to Attendance...');
const attendanceTab = page.locator('text=Attendance');
if (await attendanceTab.isVisible()) {
await attendanceTab.click();
await page.waitForTimeout(1500);
await page.screenshot({ path: `${OUT_DIR}/03-attendance.png`, fullPage: false });
}
console.log('Navigating to Settings...');
const settingsTab = page.locator('text=Settings');
if (await settingsTab.isVisible()) {
await settingsTab.click();
await page.waitForTimeout(1500);
await page.screenshot({ path: `${OUT_DIR}/04-settings.png`, fullPage: false });
}
console.log('Navigating to Account...');
await page.goto('http://127.0.0.1:3000/account');
await page.waitForTimeout(1500);
await page.screenshot({ path: `${OUT_DIR}/05-account.png`, fullPage: false });
console.log('Navigating to Onboarding...');
await page.goto('http://127.0.0.1:3000/onboarding');
await page.waitForTimeout(1500);
await page.screenshot({ path: `${OUT_DIR}/06-onboarding.png`, fullPage: false });
await browser.close();
console.log('All screenshots captured in', OUT_DIR);
}
capture().catch((err) => {
console.error(err);
process.exit(1);
});

View File

@@ -0,0 +1,33 @@
import { chromium } from 'playwright';
async function capture() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
isMobile: true,
});
const page = await context.newPage();
await page.goto('http://127.0.0.1:3000/');
await page.waitForTimeout(2000);
await page.screenshot({ path: './screenshots/10-today-collapsed.png' });
// Click extend bar
const extendBar = page.getByRole('button', { name: 'Expand calendar' });
await extendBar.click();
await page.waitForTimeout(1000);
await page.screenshot({ path: './screenshots/11-today-expanded.png' });
// Select an enabled weekday (Wednesday, Aug 12)
const day12 = page.getByRole('button', { name: /Wednesday, August 12/ });
if (await day12.isVisible()) {
await day12.click();
await page.waitForTimeout(1000);
await page.screenshot({ path: './screenshots/12-today-recollapsed-after-select.png' });
}
await browser.close();
}
capture().catch(console.error);

View File

@@ -0,0 +1,34 @@
import { chromium } from 'playwright';
async function testOnboarding() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
deviceScaleFactor: 2,
isMobile: true,
});
const page = await context.newPage();
await page.goto('http://127.0.0.1:3000/onboarding');
await page.waitForTimeout(1000);
// Fill step 1
await page.fill('input[placeholder="e.g. Sam Taylor"]', 'Alex Morgan');
await page.fill('input[placeholder="e.g. Northbridge University"]', 'Stanford University');
await page.click('text=Continue');
await page.waitForTimeout(1000);
await page.screenshot({ path: './screenshots/08-onboarding-step2.png' });
// Add a subject
await page.fill('input[placeholder="e.g. Data Structures"]', 'Algorithms');
await page.fill('input[placeholder="e.g. CS201"]', 'CS161');
await page.click('text=Add subject');
await page.waitForTimeout(500);
await page.screenshot({ path: './screenshots/09-onboarding-with-subject.png' });
await browser.close();
}
testOnboarding().catch(console.error);

11
skills-lock.json Normal file
View File

@@ -0,0 +1,11 @@
{
"version": 1,
"skills": {
"frontend-design": {
"source": "anthropics/skills",
"sourceType": "github",
"skillPath": "skills/frontend-design/SKILL.md",
"computedHash": "89496d5dd00f4810205f351759594fc2742bf8eea85a2f2b2d1de59f4bd91576"
}
}
}