Compare commits

..
Author SHA1 Message Date
Claude 95826a1f19 Self-host fonts (Fraunces, Work Sans, IBM Plex Mono); drop Google Fonts
No third-party requests remain; CSP tightened to font-src/style-src 'self'.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LSDgjk1Agjy9Z2UH2n8bc3
2026-10-15 00:31:30 +00:00
Claude cd5b21514d Polish: proper HTML document, strict CSP, lazy-load three.js, a11y fixes
- add doctype, lang and viewport (page was in quirks mode, 980px on phones)
- move inline script to app.js; add Content-Security-Policy meta
- load three.js after page load
- label week slider, wire tab/tabpanel aria, fix dark-mode week numbers

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LSDgjk1Agjy9Z2UH2n8bc3
2026-10-15 00:28:35 +00:00
Claude 8c9bf89676 Add pregnancy timeline motion: growing slider fill, size pop, week-button wave
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LSDgjk1Agjy9Z2UH2n8bc3
2026-10-15 00:24:38 +00:00
Claude b5f5518c1e Add 3D cycle ring (Three.js) with flat-ring fallback
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LSDgjk1Agjy9Z2UH2n8bc3
2026-10-15 00:22:53 +00:00
Claude 251b3af5ed Add GSAP scroll-reveal animations (self-hosted, respects reduced motion)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LSDgjk1Agjy9Z2UH2n8bc3
2026-10-15 00:19:40 +00:00
keithranaandClaude Sonnet 5.5 0b42fdeae1 Add remotion-video skill (#1)
* Add remotion-video skill

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019yhnsd9RDz7jDSUUX7oEcH

* Add Phase 2 templates to remotion-video skill

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019yhnsd9RDz7jDSUUX7oEcH

* Fix captions template background; document browser flag after test render

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019yhnsd9RDz7jDSUUX7oEcH

* Add audio/voiceover template (Phase 3), tested with real render

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019yhnsd9RDz7jDSUUX7oEcH

* Document font loading and its network requirement; captions-over-video verified

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019yhnsd9RDz7jDSUUX7oEcH

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-15 10:42:46 +11:00
62 changed files with 1475 additions and 5857 deletions

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
---
name: remotion-video
description: Create videos from React code with Remotion. Use when the user asks to make, animate, preview, or render a video, motion graphic, intro, caption, or social clip using code.
---
# Remotion Video
Remotion makes videos out of React components. Each frame is a web page. Render them in order and you get an MP4.
## Core ideas
- **Composition**: one video. Has `width`, `height`, `fps`, `durationInFrames`.
- **Frame**: `useCurrentFrame()` returns the current frame number. All animation is a function of the frame.
- **`interpolate`**: maps a frame range to a value range (fade, slide).
- **`spring`**: natural bouncy motion.
- **`Sequence`**: shows children only during a frame range.
- **`AbsoluteFill`**: full-screen layer; stack them for backgrounds.
- **`Audio` / `OffthreadVideo` / `Img`**: media. Put files in `public/` and load with `staticFile("name.mp3")`.
## Workflow
1. **Plan first.** Ask or decide: length (seconds), size (1920x1080, or 1080x1920 for vertical), fps (30), and the scenes. Keep scenes to a short list.
2. **Set up** (skip if the project exists):
```
npx create-video@latest
cd <project> && npm install
```
3. **Write** compositions in `src/`, register them in `src/Root.tsx`.
4. **Preview**: `npm run dev` (opens Remotion Studio).
5. **Render**: `npx remotion render <CompositionId> out/video.mp4`
Still frame: `npx remotion still <CompositionId> out/frame.png --frame=30`
6. **Verify**: render one still first, check it looks right, then render the full video.
## Starter example
`src/Root.tsx`
```tsx
import { Composition } from "remotion";
import { Hello } from "./Hello";
export const RemotionRoot = () => (
<Composition
id="Hello"
component={Hello}
durationInFrames={150}
fps={30}
width={1920}
height={1080}
defaultProps={{ title: "Hello, world" }}
/>
);
```
`src/Hello.tsx`
```tsx
import { AbsoluteFill, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
export const Hello = ({ title }: { title: string }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const opacity = interpolate(frame, [0, 30], [0, 1], { extrapolateRight: "clamp" });
const scale = spring({ frame, fps, config: { damping: 12 } });
return (
<AbsoluteFill style={{ backgroundColor: "#0b1020", justifyContent: "center", alignItems: "center" }}>
<h1 style={{ color: "white", fontSize: 120, opacity, transform: `scale(${scale})` }}>{title}</h1>
</AbsoluteFill>
);
};
```
## Rules of thumb
- Never animate with CSS transitions, `setTimeout`, or CSS animations. They don't render per frame. Drive everything from `useCurrentFrame()`.
- Always pass `extrapolateRight: "clamp"` to `interpolate` unless you want values to keep growing.
- Seconds to frames: `seconds * fps`.
- Use `<Sequence from={..} durationInFrames={..}>` to order scenes; `<Series>` to chain them.
- Load fonts with `@remotion/google-fonts` so they are ready before rendering.
- Keep props in `defaultProps` so the user can edit text in the Studio.
- Rendering needs Chromium and ffmpeg (Remotion installs/handles these); first render can be slow.
## Fonts
Google Fonts: `npm i @remotion/google-fonts`, then
```tsx
import { loadFont } from "@remotion/google-fonts/Inter";
const { fontFamily } = loadFont(); // use as style={{ fontFamily }}
```
It downloads the font while rendering, so the machine needs internet access to fonts.googleapis.com. If the render fails with "Failed to load font", the network is blocking it: use a local font file in `public/` with `@remotion/fonts` (`loadFont({ family, url: staticFile("x.woff2") })`) or a system font. (Not verified in the sandbox where this skill was tested, which had no access to Google.)
## Common problems
- **Can't download the browser (no internet / locked-down machine)**: point Remotion at an installed Chromium:
`npx remotion render <Id> out/video.mp4 --browser-executable=/path/to/chromium --chrome-mode=chrome-for-testing`
- **Blank/white frames**: an asset path is wrong; use `staticFile()`.
- **Flicker**: an image or font not loaded; use `<Img>` and `@remotion/google-fonts`.
- **Slow render**: lower resolution/fps while testing, or use `--concurrency`.
## Templates
Copy-paste starting points. Read the one that fits:
- `templates/captions.md` - words highlighted in time with speech
- `templates/charts.md` - animated bar chart
- `templates/intro-outro.md` - title card + chaining scenes with `Series`
- `templates/audio-voiceover.md` - background music, voiceover, auto video length
- `templates/vertical.md` - 1080x1920 clips for Reels/TikTok/Shorts
## Docs
https://www.remotion.dev/docs
@@ -0,0 +1,62 @@
# Template: Audio, music and voiceover
Put sound files in `public/` (mp3 or wav). Load them with `staticFile()`.
`src/Narrated.tsx`
```tsx
import { AbsoluteFill, Audio, Sequence, interpolate, staticFile, useVideoConfig } from "remotion";
import { getAudioDurationInSeconds } from "@remotion/media-utils";
import type { CalculateMetadataFunction } from "remotion";
type Props = { title: string; voice: string; music: string };
// Make the video exactly as long as the voiceover (+1 second of padding).
export const calcNarratedMetadata: CalculateMetadataFunction<Props> = async ({ props }) => {
const seconds = await getAudioDurationInSeconds(staticFile(props.voice));
return { durationInFrames: Math.ceil((seconds + 1) * 30) };
};
export const Narrated = ({ title, voice, music }: Props) => {
const { fps, durationInFrames } = useVideoConfig();
return (
<AbsoluteFill style={{ background: "#0b1020", justifyContent: "center", alignItems: "center" }}>
<h1 style={{ color: "white", fontSize: 110 }}>{title}</h1>
{/* Background music: quiet, fades out over the last second. */}
<Audio
src={staticFile(music)}
volume={(f) => interpolate(f, [durationInFrames - fps, durationInFrames], [0.15, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" })}
/>
{/* Voiceover starts half a second in, full volume. */}
<Sequence from={Math.round(fps * 0.5)}>
<Audio src={staticFile(voice)} volume={1} />
</Sequence>
</AbsoluteFill>
);
};
```
Register it (note `calculateMetadata`):
```tsx
<Composition
id="Narrated"
component={Narrated}
calculateMetadata={calcNarratedMetadata}
durationInFrames={300} // placeholder, replaced by calculateMetadata
fps={30} width={1920} height={1080}
defaultProps={{ title: "My story", voice: "voice.mp3", music: "music.mp3" }}
/>
```
Install: `npm i @remotion/media-utils`
Getting a voiceover
- Record yourself, or generate speech with a text-to-speech service, and save as `public/voice.mp3`. Never commit API keys; keep them in environment variables.
- Pair with `templates/captions.md`: feed it word timings from a transcription of the same file.
Rules
- Music volume 0.1-0.2 so the voice stays clear.
- `<Sequence from={...}>` delays when a sound starts.
- Audio is only in the final render (mp4). Stills (`remotion still`) have no sound.
- Check the sound made it in: `ffprobe out/video.mp4` should list an `Audio:` stream.
@@ -0,0 +1,38 @@
# Template: Captions
Words appear in time with speech. Give each word a start time in seconds.
`src/Captions.tsx`
```tsx
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
type Word = { text: string; start: number; end: number }; // seconds
export const Captions = ({ words, background = "#111" }: { words: Word[]; background?: string }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const t = frame / fps;
// Show a window of up to 5 words around the current one.
const current = words.findIndex((w) => t >= w.start && t < w.end);
const i = current === -1 ? 0 : current;
const visible = words.slice(Math.floor(i / 5) * 5, Math.floor(i / 5) * 5 + 5);
return (
<AbsoluteFill style={{ backgroundColor: background, justifyContent: "flex-end", alignItems: "center", paddingBottom: 200 }}>
<div style={{ fontSize: 72, fontWeight: 800, color: "white", textShadow: "0 4px 12px black", textAlign: "center", maxWidth: "80%" }}>
{visible.map((w, k) => (
<span key={k} style={{ color: t >= w.start && t < w.end ? "#ffd400" : "white", marginRight: 16 }}>
{w.text}
</span>
))}
</div>
</AbsoluteFill>
);
};
```
Tips
- Get word times from a transcription tool (e.g. `@remotion/captions` or Whisper) and save them as JSON in `public/`.
- `background` is the backdrop when there is no video. Pass `"transparent"` when layering over a video.
- Layer it over the video: `<AbsoluteFill><OffthreadVideo src={staticFile("clip.mp4")} /><Captions words={words} background="transparent" /></AbsoluteFill>`.
@@ -0,0 +1,37 @@
# Template: Animated bar chart
Bars grow one after another.
`src/BarChart.tsx`
```tsx
import { AbsoluteFill, spring, useCurrentFrame, useVideoConfig } from "remotion";
type Bar = { label: string; value: number };
export const BarChart = ({ data, color = "#4f8cff" }: { data: Bar[]; color?: string }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const max = Math.max(...data.map((d) => d.value));
return (
<AbsoluteFill style={{ backgroundColor: "#0b1020", padding: 120, justifyContent: "flex-end" }}>
<div style={{ display: "flex", alignItems: "flex-end", gap: 40, height: 700 }}>
{data.map((d, i) => {
const grow = spring({ frame: frame - i * 6, fps, config: { damping: 15 } });
return (
<div key={d.label} style={{ flex: 1, textAlign: "center", color: "white", fontSize: 36 }}>
<div style={{ height: (d.value / max) * 600 * grow, background: color, borderRadius: 8 }} />
<div style={{ marginTop: 16 }}>{d.label}</div>
</div>
);
})}
</div>
</AbsoluteFill>
);
};
```
Tips
- Delay each bar with `frame - i * 6` (6 frames apart).
- For lines, animate `strokeDashoffset` on an SVG path using `interpolate`.
- Keep numbers readable: show the value as text, rounded.
@@ -0,0 +1,34 @@
# Template: Title intro / outro card
A short card (2-3 seconds) with a title and subtitle. Use at the start or end.
`src/TitleCard.tsx`
```tsx
import { AbsoluteFill, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
export const TitleCard = ({ title, subtitle }: { title: string; subtitle?: string }) => {
const frame = useCurrentFrame();
const { fps, durationInFrames } = useVideoConfig();
const rise = spring({ frame, fps, config: { damping: 14 } });
const fadeOut = interpolate(frame, [durationInFrames - 15, durationInFrames], [1, 0], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
});
return (
<AbsoluteFill style={{ background: "linear-gradient(135deg,#1b2a6b,#0b1020)", justifyContent: "center", alignItems: "center", opacity: fadeOut }}>
<h1 style={{ color: "white", fontSize: 130, margin: 0, transform: `translateY(${(1 - rise) * 60}px)`, opacity: rise }}>{title}</h1>
{subtitle && <p style={{ color: "#9fb3ff", fontSize: 48, opacity: rise }}>{subtitle}</p>}
</AbsoluteFill>
);
};
```
Chain with the main video using `<Series>`:
```tsx
<Series>
<Series.Sequence durationInFrames={90}><TitleCard title="My Video" /></Series.Sequence>
<Series.Sequence durationInFrames={600}><MainScene /></Series.Sequence>
<Series.Sequence durationInFrames={90}><TitleCard title="Thanks for watching" /></Series.Sequence>
</Series>
```
@@ -0,0 +1,23 @@
# Template: Vertical clips (Reels / TikTok / Shorts)
Same code, different size. Register a vertical composition:
```tsx
<Composition
id="Vertical"
component={MyScene}
width={1080}
height={1920}
fps={30}
durationInFrames={30 * 30} // 30 seconds
/>
```
Render: `npx remotion render Vertical out/vertical.mp4`
Rules
- Keep text inside the **safe zone**: about 150px from the top, 350px from the bottom (apps cover those parts with buttons and captions), and 60px from the sides.
- Use big text (60px+). Phone screens are small.
- Keep clips under 60 seconds (Shorts limit); 15-30 seconds does best.
- Use `useVideoConfig()` for width/height instead of hard-coding, so the same scene works wide and tall.
- Put captions in the lower-middle, above the bottom safe zone (see captions.md).
+45
View File
@@ -0,0 +1,45 @@
/* CycleWise AU - scroll animations (Step 1).
Purely cosmetic: if GSAP fails to load or the visitor prefers reduced
motion, this file does nothing and the page looks exactly as before. */
(function(){
"use strict";
if (!window.gsap || !window.ScrollTrigger) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
gsap.registerPlugin(ScrollTrigger);
var done = new WeakSet();
function reveal(panel){
if (!panel || done.has(panel)) return;
done.add(panel);
// Top of the tab: hero text and picture fade up one after another.
gsap.from(panel.querySelectorAll(".hero > *"), {
opacity: 0, y: 24, duration: 0.7, stagger: 0.12, ease: "power2.out",
clearProps: "all"
});
// Everything below: fade up when it scrolls into view.
panel.querySelectorAll(
".ref-heading, .ref-grid, .timeline, .week-panel, .filmstrip, .cal-card, .detail-card"
).forEach(function(el){
gsap.from(el, {
opacity: 0, y: 32, duration: 0.7, ease: "power2.out",
clearProps: "all",
scrollTrigger: { trigger: el, start: "top 88%", once: true }
});
});
}
function activePanel(){ return document.querySelector(".mode-panel.active"); }
reveal(activePanel());
document.querySelectorAll(".mode-btn").forEach(function(btn){
btn.addEventListener("click", function(){
// Wait one tick so the page's own code switches the tab first.
setTimeout(function(){ reveal(activePanel()); ScrollTrigger.refresh(); }, 0);
});
});
})();
+539
View File
@@ -0,0 +1,539 @@
(function(){
"use strict";
/* ---------------- date helpers ---------------- */
function toDate(y,m,d){ return new Date(y,m,d); }
function fromInput(str){
if(!str) return null;
var p = str.split("-");
return new Date(+p[0], +p[1]-1, +p[2]);
}
function toInputVal(d){
return d.getFullYear()+"-"+String(d.getMonth()+1).padStart(2,"0")+"-"+String(d.getDate()).padStart(2,"0");
}
function addDays(d,n){ var r=new Date(d); r.setDate(r.getDate()+n); return r; }
function daysBetween(a,b){ // b - a, in whole days, ignoring time
var A = new Date(a.getFullYear(),a.getMonth(),a.getDate());
var B = new Date(b.getFullYear(),b.getMonth(),b.getDate());
return Math.round((B-A)/86400000);
}
function sameDay(a,b){ return a.getFullYear()===b.getFullYear() && a.getMonth()===b.getMonth() && a.getDate()===b.getDate(); }
function mod(n,m){ return ((n % m) + m) % m; }
var MONTH_NAMES = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var today = new Date(); today.setHours(0,0,0,0);
function loadLS(key, fallback){
try{ var v = localStorage.getItem(key); return v===null ? fallback : v; }catch(e){ return fallback; }
}
function saveLS(key, val){ try{ localStorage.setItem(key,val); }catch(e){} }
/* ---------------- mode switching ---------------- */
var modeBtns = document.querySelectorAll(".mode-btn");
var panels = { period: document.getElementById("mode-period"), ovulation: document.getElementById("mode-ovulation"), pregnancy: document.getElementById("mode-pregnancy") };
modeBtns.forEach(function(btn){
btn.addEventListener("click", function(){
modeBtns.forEach(function(b){ b.classList.remove("active"); b.setAttribute("aria-selected","false"); });
btn.classList.add("active"); btn.setAttribute("aria-selected","true");
Object.keys(panels).forEach(function(k){ panels[k].classList.remove("active"); });
panels[btn.dataset.mode].classList.add("active");
saveLS("ca-mode", btn.dataset.mode);
});
});
var savedMode = loadLS("ca-mode", null);
if(savedMode && panels[savedMode]){
modeBtns.forEach(function(b){ b.classList.toggle("active", b.dataset.mode===savedMode); b.setAttribute("aria-selected", b.dataset.mode===savedMode ? "true":"false"); });
Object.keys(panels).forEach(function(k){ panels[k].classList.toggle("active", k===savedMode); });
}
/* ================================================================
PHASE + OVULATION REFERENCE DATA
================================================================ */
var PHASES = {
menstrual: {
title:"Menstrual", color:"var(--period)", soft:"var(--period-soft)",
window:"Cycle day 1 through the end of bleeding",
desc:"The uterine lining sheds because no pregnancy occurred last cycle. Estrogen and progesterone are both at their lowest point of the month.",
hormone:"Estrogen & progesterone: low", energy:"Energy: lowest",
symptoms:"Cramping, fatigue, lower back ache, mood dips",
tip:"Iron-rich food, gentle movement, and heat on the lower abdomen ease cramping better than rest alone."
},
follicular: {
title:"Follicular", color:"var(--ovulation)", soft:"var(--ovulation-soft)",
window:"Cycle day 1 through ovulation (overlaps menstrual)",
desc:"The pituitary releases FSH, prompting several ovarian follicles to mature. Estrogen climbs steadily as one dominant follicle takes the lead.",
hormone:"Estrogen: rising", energy:"Energy: climbing",
symptoms:"Clearer skin, sharper focus, rising motivation",
tip:"This is the physiologically best window for starting new training blocks or demanding projects."
},
ovulatory: {
title:"Ovulatory", color:"var(--ovulation-strong)", soft:"var(--ovulation-soft)",
window:"Roughly one day, mid-cycle",
desc:"A surge in luteinizing hormone (LH) triggers the dominant follicle to release its egg. This is the single most fertile day of the cycle.",
hormone:"LH: sharp surge", energy:"Energy & libido: peak",
symptoms:"Egg-white cervical mucus, one-sided pelvic twinge (mittelschmerz)",
tip:"Ovulation predictor kits detect the LH surge roughly 24–36 hours before the egg is released."
},
luteal: {
title:"Luteal", color:"var(--pregnancy)", soft:"var(--pregnancy-soft)",
window:"Ovulation through the day before your next period",
desc:"The ruptured follicle becomes the corpus luteum and secretes progesterone to prepare the uterine lining. If no implantation occurs, hormone levels fall and the cycle restarts.",
hormone:"Progesterone: rises then falls", energy:"Energy: gradually declining",
symptoms:"Bloating, breast tenderness, irritability, food cravings (PMS)",
tip:"Basal body temperature stays elevated ~0.3–0.5°C through this phase — a useful way to confirm ovulation already happened."
}
};
// offset relative to ovulation day (0 = ovulation)
var OVULATION_DAYS = {
"-5": {fert:"Low", fertClass:"fert-low", bbt:"Baseline (pre-shift)", mucus:"Dry to sticky", note:"Sperm can survive up to 5 days, so conception is technically possible starting here."},
"-4": {fert:"Low–moderate", fertClass:"fert-low", bbt:"Baseline", mucus:"Sticky, cloudy", note:"Fertility begins climbing as estrogen rises toward its pre-ovulation peak."},
"-3": {fert:"Moderate", fertClass:"fert-mid", bbt:"Baseline", mucus:"Creamy, increasing in volume", note:"Cervical mucus is becoming more hospitable to sperm."},
"-2": {fert:"High", fertClass:"fert-high", bbt:"Baseline", mucus:"Thin, stretchy, egg-white-like", note:"One of the two most fertile days of the entire cycle."},
"-1": {fert:"Peak", fertClass:"fert-peak", bbt:"Baseline (often the day of the LH surge)", mucus:"Clear, slippery, maximum stretch", note:"Statistically the single highest-probability day for conception."},
"0": {fert:"Peak", fertClass:"fert-peak", bbt:"Still baseline — the rise hasn't happened yet", mucus:"Egg-white, abundant", note:"The egg is released and is viable for roughly 12–24 hours. Some feel a one-sided twinge (mittelschmerz)."},
"1": {fert:"Dropping fast", fertClass:"fert-mid", bbt:"Beginning to rise ~0.3–0.5°C", mucus:"Becoming tacky again", note:"The egg's fertile window is closing; BBT starts its post-ovulation climb."},
"2": {fert:"Very low", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry or minimal", note:"Progesterone from the corpus luteum keeps temperature elevated through the luteal phase."},
"3": {fert:"Essentially none", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry", note:"If fertilization happened, the embryo is traveling toward the uterus."},
"4": {fert:"Essentially none", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry", note:"Too late in the cycle for a new ovulation; luteal phase symptoms may start appearing."},
"5": {fert:"Essentially none", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry", note:"Implantation, if it happens this cycle, typically occurs around days 6–10 after ovulation."}
};
var FERT_COLOR = {"fert-low":"var(--ink-soft)","fert-mid":"var(--fertile)","fert-high":"var(--fertile-strong)","fert-peak":"var(--ovulation-strong)"};
function phaseForDayInCycle(dic, periodLen, ovulationDic){
if(dic < periodLen) return "menstrual";
if(dic < ovulationDic) return "follicular";
if(dic === ovulationDic) return "ovulatory";
return "luteal";
}
function isFertile(dic, ovulationDic){
return dic >= ovulationDic - 5 && dic <= ovulationDic;
}
/* ================================================================
PREGNANCY WEEK DATA (1–40)
================================================================ */
var WEEKS = [
{c:"a poppy seed (not yet fertilized)", m:"n/a", dev:"Pregnancy is dated from the first day of this period, before conception happens — your body is shedding last cycle's lining and preparing a fresh egg.", body:"This week looks and feels like an ordinary period.", tip:"If you're trying to conceive, this is a good week to start a prenatal vitamin with folic acid."},
{c:"an egg cell", m:"~0.1 mm", dev:"Rising estrogen prompts an egg to mature; ovulation typically occurs near the end of this week, roughly two weeks before a missed period.", body:"Cervical mucus becomes clear and stretchy around ovulation — a natural fertility sign.", tip:"This is the fertile window if you're trying to conceive — see the Ovulation tab for day-by-day detail."},
{c:"a grain of sand", m:"~0.1–0.2 mm", dev:"If sperm meets egg this week, fertilization occurs in the fallopian tube and the resulting cell begins dividing as it travels toward the uterus.", body:"No symptoms are detectable yet — even a sensitive test won't turn positive for another week or two.", tip:"Implantation, if it happens, usually occurs 6–10 days after ovulation."},
{c:"a poppy seed", m:"~0.1 mm", dev:"The fertilized egg implants in the uterine lining and begins producing hCG, the hormone home pregnancy tests detect.", body:"Most people notice no symptoms yet; a sensitive test may already turn positive near the end of this week.", tip:"A missed period is usually the first sign — testing a few days after that gives the most reliable result."},
{c:"a sesame seed", m:"~2 mm", dev:"The neural tube — the earliest structure of the brain and spinal cord — begins to form, along with the first blood vessels.", body:"A missed period is usually the first clear sign; fatigue and tender breasts may begin.", tip:"Avoid alcohol and confirm any medications with a clinician — this window is critical for early development."},
{c:"a lentil", m:"~4 mm", dev:"A primitive heart tube starts beating, and the beginnings of the face, arms, and legs appear as small buds.", body:"Morning sickness and smell sensitivity often begin here, though timing varies widely.", tip:"Small, frequent, bland meals tend to sit better than three large ones if nausea has started."},
{c:"a blueberry", m:"~1.3 cm", dev:"The brain is dividing into distinct sections, and the arm and leg buds are elongating into recognizable limbs.", body:"Bloating and mild cramping are common as the uterus makes room to grow.", tip:"This is when most people schedule their first prenatal appointment — dating scans are most accurate now."},
{c:"a raspberry", m:"~1.6 cm", dev:"Fingers and toes are forming, still webbed; the heart now has four distinct chambers.", body:"Fatigue often peaks around this point as progesterone rises sharply.", tip:"Rest when you can — first-trimester exhaustion is real and temporary, not a sign anything is wrong."},
{c:"a grape", m:"~2.3 cm · 4 g", dev:"The embryo is officially called a fetus starting around now; essential organs are all present in early form and the tail has disappeared.", body:"Nausea, food aversions, and a heightened sense of smell are often at their strongest.", tip:"Ginger tea, vitamin B6, and staying hydrated are commonly recommended first-line options for nausea."},
{c:"a kumquat", m:"~3 cm · 7 g", dev:"Vital organs — kidneys, liver, brain — are functioning in a basic form, and tiny fingernail beds are forming.", body:"A visible baby bump is still unlikely, though clothes may feel tighter.", tip:"Ask your provider about first-trimester screening options available in this window."},
{c:"a fig", m:"~4.1 cm · 10 g", dev:"The fetus can now bend its arms and legs, and tooth buds are forming beneath the gums.", body:"Round ligament twinges may start as the uterus stretches.", tip:"Gentle stretching and changing positions slowly can ease early ligament discomfort."},
{c:"a lime", m:"~5.4 cm · 14 g", dev:"Reflexes are developing — fingers can curl, and toes can wiggle, though it can't be felt yet.", body:"The end of the first trimester is near, and miscarriage risk drops meaningfully from here.", tip:"Many people choose to share their pregnancy news around now, though the choice is entirely personal."},
{c:"a plum", m:"~6.7 cm · 23 g", dev:"Vocal cords are forming, and unique fingerprints are being etched onto tiny fingertips.", body:"Some early nausea may start easing as the placenta takes over hormone production.", tip:"The nuchal translucency scan, if chosen, is typically done between now and week 13."},
{c:"a passion fruit", m:"~10 cm · 45 g", dev:"Baby can open and close fists and may even suck a thumb; genitals are differentiating, though not yet visible on ultrasound.", body:"For many, first-trimester nausea and fatigue begin to lift.", tip:"Second-trimester energy often supports resuming or starting light-to-moderate exercise — check in with your provider first."},
{c:"a peach", m:"~11.6 cm · 58 g", dev:"Vocal cords are complete and the intestines, which developed in the umbilical cord, move into the abdomen.", body:"Welcome to the second trimester — often called the most comfortable stretch of pregnancy.", tip:"An anatomy scan is usually scheduled in the coming weeks; ask your clinic when it's booked."},
{c:"a lemon", m:"~13 cm · 70 g", dev:"Fine, downy hair called lanugo begins covering the body, and the kidneys are producing urine into the amniotic fluid.", body:"A small bump may finally become visible; appetite often improves noticeably.", tip:"Iron needs rise sharply now — leafy greens, legumes, and lean meat help meet increased demand."},
{c:"an apple", m:"~14.2 cm · 95 g", dev:"The skeleton continues hardening and baby can sense light through closed eyelids.", body:"Skin changes like a faint linea nigra or darkened areolas may appear as pigment increases.", tip:"Daily SPF helps limit pregnancy-related skin pigmentation (melasma) from sun exposure."},
{c:"an avocado", m:"~16 cm · 135 g", dev:"The placenta is now fully formed and functioning as baby's life-support system.", body:"First flutters of movement ('quickening') may be felt any time from now through week 20.", tip:"Movement timing varies a lot — first pregnancies and anterior placentas often mean feeling it later."},
{c:"a pomegranate", m:"~17.7 cm · 160 g", dev:"The skeleton is converting from cartilage to true bone, and fat stores are just beginning to accumulate.", body:"The uterus is now roughly at the level of the belly button.", tip:"A pregnancy support pillow can meaningfully improve sleep as side-sleeping becomes more comfortable."},
{c:"a bell pepper", m:"~19 cm · 190 g", dev:"Ears have reached their final position and baby may begin startling at loud external sounds.", body:"Quickening is commonly felt by now — often described as bubbles or light taps.", tip:"Try narrating your day out loud — hearing is developing and familiar voices become recognizable over time."},
{c:"a mango", m:"~20.3 cm · 240 g", dev:"A waxy coating called vernix caseosa begins protecting the skin, and taste buds are forming.", body:"Backaches can start as posture shifts to balance the growing bump.", tip:"A supportive, flatter shoe and a pillow between the knees at night both help low back strain."},
{c:"a banana", m:"~25.6 cm · 300 g", dev:"The detailed anatomy ultrasound is often done around now if it hasn't happened already, and sex can typically be identified on it.", body:"Movements are stronger and more frequent; the uterus is now level with the belly button.", tip:"If you want to know the sex and haven't had the anatomy scan yet, ask your clinic to schedule it soon — it's usually done weeks 18–22."},
{c:"a carrot", m:"~27 cm · 360 g", dev:"Baby is swallowing small amounts of amniotic fluid, giving the digestive system practice.", body:"Stretch marks may start appearing on the belly, hips, or chest as skin stretches.", tip:"Moisturizing won't prevent stretch marks, but it can ease the itchiness that comes with stretching skin."},
{c:"a papaya", m:"~28.9 cm · 430 g", dev:"Eyebrows and eyelids are fully formed, and the sense of touch is developing rapidly.", body:"Braxton Hicks — brief, painless practice contractions — may be felt occasionally from here on.", tip:"Braxton Hicks usually ease with a change of position or a glass of water; true labor contractions don't."},
{c:"an ear of corn", m:"~32.2 cm · 600 g", dev:"The lungs begin producing surfactant, a substance essential for breathing air after birth — a key viability milestone.", body:"The linea nigra (a dark vertical line on the belly) may become more visible.", tip:"This week is often cited as the threshold of viability with intensive neonatal care, should birth happen very early."},
{c:"a cauliflower head", m:"~33.7 cm · 660 g", dev:"Baby can now respond to your voice, and hand grip strength is developing.", body:"The glucose screening test for gestational diabetes is typically scheduled around now.", tip:"If asked to fast beforehand, follow your clinic's instructions closely for an accurate glucose result."},
{c:"a head of lettuce", m:"~35.6 cm · 760 g", dev:"Eyes begin to open after being fused shut since early development, and hair may be visibly growing.", body:"Round ligament pain and rib discomfort can increase as space gets tighter.", tip:"A maternity support band can ease rib and ligament pressure during long periods of standing or walking."},
{c:"a bunch of scallions", m:"~36.6 cm · 875 g", dev:"Brain tissue is developing rapidly, and baby is developing regular hiccups you may be able to feel.", body:"Third trimester begins soon — appointments typically become more frequent from here.", tip:"Hiccup-like twitches are completely normal and are the diaphragm practicing its rhythm."},
{c:"an eggplant", m:"~37.6 cm · 1.1 kg", dev:"Eyes can blink now, and baby may cycle through active REM sleep.", body:"Welcome to the third trimester — the home stretch begins.", tip:"This is a common time to start planning a hospital bag and reviewing birth preferences."},
{c:"a butternut squash", m:"~38.6 cm · 1.2 kg", dev:"Bones are fully formed but still soft and flexible, ready to move through the birth canal.", body:"Frequent urination often returns as the head engages lower in the pelvis.", tip:"Kick counts become a useful daily check-in — note baby's typical pattern of movement."},
{c:"a large cabbage", m:"~39.9 cm · 1.3 kg", dev:"The brain is developing at its fastest rate yet, adding folds and surface area.", body:"Sleep can become harder to find as the bump limits comfortable positions.", tip:"A full-body pregnancy pillow supports the belly, back, and knees simultaneously."},
{c:"a coconut", m:"~41.1 cm · 1.5 kg", dev:"All five senses are now functioning, and baby is gaining roughly half a pound a week.", body:"Colostrum, the first form of breast milk, may begin to leak slightly.", tip:"A few nursing pads in your bag can help if colostrum leaking becomes noticeable."},
{c:"a jicama", m:"~42.4 cm · 1.7 kg", dev:"Baby is practicing breathing movements against a closed airway, strengthening the lungs.", body:"Swelling and mild carpal tunnel tingling in the hands can appear from fluid retention.", tip:"Report sudden or severe swelling to your provider promptly — it can occasionally signal preeclampsia."},
{c:"a pineapple", m:"~43.7 cm · 1.9 kg", dev:"Bones are hardening overall, though the skull stays deliberately soft and flexible for delivery.", body:"Pelvic pressure increases as baby continues descending.", tip:"Prenatal massage or a warm bath can ease the deep pelvic ache many feel this week."},
{c:"a cantaloupe", m:"~45 cm · 2.1 kg", dev:"The central nervous system is maturing quickly, and baby's grip is now quite strong.", body:"Braxton Hicks contractions often become more noticeable and frequent.", tip:"Time any contractions that feel different — regular, intensifying, closer together warrants a call to your provider."},
{c:"a honeydew melon", m:"~46.2 cm · 2.4 kg", dev:"The kidneys are fully developed, and the liver is processing waste products on its own.", body:"You may feel baby 'drop' lower as it settles into position for birth.", tip:"Lightening (the baby dropping) can ease heartburn but often increases bathroom trips."},
{c:"a head of romaine", m:"~47.4 cm · 2.6 kg", dev:"Most physical development is complete; the focus now is steady weight gain.", body:"You've just reached 'early term' — babies born from here on tend to do very well.", tip:"Pack your hospital bag if you haven't yet — early-term babies can arrive with little warning."},
{c:"a leek", m:"~49.8 cm · 3.1 kg", dev:"Baby continues laying down fat for temperature regulation after birth, and the brain is still rapidly developing.", body:"Nesting instinct and a burst of energy are common right before labor.", tip:"Balance nesting energy with rest — labor's timing is unpredictable."},
{c:"a mini watermelon", m:"~50.7 cm · 3.3 kg", dev:"Full term. The lungs are completing final maturation in preparation for that first breath.", body:"Increased pelvic pressure and more frequent, intense Braxton Hicks are common.", tip:"Watch for your labor signs: regular contractions, water breaking, or a bloody show."},
{c:"a small pumpkin", m:"~51.2 cm · 3.5 kg", dev:"Baby is fully developed and simply continuing to grow, ready to meet you.", body:"If labor hasn't started, your provider will discuss monitoring or induction options.", tip:"Most babies arrive within two weeks of their due date in either direction — both are entirely normal."}
];
/* ================================================================
SVG helpers
================================================================ */
function polarToXY(cx,cy,r,angleDeg){
var rad = (angleDeg-90) * Math.PI/180;
return [cx + r*Math.cos(rad), cy + r*Math.sin(rad)];
}
function arcPath(cx,cy,r,startDeg,endDeg){
if(endDeg <= startDeg) endDeg = startDeg + 0.01;
var s = polarToXY(cx,cy,r,startDeg), e = polarToXY(cx,cy,r,endDeg);
var large = (endDeg-startDeg) > 180 ? 1 : 0;
return "M "+s[0].toFixed(2)+" "+s[1].toFixed(2)+" A "+r+" "+r+" 0 "+large+" 1 "+e[0].toFixed(2)+" "+e[1].toFixed(2);
}
/* ================================================================
SHARED STATE: period start / cycle length / period length
================================================================ */
var exampleStart = addDays(today, -10);
var startInput = document.getElementById("p-start");
var cycleLenInput = document.getElementById("p-cyclelen");
var periodLenInput = document.getElementById("p-periodlen");
var savedStart = loadLS("ca-start", null);
var savedCycleLen = loadLS("ca-cyclelen", null);
var savedPeriodLen = loadLS("ca-periodlen", null);
var usingExample = !savedStart;
startInput.value = savedStart || toInputVal(exampleStart);
cycleLenInput.value = savedCycleLen || 28;
periodLenInput.value = savedPeriodLen || 5;
function getCycleState(){
return {
start: fromInput(startInput.value) || exampleStart,
cycleLen: Math.max(21, Math.min(35, parseInt(cycleLenInput.value,10) || 28)),
periodLen: Math.max(2, Math.min(10, parseInt(periodLenInput.value,10) || 5))
};
}
var pCalMonth = new Date(today.getFullYear(), today.getMonth(), 1);
var oCalMonth = new Date(today.getFullYear(), today.getMonth(), 1);
var pSelectedDate = new Date(today);
var oSelectedDate = new Date(today);
[startInput,cycleLenInput,periodLenInput].forEach(function(inp){
inp.addEventListener("input", function(){
saveLS("ca-start", startInput.value);
saveLS("ca-cyclelen", cycleLenInput.value);
saveLS("ca-periodlen", periodLenInput.value);
usingExample = false;
document.getElementById("p-example-note").style.display = "none";
document.getElementById("pr-example-note").style.display = "none";
renderAll();
});
});
if(!usingExample) document.getElementById("p-example-note").style.display = "none";
/* ================================================================
CALENDAR RENDERING (shared builder)
================================================================ */
function buildCalendar(gridEl, weekdayHeaderIgnored, monthDate, dayClassifier, onSelect, selectedDate){
gridEl.innerHTML = "";
var year = monthDate.getFullYear(), month = monthDate.getMonth();
var firstDow = new Date(year,month,1).getDay();
var daysInMonth = new Date(year,month+1,0).getDate();
var totalCells = Math.ceil((firstDow+daysInMonth)/7)*7;
for(var i=0;i<totalCells;i++){
var dayNum = i - firstDow + 1;
var cell = document.createElement("button");
cell.className = "day-cell";
if(dayNum < 1 || dayNum > daysInMonth){
cell.classList.add("pad");
gridEl.appendChild(cell);
continue;
}
var d = new Date(year,month,dayNum);
var info = dayClassifier(d);
cell.innerHTML = "<span>"+dayNum+"</span>";
if(info.period) cell.classList.add("is-period");
if(info.fertile) cell.classList.add("is-fertile");
if(info.ovulation) cell.classList.add("is-ovulation");
if(sameDay(d,today)) cell.classList.add("today");
if(selectedDate && sameDay(d,selectedDate)) cell.classList.add("selected");
cell.setAttribute("aria-label", d.toDateString());
cell.addEventListener("click", function(dd){ return function(){ onSelect(dd); }; }(d));
gridEl.appendChild(cell);
}
}
function classifyForCycle(d, state){
var dic = mod(daysBetween(state.start, d), state.cycleLen);
var ovDic = mod(state.cycleLen - 14, state.cycleLen);
return {
period: dic < state.periodLen,
fertile: isFertile(dic, ovDic),
ovulation: dic === ovDic,
dic: dic, ovDic: ovDic
};
}
/* ---------------- PERIOD tab render ---------------- */
function renderPeriodCalendar(){
var state = getCycleState();
document.getElementById("p-cal-title").textContent = MONTH_NAMES[pCalMonth.getMonth()] + " " + pCalMonth.getFullYear();
buildCalendar(document.getElementById("p-daygrid"), null, pCalMonth,
function(d){ return classifyForCycle(d, state); },
function(d){ pSelectedDate = d; renderPeriodDetail(); renderPeriodCalendar(); },
pSelectedDate
);
}
function renderPeriodDetail(){
var state = getCycleState();
var info = classifyForCycle(pSelectedDate, state);
var phaseKey = phaseForDayInCycle(info.dic, state.periodLen, info.ovDic);
var phase = PHASES[phaseKey];
var el = document.getElementById("p-detail");
el.innerHTML =
'<span class="d-date">'+pSelectedDate.toDateString()+'</span>'+
'<span class="pill" style="background:'+phase.soft+';color:'+phase.color+'">'+phase.title+' phase'+(info.fertile?' · fertile window':'')+'</span>'+
'<div class="d-phase">Cycle day '+(info.dic+1)+'</div>'+
'<p class="d-desc">'+phase.desc+'</p>'+
'<div class="d-grid">'+
'<div class="d-mini"><div class="k">Hormones</div><div class="v">'+phase.hormone+'</div></div>'+
'<div class="d-mini"><div class="k">Typical symptoms</div><div class="v" style="font-weight:500;font-size:0.82rem;">'+phase.symptoms+'</div></div>'+
'</div>'+
'<p class="d-desc"><strong style="color:var(--ink)">Care note — </strong>'+phase.tip+'</p>';
}
function renderPeriodStats(){
var state = getCycleState();
var dic = mod(daysBetween(state.start, today), state.cycleLen);
var ovDic = mod(state.cycleLen - 14, state.cycleLen);
var daysToNextPeriod = mod(state.cycleLen - dic, state.cycleLen);
if(daysToNextPeriod === 0 && dic !== 0) daysToNextPeriod = state.cycleLen;
var daysToOvulation = mod(ovDic - dic, state.cycleLen);
var phaseKey = phaseForDayInCycle(dic, state.periodLen, ovDic);
document.getElementById("period-stats").innerHTML =
statTile(dic+1, "Cycle day today") +
statTile(PHASES[phaseKey].title, "Current phase") +
statTile(dic===0 ? "Today" : (daysToNextPeriod+"d"), "Until next period") +
statTile(dic===ovDic ? "Today" : (daysToOvulation+"d"), "Until ovulation");
// hero ring
var cx=100, cy=100, r=88;
var perStart=0, perEnd = state.periodLen/state.cycleLen*360;
var follEnd = ovDic/state.cycleLen*360;
var fertStart = Math.max(0,(ovDic-5))/state.cycleLen*360;
var lutStart = (ovDic+1)/state.cycleLen*360;
document.getElementById("phase-arc-menstrual").setAttribute("d", arcPath(cx,cy,r,perStart,perEnd));
document.getElementById("phase-arc-follicular").setAttribute("d", arcPath(cx,cy,r,perEnd,fertStart));
document.getElementById("phase-arc-fertile").setAttribute("d", arcPath(cx,cy,r,fertStart,follEnd+ (360/state.cycleLen)));
document.getElementById("phase-arc-luteal").setAttribute("d", arcPath(cx,cy,r,lutStart,360));
var todayAngle = dic/state.cycleLen*360;
var tp = polarToXY(cx,cy,r,todayAngle);
document.getElementById("today-marker").setAttribute("cx", tp[0]);
document.getElementById("today-marker").setAttribute("cy", tp[1]);
document.getElementById("cycle-day-big").textContent = dic+1;
// hand the same numbers to the optional 3D ring (ring3d.js)
window.cycleRingData = {perEnd:perEnd, fertStart:fertStart, fertEnd:follEnd+(360/state.cycleLen),
lutStart:lutStart, todayAngle:todayAngle};
window.dispatchEvent(new CustomEvent("cycle:ring", {detail: window.cycleRingData}));
}
function statTile(num,label){
return '<div class="stat-tile"><div class="num">'+num+'</div><div class="lbl">'+label+'</div></div>';
}
document.getElementById("p-prev").addEventListener("click", function(){ pCalMonth.setMonth(pCalMonth.getMonth()-1); renderPeriodCalendar(); });
document.getElementById("p-next").addEventListener("click", function(){ pCalMonth.setMonth(pCalMonth.getMonth()+1); renderPeriodCalendar(); });
function renderPhaseRefGrid(){
var order = ["menstrual","follicular","ovulatory","luteal"];
document.getElementById("phase-ref-grid").innerHTML = order.map(function(key,i){
var p = PHASES[key];
return '<div class="ref-card"><span class="r-num">0'+(i+1)+'</span><h4 style="color:'+p.color+'">'+p.title+'</h4>'+
'<p>'+p.desc+'</p>'+
'<div class="tag-row"><span class="tagchip">'+p.window+'</span></div></div>';
}).join("");
}
/* ---------------- OVULATION tab render ---------------- */
var ovSelectedOffset = 0;
function renderOvTimeline(){
var wrap = document.getElementById("ov-timeline");
wrap.innerHTML = "";
for(var off=-5; off<=5; off++){
var d = OVULATION_DAYS[String(off)];
var btn = document.createElement("button");
btn.className = "tl-btn" + (off===ovSelectedOffset ? " active":"");
btn.innerHTML = '<div class="tl-day">'+(off===0?"OVUL.":(off>0?"+":"")+off)+'</div>'+
'<div class="tl-fert" style="background:'+FERT_COLOR[d.fertClass]+'"></div>';
btn.addEventListener("click", function(o){ return function(){ ovSelectedOffset=o; renderOvTimeline(); renderOvDetailFromOffset(); }; }(off));
wrap.appendChild(btn);
}
}
function renderOvDetailFromOffset(){
var d = OVULATION_DAYS[String(ovSelectedOffset)];
var el = document.getElementById("o-detail");
var label = ovSelectedOffset===0 ? "Ovulation day" : (ovSelectedOffset>0 ? ovSelectedOffset+" day"+(ovSelectedOffset>1?"s":"")+" after ovulation" : Math.abs(ovSelectedOffset)+" day"+(ovSelectedOffset<-1?"s":"")+" before ovulation");
el.innerHTML =
'<span class="d-date">'+label+'</span>'+
'<span class="pill" style="background:var(--ovulation-soft);color:'+FERT_COLOR[d.fertClass]+'">Fertility: '+d.fert+'</span>'+
'<div class="d-phase">'+(ovSelectedOffset===0?"Egg release":(ovSelectedOffset<0?"Building fertility":"Fertility fading"))+'</div>'+
'<div class="d-grid">'+
'<div class="d-mini"><div class="k">Basal body temp</div><div class="v" style="font-size:0.82rem;">'+d.bbt+'</div></div>'+
'<div class="d-mini"><div class="k">Cervical mucus</div><div class="v" style="font-size:0.82rem;">'+d.mucus+'</div></div>'+
'</div>'+
'<p class="d-desc">'+d.note+'</p>';
}
function renderOvulationCalendar(){
var state = getCycleState();
document.getElementById("o-cal-title").textContent = MONTH_NAMES[oCalMonth.getMonth()] + " " + oCalMonth.getFullYear();
buildCalendar(document.getElementById("o-daygrid"), null, oCalMonth,
function(d){ return classifyForCycle(d, state); },
function(d){
oSelectedDate = d;
var info = classifyForCycle(d, state);
var offset = info.dic - info.ovDic;
if(offset < -5) offset = -5; if(offset > 5) offset = 5;
ovSelectedOffset = offset;
renderOvTimeline(); renderOvDetailFromOffset(); renderOvulationCalendar();
},
oSelectedDate
);
}
function renderOvulationStats(){
var state = getCycleState();
var dic = mod(daysBetween(state.start, today), state.cycleLen);
var ovDic = mod(state.cycleLen - 14, state.cycleLen);
var daysToOvulation = mod(ovDic - dic, state.cycleLen);
var fertileStartDic = mod(ovDic-5, state.cycleLen);
var inFertile = isFertile(dic, ovDic);
var daysToFertile = inFertile ? 0 : mod(fertileStartDic - dic, state.cycleLen);
document.getElementById("ovulation-stats").innerHTML =
statTile(inFertile ? "Yes" : "No", "In fertile window") +
statTile(dic===ovDic ? "Today" : daysToOvulation+"d", "Until ovulation") +
statTile(inFertile ? "Now" : daysToFertile+"d", "Fertile window") +
statTile("6 days", "Window length");
}
document.getElementById("o-prev").addEventListener("click", function(){ oCalMonth.setMonth(oCalMonth.getMonth()-1); renderOvulationCalendar(); });
document.getElementById("o-next").addEventListener("click", function(){ oCalMonth.setMonth(oCalMonth.getMonth()+1); renderOvulationCalendar(); });
/* ================================================================
PREGNANCY tab
================================================================ */
var lmpInput = document.getElementById("pr-lmp");
var exampleLMP = addDays(today, -20*7 - 3);
var savedLMP = loadLS("ca-lmp", null);
lmpInput.value = savedLMP || toInputVal(exampleLMP);
if(savedLMP) document.getElementById("pr-example-note").style.display = "none";
var slider = document.getElementById("week-slider");
var prCalMonth = new Date(today.getFullYear(), today.getMonth(), 1);
lmpInput.addEventListener("input", function(){
saveLS("ca-lmp", lmpInput.value);
document.getElementById("pr-example-note").style.display = "none";
document.getElementById("p-example-note").style.display = "none";
syncSliderToLMP();
renderPregnancy();
});
function getLMP(){ return fromInput(lmpInput.value) || exampleLMP; }
function currentGestWeek(){
var lmp = getLMP();
var w = Math.floor(daysBetween(lmp,today)/7) + 1;
return Math.max(1, Math.min(40, w));
}
function syncSliderToLMP(){ slider.value = currentGestWeek(); }
syncSliderToLMP();
function renderPregnancyStats(){
var lmp = getLMP();
var due = addDays(lmp, 280);
var week = currentGestWeek();
var daysLeft = Math.max(0, daysBetween(today, due));
document.getElementById("pregnancy-stats").innerHTML =
statTile(week, "Weeks along") +
statTile(Math.floor((week-1)/13)+1 <= 3 ? ["First","Second","Third"][Math.min(2,Math.floor((week-1)/13))] : "Third", "Trimester") +
statTile(daysLeft, "Days to due date") +
statTile(due.toLocaleDateString(undefined,{month:"short",day:"numeric"}), "Estimated due date");
var pct = (week-1)/39;
var pathLen = 230;
var offset = pathLen - pct*pathLen;
var path = document.getElementById("pregnancy-progress-path");
path.setAttribute("stroke-dashoffset", offset.toFixed(1));
try{
var totalLen = path.getTotalLength ? path.getTotalLength() : pathLen;
var pt = path.getPointAtLength ? path.getPointAtLength(pct*totalLen) : null;
if(pt) { document.getElementById("pregnancy-progress-dot").setAttribute("cx",pt.x); document.getElementById("pregnancy-progress-dot").setAttribute("cy",pt.y); }
}catch(e){}
}
function renderWeekPanel(week){
var w = WEEKS[week-1];
document.getElementById("wk-badge").textContent = "WEEK " + week;
document.getElementById("wk-compare").textContent = "size of " + w.c;
document.getElementById("wk-metric").textContent = w.m === "n/a" ? "not yet fertilized" : "≈ " + w.m;
document.getElementById("wk-dev").textContent = w.dev;
document.getElementById("wk-body").textContent = w.body;
document.getElementById("wk-tip").textContent = w.tip;
var tri = week<=13?1:(week<=27?2:3);
var triColor = "var(--pregnancy)";
document.getElementById("wk-blob").innerHTML =
'<svg width="96" height="96" viewBox="0 0 96 96"><circle cx="48" cy="48" r="'+(14+week*0.9)+'" fill="'+ (tri===1?"var(--pregnancy-soft)":tri===2?"var(--pregnancy)":"var(--pregnancy-strong)") +'" opacity="0.85"/></svg>';
document.querySelectorAll(".film-item").forEach(function(f){ f.classList.toggle("active", +f.dataset.week===week); });
var active = document.querySelector('.film-item[data-week="'+week+'"]');
if(active) active.scrollIntoView({inline:"center", block:"nearest", behavior:"smooth"});
}
slider.addEventListener("input", function(){ renderWeekPanel(+slider.value); });
function buildFilmstrip(){
var wrap = document.getElementById("week-filmstrip");
wrap.innerHTML = "";
for(var w=1; w<=40; w++){
var item = document.createElement("button");
item.className = "film-item";
item.dataset.week = w;
item.innerHTML = '<div class="fw">WK</div><div class="fn">'+w+'</div>';
item.addEventListener("click", function(ww){ return function(){ slider.value=ww; renderWeekPanel(ww); }; }(w));
wrap.appendChild(item);
}
}
function renderPregnancyCalendar(){
var lmp = getLMP();
document.getElementById("pr-cal-title").textContent = MONTH_NAMES[prCalMonth.getMonth()] + " " + prCalMonth.getFullYear();
var grid = document.getElementById("pr-daygrid");
grid.innerHTML = "";
var year = prCalMonth.getFullYear(), month = prCalMonth.getMonth();
var firstDow = new Date(year,month,1).getDay();
var daysInMonth = new Date(year,month+1,0).getDate();
var totalCells = Math.ceil((firstDow+daysInMonth)/7)*7;
for(var i=0;i<totalCells;i++){
var dayNum = i - firstDow + 1;
var cell = document.createElement("button");
cell.className = "day-cell";
if(dayNum<1 || dayNum>daysInMonth){ cell.classList.add("pad"); grid.appendChild(cell); continue; }
var d = new Date(year,month,dayNum);
var wk = Math.floor(daysBetween(lmp,d)/7)+1;
var inRange = wk>=1 && wk<=42;
cell.innerHTML = "<span>"+dayNum+"</span>" + (inRange ? '<span class="dot-row" style="position:static;margin-top:2px;font-size:0.55rem;color:var(--pregnancy-strong)">W'+wk+'</span>' : "");
if(inRange && wk<=40) cell.classList.add("is-fertile");
if(sameDay(d,today)) cell.classList.add("today");
cell.addEventListener("click", function(ww){ return function(){ if(ww>=1&&ww<=40){ slider.value=ww; renderWeekPanel(ww); } }; }(wk));
grid.appendChild(cell);
}
}
document.getElementById("pr-prev").addEventListener("click", function(){ prCalMonth.setMonth(prCalMonth.getMonth()-1); renderPregnancyCalendar(); });
document.getElementById("pr-next").addEventListener("click", function(){ prCalMonth.setMonth(prCalMonth.getMonth()+1); renderPregnancyCalendar(); });
function renderPregnancy(){
renderPregnancyStats();
renderWeekPanel(currentGestWeek());
renderPregnancyCalendar();
}
/* ================================================================
INIT
================================================================ */
function renderAll(){
renderPeriodStats();
renderPeriodCalendar();
renderPeriodDetail();
renderOvulationStats();
renderOvTimeline();
renderOvDetailFromOffset();
renderOvulationCalendar();
renderPregnancy();
}
renderPhaseRefGrid();
buildFilmstrip();
slider.value = currentGestWeek();
renderAll();
})();
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The Fraunces Project Authors (github.com/undercasetype/Fraunces) Fraunces-Italic[SOFT,WONK,opsz,wght].ttf: Copyright 2020 The Fraunces Project Authors (github.com/undercasetype/Fraunces)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ThinItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLight.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Light.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-LightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Regular.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Italic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Medium.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-MediumItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Bold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-BoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2019 The Work Sans Project Authors (https://github.com/weiweihuanghuang/Work-Sans) WorkSans-Italic[wght].ttf: Copyright 2019 The Work Sans Project Authors (https://github.com/weiweihuanghuang/Work-Sans)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+15
View File
@@ -0,0 +1,15 @@
/* Self-hosted fonts (Latin subset), SIL Open Font License 1.1 - see OFL-*.txt */
@font-face{font-family:"Fraunces";font-style:normal;font-weight:400;font-display:swap;src:url("fraunces-latin-400-normal.woff2") format("woff2");}
@font-face{font-family:"Fraunces";font-style:normal;font-weight:500;font-display:swap;src:url("fraunces-latin-500-normal.woff2") format("woff2");}
@font-face{font-family:"Fraunces";font-style:normal;font-weight:600;font-display:swap;src:url("fraunces-latin-600-normal.woff2") format("woff2");}
@font-face{font-family:"Fraunces";font-style:normal;font-weight:700;font-display:swap;src:url("fraunces-latin-700-normal.woff2") format("woff2");}
@font-face{font-family:"Fraunces";font-style:normal;font-weight:900;font-display:swap;src:url("fraunces-latin-900-normal.woff2") format("woff2");}
@font-face{font-family:"Fraunces";font-style:italic;font-weight:500;font-display:swap;src:url("fraunces-latin-500-italic.woff2") format("woff2");}
@font-face{font-family:"Fraunces";font-style:italic;font-weight:600;font-display:swap;src:url("fraunces-latin-600-italic.woff2") format("woff2");}
@font-face{font-family:"Work Sans";font-style:normal;font-weight:400;font-display:swap;src:url("work-sans-latin-400-normal.woff2") format("woff2");}
@font-face{font-family:"Work Sans";font-style:normal;font-weight:500;font-display:swap;src:url("work-sans-latin-500-normal.woff2") format("woff2");}
@font-face{font-family:"Work Sans";font-style:normal;font-weight:600;font-display:swap;src:url("work-sans-latin-600-normal.woff2") format("woff2");}
@font-face{font-family:"Work Sans";font-style:normal;font-weight:700;font-display:swap;src:url("work-sans-latin-700-normal.woff2") format("woff2");}
@font-face{font-family:"IBM Plex Mono";font-style:normal;font-weight:400;font-display:swap;src:url("ibm-plex-mono-latin-400-normal.woff2") format("woff2");}
@font-face{font-family:"IBM Plex Mono";font-style:normal;font-weight:500;font-display:swap;src:url("ibm-plex-mono-latin-500-normal.woff2") format("woff2");}
@font-face{font-family:"IBM Plex Mono";font-style:normal;font-weight:600;font-display:swap;src:url("ibm-plex-mono-latin-600-normal.woff2") format("woff2");}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+32 -550
View File
@@ -1,7 +1,11 @@
<!doctype html>
<html lang="en-AU">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
<title>CycleWise AU</title> <title>CycleWise AU</title>
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="stylesheet" href="fonts/fonts.css">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,wght@0,400;0,500;0,600;0,700;0,900;1,500;1,600&family=Work+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style> <style>
:root{ :root{
--paper:#FBF7F2; --paper:#FBF7F2;
@@ -131,6 +135,7 @@ button{font-family:inherit;}
.mode-panel.active{display:block;animation:rise .4s ease both;} .mode-panel.active{display:block;animation:rise .4s ease both;}
@keyframes rise{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:none;}} @keyframes rise{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:none;}}
@media (prefers-reduced-motion: reduce){.mode-panel.active{animation:none;}} @media (prefers-reduced-motion: reduce){.mode-panel.active{animation:none;}}
@media (prefers-color-scheme: dark){.mode-btn[data-mode="pregnancy"].active{color:#1B1417;}}
.hero{ .hero{
display:grid;grid-template-columns:1.3fr 1fr;gap:40px; display:grid;grid-template-columns:1.3fr 1fr;gap:40px;
@@ -144,7 +149,11 @@ button{font-family:inherit;}
} }
.hero h1{font-size:clamp(1.9rem,3.4vw,2.7rem);font-weight:600;line-height:1.08;} .hero h1{font-size:clamp(1.9rem,3.4vw,2.7rem);font-weight:600;line-height:1.08;}
.hero p.lede{color:var(--ink-soft);font-size:1.02rem;line-height:1.6;max-width:52ch;margin-top:14px;} .hero p.lede{color:var(--ink-soft);font-size:1.02rem;line-height:1.6;max-width:52ch;margin-top:14px;}
.hero-art{display:flex;justify-content:center;} .hero-art{display:flex;justify-content:center;position:relative;}
.hero-art.has-3d{align-items:center;}
.hero-art.has-3d .ring3d{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}
.hero-art.has-3d svg{position:relative;max-width:300px;}
.hero-art.has-3d svg path,.hero-art.has-3d svg circle{display:none;}
.hero-art svg{width:100%;max-width:220px;height:auto;} .hero-art svg{width:100%;max-width:220px;height:auto;}
.stat-row{display:flex;gap:12px;flex-wrap:wrap;margin-top:22px;} .stat-row{display:flex;gap:12px;flex-wrap:wrap;margin-top:22px;}
@@ -262,7 +271,7 @@ button{font-family:inherit;}
text-transform:uppercase;letter-spacing:0.05em;margin-bottom:8px;font-weight:600;} text-transform:uppercase;letter-spacing:0.05em;margin-bottom:8px;font-weight:600;}
input[type="range"].week-slider{ input[type="range"].week-slider{
width:100%;-webkit-appearance:none;appearance:none;height:8px;border-radius:999px; width:100%;-webkit-appearance:none;appearance:none;height:8px;border-radius:999px;
background:linear-gradient(to right, var(--pregnancy-soft) 0%, var(--pregnancy-soft) 100%); background:linear-gradient(to right, var(--pregnancy) 0, var(--pregnancy) calc(11px + (100% - 22px) * var(--f,0)), var(--pregnancy-soft) calc(11px + (100% - 22px) * var(--f,0)), var(--pregnancy-soft) 100%);
outline:none;cursor:pointer; outline:none;cursor:pointer;
} }
input[type="range"].week-slider::-webkit-slider-thumb{ input[type="range"].week-slider::-webkit-slider-thumb{
@@ -297,6 +306,7 @@ input[type="range"].week-slider::-moz-range-thumb{
.filmstrip{display:flex;gap:8px;overflow-x:auto;padding:4px 2px 20px;margin-top:8px;} .filmstrip{display:flex;gap:8px;overflow-x:auto;padding:4px 2px 20px;margin-top:8px;}
.film-item{ .film-item{
color:var(--ink);
flex:none;width:64px;height:64px;border-radius:12px;border:1px solid var(--line); flex:none;width:64px;height:64px;border-radius:12px;border:1px solid var(--line);
background:var(--surface);display:flex;flex-direction:column;align-items:center;justify-content:center; background:var(--surface);display:flex;flex-direction:column;align-items:center;justify-content:center;
cursor:pointer;font-family:"IBM Plex Mono",monospace; cursor:pointer;font-family:"IBM Plex Mono",monospace;
@@ -310,7 +320,8 @@ footer.note{
font-size:0.78rem;color:var(--ink-soft);line-height:1.6; font-size:0.78rem;color:var(--ink-soft);line-height:1.6;
} }
</style> </style>
</head>
<body>
<div class="app"> <div class="app">
<header class="topbar"> <header class="topbar">
<div class="wordmark"> <div class="wordmark">
@@ -324,15 +335,15 @@ footer.note{
<span class="tag">Menstrual &amp; Pregnancy Charting</span> <span class="tag">Menstrual &amp; Pregnancy Charting</span>
</div> </div>
<nav class="mode-switch" role="tablist" aria-label="Tracking mode"> <nav class="mode-switch" role="tablist" aria-label="Tracking mode">
<button class="mode-btn active" data-mode="period" role="tab" aria-selected="true">Period</button> <button class="mode-btn active" id="tab-period" aria-controls="mode-period" data-mode="period" role="tab" aria-selected="true">Period</button>
<button class="mode-btn" data-mode="ovulation" role="tab" aria-selected="false">Ovulation</button> <button class="mode-btn" id="tab-ovulation" aria-controls="mode-ovulation" data-mode="ovulation" role="tab" aria-selected="false">Ovulation</button>
<button class="mode-btn" data-mode="pregnancy" role="tab" aria-selected="false">Pregnancy</button> <button class="mode-btn" id="tab-pregnancy" aria-controls="mode-pregnancy" data-mode="pregnancy" role="tab" aria-selected="false">Pregnancy</button>
</nav> </nav>
</header> </header>
<main> <main>
<!-- ================= PERIOD ================= --> <!-- ================= PERIOD ================= -->
<section id="mode-period" class="mode-panel active"> <section id="mode-period" class="mode-panel active" role="tabpanel" aria-labelledby="tab-period">
<div class="hero"> <div class="hero">
<div> <div>
<span class="eyebrow" style="color:var(--period)">01 — Menstrual Cycle</span> <span class="eyebrow" style="color:var(--period)">01 — Menstrual Cycle</span>
@@ -398,7 +409,7 @@ footer.note{
</section> </section>
<!-- ================= OVULATION ================= --> <!-- ================= OVULATION ================= -->
<section id="mode-ovulation" class="mode-panel"> <section id="mode-ovulation" class="mode-panel" role="tabpanel" aria-labelledby="tab-ovulation">
<div class="hero"> <div class="hero">
<div> <div>
<span class="eyebrow" style="color:var(--ovulation)">02 — Fertile Window</span> <span class="eyebrow" style="color:var(--ovulation)">02 — Fertile Window</span>
@@ -446,7 +457,7 @@ footer.note{
</section> </section>
<!-- ================= PREGNANCY ================= --> <!-- ================= PREGNANCY ================= -->
<section id="mode-pregnancy" class="mode-panel"> <section id="mode-pregnancy" class="mode-panel" role="tabpanel" aria-labelledby="tab-pregnancy">
<div class="hero"> <div class="hero">
<div> <div>
<span class="eyebrow" style="color:var(--pregnancy)">03 — Forty Weeks</span> <span class="eyebrow" style="color:var(--pregnancy)">03 — Forty Weeks</span>
@@ -476,7 +487,7 @@ footer.note{
<span style="color:var(--pregnancy)">Trimester 2 · Weeks 14–27</span> <span style="color:var(--pregnancy)">Trimester 2 · Weeks 14–27</span>
<span style="color:var(--pregnancy)">Trimester 3 · Weeks 28–40</span> <span style="color:var(--pregnancy)">Trimester 3 · Weeks 28–40</span>
</div> </div>
<input type="range" class="week-slider" id="week-slider" min="1" max="40" value="20"> <input type="range" class="week-slider" id="week-slider" aria-label="Pregnancy week, 1 to 40" min="1" max="40" value="20">
<div class="week-ticks"><span>Wk 1</span><span>Wk 13</span><span>Wk 27</span><span>Wk 40</span></div> <div class="week-ticks"><span>Wk 1</span><span>Wk 13</span><span>Wk 27</span><span>Wk 40</span></div>
</div> </div>
@@ -524,540 +535,11 @@ footer.note{
</footer> </footer>
</div> </div>
<script> <script src="app.js"></script>
(function(){ <script src="vendor/gsap.min.js"></script>
"use strict"; <script src="vendor/ScrollTrigger.min.js"></script>
<script src="ring3d.js"></script>
/* ---------------- date helpers ---------------- */ <script src="animations.js"></script>
function toDate(y,m,d){ return new Date(y,m,d); } <script src="timeline.js"></script>
function fromInput(str){ </body>
if(!str) return null; </html>
var p = str.split("-");
return new Date(+p[0], +p[1]-1, +p[2]);
}
function toInputVal(d){
return d.getFullYear()+"-"+String(d.getMonth()+1).padStart(2,"0")+"-"+String(d.getDate()).padStart(2,"0");
}
function addDays(d,n){ var r=new Date(d); r.setDate(r.getDate()+n); return r; }
function daysBetween(a,b){ // b - a, in whole days, ignoring time
var A = new Date(a.getFullYear(),a.getMonth(),a.getDate());
var B = new Date(b.getFullYear(),b.getMonth(),b.getDate());
return Math.round((B-A)/86400000);
}
function sameDay(a,b){ return a.getFullYear()===b.getFullYear() && a.getMonth()===b.getMonth() && a.getDate()===b.getDate(); }
function mod(n,m){ return ((n % m) + m) % m; }
var MONTH_NAMES = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var today = new Date(); today.setHours(0,0,0,0);
function loadLS(key, fallback){
try{ var v = localStorage.getItem(key); return v===null ? fallback : v; }catch(e){ return fallback; }
}
function saveLS(key, val){ try{ localStorage.setItem(key,val); }catch(e){} }
/* ---------------- mode switching ---------------- */
var modeBtns = document.querySelectorAll(".mode-btn");
var panels = { period: document.getElementById("mode-period"), ovulation: document.getElementById("mode-ovulation"), pregnancy: document.getElementById("mode-pregnancy") };
modeBtns.forEach(function(btn){
btn.addEventListener("click", function(){
modeBtns.forEach(function(b){ b.classList.remove("active"); b.setAttribute("aria-selected","false"); });
btn.classList.add("active"); btn.setAttribute("aria-selected","true");
Object.keys(panels).forEach(function(k){ panels[k].classList.remove("active"); });
panels[btn.dataset.mode].classList.add("active");
saveLS("ca-mode", btn.dataset.mode);
});
});
var savedMode = loadLS("ca-mode", null);
if(savedMode && panels[savedMode]){
modeBtns.forEach(function(b){ b.classList.toggle("active", b.dataset.mode===savedMode); b.setAttribute("aria-selected", b.dataset.mode===savedMode ? "true":"false"); });
Object.keys(panels).forEach(function(k){ panels[k].classList.toggle("active", k===savedMode); });
}
/* ================================================================
PHASE + OVULATION REFERENCE DATA
================================================================ */
var PHASES = {
menstrual: {
title:"Menstrual", color:"var(--period)", soft:"var(--period-soft)",
window:"Cycle day 1 through the end of bleeding",
desc:"The uterine lining sheds because no pregnancy occurred last cycle. Estrogen and progesterone are both at their lowest point of the month.",
hormone:"Estrogen & progesterone: low", energy:"Energy: lowest",
symptoms:"Cramping, fatigue, lower back ache, mood dips",
tip:"Iron-rich food, gentle movement, and heat on the lower abdomen ease cramping better than rest alone."
},
follicular: {
title:"Follicular", color:"var(--ovulation)", soft:"var(--ovulation-soft)",
window:"Cycle day 1 through ovulation (overlaps menstrual)",
desc:"The pituitary releases FSH, prompting several ovarian follicles to mature. Estrogen climbs steadily as one dominant follicle takes the lead.",
hormone:"Estrogen: rising", energy:"Energy: climbing",
symptoms:"Clearer skin, sharper focus, rising motivation",
tip:"This is the physiologically best window for starting new training blocks or demanding projects."
},
ovulatory: {
title:"Ovulatory", color:"var(--ovulation-strong)", soft:"var(--ovulation-soft)",
window:"Roughly one day, mid-cycle",
desc:"A surge in luteinizing hormone (LH) triggers the dominant follicle to release its egg. This is the single most fertile day of the cycle.",
hormone:"LH: sharp surge", energy:"Energy & libido: peak",
symptoms:"Egg-white cervical mucus, one-sided pelvic twinge (mittelschmerz)",
tip:"Ovulation predictor kits detect the LH surge roughly 24–36 hours before the egg is released."
},
luteal: {
title:"Luteal", color:"var(--pregnancy)", soft:"var(--pregnancy-soft)",
window:"Ovulation through the day before your next period",
desc:"The ruptured follicle becomes the corpus luteum and secretes progesterone to prepare the uterine lining. If no implantation occurs, hormone levels fall and the cycle restarts.",
hormone:"Progesterone: rises then falls", energy:"Energy: gradually declining",
symptoms:"Bloating, breast tenderness, irritability, food cravings (PMS)",
tip:"Basal body temperature stays elevated ~0.3–0.5°C through this phase — a useful way to confirm ovulation already happened."
}
};
// offset relative to ovulation day (0 = ovulation)
var OVULATION_DAYS = {
"-5": {fert:"Low", fertClass:"fert-low", bbt:"Baseline (pre-shift)", mucus:"Dry to sticky", note:"Sperm can survive up to 5 days, so conception is technically possible starting here."},
"-4": {fert:"Low–moderate", fertClass:"fert-low", bbt:"Baseline", mucus:"Sticky, cloudy", note:"Fertility begins climbing as estrogen rises toward its pre-ovulation peak."},
"-3": {fert:"Moderate", fertClass:"fert-mid", bbt:"Baseline", mucus:"Creamy, increasing in volume", note:"Cervical mucus is becoming more hospitable to sperm."},
"-2": {fert:"High", fertClass:"fert-high", bbt:"Baseline", mucus:"Thin, stretchy, egg-white-like", note:"One of the two most fertile days of the entire cycle."},
"-1": {fert:"Peak", fertClass:"fert-peak", bbt:"Baseline (often the day of the LH surge)", mucus:"Clear, slippery, maximum stretch", note:"Statistically the single highest-probability day for conception."},
"0": {fert:"Peak", fertClass:"fert-peak", bbt:"Still baseline — the rise hasn't happened yet", mucus:"Egg-white, abundant", note:"The egg is released and is viable for roughly 12–24 hours. Some feel a one-sided twinge (mittelschmerz)."},
"1": {fert:"Dropping fast", fertClass:"fert-mid", bbt:"Beginning to rise ~0.3–0.5°C", mucus:"Becoming tacky again", note:"The egg's fertile window is closing; BBT starts its post-ovulation climb."},
"2": {fert:"Very low", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry or minimal", note:"Progesterone from the corpus luteum keeps temperature elevated through the luteal phase."},
"3": {fert:"Essentially none", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry", note:"If fertilization happened, the embryo is traveling toward the uterus."},
"4": {fert:"Essentially none", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry", note:"Too late in the cycle for a new ovulation; luteal phase symptoms may start appearing."},
"5": {fert:"Essentially none", fertClass:"fert-low", bbt:"Elevated, holding", mucus:"Dry", note:"Implantation, if it happens this cycle, typically occurs around days 6–10 after ovulation."}
};
var FERT_COLOR = {"fert-low":"var(--ink-soft)","fert-mid":"var(--fertile)","fert-high":"var(--fertile-strong)","fert-peak":"var(--ovulation-strong)"};
function phaseForDayInCycle(dic, periodLen, ovulationDic){
if(dic < periodLen) return "menstrual";
if(dic < ovulationDic) return "follicular";
if(dic === ovulationDic) return "ovulatory";
return "luteal";
}
function isFertile(dic, ovulationDic){
return dic >= ovulationDic - 5 && dic <= ovulationDic;
}
/* ================================================================
PREGNANCY WEEK DATA (1–40)
================================================================ */
var WEEKS = [
{c:"a poppy seed (not yet fertilized)", m:"n/a", dev:"Pregnancy is dated from the first day of this period, before conception happens — your body is shedding last cycle's lining and preparing a fresh egg.", body:"This week looks and feels like an ordinary period.", tip:"If you're trying to conceive, this is a good week to start a prenatal vitamin with folic acid."},
{c:"an egg cell", m:"~0.1 mm", dev:"Rising estrogen prompts an egg to mature; ovulation typically occurs near the end of this week, roughly two weeks before a missed period.", body:"Cervical mucus becomes clear and stretchy around ovulation — a natural fertility sign.", tip:"This is the fertile window if you're trying to conceive — see the Ovulation tab for day-by-day detail."},
{c:"a grain of sand", m:"~0.1–0.2 mm", dev:"If sperm meets egg this week, fertilization occurs in the fallopian tube and the resulting cell begins dividing as it travels toward the uterus.", body:"No symptoms are detectable yet — even a sensitive test won't turn positive for another week or two.", tip:"Implantation, if it happens, usually occurs 6–10 days after ovulation."},
{c:"a poppy seed", m:"~0.1 mm", dev:"The fertilized egg implants in the uterine lining and begins producing hCG, the hormone home pregnancy tests detect.", body:"Most people notice no symptoms yet; a sensitive test may already turn positive near the end of this week.", tip:"A missed period is usually the first sign — testing a few days after that gives the most reliable result."},
{c:"a sesame seed", m:"~2 mm", dev:"The neural tube — the earliest structure of the brain and spinal cord — begins to form, along with the first blood vessels.", body:"A missed period is usually the first clear sign; fatigue and tender breasts may begin.", tip:"Avoid alcohol and confirm any medications with a clinician — this window is critical for early development."},
{c:"a lentil", m:"~4 mm", dev:"A primitive heart tube starts beating, and the beginnings of the face, arms, and legs appear as small buds.", body:"Morning sickness and smell sensitivity often begin here, though timing varies widely.", tip:"Small, frequent, bland meals tend to sit better than three large ones if nausea has started."},
{c:"a blueberry", m:"~1.3 cm", dev:"The brain is dividing into distinct sections, and the arm and leg buds are elongating into recognizable limbs.", body:"Bloating and mild cramping are common as the uterus makes room to grow.", tip:"This is when most people schedule their first prenatal appointment — dating scans are most accurate now."},
{c:"a raspberry", m:"~1.6 cm", dev:"Fingers and toes are forming, still webbed; the heart now has four distinct chambers.", body:"Fatigue often peaks around this point as progesterone rises sharply.", tip:"Rest when you can — first-trimester exhaustion is real and temporary, not a sign anything is wrong."},
{c:"a grape", m:"~2.3 cm · 4 g", dev:"The embryo is officially called a fetus starting around now; essential organs are all present in early form and the tail has disappeared.", body:"Nausea, food aversions, and a heightened sense of smell are often at their strongest.", tip:"Ginger tea, vitamin B6, and staying hydrated are commonly recommended first-line options for nausea."},
{c:"a kumquat", m:"~3 cm · 7 g", dev:"Vital organs — kidneys, liver, brain — are functioning in a basic form, and tiny fingernail beds are forming.", body:"A visible baby bump is still unlikely, though clothes may feel tighter.", tip:"Ask your provider about first-trimester screening options available in this window."},
{c:"a fig", m:"~4.1 cm · 10 g", dev:"The fetus can now bend its arms and legs, and tooth buds are forming beneath the gums.", body:"Round ligament twinges may start as the uterus stretches.", tip:"Gentle stretching and changing positions slowly can ease early ligament discomfort."},
{c:"a lime", m:"~5.4 cm · 14 g", dev:"Reflexes are developing — fingers can curl, and toes can wiggle, though it can't be felt yet.", body:"The end of the first trimester is near, and miscarriage risk drops meaningfully from here.", tip:"Many people choose to share their pregnancy news around now, though the choice is entirely personal."},
{c:"a plum", m:"~6.7 cm · 23 g", dev:"Vocal cords are forming, and unique fingerprints are being etched onto tiny fingertips.", body:"Some early nausea may start easing as the placenta takes over hormone production.", tip:"The nuchal translucency scan, if chosen, is typically done between now and week 13."},
{c:"a passion fruit", m:"~10 cm · 45 g", dev:"Baby can open and close fists and may even suck a thumb; genitals are differentiating, though not yet visible on ultrasound.", body:"For many, first-trimester nausea and fatigue begin to lift.", tip:"Second-trimester energy often supports resuming or starting light-to-moderate exercise — check in with your provider first."},
{c:"a peach", m:"~11.6 cm · 58 g", dev:"Vocal cords are complete and the intestines, which developed in the umbilical cord, move into the abdomen.", body:"Welcome to the second trimester — often called the most comfortable stretch of pregnancy.", tip:"An anatomy scan is usually scheduled in the coming weeks; ask your clinic when it's booked."},
{c:"a lemon", m:"~13 cm · 70 g", dev:"Fine, downy hair called lanugo begins covering the body, and the kidneys are producing urine into the amniotic fluid.", body:"A small bump may finally become visible; appetite often improves noticeably.", tip:"Iron needs rise sharply now — leafy greens, legumes, and lean meat help meet increased demand."},
{c:"an apple", m:"~14.2 cm · 95 g", dev:"The skeleton continues hardening and baby can sense light through closed eyelids.", body:"Skin changes like a faint linea nigra or darkened areolas may appear as pigment increases.", tip:"Daily SPF helps limit pregnancy-related skin pigmentation (melasma) from sun exposure."},
{c:"an avocado", m:"~16 cm · 135 g", dev:"The placenta is now fully formed and functioning as baby's life-support system.", body:"First flutters of movement ('quickening') may be felt any time from now through week 20.", tip:"Movement timing varies a lot — first pregnancies and anterior placentas often mean feeling it later."},
{c:"a pomegranate", m:"~17.7 cm · 160 g", dev:"The skeleton is converting from cartilage to true bone, and fat stores are just beginning to accumulate.", body:"The uterus is now roughly at the level of the belly button.", tip:"A pregnancy support pillow can meaningfully improve sleep as side-sleeping becomes more comfortable."},
{c:"a bell pepper", m:"~19 cm · 190 g", dev:"Ears have reached their final position and baby may begin startling at loud external sounds.", body:"Quickening is commonly felt by now — often described as bubbles or light taps.", tip:"Try narrating your day out loud — hearing is developing and familiar voices become recognizable over time."},
{c:"a mango", m:"~20.3 cm · 240 g", dev:"A waxy coating called vernix caseosa begins protecting the skin, and taste buds are forming.", body:"Backaches can start as posture shifts to balance the growing bump.", tip:"A supportive, flatter shoe and a pillow between the knees at night both help low back strain."},
{c:"a banana", m:"~25.6 cm · 300 g", dev:"The detailed anatomy ultrasound is often done around now if it hasn't happened already, and sex can typically be identified on it.", body:"Movements are stronger and more frequent; the uterus is now level with the belly button.", tip:"If you want to know the sex and haven't had the anatomy scan yet, ask your clinic to schedule it soon — it's usually done weeks 18–22."},
{c:"a carrot", m:"~27 cm · 360 g", dev:"Baby is swallowing small amounts of amniotic fluid, giving the digestive system practice.", body:"Stretch marks may start appearing on the belly, hips, or chest as skin stretches.", tip:"Moisturizing won't prevent stretch marks, but it can ease the itchiness that comes with stretching skin."},
{c:"a papaya", m:"~28.9 cm · 430 g", dev:"Eyebrows and eyelids are fully formed, and the sense of touch is developing rapidly.", body:"Braxton Hicks — brief, painless practice contractions — may be felt occasionally from here on.", tip:"Braxton Hicks usually ease with a change of position or a glass of water; true labor contractions don't."},
{c:"an ear of corn", m:"~32.2 cm · 600 g", dev:"The lungs begin producing surfactant, a substance essential for breathing air after birth — a key viability milestone.", body:"The linea nigra (a dark vertical line on the belly) may become more visible.", tip:"This week is often cited as the threshold of viability with intensive neonatal care, should birth happen very early."},
{c:"a cauliflower head", m:"~33.7 cm · 660 g", dev:"Baby can now respond to your voice, and hand grip strength is developing.", body:"The glucose screening test for gestational diabetes is typically scheduled around now.", tip:"If asked to fast beforehand, follow your clinic's instructions closely for an accurate glucose result."},
{c:"a head of lettuce", m:"~35.6 cm · 760 g", dev:"Eyes begin to open after being fused shut since early development, and hair may be visibly growing.", body:"Round ligament pain and rib discomfort can increase as space gets tighter.", tip:"A maternity support band can ease rib and ligament pressure during long periods of standing or walking."},
{c:"a bunch of scallions", m:"~36.6 cm · 875 g", dev:"Brain tissue is developing rapidly, and baby is developing regular hiccups you may be able to feel.", body:"Third trimester begins soon — appointments typically become more frequent from here.", tip:"Hiccup-like twitches are completely normal and are the diaphragm practicing its rhythm."},
{c:"an eggplant", m:"~37.6 cm · 1.1 kg", dev:"Eyes can blink now, and baby may cycle through active REM sleep.", body:"Welcome to the third trimester — the home stretch begins.", tip:"This is a common time to start planning a hospital bag and reviewing birth preferences."},
{c:"a butternut squash", m:"~38.6 cm · 1.2 kg", dev:"Bones are fully formed but still soft and flexible, ready to move through the birth canal.", body:"Frequent urination often returns as the head engages lower in the pelvis.", tip:"Kick counts become a useful daily check-in — note baby's typical pattern of movement."},
{c:"a large cabbage", m:"~39.9 cm · 1.3 kg", dev:"The brain is developing at its fastest rate yet, adding folds and surface area.", body:"Sleep can become harder to find as the bump limits comfortable positions.", tip:"A full-body pregnancy pillow supports the belly, back, and knees simultaneously."},
{c:"a coconut", m:"~41.1 cm · 1.5 kg", dev:"All five senses are now functioning, and baby is gaining roughly half a pound a week.", body:"Colostrum, the first form of breast milk, may begin to leak slightly.", tip:"A few nursing pads in your bag can help if colostrum leaking becomes noticeable."},
{c:"a jicama", m:"~42.4 cm · 1.7 kg", dev:"Baby is practicing breathing movements against a closed airway, strengthening the lungs.", body:"Swelling and mild carpal tunnel tingling in the hands can appear from fluid retention.", tip:"Report sudden or severe swelling to your provider promptly — it can occasionally signal preeclampsia."},
{c:"a pineapple", m:"~43.7 cm · 1.9 kg", dev:"Bones are hardening overall, though the skull stays deliberately soft and flexible for delivery.", body:"Pelvic pressure increases as baby continues descending.", tip:"Prenatal massage or a warm bath can ease the deep pelvic ache many feel this week."},
{c:"a cantaloupe", m:"~45 cm · 2.1 kg", dev:"The central nervous system is maturing quickly, and baby's grip is now quite strong.", body:"Braxton Hicks contractions often become more noticeable and frequent.", tip:"Time any contractions that feel different — regular, intensifying, closer together warrants a call to your provider."},
{c:"a honeydew melon", m:"~46.2 cm · 2.4 kg", dev:"The kidneys are fully developed, and the liver is processing waste products on its own.", body:"You may feel baby 'drop' lower as it settles into position for birth.", tip:"Lightening (the baby dropping) can ease heartburn but often increases bathroom trips."},
{c:"a head of romaine", m:"~47.4 cm · 2.6 kg", dev:"Most physical development is complete; the focus now is steady weight gain.", body:"You've just reached 'early term' — babies born from here on tend to do very well.", tip:"Pack your hospital bag if you haven't yet — early-term babies can arrive with little warning."},
{c:"a leek", m:"~49.8 cm · 3.1 kg", dev:"Baby continues laying down fat for temperature regulation after birth, and the brain is still rapidly developing.", body:"Nesting instinct and a burst of energy are common right before labor.", tip:"Balance nesting energy with rest — labor's timing is unpredictable."},
{c:"a mini watermelon", m:"~50.7 cm · 3.3 kg", dev:"Full term. The lungs are completing final maturation in preparation for that first breath.", body:"Increased pelvic pressure and more frequent, intense Braxton Hicks are common.", tip:"Watch for your labor signs: regular contractions, water breaking, or a bloody show."},
{c:"a small pumpkin", m:"~51.2 cm · 3.5 kg", dev:"Baby is fully developed and simply continuing to grow, ready to meet you.", body:"If labor hasn't started, your provider will discuss monitoring or induction options.", tip:"Most babies arrive within two weeks of their due date in either direction — both are entirely normal."}
];
/* ================================================================
SVG helpers
================================================================ */
function polarToXY(cx,cy,r,angleDeg){
var rad = (angleDeg-90) * Math.PI/180;
return [cx + r*Math.cos(rad), cy + r*Math.sin(rad)];
}
function arcPath(cx,cy,r,startDeg,endDeg){
if(endDeg <= startDeg) endDeg = startDeg + 0.01;
var s = polarToXY(cx,cy,r,startDeg), e = polarToXY(cx,cy,r,endDeg);
var large = (endDeg-startDeg) > 180 ? 1 : 0;
return "M "+s[0].toFixed(2)+" "+s[1].toFixed(2)+" A "+r+" "+r+" 0 "+large+" 1 "+e[0].toFixed(2)+" "+e[1].toFixed(2);
}
/* ================================================================
SHARED STATE: period start / cycle length / period length
================================================================ */
var exampleStart = addDays(today, -10);
var startInput = document.getElementById("p-start");
var cycleLenInput = document.getElementById("p-cyclelen");
var periodLenInput = document.getElementById("p-periodlen");
var savedStart = loadLS("ca-start", null);
var savedCycleLen = loadLS("ca-cyclelen", null);
var savedPeriodLen = loadLS("ca-periodlen", null);
var usingExample = !savedStart;
startInput.value = savedStart || toInputVal(exampleStart);
cycleLenInput.value = savedCycleLen || 28;
periodLenInput.value = savedPeriodLen || 5;
function getCycleState(){
return {
start: fromInput(startInput.value) || exampleStart,
cycleLen: Math.max(21, Math.min(35, parseInt(cycleLenInput.value,10) || 28)),
periodLen: Math.max(2, Math.min(10, parseInt(periodLenInput.value,10) || 5))
};
}
var pCalMonth = new Date(today.getFullYear(), today.getMonth(), 1);
var oCalMonth = new Date(today.getFullYear(), today.getMonth(), 1);
var pSelectedDate = new Date(today);
var oSelectedDate = new Date(today);
[startInput,cycleLenInput,periodLenInput].forEach(function(inp){
inp.addEventListener("input", function(){
saveLS("ca-start", startInput.value);
saveLS("ca-cyclelen", cycleLenInput.value);
saveLS("ca-periodlen", periodLenInput.value);
usingExample = false;
document.getElementById("p-example-note").style.display = "none";
document.getElementById("pr-example-note").style.display = "none";
renderAll();
});
});
if(!usingExample) document.getElementById("p-example-note").style.display = "none";
/* ================================================================
CALENDAR RENDERING (shared builder)
================================================================ */
function buildCalendar(gridEl, weekdayHeaderIgnored, monthDate, dayClassifier, onSelect, selectedDate){
gridEl.innerHTML = "";
var year = monthDate.getFullYear(), month = monthDate.getMonth();
var firstDow = new Date(year,month,1).getDay();
var daysInMonth = new Date(year,month+1,0).getDate();
var totalCells = Math.ceil((firstDow+daysInMonth)/7)*7;
for(var i=0;i<totalCells;i++){
var dayNum = i - firstDow + 1;
var cell = document.createElement("button");
cell.className = "day-cell";
if(dayNum < 1 || dayNum > daysInMonth){
cell.classList.add("pad");
gridEl.appendChild(cell);
continue;
}
var d = new Date(year,month,dayNum);
var info = dayClassifier(d);
cell.innerHTML = "<span>"+dayNum+"</span>";
if(info.period) cell.classList.add("is-period");
if(info.fertile) cell.classList.add("is-fertile");
if(info.ovulation) cell.classList.add("is-ovulation");
if(sameDay(d,today)) cell.classList.add("today");
if(selectedDate && sameDay(d,selectedDate)) cell.classList.add("selected");
cell.setAttribute("aria-label", d.toDateString());
cell.addEventListener("click", function(dd){ return function(){ onSelect(dd); }; }(d));
gridEl.appendChild(cell);
}
}
function classifyForCycle(d, state){
var dic = mod(daysBetween(state.start, d), state.cycleLen);
var ovDic = mod(state.cycleLen - 14, state.cycleLen);
return {
period: dic < state.periodLen,
fertile: isFertile(dic, ovDic),
ovulation: dic === ovDic,
dic: dic, ovDic: ovDic
};
}
/* ---------------- PERIOD tab render ---------------- */
function renderPeriodCalendar(){
var state = getCycleState();
document.getElementById("p-cal-title").textContent = MONTH_NAMES[pCalMonth.getMonth()] + " " + pCalMonth.getFullYear();
buildCalendar(document.getElementById("p-daygrid"), null, pCalMonth,
function(d){ return classifyForCycle(d, state); },
function(d){ pSelectedDate = d; renderPeriodDetail(); renderPeriodCalendar(); },
pSelectedDate
);
}
function renderPeriodDetail(){
var state = getCycleState();
var info = classifyForCycle(pSelectedDate, state);
var phaseKey = phaseForDayInCycle(info.dic, state.periodLen, info.ovDic);
var phase = PHASES[phaseKey];
var el = document.getElementById("p-detail");
el.innerHTML =
'<span class="d-date">'+pSelectedDate.toDateString()+'</span>'+
'<span class="pill" style="background:'+phase.soft+';color:'+phase.color+'">'+phase.title+' phase'+(info.fertile?' · fertile window':'')+'</span>'+
'<div class="d-phase">Cycle day '+(info.dic+1)+'</div>'+
'<p class="d-desc">'+phase.desc+'</p>'+
'<div class="d-grid">'+
'<div class="d-mini"><div class="k">Hormones</div><div class="v">'+phase.hormone+'</div></div>'+
'<div class="d-mini"><div class="k">Typical symptoms</div><div class="v" style="font-weight:500;font-size:0.82rem;">'+phase.symptoms+'</div></div>'+
'</div>'+
'<p class="d-desc"><strong style="color:var(--ink)">Care note — </strong>'+phase.tip+'</p>';
}
function renderPeriodStats(){
var state = getCycleState();
var dic = mod(daysBetween(state.start, today), state.cycleLen);
var ovDic = mod(state.cycleLen - 14, state.cycleLen);
var daysToNextPeriod = mod(state.cycleLen - dic, state.cycleLen);
if(daysToNextPeriod === 0 && dic !== 0) daysToNextPeriod = state.cycleLen;
var daysToOvulation = mod(ovDic - dic, state.cycleLen);
var phaseKey = phaseForDayInCycle(dic, state.periodLen, ovDic);
document.getElementById("period-stats").innerHTML =
statTile(dic+1, "Cycle day today") +
statTile(PHASES[phaseKey].title, "Current phase") +
statTile(dic===0 ? "Today" : (daysToNextPeriod+"d"), "Until next period") +
statTile(dic===ovDic ? "Today" : (daysToOvulation+"d"), "Until ovulation");
// hero ring
var cx=100, cy=100, r=88;
var perStart=0, perEnd = state.periodLen/state.cycleLen*360;
var follEnd = ovDic/state.cycleLen*360;
var fertStart = Math.max(0,(ovDic-5))/state.cycleLen*360;
var lutStart = (ovDic+1)/state.cycleLen*360;
document.getElementById("phase-arc-menstrual").setAttribute("d", arcPath(cx,cy,r,perStart,perEnd));
document.getElementById("phase-arc-follicular").setAttribute("d", arcPath(cx,cy,r,perEnd,fertStart));
document.getElementById("phase-arc-fertile").setAttribute("d", arcPath(cx,cy,r,fertStart,follEnd+ (360/state.cycleLen)));
document.getElementById("phase-arc-luteal").setAttribute("d", arcPath(cx,cy,r,lutStart,360));
var todayAngle = dic/state.cycleLen*360;
var tp = polarToXY(cx,cy,r,todayAngle);
document.getElementById("today-marker").setAttribute("cx", tp[0]);
document.getElementById("today-marker").setAttribute("cy", tp[1]);
document.getElementById("cycle-day-big").textContent = dic+1;
}
function statTile(num,label){
return '<div class="stat-tile"><div class="num">'+num+'</div><div class="lbl">'+label+'</div></div>';
}
document.getElementById("p-prev").addEventListener("click", function(){ pCalMonth.setMonth(pCalMonth.getMonth()-1); renderPeriodCalendar(); });
document.getElementById("p-next").addEventListener("click", function(){ pCalMonth.setMonth(pCalMonth.getMonth()+1); renderPeriodCalendar(); });
function renderPhaseRefGrid(){
var order = ["menstrual","follicular","ovulatory","luteal"];
document.getElementById("phase-ref-grid").innerHTML = order.map(function(key,i){
var p = PHASES[key];
return '<div class="ref-card"><span class="r-num">0'+(i+1)+'</span><h4 style="color:'+p.color+'">'+p.title+'</h4>'+
'<p>'+p.desc+'</p>'+
'<div class="tag-row"><span class="tagchip">'+p.window+'</span></div></div>';
}).join("");
}
/* ---------------- OVULATION tab render ---------------- */
var ovSelectedOffset = 0;
function renderOvTimeline(){
var wrap = document.getElementById("ov-timeline");
wrap.innerHTML = "";
for(var off=-5; off<=5; off++){
var d = OVULATION_DAYS[String(off)];
var btn = document.createElement("button");
btn.className = "tl-btn" + (off===ovSelectedOffset ? " active":"");
btn.innerHTML = '<div class="tl-day">'+(off===0?"OVUL.":(off>0?"+":"")+off)+'</div>'+
'<div class="tl-fert" style="background:'+FERT_COLOR[d.fertClass]+'"></div>';
btn.addEventListener("click", function(o){ return function(){ ovSelectedOffset=o; renderOvTimeline(); renderOvDetailFromOffset(); }; }(off));
wrap.appendChild(btn);
}
}
function renderOvDetailFromOffset(){
var d = OVULATION_DAYS[String(ovSelectedOffset)];
var el = document.getElementById("o-detail");
var label = ovSelectedOffset===0 ? "Ovulation day" : (ovSelectedOffset>0 ? ovSelectedOffset+" day"+(ovSelectedOffset>1?"s":"")+" after ovulation" : Math.abs(ovSelectedOffset)+" day"+(ovSelectedOffset<-1?"s":"")+" before ovulation");
el.innerHTML =
'<span class="d-date">'+label+'</span>'+
'<span class="pill" style="background:var(--ovulation-soft);color:'+FERT_COLOR[d.fertClass]+'">Fertility: '+d.fert+'</span>'+
'<div class="d-phase">'+(ovSelectedOffset===0?"Egg release":(ovSelectedOffset<0?"Building fertility":"Fertility fading"))+'</div>'+
'<div class="d-grid">'+
'<div class="d-mini"><div class="k">Basal body temp</div><div class="v" style="font-size:0.82rem;">'+d.bbt+'</div></div>'+
'<div class="d-mini"><div class="k">Cervical mucus</div><div class="v" style="font-size:0.82rem;">'+d.mucus+'</div></div>'+
'</div>'+
'<p class="d-desc">'+d.note+'</p>';
}
function renderOvulationCalendar(){
var state = getCycleState();
document.getElementById("o-cal-title").textContent = MONTH_NAMES[oCalMonth.getMonth()] + " " + oCalMonth.getFullYear();
buildCalendar(document.getElementById("o-daygrid"), null, oCalMonth,
function(d){ return classifyForCycle(d, state); },
function(d){
oSelectedDate = d;
var info = classifyForCycle(d, state);
var offset = info.dic - info.ovDic;
if(offset < -5) offset = -5; if(offset > 5) offset = 5;
ovSelectedOffset = offset;
renderOvTimeline(); renderOvDetailFromOffset(); renderOvulationCalendar();
},
oSelectedDate
);
}
function renderOvulationStats(){
var state = getCycleState();
var dic = mod(daysBetween(state.start, today), state.cycleLen);
var ovDic = mod(state.cycleLen - 14, state.cycleLen);
var daysToOvulation = mod(ovDic - dic, state.cycleLen);
var fertileStartDic = mod(ovDic-5, state.cycleLen);
var inFertile = isFertile(dic, ovDic);
var daysToFertile = inFertile ? 0 : mod(fertileStartDic - dic, state.cycleLen);
document.getElementById("ovulation-stats").innerHTML =
statTile(inFertile ? "Yes" : "No", "In fertile window") +
statTile(dic===ovDic ? "Today" : daysToOvulation+"d", "Until ovulation") +
statTile(inFertile ? "Now" : daysToFertile+"d", "Fertile window") +
statTile("6 days", "Window length");
}
document.getElementById("o-prev").addEventListener("click", function(){ oCalMonth.setMonth(oCalMonth.getMonth()-1); renderOvulationCalendar(); });
document.getElementById("o-next").addEventListener("click", function(){ oCalMonth.setMonth(oCalMonth.getMonth()+1); renderOvulationCalendar(); });
/* ================================================================
PREGNANCY tab
================================================================ */
var lmpInput = document.getElementById("pr-lmp");
var exampleLMP = addDays(today, -20*7 - 3);
var savedLMP = loadLS("ca-lmp", null);
lmpInput.value = savedLMP || toInputVal(exampleLMP);
if(savedLMP) document.getElementById("pr-example-note").style.display = "none";
var slider = document.getElementById("week-slider");
var prCalMonth = new Date(today.getFullYear(), today.getMonth(), 1);
lmpInput.addEventListener("input", function(){
saveLS("ca-lmp", lmpInput.value);
document.getElementById("pr-example-note").style.display = "none";
document.getElementById("p-example-note").style.display = "none";
syncSliderToLMP();
renderPregnancy();
});
function getLMP(){ return fromInput(lmpInput.value) || exampleLMP; }
function currentGestWeek(){
var lmp = getLMP();
var w = Math.floor(daysBetween(lmp,today)/7) + 1;
return Math.max(1, Math.min(40, w));
}
function syncSliderToLMP(){ slider.value = currentGestWeek(); }
syncSliderToLMP();
function renderPregnancyStats(){
var lmp = getLMP();
var due = addDays(lmp, 280);
var week = currentGestWeek();
var daysLeft = Math.max(0, daysBetween(today, due));
document.getElementById("pregnancy-stats").innerHTML =
statTile(week, "Weeks along") +
statTile(Math.floor((week-1)/13)+1 <= 3 ? ["First","Second","Third"][Math.min(2,Math.floor((week-1)/13))] : "Third", "Trimester") +
statTile(daysLeft, "Days to due date") +
statTile(due.toLocaleDateString(undefined,{month:"short",day:"numeric"}), "Estimated due date");
var pct = (week-1)/39;
var pathLen = 230;
var offset = pathLen - pct*pathLen;
var path = document.getElementById("pregnancy-progress-path");
path.setAttribute("stroke-dashoffset", offset.toFixed(1));
try{
var totalLen = path.getTotalLength ? path.getTotalLength() : pathLen;
var pt = path.getPointAtLength ? path.getPointAtLength(pct*totalLen) : null;
if(pt) { document.getElementById("pregnancy-progress-dot").setAttribute("cx",pt.x); document.getElementById("pregnancy-progress-dot").setAttribute("cy",pt.y); }
}catch(e){}
}
function renderWeekPanel(week){
var w = WEEKS[week-1];
document.getElementById("wk-badge").textContent = "WEEK " + week;
document.getElementById("wk-compare").textContent = "size of " + w.c;
document.getElementById("wk-metric").textContent = w.m === "n/a" ? "not yet fertilized" : "≈ " + w.m;
document.getElementById("wk-dev").textContent = w.dev;
document.getElementById("wk-body").textContent = w.body;
document.getElementById("wk-tip").textContent = w.tip;
var tri = week<=13?1:(week<=27?2:3);
var triColor = "var(--pregnancy)";
document.getElementById("wk-blob").innerHTML =
'<svg width="96" height="96" viewBox="0 0 96 96"><circle cx="48" cy="48" r="'+(14+week*0.9)+'" fill="'+ (tri===1?"var(--pregnancy-soft)":tri===2?"var(--pregnancy)":"var(--pregnancy-strong)") +'" opacity="0.85"/></svg>';
document.querySelectorAll(".film-item").forEach(function(f){ f.classList.toggle("active", +f.dataset.week===week); });
var active = document.querySelector('.film-item[data-week="'+week+'"]');
if(active) active.scrollIntoView({inline:"center", block:"nearest", behavior:"smooth"});
}
slider.addEventListener("input", function(){ renderWeekPanel(+slider.value); });
function buildFilmstrip(){
var wrap = document.getElementById("week-filmstrip");
wrap.innerHTML = "";
for(var w=1; w<=40; w++){
var item = document.createElement("button");
item.className = "film-item";
item.dataset.week = w;
item.innerHTML = '<div class="fw">WK</div><div class="fn">'+w+'</div>';
item.addEventListener("click", function(ww){ return function(){ slider.value=ww; renderWeekPanel(ww); }; }(w));
wrap.appendChild(item);
}
}
function renderPregnancyCalendar(){
var lmp = getLMP();
document.getElementById("pr-cal-title").textContent = MONTH_NAMES[prCalMonth.getMonth()] + " " + prCalMonth.getFullYear();
var grid = document.getElementById("pr-daygrid");
grid.innerHTML = "";
var year = prCalMonth.getFullYear(), month = prCalMonth.getMonth();
var firstDow = new Date(year,month,1).getDay();
var daysInMonth = new Date(year,month+1,0).getDate();
var totalCells = Math.ceil((firstDow+daysInMonth)/7)*7;
for(var i=0;i<totalCells;i++){
var dayNum = i - firstDow + 1;
var cell = document.createElement("button");
cell.className = "day-cell";
if(dayNum<1 || dayNum>daysInMonth){ cell.classList.add("pad"); grid.appendChild(cell); continue; }
var d = new Date(year,month,dayNum);
var wk = Math.floor(daysBetween(lmp,d)/7)+1;
var inRange = wk>=1 && wk<=42;
cell.innerHTML = "<span>"+dayNum+"</span>" + (inRange ? '<span class="dot-row" style="position:static;margin-top:2px;font-size:0.55rem;color:var(--pregnancy-strong)">W'+wk+'</span>' : "");
if(inRange && wk<=40) cell.classList.add("is-fertile");
if(sameDay(d,today)) cell.classList.add("today");
cell.addEventListener("click", function(ww){ return function(){ if(ww>=1&&ww<=40){ slider.value=ww; renderWeekPanel(ww); } }; }(wk));
grid.appendChild(cell);
}
}
document.getElementById("pr-prev").addEventListener("click", function(){ prCalMonth.setMonth(prCalMonth.getMonth()-1); renderPregnancyCalendar(); });
document.getElementById("pr-next").addEventListener("click", function(){ prCalMonth.setMonth(prCalMonth.getMonth()+1); renderPregnancyCalendar(); });
function renderPregnancy(){
renderPregnancyStats();
renderWeekPanel(currentGestWeek());
renderPregnancyCalendar();
}
/* ================================================================
INIT
================================================================ */
function renderAll(){
renderPeriodStats();
renderPeriodCalendar();
renderPeriodDetail();
renderOvulationStats();
renderOvTimeline();
renderOvDetailFromOffset();
renderOvulationCalendar();
renderPregnancy();
}
renderPhaseRefGrid();
buildFilmstrip();
slider.value = currentGestWeek();
renderAll();
})();
</script>
-12
View File
@@ -1,12 +0,0 @@
# Copy to .env style settings on your host. Never commit real values.
ADMIN_EMAIL=rana.krunal7558@gmail.com
ADMIN_PASSWORD=pick-a-long-password-here
# Where new tickets are emailed (this is already the default)
TICKET_TO=rana.krunal7558@gmail.com
# Gmail sending: use an "App Password", not your normal password
SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
SMTP_USER=rana.krunal7558@gmail.com
SMTP_PASS=your-16-letter-app-password
# Set to 1 when hosted behind a proxy (most hosts)
TRUST_PROXY=1
-4
View File
@@ -1,4 +0,0 @@
node_modules
dist
server/data
.env
-25
View File
@@ -1,25 +0,0 @@
# Deploy checklist (Hostinger)
## A. Before you start
- [ ] Plan is Business Web Hosting or a Cloud plan (Node.js Web App supported)
- [ ] Gmail app password created (myaccount.google.com > Security > 2-Step Verification > App passwords)
## B. In hPanel: Websites > Add website > Node.js Web App > Import Git repository
- [ ] Repo: keithrana/cycle-atlas
- [ ] Branch: claude/sleepy-goodall-rykli1 (NOT main)
- [ ] Root/app directory: it-support (if no such box, ask Claude to split into its own repo)
- [ ] Node version: 22.x or 24.x
- [ ] Build command: npm run build
- [ ] Start command: npm start (entry file, if asked: server/index.js)
## C. Environment variables (type them only into Hostinger, never into chat or Git)
ADMIN_EMAIL, ADMIN_PASSWORD (10+ chars), SMTP_HOST=smtp.gmail.com, SMTP_PORT=465,
SMTP_USER, SMTP_PASS (Gmail app password), TRUST_PROXY=1, DATA_DIR=/home/<your-username>/helpdesk-data
## D. Deploy, then test in order
1. [ ] Page loads over https:// and the video plays
2. [ ] Search "wifi" shows answers; send a test ticket
3. [ ] Email arrives at rana.krunal7558@gmail.com (check Spam)
4. [ ] /#/staff login works and the ticket is listed
5. [ ] Add a test FAQ, redeploy, confirm it is still there (proves data is kept)
6. [ ] Log out; /#/staff asks for login again
-18
View File
@@ -1,18 +0,0 @@
# IT Support Site: PRD (plan)
Restaurant analogy: the FAQ database is the **kitchen's recipe book**. The website is the **dining room**.
## Core features
1. Cinematic hero: looping video, glass buttons (exactly as specified)
2. Search bar in the hero: type a problem, get matching answers
3. Category chips: browse the 11 topics (Access, Network, Hardware...)
4. FAQ answer cards: question, answer, optional "official guide" link
5. Footer social icons
## Phased roadmap
- **Phase 1 – Food stand (TODAY):** hero + search + categories + 87 FAQs from the database, baked in as a JSON file. No server.
- **Phase 2 – Small restaurant (DONE, browser-only storage):** "Was this helpful?" votes, "Contact IT" ticket form, shareable links per question.
- **Phase 3 – Full restaurant (DONE):** small back-of-house server + real database, staff login, admin page to edit FAQs, ticket tracking.
## Test ladder
1. Page loads, no console errors 2. Buttons/search work 3. Real data/links work 4. Security (no raw HTML injection, safe links)
-11
View File
@@ -1,11 +0,0 @@
# HelpDesk IT Support
Run locally (needs Node 22+):
npm install
npm run build
ADMIN_EMAIL=you@example.com ADMIN_PASSWORD='a-long-password' npm start
Open http://localhost:3001 (staff login: http://localhost:3001/#/staff)
For development with live reload: run `npm run server` and `npm run dev` in two terminals.
Settings are listed in `.env.example`. Data lives in `server/data/helpdesk.db`: back it up, and keep it on a persistent disk when hosting.
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HelpDesk | IT Support</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
-3528
View File
File diff suppressed because it is too large. Load diff
-30
View File
@@ -1,30 +0,0 @@
{
"name": "it-support",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"server": "node server/index.js",
"start": "NODE_ENV=production node server/index.js"
},
"dependencies": {
"express": "^4.22.3",
"lucide-react": "^0.460.0",
"nodemailer": "^10.0.13",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.15",
"typescript": "~5.6.2",
"vite": "^5.4.11"
}
}
-1
View File
@@ -1 +0,0 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
-48
View File
@@ -1,48 +0,0 @@
import { scryptSync, randomBytes, timingSafeEqual, createHash } from 'node:crypto'
import { db } from './db.js'
export const SESSION_DAYS = 7
export const hashPassword = (pw) => {
const salt = randomBytes(16)
return `${salt.toString('hex')}:${scryptSync(pw, salt, 64).toString('hex')}`
}
export const verifyPassword = (pw, stored) => {
const [salt, hash] = stored.split(':')
const a = Buffer.from(hash, 'hex')
const b = scryptSync(pw, Buffer.from(salt, 'hex'), 64)
return a.length === b.length && timingSafeEqual(a, b)
}
const sha = (t) => createHash('sha256').update(t).digest('hex')
export function createSession(staffId) {
const token = randomBytes(32).toString('hex')
db.prepare('INSERT INTO sessions VALUES (?,?,?)').run(sha(token), staffId, Date.now() + SESSION_DAYS * 864e5)
return token
}
export const destroySession = (token) => db.prepare('DELETE FROM sessions WHERE token_hash=?').run(sha(token))
function cookieToken(req) {
const m = /(?:^|;\s*)session=([a-f0-9]{64})/.exec(req.headers.cookie || '')
return m ? m[1] : null
}
export { cookieToken }
export function requireStaff(req, res, next) {
const token = cookieToken(req)
const row = token && db.prepare('SELECT s.id, s.email, s.name, x.expires FROM sessions x JOIN staff s ON s.id=x.staff_id WHERE x.token_hash=?').get(sha(token))
if (!row || row.expires < Date.now()) return res.status(401).json({ error: 'Please log in.' })
req.staff = row
next()
}
// Tiny in-memory rate limiter: `max` hits per `windowMs` per IP+bucket.
const hits = new Map()
export const rateLimit = (bucket, max, windowMs) => (req, res, next) => {
const key = `${bucket}:${req.ip}`
const now = Date.now()
const recent = (hits.get(key) || []).filter((t) => now - t < windowMs)
if (recent.length >= max) return res.status(429).json({ error: 'Too many tries. Please wait a bit.' })
recent.push(now)
hits.set(key, recent)
next()
}
-24
View File
@@ -1,24 +0,0 @@
import { DatabaseSync } from 'node:sqlite'
import { readFileSync, mkdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const dataDir = process.env.DATA_DIR || join(here, 'data')
mkdirSync(dataDir, { recursive: true })
export const db = new DatabaseSync(join(dataDir, 'helpdesk.db'))
db.exec(`
CREATE TABLE IF NOT EXISTS faqs (id INTEGER PRIMARY KEY AUTOINCREMENT, category TEXT NOT NULL, question TEXT NOT NULL, answer TEXT NOT NULL, link TEXT NOT NULL DEFAULT '', link_label TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS tickets (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL, topic TEXT NOT NULL, message TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'open', emailed INTEGER NOT NULL DEFAULT 0, created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS votes (id INTEGER PRIMARY KEY AUTOINCREMENT, faq_id INTEGER NOT NULL, vote TEXT NOT NULL, created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS staff (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, name TEXT NOT NULL, password_hash TEXT NOT NULL, created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sessions (token_hash TEXT PRIMARY KEY, staff_id INTEGER NOT NULL, expires INTEGER NOT NULL);
`)
// First run: copy the 87 FAQs from the bundled file into the real database.
if (db.prepare('SELECT COUNT(*) AS n FROM faqs').get().n === 0) {
const seed = JSON.parse(readFileSync(join(here, '..', 'src', 'data', 'faqs.json'), 'utf8'))
const ins = db.prepare('INSERT INTO faqs (id, category, question, answer, link, link_label) VALUES (?,?,?,?,?,?)')
for (const f of seed) ins.run(f.id, f.category, f.question, f.answer, f.link, f.linkLabel)
}
-151
View File
@@ -1,151 +0,0 @@
import express from 'express'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { randomBytes } from 'node:crypto'
import { db } from './db.js'
import { hashPassword, verifyPassword, createSession, destroySession, cookieToken, requireStaff, rateLimit, SESSION_DAYS } from './auth.js'
import { sendTicketEmail, emailConfigured } from './mail.js'
const app = express()
const prod = process.env.NODE_ENV === 'production'
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const clean = (s, max) => String(s ?? '').replace(/[\r\n]+/g, ' ').trim().slice(0, max)
const cleanBlock = (s, max) => String(s ?? '').trim().slice(0, max)
const isHttpUrl = (u) => { try { return ['http:', 'https:'].includes(new URL(u).protocol) } catch { return false } }
app.set('trust proxy', process.env.TRUST_PROXY ? 1 : false)
app.disable('x-powered-by')
app.use((req, res, next) => {
res.set({
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'same-origin',
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; media-src https://d8j0ntlcm91z4.cloudfront.net; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'",
})
next()
})
app.use(express.json({ limit: '20kb' }))
// Block cross-site writes: browsers always send Origin on POST/PUT/PATCH/DELETE from other sites.
app.use((req, res, next) => {
if (['GET', 'HEAD'].includes(req.method)) return next()
const origin = req.headers.origin
if (origin && new URL(origin).host !== req.headers.host) return res.status(403).json({ error: 'Bad origin.' })
next()
})
// ---------- Public ----------
const faqOut = (r) => ({ id: r.id, category: r.category, question: r.question, answer: r.answer, link: r.link, linkLabel: r.link_label })
app.get('/api/faqs', (_req, res) => res.json(db.prepare('SELECT * FROM faqs ORDER BY id').all().map(faqOut)))
app.post('/api/tickets', rateLimit('ticket', 5, 3600e3), async (req, res) => {
const t = {
id: `IT-${Date.now().toString(36).toUpperCase()}${randomBytes(2).toString('hex').toUpperCase()}`,
name: clean(req.body.name, 100), email: clean(req.body.email, 200),
topic: clean(req.body.topic, 100), message: cleanBlock(req.body.message, 2000),
}
if (!t.name) return res.status(400).json({ error: 'Please enter your name.' })
if (!EMAIL_RE.test(t.email)) return res.status(400).json({ error: 'Please enter a valid email.' })
if (t.message.length < 10) return res.status(400).json({ error: 'Please describe the problem (at least 10 characters).' })
db.prepare('INSERT INTO tickets (id,name,email,topic,message,created) VALUES (?,?,?,?,?,?)').run(t.id, t.name, t.email, t.topic, t.message, new Date().toISOString())
const emailed = await sendTicketEmail(t)
if (emailed) db.prepare('UPDATE tickets SET emailed=1 WHERE id=?').run(t.id)
res.status(201).json({ id: t.id })
})
app.post('/api/votes', rateLimit('vote', 30, 3600e3), (req, res) => {
const faqId = Number(req.body.faqId)
const vote = req.body.vote
if (!['up', 'down'].includes(vote) || !db.prepare('SELECT 1 FROM faqs WHERE id=?').get(faqId)) return res.status(400).json({ error: 'Bad vote.' })
db.prepare('INSERT INTO votes (faq_id,vote,created) VALUES (?,?,?)').run(faqId, vote, new Date().toISOString())
res.status(201).json({ ok: true })
})
// ---------- Staff login ----------
app.post('/api/login', rateLimit('login', 10, 15 * 60e3), (req, res) => {
const row = db.prepare('SELECT * FROM staff WHERE email=?').get(clean(req.body.email, 200).toLowerCase())
// Same message either way so attackers can't learn which emails exist.
if (!row || !verifyPassword(String(req.body.password ?? ''), row.password_hash)) return res.status(401).json({ error: 'Wrong email or password.' })
const token = createSession(row.id)
res.cookie('session', token, { httpOnly: true, sameSite: 'strict', secure: prod, maxAge: SESSION_DAYS * 864e5, path: '/' })
res.json({ name: row.name, email: row.email })
})
app.post('/api/logout', (req, res) => {
const t = cookieToken(req)
if (t) destroySession(t)
res.clearCookie('session', { path: '/' })
res.json({ ok: true })
})
app.get('/api/me', requireStaff, (req, res) => res.json({ name: req.staff.name, email: req.staff.email }))
// ---------- Staff only ----------
app.get('/api/staff/status', requireStaff, (_req, res) => res.json({ emailConfigured }))
app.get('/api/staff/tickets', requireStaff, (_req, res) => res.json(db.prepare('SELECT * FROM tickets ORDER BY created DESC').all()))
app.patch('/api/staff/tickets/:id', requireStaff, (req, res) => {
if (!['open', 'in_progress', 'closed'].includes(req.body.status)) return res.status(400).json({ error: 'Bad status.' })
db.prepare('UPDATE tickets SET status=? WHERE id=?').run(req.body.status, req.params.id)
res.json({ ok: true })
})
app.get('/api/staff/faqs', requireStaff, (_req, res) => {
const votes = db.prepare("SELECT faq_id, SUM(vote='up') AS up, SUM(vote='down') AS down FROM votes GROUP BY faq_id").all()
const byId = new Map(votes.map((v) => [v.faq_id, v]))
res.json(db.prepare('SELECT * FROM faqs ORDER BY id').all().map((r) => ({ ...faqOut(r), up: byId.get(r.id)?.up ?? 0, down: byId.get(r.id)?.down ?? 0 })))
})
function faqFields(body) {
const f = { category: clean(body.category, 100), question: clean(body.question, 300), answer: cleanBlock(body.answer, 3000), link: clean(body.link, 500), link_label: clean(body.linkLabel, 200) }
if (!f.category || !f.question || !f.answer) return { error: 'Category, question and answer are required.' }
if (f.link && !isHttpUrl(f.link)) return { error: 'Link must start with http:// or https://' }
return { f }
}
app.post('/api/staff/faqs', requireStaff, (req, res) => {
const { f, error } = faqFields(req.body)
if (error) return res.status(400).json({ error })
const r = db.prepare('INSERT INTO faqs (category,question,answer,link,link_label) VALUES (?,?,?,?,?)').run(f.category, f.question, f.answer, f.link, f.link_label)
res.status(201).json({ id: Number(r.lastInsertRowid) })
})
app.put('/api/staff/faqs/:id', requireStaff, (req, res) => {
const { f, error } = faqFields(req.body)
if (error) return res.status(400).json({ error })
db.prepare('UPDATE faqs SET category=?,question=?,answer=?,link=?,link_label=? WHERE id=?').run(f.category, f.question, f.answer, f.link, f.link_label, req.params.id)
res.json({ ok: true })
})
app.delete('/api/staff/faqs/:id', requireStaff, (req, res) => {
db.prepare('DELETE FROM faqs WHERE id=?').run(req.params.id)
res.json({ ok: true })
})
app.get('/api/staff/team', requireStaff, (_req, res) => res.json(db.prepare('SELECT id,email,name,created FROM staff ORDER BY id').all()))
app.post('/api/staff/team', requireStaff, (req, res) => {
const email = clean(req.body.email, 200).toLowerCase(), name = clean(req.body.name, 100), pw = String(req.body.password ?? '')
if (!EMAIL_RE.test(email) || !name) return res.status(400).json({ error: 'Name and a valid email are required.' })
if (pw.length < 10) return res.status(400).json({ error: 'Password must be at least 10 characters.' })
if (db.prepare('SELECT 1 FROM staff WHERE email=?').get(email)) return res.status(409).json({ error: 'That email is already on the team.' })
db.prepare('INSERT INTO staff (email,name,password_hash,created) VALUES (?,?,?,?)').run(email, name, hashPassword(pw), new Date().toISOString())
res.status(201).json({ ok: true })
})
app.delete('/api/staff/team/:id', requireStaff, (req, res) => {
if (Number(req.params.id) === req.staff.id) return res.status(400).json({ error: "You can't remove yourself." })
db.prepare('DELETE FROM sessions WHERE staff_id=?').run(req.params.id)
db.prepare('DELETE FROM staff WHERE id=?').run(req.params.id)
res.json({ ok: true })
})
app.use('/api', (_req, res) => res.status(404).json({ error: 'Not found.' }))
// ---------- First staff member ----------
if (db.prepare('SELECT COUNT(*) AS n FROM staff').get().n === 0) {
const { ADMIN_EMAIL, ADMIN_PASSWORD } = process.env
if (ADMIN_EMAIL && ADMIN_PASSWORD && ADMIN_PASSWORD.length >= 10) {
db.prepare('INSERT INTO staff (email,name,password_hash,created) VALUES (?,?,?,?)').run(ADMIN_EMAIL.toLowerCase(), 'Admin', hashPassword(ADMIN_PASSWORD), new Date().toISOString())
console.log(`Created first staff login: ${ADMIN_EMAIL}`)
} else console.warn('No staff yet. Set ADMIN_EMAIL and ADMIN_PASSWORD (10+ characters) and restart.')
}
if (!emailConfigured) console.warn('Email not configured (SMTP_HOST/SMTP_USER/SMTP_PASS). Tickets are saved but not emailed.')
// ---------- Serve the website (production) ----------
const dist = join(dirname(fileURLToPath(import.meta.url)), '..', 'dist')
if (existsSync(dist)) app.use(express.static(dist))
const port = Number(process.env.PORT || 3001)
app.listen(port, () => console.log(`HelpDesk server on http://localhost:${port}`))
-25
View File
@@ -1,25 +0,0 @@
import nodemailer from 'nodemailer'
const { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, TICKET_TO = 'rana.krunal7558@gmail.com' } = process.env
const transporter = SMTP_HOST && SMTP_USER && SMTP_PASS
? nodemailer.createTransport({ host: SMTP_HOST, port: Number(SMTP_PORT || 465), secure: Number(SMTP_PORT || 465) === 465, auth: { user: SMTP_USER, pass: SMTP_PASS } })
: null
export const emailConfigured = !!transporter
export async function sendTicketEmail(t) {
if (!transporter) return false
try {
await transporter.sendMail({
from: SMTP_USER,
to: TICKET_TO,
replyTo: t.email,
subject: `[${t.id}] ${t.topic}: new IT request from ${t.name}`,
text: `Ticket: ${t.id}\nFrom: ${t.name} <${t.email}>\nTopic: ${t.topic}\n\n${t.message}\n`,
})
return true
} catch (e) {
console.error('Email failed:', e.message)
return false
}
}
-165
View File
@@ -1,165 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowRight, Globe, Instagram, Twitter } from 'lucide-react'
import VideoBackground from './VideoBackground'
import FaqList from './Faq'
import ContactForm from './ContactForm'
import type { Faq } from './types'
import Staff from './Staff'
import faqData from './data/faqs.json'
const bundledFaqs = faqData as Faq[]
export default function App() {
const [faqs, setFaqs] = useState<Faq[]>(bundledFaqs)
const [isStaff, setIsStaff] = useState(location.hash.startsWith('#/staff'))
const categories = useMemo(() => Array.from(new Set(faqs.map((f) => f.category))), [faqs])
useEffect(() => {
fetch('/api/faqs').then((r) => (r.ok ? r.json() : Promise.reject())).then(setFaqs).catch(() => {})
const onHash = () => setIsStaff(location.hash.startsWith('#/staff'))
window.addEventListener('hashchange', onHash)
return () => window.removeEventListener('hashchange', onHash)
}, [])
const [query, setQuery] = useState('')
const [category, setCategory] = useState<string | null>(null)
const answersRef = useRef<HTMLElement>(null)
const results = useMemo(() => {
const words = query.toLowerCase().split(/\s+/).filter(Boolean)
return faqs.filter((f) => {
if (category && f.category !== category) return false
const text = `${f.question} ${f.answer} ${f.category}`.toLowerCase()
return words.every((w) => text.includes(w))
})
}, [query, category, faqs])
if (isStaff) return <Staff />
const scrollToAnswers = () => answersRef.current?.scrollIntoView({ behavior: 'smooth' })
return (
<div className="bg-black">
<div className="min-h-screen bg-black overflow-hidden relative flex flex-col">
<VideoBackground />
<nav className="relative z-20 pl-6 pr-6 py-6">
<div className="liquid-glass rounded-full px-6 py-3 flex items-center justify-between max-w-5xl mx-auto">
<div className="flex items-center gap-8">
<div className="flex items-center gap-2 text-white font-semibold text-lg">
<Globe size={24} />
<span>HelpDesk</span>
</div>
<div className="hidden md:flex items-center gap-8">
{[
['Topics', '#answers'],
['Search', '#top'],
['Contact', '#contact'],
].map(([label, href]) => (
<a key={label} href={href} className="text-white/80 hover:text-white transition-colors text-sm font-medium">
{label}
</a>
))}
</div>
</div>
<div className="flex items-center gap-4">
<a href="#contact" className="text-white text-sm font-medium">Contact IT</a>
<a href="#/staff" className="liquid-glass rounded-full px-6 py-2 text-white text-sm font-medium">Staff login</a>
</div>
</div>
</nav>
<div
id="top"
className="relative z-10 flex-1 flex flex-col items-center justify-center px-6 py-12 text-center -translate-y-[20%]"
>
<h1
className="text-5xl md:text-6xl lg:text-7xl text-white mb-8 tracking-tight whitespace-nowrap"
style={{ fontFamily: "'Instrument Serif', serif" }}
>
IT help, <em>made simple</em>
</h1>
<div className="max-w-xl w-full space-y-4">
<form
className="liquid-glass rounded-full pl-6 pr-2 py-2 flex items-center gap-3"
onSubmit={(e) => {
e.preventDefault()
scrollToAnswers()
}}
>
<input
type="text"
value={query}
maxLength={200}
onChange={(e) => setQuery(e.target.value)}
placeholder="Describe your problem"
aria-label="Search IT help"
className="bg-transparent outline-none flex-1 text-white placeholder:text-white/40 text-base"
/>
<button type="submit" aria-label="Search" className="bg-white rounded-full p-3 text-black">
<ArrowRight size={20} />
</button>
</form>
<p className="text-white text-sm leading-relaxed px-4">
Locked out? Wi-Fi down? Printer acting up? Search {faqs.length} plain-English answers to the most common IT problems.
</p>
<div className="flex justify-center">
<button
onClick={scrollToAnswers}
className="liquid-glass rounded-full px-8 py-3 text-white text-sm font-medium hover:bg-white/5 transition-colors"
>
Browse all topics
</button>
</div>
</div>
</div>
<div className="relative z-10 flex justify-center gap-4 pb-12">
{[
{ Icon: Instagram, label: 'Instagram' },
{ Icon: Twitter, label: 'Twitter' },
{ Icon: Globe, label: 'Website' },
].map(({ Icon, label }) => (
<button
key={label}
aria-label={label}
className="liquid-glass rounded-full p-4 text-white/80 hover:text-white hover:bg-white/5 transition-all"
>
<Icon size={20} />
</button>
))}
</div>
</div>
<section id="answers" ref={answersRef} className="max-w-3xl mx-auto px-6 py-20">
<h2 className="text-4xl text-white mb-2" style={{ fontFamily: "'Instrument Serif', serif" }}>
Answers
</h2>
<p className="text-white/60 text-sm mb-6" aria-live="polite">
Showing {results.length} of {faqs.length}
</p>
<div className="flex flex-wrap gap-2 mb-8">
{[null, ...categories].map((c) => (
<button
key={c ?? 'all'}
onClick={() => setCategory(c)}
aria-pressed={category === c}
className={`liquid-glass rounded-full px-4 py-2 text-sm transition-colors ${
category === c ? 'bg-white/20 text-white' : 'text-white/70 hover:text-white hover:bg-white/5'
}`}
>
{c ?? 'All'}
</button>
))}
</div>
<FaqList items={results} />
</section>
<ContactForm topics={categories} />
<footer id="about" className="max-w-3xl mx-auto px-6 pb-16 text-center text-white/50 text-sm">
General guidance only. For account-specific problems, contact your organisation's IT service desk.
</footer>
</div>
)
}
-80
View File
@@ -1,80 +0,0 @@
import { useState } from 'react'
import { Send } from 'lucide-react'
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const inputCls = 'w-full bg-transparent outline-none text-white placeholder:text-white/40 text-base'
export default function ContactForm({ topics }: { topics: string[] }) {
const [form, setForm] = useState({ name: '', email: '', topic: topics[0] ?? '', message: '' })
const [errors, setErrors] = useState<Record<string, string>>({})
const [ticketId, setTicketId] = useState<string | null>(null)
const [sending, setSending] = useState(false)
const [serverError, setServerError] = useState('')
const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) =>
setForm({ ...form, [k]: e.target.value })
const submit = async (e: React.FormEvent) => {
e.preventDefault()
const errs: Record<string, string> = {}
if (!form.name.trim()) errs.name = 'Please enter your name.'
if (!EMAIL_RE.test(form.email.trim())) errs.email = 'Please enter a valid email.'
if (form.message.trim().length < 10) errs.message = 'Please describe the problem (at least 10 characters).'
setErrors(errs)
setServerError('')
if (Object.keys(errs).length) return
setSending(true)
try {
const res = await fetch('/api/tickets', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) })
const data = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(data.error || 'Something went wrong. Please try again.')
setTicketId(data.id)
setForm({ name: '', email: '', topic: topics[0] ?? '', message: '' })
} catch (err) {
setServerError(err instanceof Error ? err.message : 'Could not reach the server.')
} finally {
setSending(false)
}
}
const field = 'liquid-glass rounded-3xl px-6 py-4'
const err = (k: string) => errors[k] && <p role="alert" className="text-red-300 text-sm mt-1 px-2">{errors[k]}</p>
return (
<section id="contact" className="max-w-3xl mx-auto px-6 pb-20">
<h2 className="text-4xl text-white mb-2" style={{ fontFamily: "'Instrument Serif', serif" }}>Contact IT</h2>
<p className="text-white/60 text-sm mb-6">Can't find your answer? Tell us what's wrong.</p>
{ticketId ? (
<div className="liquid-glass rounded-3xl p-8 text-white" role="status">
<p className="text-xl mb-2">Request sent. Your ticket number is <strong>{ticketId}</strong>.</p>
<p className="text-white/70 text-sm mb-4">Our IT team has been notified. Keep this number if you follow up.</p>
<button onClick={() => setTicketId(null)} className="liquid-glass rounded-full px-6 py-2 text-sm hover:bg-white/5">Send another</button>
</div>
) : (
<form onSubmit={submit} noValidate className="space-y-3">
<div>
<div className={field}><input className={inputCls} placeholder="Your name" aria-label="Your name" maxLength={100} value={form.name} onChange={set('name')} /></div>
{err('name')}
</div>
<div>
<div className={field}><input className={inputCls} type="email" placeholder="Your email" aria-label="Your email" maxLength={200} value={form.email} onChange={set('email')} /></div>
{err('email')}
</div>
<div className={field}>
<select className={`${inputCls} [&>option]:text-black`} aria-label="Topic" value={form.topic} onChange={set('topic')}>
{topics.map((t) => <option key={t}>{t}</option>)}
</select>
</div>
<div>
<div className={field}><textarea className={`${inputCls} resize-none`} rows={5} placeholder="What's the problem?" aria-label="Problem description" maxLength={2000} value={form.message} onChange={set('message')} /></div>
{err('message')}
</div>
{serverError && <p role="alert" className="text-red-300 text-sm px-2">{serverError}</p>}
<button type="submit" disabled={sending} className="bg-white text-black rounded-full px-8 py-3 text-sm font-medium inline-flex items-center gap-2 disabled:opacity-60">
<Send size={16} /> {sending ? 'Sending...' : 'Send request'}
</button>
</form>
)}
</section>
)
}
-120
View File
@@ -1,120 +0,0 @@
import { useEffect, useState } from 'react'
import { Check, ExternalLink, Link2, SearchX, ThumbsDown, ThumbsUp } from 'lucide-react'
import type { Faq } from './types'
import { load, save } from './storage'
type Votes = Record<number, 'up' | 'down'>
function safeUrl(url: string): string | null {
try {
const u = new URL(url)
return u.protocol === 'https:' || u.protocol === 'http:' ? u.href : null
} catch {
return null
}
}
function FaqCard({ f, forceOpen, vote, onVote }: { f: Faq; forceOpen: boolean; vote?: 'up' | 'down'; onVote: (v: 'up' | 'down') => void }) {
const [copied, setCopied] = useState(false)
const href = f.link ? safeUrl(f.link) : null
const copyLink = async () => {
const url = `${location.origin}${location.pathname}#faq-${f.id}`
try {
await navigator.clipboard.writeText(url)
setCopied(true)
window.setTimeout(() => setCopied(false), 2000)
} catch {
location.hash = `faq-${f.id}`
}
}
const voteBtn = (v: 'up' | 'down', label: string, Icon: typeof ThumbsUp) => (
<button
onClick={() => onVote(v)}
aria-pressed={vote === v}
className={`liquid-glass rounded-full px-4 py-2 inline-flex items-center gap-2 text-sm transition-colors ${
vote === v ? 'bg-white/20 text-white' : 'text-white/70 hover:text-white hover:bg-white/5'
}`}
>
<Icon size={14} /> {label}
</button>
)
return (
<li id={`faq-${f.id}`} className="scroll-mt-6">
<details className="liquid-glass rounded-3xl group" open={forceOpen || undefined}>
<summary className="cursor-pointer list-none px-6 py-5 flex items-start justify-between gap-4 text-white">
<span>
<span className="block text-xs uppercase tracking-wider text-white/50 mb-1">{f.category}</span>
<span className="text-lg">{f.question}</span>
</span>
<span className="text-white/60 transition-transform group-open:rotate-45 text-2xl leading-none">+</span>
</summary>
<div className="px-6 pb-6 text-white/80 text-sm leading-relaxed">
<p>{f.answer}</p>
{href && (
<a href={href} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 mt-4 text-white hover:underline">
{f.linkLabel || 'Official guide'} <ExternalLink size={14} />
</a>
)}
<div className="mt-5 flex flex-wrap items-center gap-2">
<span className="text-white/50 mr-1">Was this helpful?</span>
{voteBtn('up', 'Yes', ThumbsUp)}
{voteBtn('down', 'No', ThumbsDown)}
<button
onClick={copyLink}
className="liquid-glass rounded-full px-4 py-2 inline-flex items-center gap-2 text-sm text-white/70 hover:text-white hover:bg-white/5 transition-colors ml-auto"
>
{copied ? <Check size={14} /> : <Link2 size={14} />} {copied ? 'Link copied' : 'Copy link'}
</button>
</div>
{vote === 'down' && (
<p className="mt-3 text-white/60">
Sorry about that. <a href="#contact" className="text-white underline">Contact IT</a> and we'll help directly.
</p>
)}
</div>
</details>
</li>
)
}
export default function FaqList({ items }: { items: Faq[] }) {
const [votes, setVotes] = useState<Votes>(() => load<Votes>('faq-votes', {}))
const [hashId, setHashId] = useState<number | null>(null)
useEffect(() => {
const read = () => {
const m = /^#faq-(\d+)$/.exec(location.hash)
setHashId(m ? Number(m[1]) : null)
if (m) window.setTimeout(() => document.getElementById(`faq-${m[1]}`)?.scrollIntoView({ behavior: 'smooth' }), 50)
}
read()
window.addEventListener('hashchange', read)
return () => window.removeEventListener('hashchange', read)
}, [])
const onVote = (id: number, v: 'up' | 'down') => {
const next = { ...votes, [id]: v }
setVotes(next)
save('faq-votes', next)
fetch('/api/votes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ faqId: id, vote: v }) }).catch(() => {})
}
if (items.length === 0) {
return (
<div className="liquid-glass rounded-3xl p-10 text-center text-white/70">
<SearchX className="mx-auto mb-3" size={28} />
<p>No answers found. Try different words, or <a href="#contact" className="text-white underline">contact IT</a>.</p>
</div>
)
}
return (
<ul className="space-y-3">
{items.map((f) => (
<FaqCard key={f.id} f={f} forceOpen={hashId === f.id} vote={votes[f.id]} onVote={(v) => onVote(f.id, v)} />
))}
</ul>
)
}
-175
View File
@@ -1,175 +0,0 @@
import { useCallback, useEffect, useState } from 'react'
import { LogOut } from 'lucide-react'
interface Ticket { id: string; name: string; email: string; topic: string; message: string; status: string; emailed: number; created: string }
interface StaffFaq { id: number; category: string; question: string; answer: string; link: string; linkLabel: string; up: number; down: number }
interface Member { id: number; email: string; name: string }
type Tab = 'tickets' | 'faqs' | 'team'
async function api<T = unknown>(path: string, method = 'GET', body?: unknown): Promise<T> {
const res = await fetch(`/api${path}`, { method, headers: body ? { 'Content-Type': 'application/json' } : undefined, body: body ? JSON.stringify(body) : undefined })
const data = await res.json().catch(() => ({}))
if (!res.ok) throw Object.assign(new Error(data.error || 'Request failed'), { status: res.status })
return data as T
}
const box = 'liquid-glass rounded-3xl p-6 text-white'
const input = 'w-full bg-white/5 rounded-2xl px-4 py-3 text-white placeholder:text-white/40 outline-none'
const btn = 'liquid-glass rounded-full px-5 py-2 text-sm text-white hover:bg-white/5 transition-colors'
function Login({ onDone }: { onDone: () => void }) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const submit = async (e: React.FormEvent) => {
e.preventDefault()
try { await api('/login', 'POST', { email, password }); onDone() } catch (err) { setError((err as Error).message) }
}
return (
<form onSubmit={submit} className={`${box} max-w-sm mx-auto space-y-3`}>
<h1 className="text-3xl mb-2" style={{ fontFamily: "'Instrument Serif', serif" }}>Staff login</h1>
<input className={input} type="email" placeholder="Email" aria-label="Email" value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="username" />
<input className={input} type="password" placeholder="Password" aria-label="Password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
{error && <p role="alert" className="text-red-300 text-sm">{error}</p>}
<button type="submit" className="bg-white text-black rounded-full px-6 py-2 text-sm font-medium">Log in</button>
</form>
)
}
function Tickets() {
const [rows, setRows] = useState<Ticket[]>([])
const load = useCallback(() => api<Ticket[]>('/staff/tickets').then(setRows), [])
useEffect(() => { load() }, [load])
const setStatus = async (id: string, status: string) => { await api(`/staff/tickets/${id}`, 'PATCH', { status }); load() }
if (!rows.length) return <p className="text-white/60">No tickets yet.</p>
return (
<ul className="space-y-3">
{rows.map((t) => (
<li key={t.id} className={box}>
<div className="flex flex-wrap justify-between gap-2 text-sm text-white/60">
<span>{t.id} · {t.topic} · {new Date(t.created).toLocaleString()}</span>
<span>{t.emailed ? 'emailed' : 'not emailed'}</span>
</div>
<p className="mt-2 whitespace-pre-wrap">{t.message}</p>
<p className="mt-2 text-sm text-white/70">{t.name} · <a className="underline" href={`mailto:${encodeURIComponent(t.email)}`}>{t.email}</a></p>
<select aria-label="Status" value={t.status} onChange={(e) => setStatus(t.id, e.target.value)} className="mt-3 bg-white/10 rounded-full px-4 py-2 text-sm [&>option]:text-black">
<option value="open">Open</option><option value="in_progress">In progress</option><option value="closed">Closed</option>
</select>
</li>
))}
</ul>
)
}
const emptyFaq = { category: '', question: '', answer: '', link: '', linkLabel: '' }
function Faqs() {
const [rows, setRows] = useState<StaffFaq[]>([])
const [editing, setEditing] = useState<(typeof emptyFaq & { id?: number }) | null>(null)
const [error, setError] = useState('')
const load = useCallback(() => api<StaffFaq[]>('/staff/faqs').then(setRows), [])
useEffect(() => { load() }, [load])
const save = async (e: React.FormEvent) => {
e.preventDefault()
if (!editing) return
try {
if (editing.id) await api(`/staff/faqs/${editing.id}`, 'PUT', editing)
else await api('/staff/faqs', 'POST', editing)
setEditing(null); setError(''); load()
} catch (err) { setError((err as Error).message) }
}
const remove = async (f: StaffFaq) => { if (confirm(`Delete "${f.question}"?`)) { await api(`/staff/faqs/${f.id}`, 'DELETE'); load() } }
const set = (k: keyof typeof emptyFaq) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => editing && setEditing({ ...editing, [k]: e.target.value })
return (
<div className="space-y-4">
{editing ? (
<form onSubmit={save} className={`${box} space-y-3`}>
<input className={input} placeholder="Category" aria-label="Category" value={editing.category} onChange={set('category')} />
<input className={input} placeholder="Question" aria-label="Question" value={editing.question} onChange={set('question')} />
<textarea className={input} rows={5} placeholder="Answer" aria-label="Answer" value={editing.answer} onChange={set('answer')} />
<input className={input} placeholder="Link (optional, https://...)" aria-label="Link" value={editing.link} onChange={set('link')} />
<input className={input} placeholder="Link label (optional)" aria-label="Link label" value={editing.linkLabel} onChange={set('linkLabel')} />
{error && <p role="alert" className="text-red-300 text-sm">{error}</p>}
<div className="flex gap-2"><button type="submit" className="bg-white text-black rounded-full px-6 py-2 text-sm font-medium">Save</button><button type="button" className={btn} onClick={() => { setEditing(null); setError('') }}>Cancel</button></div>
</form>
) : <button className={btn} onClick={() => setEditing({ ...emptyFaq })}>+ Add FAQ</button>}
<ul className="space-y-2">
{rows.map((f) => (
<li key={f.id} className={`${box} flex flex-wrap items-center justify-between gap-3 !py-4`}>
<span><span className="block text-xs text-white/50">{f.category}</span>{f.question}</span>
<span className="flex items-center gap-3 text-sm text-white/70">
👍 {f.up} 👎 {f.down}
<button className={btn} onClick={() => setEditing(f)}>Edit</button>
<button className={btn} onClick={() => remove(f)}>Delete</button>
</span>
</li>
))}
</ul>
</div>
)
}
function Team({ me }: { me: string }) {
const [rows, setRows] = useState<Member[]>([])
const [f, setF] = useState({ name: '', email: '', password: '' })
const [error, setError] = useState('')
const load = useCallback(() => api<Member[]>('/staff/team').then(setRows), [])
useEffect(() => { load() }, [load])
const add = async (e: React.FormEvent) => {
e.preventDefault()
try { await api('/staff/team', 'POST', f); setF({ name: '', email: '', password: '' }); setError(''); load() } catch (err) { setError((err as Error).message) }
}
const remove = async (m: Member) => { if (confirm(`Remove ${m.name}?`)) { try { await api(`/staff/team/${m.id}`, 'DELETE'); load() } catch (err) { setError((err as Error).message) } } }
return (
<div className="space-y-4">
<ul className="space-y-2">
{rows.map((m) => (
<li key={m.id} className={`${box} flex items-center justify-between !py-4`}>
<span>{m.name} <span className="text-white/60 text-sm">· {m.email}</span></span>
{m.email !== me && <button className={btn} onClick={() => remove(m)}>Remove</button>}
</li>
))}
</ul>
<form onSubmit={add} className={`${box} space-y-3`}>
<h2 className="text-xl">Add a team member</h2>
<input className={input} placeholder="Name" aria-label="Name" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} />
<input className={input} type="email" placeholder="Email" aria-label="Email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} />
<input className={input} type="password" placeholder="Temporary password (10+ characters)" aria-label="Password" value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} autoComplete="new-password" />
{error && <p role="alert" className="text-red-300 text-sm">{error}</p>}
<button type="submit" className="bg-white text-black rounded-full px-6 py-2 text-sm font-medium">Add</button>
</form>
</div>
)
}
export default function Staff() {
const [me, setMe] = useState<{ name: string; email: string } | null | undefined>(undefined)
const [emailOk, setEmailOk] = useState(true)
const [tab, setTab] = useState<Tab>('tickets')
const check = useCallback(() => {
api<{ name: string; email: string }>('/me').then((m) => { setMe(m); api<{ emailConfigured: boolean }>('/staff/status').then((s) => setEmailOk(s.emailConfigured)) }).catch(() => setMe(null))
}, [])
useEffect(() => { check() }, [check])
const logout = async () => { await api('/logout', 'POST'); setMe(null) }
return (
<div className="min-h-screen bg-black text-white px-6 py-10">
<div className="max-w-3xl mx-auto">
<div className="flex items-center justify-between mb-8">
<a href="#" className="text-white/70 hover:text-white text-sm">← Back to site</a>
{me && <button onClick={logout} className={`${btn} inline-flex items-center gap-2`}><LogOut size={14} /> Log out ({me.name})</button>}
</div>
{me === undefined ? <p className="text-white/60">Loading...</p> : me === null ? <Login onDone={check} /> : (
<>
{!emailOk && <p className="mb-4 text-amber-300 text-sm">Email is not set up on the server yet, so new tickets are saved here but not emailed.</p>}
<div className="flex gap-2 mb-6">
{(['tickets', 'faqs', 'team'] as Tab[]).map((t) => (
<button key={t} onClick={() => setTab(t)} aria-pressed={tab === t} className={`${btn} capitalize ${tab === t ? 'bg-white/20' : ''}`}>{t === 'faqs' ? 'FAQs' : t}</button>
))}
</div>
{tab === 'tickets' && <Tickets />}{tab === 'faqs' && <Faqs />}{tab === 'team' && <Team me={me.email} />}
</>
)}
</div>
</div>
)
}
-66
View File
@@ -1,66 +0,0 @@
import { useCallback, useEffect, useRef } from 'react'
const VIDEO_URL =
'https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260328_115001_bcdaa3b4-03de-47e7-ad63-ae3e392c32d4.mp4'
const FADE_MS = 500
const FADE_OUT_REMAINING = 0.55
export default function VideoBackground() {
const videoRef = useRef<HTMLVideoElement>(null)
const rafRef = useRef<number | null>(null)
const fadingOutRef = useRef(false)
const fadeTo = useCallback((target: number) => {
const video = videoRef.current
if (!video) return
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
const startOpacity = parseFloat(video.style.opacity || '0')
const startTime = performance.now()
const step = (now: number) => {
const t = Math.min((now - startTime) / FADE_MS, 1)
video.style.opacity = String(startOpacity + (target - startOpacity) * t)
rafRef.current = t < 1 ? requestAnimationFrame(step) : null
}
rafRef.current = requestAnimationFrame(step)
}, [])
useEffect(() => () => {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
}, [])
const handleTimeUpdate = () => {
const video = videoRef.current
if (!video || !video.duration || fadingOutRef.current) return
if (video.duration - video.currentTime <= FADE_OUT_REMAINING) {
fadingOutRef.current = true
fadeTo(0)
}
}
const handleEnded = () => {
const video = videoRef.current
if (!video) return
video.style.opacity = '0'
window.setTimeout(() => {
video.currentTime = 0
void video.play().catch(() => {})
fadingOutRef.current = false
fadeTo(1)
}, 100)
}
return (
<video
ref={videoRef}
src={VIDEO_URL}
autoPlay
muted
playsInline
style={{ opacity: 0 }}
className="absolute inset-0 w-full h-full object-cover translate-y-[17%]"
onLoadedData={() => fadeTo(1)}
onTimeUpdate={handleTimeUpdate}
onEnded={handleEnded}
/>
)
}
-698
View File
@@ -1,698 +0,0 @@
[
{
"id": 1,
"category": "Access & logins",
"question": "I forgot my password",
"answer": "Most organisations have a self-service reset link on the sign-in page, usually 'Forgot password' or 'Can't access your account'. You'll be asked to verify your identity, normally with a code sent to a backup email or phone number you registered earlier. If there's no self-service option, or verification fails, your IT service desk can reset it after confirming your identity another way. Keep any backup codes you were given when MFA was set up somewhere safe, they're often the fastest way back in.",
"link": "https://support.microsoft.com/en-us/account-billing/how-to-reset-your-microsoft-account-password-eff4f067-5042-c1a3-fe72-b04d60556c37",
"linkLabel": "Microsoft: reset your password"
},
{
"id": 2,
"category": "Access & logins",
"question": "I'm locked out after too many failed attempts",
"answer": "This is a security feature, not a fault, it stops someone guessing your password repeatedly. Most systems clear the lockout automatically after a set time, often 15 to 30 minutes, so waiting is sometimes the fastest fix. If it's urgent, or the lockout doesn't clear itself, your IT service desk can unlock the account manually once they've verified it's really you.",
"link": "",
"linkLabel": ""
},
{
"id": 3,
"category": "Access & logins",
"question": "My multi-factor login (authenticator app) isn't working",
"answer": "If you've lost your phone or the authenticator app stopped generating valid codes, try a saved backup code first, most systems issue a set of one-time codes when MFA is first set up. If you don't have one, contact IT to re-register your MFA device, this normally requires an identity check (staff or student ID, or a manager confirming it's you) since it's effectively resetting your account security.",
"link": "",
"linkLabel": ""
},
{
"id": 4,
"category": "Access & logins",
"question": "My account is disabled or expired after returning from leave",
"answer": "Accounts are sometimes automatically disabled after a period of inactivity, or a leave period that wasn't flagged as 'returning' in the system. This is an account status issue in the directory (Active Directory or similar), not a password problem, ask IT to check whether the account itself is disabled or expired rather than resetting the password again.",
"link": "",
"linkLabel": ""
},
{
"id": 5,
"category": "Access & logins",
"question": "Single sign-on (SSO) keeps redirecting in a loop",
"answer": "An SSO loop, bouncing between your organisation's login page and the app without ever landing you in, is usually a cookie or session problem rather than your password. Try a private or incognito browser window first, if that works cleanly, clear cookies for your organisation's login domain. If it still loops, the connection between your identity provider and that specific app may need IT to check its configuration.",
"link": "",
"linkLabel": ""
},
{
"id": 6,
"category": "Access & logins",
"question": "A guest or contractor account isn't working",
"answer": "Guest and contractor accounts usually go through a separate approval process, often needing an internal sponsor, and typically expire automatically after a set period for security. If a guest account stops working, check with the person who sponsored the access first, then IT if they confirm it should still be active.",
"link": "",
"linkLabel": ""
},
{
"id": 7,
"category": "Access & logins",
"question": "My security questions aren't being accepted during recovery",
"answer": "Recovery answers need to match exactly what was originally entered, including capitalisation in some systems, so a common cause is simply misremembering the exact wording. If you've genuinely forgotten the answers, look for a 'try another way' option instead of repeatedly guessing, most recovery tools offer an alternative path such as an email or SMS code.",
"link": "",
"linkLabel": ""
},
{
"id": 8,
"category": "Access & logins",
"question": "A new password keeps being rejected as too weak or previously used",
"answer": "Organisations enforce password rules (minimum length, a mix of character types, and often a block on reusing recent passwords) to reduce the risk of a compromised account. A longer passphrase, three or four random unrelated words plus a number and symbol, is both stronger and easier to remember than a short complex one, and tends to pass these checks more easily. Avoid names, birthdays or the organisation's own name.",
"link": "",
"linkLabel": ""
},
{
"id": 9,
"category": "Network & wifi",
"question": "My wifi keeps dropping",
"answer": "Try moving closer to the access point, restarting your device's wifi, and checking if other devices nearby have the same problem, that tells you whether it's your device or the network. On a corporate or school network with certificate-based login (802.1x), an expired certificate is a common cause, IT can reissue it. A network adapter driver that's out of date after a Windows update is another very common cause worth ruling out.",
"link": "https://support.microsoft.com/en-us/windows/fix-wi-fi-connection-issues-in-windows-9424a1f7-6a3b-65a6-4d78-7f07eee84d2c",
"linkLabel": "Microsoft: fix Wi-Fi connection issues"
},
{
"id": 10,
"category": "Network & wifi",
"question": "The VPN won't connect",
"answer": "Check your normal internet connection works first. Then fully close and reopen the VPN app rather than just reconnecting, a half-open session is a common cause. Public wifi (cafes, hotels) sometimes blocks VPN traffic entirely until you've accepted its own login page in a browser first.",
"link": "",
"linkLabel": ""
},
{
"id": 11,
"category": "Network & wifi",
"question": "I can't reach a shared drive or folder",
"answer": "Confirm you're connected to the VPN or office network, shared drives usually don't work from the open internet. If it still fails, the folder permissions may have changed, ask IT to check your access rather than repeatedly trying to reconnect.",
"link": "",
"linkLabel": ""
},
{
"id": 12,
"category": "Network & wifi",
"question": "I'm getting an IP conflict or 'limited connectivity' message",
"answer": "This usually means your device didn't get a valid address from the network's DHCP server, often after being moved between networks or waking from sleep. Disconnecting and reconnecting to wifi, or running `ipconfig /release` then `ipconfig /renew` on Windows, fixes most cases. If it keeps happening on the same device, report it, it can indicate a DHCP address pool running low.",
"link": "",
"linkLabel": ""
},
{
"id": 13,
"category": "Network & wifi",
"question": "A captive portal (hotel or cafe wifi login page) won't load",
"answer": "If the login page doesn't appear automatically, try opening a plain, non-secure website, some networks only trigger the portal on unencrypted traffic. A corporate VPN client often blocks the portal from appearing at all, disconnect the VPN first, log in to the wifi, then reconnect the VPN.",
"link": "",
"linkLabel": ""
},
{
"id": 14,
"category": "Network & wifi",
"question": "Wifi shows connected but the internet is very slow",
"answer": "Being 'connected' only confirms a local network link, not that everything beyond it is fast. Run a speed test, then check whether it's isolated to one device (a device or driver issue) or affects everyone nearby, which usually points to the access point, the internet link itself, or a bandwidth-heavy device worth reporting to IT.",
"link": "",
"linkLabel": ""
},
{
"id": 15,
"category": "Network & wifi",
"question": "A mapped network drive keeps failing after a password change",
"answer": "A mapped drive often stores the old credentials separately, so it can keep failing silently even though you can log in to everything else fine. Disconnect the mapped drive and reconnect it fresh, entering the new password when prompted, rather than relying on the saved ones.",
"link": "",
"linkLabel": ""
},
{
"id": 16,
"category": "Network & wifi",
"question": "A Bluetooth device won't pair",
"answer": "Turn Bluetooth off and on again on both devices, and make sure the device is actually in pairing mode. If it was previously paired with a different computer, 'forget' or remove the old pairing on both ends first, most Bluetooth accessories only hold a limited number of paired connections at once.",
"link": "",
"linkLabel": ""
},
{
"id": 17,
"category": "Hardware",
"question": "The printer won't print",
"answer": "Check it's powered on, has paper and toner, and that you picked the right printer name in the print dialog. Network printers can show as 'offline' if they've lost wifi, turning them off and on again often fixes this.",
"link": "",
"linkLabel": ""
},
{
"id": 18,
"category": "Hardware",
"question": "An external monitor isn't detected",
"answer": "Check the cable is firmly in at both ends and try a different port or cable if you have one. Then open your display settings and click 'Detect'. A driver or graphics update can also help on older laptops.",
"link": "",
"linkLabel": ""
},
{
"id": 19,
"category": "Hardware",
"question": "A USB device isn't recognised",
"answer": "Try a different USB port, and a different cable if it's detachable. If it still doesn't show up, check Device Manager (Windows) or System Report (Mac) for a warning icon next to the device.",
"link": "",
"linkLabel": ""
},
{
"id": 20,
"category": "Hardware",
"question": "A laptop won't turn on at all",
"answer": "First rule out a flat battery, plug in the charger, check for a charging light, then leave it 15 to 30 minutes before trying again, some laptops won't start with a completely dead battery even while charging. If there's a charging light but still nothing on screen, try an external monitor, that tells you whether it's a screen problem or the laptop genuinely isn't starting.",
"link": "",
"linkLabel": ""
},
{
"id": 21,
"category": "Hardware",
"question": "The battery is draining fast or won't charge",
"answer": "Test the charger and cable on a different device or outlet first, to rule out a faulty charger rather than the laptop itself. Battery health does genuinely fade over 2 to 4 years of daily use, if the laptop is older and the drop was gradual, a battery replacement through IT asset management is often the real fix rather than a software setting.",
"link": "",
"linkLabel": ""
},
{
"id": 22,
"category": "Hardware",
"question": "The keyboard or trackpad isn't responding",
"answer": "Restart the device first, a stuck driver is a common and simple cause. If only specific keys are affected, check for anything physically stuck underneath, common after spills or crumbs, and try an external USB keyboard or mouse to confirm whether it's the built-in hardware or a wider fault.",
"link": "",
"linkLabel": ""
},
{
"id": 23,
"category": "Hardware",
"question": "A docking station isn't detecting monitors or peripherals",
"answer": "Confirm the dock itself has power, many need their own power cable, not just the laptop cable, and try unplugging the laptop from the dock and reconnecting it firmly. Docks that connect via USB-C or Thunderbolt can be picky about cable quality, swap the cable before assuming the dock has failed.",
"link": "",
"linkLabel": ""
},
{
"id": 24,
"category": "Hardware",
"question": "The webcam isn't detected by any app",
"answer": "Some laptops have a physical privacy shutter or a function-key toggle that disables the camera entirely, check for both before assuming it's broken. Checking Device Manager (Windows) or System Information (Mac) shows whether the operating system sees the camera at all, if it's not listed there, it's a driver or hardware fault rather than an app setting.",
"link": "",
"linkLabel": ""
},
{
"id": 25,
"category": "Software & apps",
"question": "My computer is running very slow",
"answer": "Restart it first, this clears a surprising number of slowdowns. After that, check how much storage is free and close programs you're not using that start automatically. If it's still slow, let IT know, it could be a background update or a bigger issue.",
"link": "",
"linkLabel": ""
},
{
"id": 26,
"category": "Software & apps",
"question": "An app keeps crashing or won't open",
"answer": "Close and reopen it, then restart your computer if that doesn't help. Check whether an update is available. If it's an approved work app that IT installed for you, they may need to reinstall it rather than you doing it yourself.",
"link": "",
"linkLabel": ""
},
{
"id": 27,
"category": "Software & apps",
"question": "My email isn't syncing or I'm missing messages",
"answer": "Check your internet connection and your junk or spam folder. Also check your mailbox isn't full, a full mailbox silently stops receiving mail in some systems. Outlook and Gmail both have a 'repair account' option worth trying.",
"link": "",
"linkLabel": ""
},
{
"id": 28,
"category": "Software & apps",
"question": "My camera isn't working in Microsoft Teams",
"answer": "Close other apps that might already be using the camera (like Zoom or FaceTime), unplug and reconnect it if it's external, and restart the device. Make a test call from Teams' device settings to check camera, mic and speaker together in one go.",
"link": "https://support.microsoft.com/en-US/teams/meetings/my-camera-isn-t-working-in-microsoft-teams",
"linkLabel": "Microsoft: Teams camera troubleshooting"
},
{
"id": 29,
"category": "Software & apps",
"question": "Zoom audio or video isn't working",
"answer": "Check the correct microphone, speaker and camera are selected inside Zoom's own settings, not just that your device isn't muted at the operating system level. If it's a browser-based meeting, the browser also needs camera and microphone permission granted specifically for that site.",
"link": "https://support.zoom.us/",
"linkLabel": "Zoom support"
},
{
"id": 30,
"category": "Software & apps",
"question": "Windows Update is stuck or won't install",
"answer": "Restart the device once and let it sit for at least 30 minutes, some updates genuinely take a long time on the 'working on updates' screen, and interrupting them can cause more problems than waiting. If it's still stuck well beyond that, or fails repeatedly, note the exact error code for IT, the built-in update troubleshooter resolves a lot of common stuck updates on its own.",
"link": "",
"linkLabel": ""
},
{
"id": 31,
"category": "Software & apps",
"question": "Office or Microsoft 365 shows 'unlicensed product' or won't activate",
"answer": "This usually means the app can't confirm your licence with Microsoft's servers, often because you're signed in with the wrong account, or you've been offline too long since the last successful check-in. Sign out and back in with your work or school account specifically, not a personal Microsoft account, and make sure you're online or on VPN when it tries to reactivate.",
"link": "",
"linkLabel": ""
},
{
"id": 32,
"category": "Software & apps",
"question": "'Access denied' or 'permission denied' opening a file",
"answer": "This is almost always a permissions setting on the file or folder itself, not a fault with your computer. Confirm you're opening it from the right location, a synced local copy can behave differently to the shared original, and if you believe you should have access, ask the file's owner or IT to check the permission list rather than trying to force it open.",
"link": "",
"linkLabel": ""
},
{
"id": 33,
"category": "Security",
"question": "I received a suspicious email, is it phishing?",
"answer": "Don't click links or open attachments. Check the sender's actual email address, not just the display name, and look for urgency or requests for passwords or gift cards, common phishing signs. Report it to your IT security team rather than deleting it, they may need to warn others across the organisation.",
"link": "https://www.cyber.gov.au/report-and-recover",
"linkLabel": "ACSC: report a cybercrime (ReportCyber)"
},
{
"id": 34,
"category": "Security",
"question": "My computer crashed or showed a blue screen",
"answer": "Note down any error code or message shown before it restarts, a photo on your phone is fine. Restart the computer. If it happens more than once, that error code is exactly what IT will need to diagnose it.",
"link": "",
"linkLabel": ""
},
{
"id": 35,
"category": "Security",
"question": "I think I've been hit by ransomware",
"answer": "If files suddenly become inaccessible with strange new extensions, or a ransom note appears, disconnect the device from the network immediately (unplug the cable or turn off wifi) without shutting it down, this can stop it spreading before you power off. Don't pay anything and don't try to remove it yourself, contact IT security immediately, this is treated as a priority incident.",
"link": "",
"linkLabel": ""
},
{
"id": 36,
"category": "Security",
"question": "I suspect my account has been compromised",
"answer": "Change your password immediately from a device you trust, and check for any MFA devices, mail forwarding rules, or app connections you don't recognise, attackers often quietly add a forwarding rule or a second MFA device to keep access even after the password changes. Report it to IT security even after you've changed the password, they may need to check for wider impact.",
"link": "",
"linkLabel": ""
},
{
"id": 37,
"category": "Security",
"question": "What actually makes a strong password or passphrase",
"answer": "Length matters more than complexity, three or four random unrelated words make a passphrase that's both stronger and easier to remember than a short complex one. Never reuse a password across personal and work accounts, and use a password manager rather than trying to remember unique passwords for everything, most organisations provide or approve one.",
"link": "",
"linkLabel": ""
},
{
"id": 38,
"category": "Security",
"question": "How to report a data breach or accidental data exposure",
"answer": "If personal or sensitive information was sent to the wrong person, uploaded somewhere public by mistake, or a device holding such data is lost or stolen, report it to IT and your privacy contact as soon as possible. Timing genuinely matters for breach response, and in government and other regulated sectors there can be mandatory notification obligations attached.",
"link": "https://www.cyber.gov.au/report-and-recover",
"linkLabel": "ACSC: report and recover"
},
{
"id": 39,
"category": "Security",
"question": "Windows is asking for a BitLocker recovery key",
"answer": "This usually appears after a hardware or firmware change, like a BIOS update, a new battery, or a changed boot order, that the encryption chip treats as suspicious, it's the protection working as intended, not a sign of a hack. The 48-digit recovery key is normally stored in your organisation's directory (Azure AD/Intune) or was saved separately when the device was set up, IT can retrieve it if you don't have it yourself. Microsoft itself cannot recover a lost key, so if neither you nor IT can locate it, the drive has to be reset.",
"link": "https://support.microsoft.com/en-us/help/4026181",
"linkLabel": "Microsoft: find your BitLocker recovery key"
},
{
"id": 40,
"category": "Security",
"question": "A Mac is asking for a FileVault recovery key",
"answer": "Similar to Windows BitLocker, this appears after certain hardware or firmware changes and is the encryption protecting your data working as designed. The recovery key is usually escrowed with your organisation's MDM (Jamf or similar), IT can retrieve it if it wasn't saved when the device was set up.",
"link": "",
"linkLabel": ""
},
{
"id": 41,
"category": "Security",
"question": "Antivirus or endpoint protection just quarantined a file or blocked something",
"answer": "Don't try to restore or override it yourself, even if you're confident the file is safe, false positives do happen but confirming that is IT security's job, not yours. Report exactly what you were doing and what the alert said, that detail is what determines whether it's a false positive or something needing wider action.",
"link": "",
"linkLabel": ""
},
{
"id": 42,
"category": "Security",
"question": "A USB drive or device is blocked by policy",
"answer": "Many organisations block USB storage devices entirely as a data-loss-prevention measure, this is deliberate policy rather than a fault, and it usually can't be worked around with a different port or drive. If you have a genuine business need to transfer files this way, request an exception through IT rather than trying another device.",
"link": "",
"linkLabel": ""
},
{
"id": 43,
"category": "Sector notes",
"question": "Why are some settings locked on my device?",
"answer": "Government, school and many corporate devices are deliberately locked down for security, this is policy, not a fault. Australian government agencies generally follow the ACSC's Essential Eight security controls, which is why things like installing your own software or changing certain settings are restricted to IT staff.",
"link": "https://www.cyber.gov.au/resources-business-and-government/essential-cybersecurity/essential-eight",
"linkLabel": "ACSC: Essential Eight explained"
},
{
"id": 44,
"category": "Sector notes",
"question": "School: why is a legitimate website or resource blocked?",
"answer": "Australian schools typically apply internet content filtering as required by state and territory education department policy, and manage student devices through a mobile device management (MDM) system. If a legitimate educational site is blocked, that's a filtering rule, not a fault, report it to the school's IT support so they can review or whitelist it rather than trying to work around the filter.",
"link": "",
"linkLabel": ""
},
{
"id": 45,
"category": "Sector notes",
"question": "Government: why can't I install software myself?",
"answer": "Restricting who can install software (application control) is one of the Essential Eight strategies Australian government agencies are expected to implement, it stops unapproved or malicious software running on government devices. If you need software for a work purpose, the usual path is a request to IT for review and installation through an approved, managed process.",
"link": "https://www.cyber.gov.au/resources-business-and-government/essential-cybersecurity/essential-eight",
"linkLabel": "ACSC: Essential Eight explained"
},
{
"id": 46,
"category": "Sector notes",
"question": "Corporate: why can't I do everything on my personal (BYOD) device?",
"answer": "A personal device enrolled for work access (BYOD) is usually only given a limited, contained work profile rather than full management of the whole device, protecting both your personal data and the organisation's. If a work app or file won't open, or copy-paste out of a work app is blocked, that's often a deliberate BYOD policy restriction rather than a technical fault.",
"link": "",
"linkLabel": ""
},
{
"id": 47,
"category": "How IT support works",
"question": "What do Level 1, 2, 3 (and 4) support actually mean?",
"answer": "Level 1 is the frontline help desk, handling common self-service issues like this page's Access, Wifi and Hardware topics, usually resolved in one call or ticket. Level 2 is more technical staff who handle things needing deeper diagnosis, like the Network Hardware topics here. Level 3 is specialist or senior engineers, often involved in design and complex incidents, and Level 4 is the vendor's own support (Cisco TAC, Fortinet support), brought in when the issue is inside the product itself, not the configuration.",
"link": "",
"linkLabel": ""
},
{
"id": 48,
"category": "How IT support works",
"question": "When should something be escalated to the next level?",
"answer": "As a general rule, escalate when the fix needs a permission, tool, or specialist knowledge the current level doesn't have, not simply because an issue is taking a long time. A good escalation includes what's already been tried, exact error messages, and which users or systems are affected, that context is what actually speeds up the next level's diagnosis.",
"link": "",
"linkLabel": ""
},
{
"id": 49,
"category": "How IT support works",
"question": "What's the difference between an incident, a request, and a problem?",
"answer": "An incident is something broken right now (the printer isn't printing, the VPN is down), the goal is to restore service quickly. A request is asking for something new (new software, more storage, account access), it follows an approval process rather than a fix. A problem is the underlying root cause behind repeated incidents, if the same printer fails every Monday, that pattern gets investigated as a problem so it stops recurring, rather than just fixed each time it happens.",
"link": "",
"linkLabel": ""
},
{
"id": 50,
"category": "How IT support works",
"question": "Where does a change request fit in?",
"answer": "A change request is a planned, deliberate modification to a system, like a firmware upgrade or a new firewall rule, done through an approval process because unplanned changes are one of the most common causes of new incidents. This is why network hardware changes especially are usually scheduled for a maintenance window rather than made on the spot.",
"link": "",
"linkLabel": ""
},
{
"id": 51,
"category": "Mobile & remote work",
"question": "A phone or tablet won't enrol in the company's mobile device management (MDM)",
"answer": "Confirm you're using the exact enrolment method IT specified (a QR code, an enrolment URL, or a specific app store link), a generic 'add work account' option in phone settings sometimes skips steps the proper enrolment method includes. Also check the device's operating system version meets what IT requires, MDM enrolment is commonly blocked on outdated OS versions for security reasons.",
"link": "",
"linkLabel": ""
},
{
"id": 52,
"category": "Mobile & remote work",
"question": "Work email or apps stopped working on a personal phone after an update",
"answer": "A phone OS update can reset app permissions or trigger a compliance re-check by the organisation's MDM, temporarily blocking access until the device is confirmed to still meet security requirements like having a passcode set. Check for a compliance or 'action needed' notification from the company portal app before assuming it's broken.",
"link": "",
"linkLabel": ""
},
{
"id": 53,
"category": "Mobile & remote work",
"question": "A mobile VPN drops every time the screen locks",
"answer": "Many phones aggressively kill background network connections to save battery, including VPN apps, unless the app is specifically excluded from battery optimisation. Check the phone's battery settings for an 'unrestricted' or 'no optimisation' option for that VPN app specifically.",
"link": "",
"linkLabel": ""
},
{
"id": 54,
"category": "Mobile & remote work",
"question": "A remote desktop (RDP) session freezes or won't connect",
"answer": "Confirm you're connected to the VPN first if the remote machine is inside a private network, RDP almost never works over the open internet directly, for good security reasons. If the VPN is connected but it still fails, check whether the remote machine is actually powered on and not asleep, a surprisingly common cause.",
"link": "",
"linkLabel": ""
},
{
"id": 55,
"category": "Mobile & remote work",
"question": "A VDI session (Citrix, Horizon) is slow or won't launch",
"answer": "Test your own internet connection's latency and stability first, VDI performance is very sensitive to a poor home connection in a way a locally installed app isn't. If your connection is fine, try a different VDI client version or a browser-based login as a workaround while reporting the failure to IT with the exact error shown.",
"link": "",
"linkLabel": ""
},
{
"id": 56,
"category": "Mobile & remote work",
"question": "Working from home, the VPN connects but internal apps still time out",
"answer": "Some VPN setups use 'split tunnelling', where only traffic for specific internal systems goes through the VPN and everything else uses your home internet directly, if a newer internal app isn't yet included in that list, it will time out even with the VPN connected. That's a configuration detail for IT to add, not something you can usually fix from your end.",
"link": "",
"linkLabel": ""
},
{
"id": 57,
"category": "Cloud storage & sync",
"question": "OneDrive is stuck on 'processing changes' or won't sync",
"answer": "Pause and resume syncing from the OneDrive icon in the system tray, this resets a stuck sync engine more often than you'd expect. A very long file path, a file open in another program, or special characters in a file name are the next most common causes of a stuck sync. Moving the affected file out of the synced folder and back in again can also clear a single stuck item without resetting the whole sync.",
"link": "https://support.microsoft.com/en-us/onedrive/fix-onedrive-sync-problems",
"linkLabel": "Microsoft: fix OneDrive sync problems"
},
{
"id": 58,
"category": "Cloud storage & sync",
"question": "Google Drive shows a red exclamation mark on a file",
"answer": "This means that specific file failed to sync, usually because it's open in another application, too large for your remaining storage quota, or has a file type or name Drive can't handle. Hover over the icon for the exact reason, then close the file elsewhere or check your storage quota before retrying.",
"link": "",
"linkLabel": ""
},
{
"id": 59,
"category": "Cloud storage & sync",
"question": "Cloud storage quota is full",
"answer": "Check what's actually taking up space first, large video files and old email attachments are common causes, rather than immediately requesting more storage. If you genuinely need more for legitimate work purposes, that's a request rather than an incident (see 'How IT support works'), so it goes through IT's normal approval process.",
"link": "",
"linkLabel": ""
},
{
"id": 60,
"category": "Cloud storage & sync",
"question": "A shared file link says 'access denied' for someone outside the organisation",
"answer": "Many organisations restrict external sharing by default for security, so a link that works fine internally can fail for an outside recipient. Check the specific sharing settings on that file or folder, external sharing is often something that needs to be deliberately enabled per-file or per-site, rather than being on by default.",
"link": "",
"linkLabel": ""
},
{
"id": 61,
"category": "Cloud storage & sync",
"question": "Files show as 'online-only' and won't open without internet",
"answer": "Cloud sync clients often keep infrequently used files as a placeholder to save local disk space, downloading the real content only when opened, which fails without an internet connection. Right-click the specific file or folder you need offline and choose 'always keep on this device' before you lose connectivity, before a flight or a site visit, for example.",
"link": "",
"linkLabel": ""
},
{
"id": 62,
"category": "macOS specific",
"question": "A Mac update is stuck or won't install",
"answer": "Confirm there's enough free disk space, macOS updates need significant free space to stage the install and fail silently without it. Restart once and try again from System Settings rather than clicking install repeatedly, which can leave the updater in a confused state.",
"link": "",
"linkLabel": ""
},
{
"id": 63,
"category": "macOS specific",
"question": "Time Machine backup keeps failing",
"answer": "Check the backup drive isn't full and is actually connected and mounted, an intermittent external drive connection is the most common cause. If backing up to a network location, confirm you can still reach that server or NAS at all, a backup failure is often really a network or permissions issue in disguise.",
"link": "",
"linkLabel": ""
},
{
"id": 64,
"category": "macOS specific",
"question": "A Mac keeps asking for the keychain password unexpectedly",
"answer": "This usually happens after a password change that the login keychain doesn't yet know about, since it's a separate password store from your account login. Go to Keychain Access and update or reset the login keychain's password to match your new account password, rather than repeatedly dismissing the prompt. Resetting the keychain does clear its saved passwords, so only do this if you can't recover the old one.",
"link": "https://support.apple.com/guide/keychain-access/kyca2429/mac",
"linkLabel": "Apple: update your keychain password"
},
{
"id": 65,
"category": "macOS specific",
"question": "A Mac won't join a corporate wifi network with certificate login",
"answer": "Confirm the required certificate is actually installed in the Mac's keychain, it's normally pushed automatically by MDM (Jamf or similar) but can fail to install if the Mac hasn't checked in with MDM recently. Manually forcing an MDM check-in (System Settings > general profile management) before retrying the wifi connection resolves this in many cases.",
"link": "",
"linkLabel": ""
},
{
"id": 66,
"category": "Network hardware (IT staff)",
"question": "A Cisco switch port shows no link light",
"answer": "Start at the physical layer: reseat the cable, try a different port, and check for a bad SFP. Then confirm the port isn't administratively shut down with `show interfaces status`, if it is, `no shutdown` brings it back up.",
"link": "",
"linkLabel": ""
},
{
"id": 67,
"category": "Network hardware (IT staff)",
"question": "A Cisco port went err-disabled",
"answer": "This means the switch shut the port down itself, usually after a security violation, a BPDU guard trip, or a duplex mismatch. Check the reason with `show interfaces status err-disabled`, fix the underlying cause, then cycle the port with `shutdown` then `no shutdown`.",
"link": "",
"linkLabel": ""
},
{
"id": 68,
"category": "Network hardware (IT staff)",
"question": "Devices can't reach each other across a Cisco VLAN or trunk",
"answer": "Confirm the VLAN exists on both switches with `show vlan brief`, then check the trunk with `show interfaces trunk`. A mismatched native VLAN or a VLAN missing from the allowed list is the most common cause.",
"link": "",
"linkLabel": ""
},
{
"id": 69,
"category": "Network hardware (IT staff)",
"question": "A Cisco router or Layer 3 switch can't reach a remote subnet",
"answer": "Check `show ip interface brief` to confirm the interface is up, then `show ip route` to confirm a route exists. `ping` and `traceroute` will show exactly where the path breaks.",
"link": "",
"linkLabel": ""
},
{
"id": 70,
"category": "Network hardware (IT staff)",
"question": "A Cisco device is running hot (high CPU)",
"answer": "Check `show processes cpu sorted` to see what's using it. A spanning-tree loop or broadcast storm is a common cause on switches, `show spanning-tree` will show repeated topology changes if that's happening.",
"link": "",
"linkLabel": ""
},
{
"id": 71,
"category": "Network hardware (IT staff)",
"question": "A FortiGate isn't passing traffic that looks like it should be allowed",
"answer": "Confirm a firewall policy actually matches the source, destination and service, then use `diagnose sniffer packet any 'host x.x.x.x' 4` to see if traffic is arriving, and `diagnose debug flow` to see how the FortiGate is treating it.",
"link": "",
"linkLabel": ""
},
{
"id": 72,
"category": "Network hardware (IT staff)",
"question": "A FortiGate site-to-site IPsec VPN won't come up",
"answer": "Phase 1 and Phase 2 settings (encryption, PSK or certificate, proposals) must match exactly on both ends. `diagnose vpn ike log-filter` with `diagnose debug application ike -1` shows exactly where negotiation is failing.",
"link": "",
"linkLabel": ""
},
{
"id": 73,
"category": "Network hardware (IT staff)",
"question": "A FortiGate is slow or unresponsive",
"answer": "Check `get system performance status` for CPU, memory and session count, and `diagnose sys top` to see which process is responsible. A nearly-full session table is a common cause on busy units.",
"link": "",
"linkLabel": ""
},
{
"id": 74,
"category": "Network hardware (IT staff)",
"question": "Can't reach the FortiGate admin GUI from a particular network",
"answer": "FortiGate can restrict admin access to trusted hosts and specific interfaces. Check the admin account's trusted host settings and confirm the interface you're connecting through has HTTPS/SSH admin access enabled.",
"link": "",
"linkLabel": ""
},
{
"id": 75,
"category": "Network hardware (IT staff)",
"question": "How to safely back up a Cisco device's configuration",
"answer": "Before any change, save the running config to the startup config with `copy running-config startup-config`, then copy it off the device via TFTP or SCP so there's an external copy too. Always confirm the backup completed before making changes.",
"link": "",
"linkLabel": ""
},
{
"id": 76,
"category": "Network hardware (IT staff)",
"question": "How to safely upgrade Cisco IOS firmware",
"answer": "Confirm the new image is supported on the exact hardware model and that there's enough flash and RAM. Copy the image to flash, verify its checksum, set the new boot variable, save the config, then reload in a maintenance window in case it needs rolling back.",
"link": "",
"linkLabel": ""
},
{
"id": 77,
"category": "Network hardware (IT staff)",
"question": "Lost the password to a Cisco device",
"answer": "Password recovery needs physical console access and a reboot into ROMMON mode to bypass the startup config temporarily. This is a standard, well-documented process, but the exact key combination differs by model, check the vendor documentation for your specific device first.",
"link": "https://www.cisco.com/c/en/us/support/index.html",
"linkLabel": "Cisco Support"
},
{
"id": 78,
"category": "Network hardware (IT staff)",
"question": "A wireless access point won't join the Cisco WLC",
"answer": "Check the AP can discover the controller (DHCP option 43, DNS, or same-subnet broadcast), and that the AP's firmware is compatible with the controller's software version, a mismatch is a common cause of a failed join.",
"link": "",
"linkLabel": ""
},
{
"id": 79,
"category": "Network hardware (IT staff)",
"question": "Traffic is blocked on a Cisco ASA despite a matching ACL",
"answer": "Check NAT rules aren't exempting or redirecting the traffic unexpectedly, and confirm the ACL is applied in the right direction on the right interface. `packet-tracer` simulates a specific flow and shows exactly which rule drops it.",
"link": "",
"linkLabel": ""
},
{
"id": 80,
"category": "Network hardware (IT staff)",
"question": "One FortiGate in an HA cluster won't sync",
"answer": "Check both units are running the identical firmware version first, a mismatch is the most common HA sync blocker. `diagnose sys ha status` shows the current sync state and any errors.",
"link": "",
"linkLabel": ""
},
{
"id": 81,
"category": "Network hardware (IT staff)",
"question": "A FortiSwitch isn't showing up under FortiGate management",
"answer": "FortiGate manages FortiSwitches over FortiLink, confirm the FortiLink interface is correctly configured and that the switch port used for FortiLink hasn't been repurposed for something else.",
"link": "",
"linkLabel": ""
},
{
"id": 82,
"category": "Network hardware (IT staff)",
"question": "A FortiAP won't join its FortiGate",
"answer": "Confirm the AP can discover the FortiGate (same subnet, or DHCP option 138/CAPWAP discovery across routed networks) and that the AP and FortiGate firmware are a supported combination.",
"link": "",
"linkLabel": ""
},
{
"id": 83,
"category": "Network hardware (IT staff)",
"question": "SD-WAN traffic is taking the wrong path on a FortiGate",
"answer": "Check the SD-WAN rule order, first match wins, and whether the SLA health checks for that link are actually passing, a failed health check silently removes a path from consideration. `diagnose sys sdwan` shows live link status.",
"link": "",
"linkLabel": ""
},
{
"id": 84,
"category": "Network hardware (IT staff)",
"question": "A FortiGate says its licence or support contract has expired",
"answer": "An expired contract stops signature and firmware updates but doesn't usually stop the firewall passing traffic. Check the exact status with `get system status`, then renew through your reseller or Fortinet, running without updates for long is a real security risk.",
"link": "",
"linkLabel": ""
},
{
"id": 85,
"category": "Network hardware (IT staff)",
"question": "Where to find full Cisco documentation and command syntax",
"answer": "Always confirm exact command syntax against Cisco's own docs, it changes between switch/router models and IOS versions.",
"link": "https://www.cisco.com/c/en/us/support/index.html",
"linkLabel": "Cisco Support"
},
{
"id": 86,
"category": "Network hardware (IT staff)",
"question": "Where to find full Fortinet documentation and command syntax",
"answer": "FortiOS CLI commands and defaults vary by firmware version, the official Fortinet Document Library is the source of truth.",
"link": "https://docs.fortinet.com/",
"linkLabel": "Fortinet Document Library"
},
{
"id": 87,
"category": "Network hardware (IT staff)",
"question": "An IPsec tunnel looks correctly configured but still won't come up",
"answer": "When the config looks right on paper, checking the live IKE negotiation logs tells you more than re-checking the configuration a third time. Fortinet's own support community has a detailed walkthrough of the exact `diagnose` commands and log filters their engineers use for exactly this scenario.",
"link": "https://community.fortinet.com/t5/FortiGate/Troubleshooting-Tip-IPsec-VPN-tunnels/ta-p/195955",
"linkLabel": "Fortinet Community: IPsec VPN troubleshooting"
}
]
-37
View File
@@ -1,37 +0,0 @@
@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
.liquid-glass {
background: rgba(255, 255, 255, 0.01);
background-blend-mode: luminosity;
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: none;
box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.1);
position: relative;
overflow: hidden;
}
.liquid-glass::before {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
padding: 1.4px;
background: linear-gradient(
180deg,
rgba(255, 255, 255, 0.45) 0%,
rgba(255, 255, 255, 0.15) 20%,
rgba(255, 255, 255, 0) 40%,
rgba(255, 255, 255, 0) 60%,
rgba(255, 255, 255, 0.15) 80%,
rgba(255, 255, 255, 0.45) 100%
);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
-10
View File
@@ -1,10 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
-17
View File
@@ -1,17 +0,0 @@
// Safe wrappers: localStorage can be blocked (private mode), so never let it crash the page.
export function load<T>(key: string, fallback: T): T {
try {
const raw = localStorage.getItem(key)
return raw ? (JSON.parse(raw) as T) : fallback
} catch {
return fallback
}
}
export function save(key: string, value: unknown): void {
try {
localStorage.setItem(key, JSON.stringify(value))
} catch {
/* ignore */
}
}
-8
View File
@@ -1,8 +0,0 @@
export interface Faq {
id: number
category: string
question: string
answer: string
link: string
linkLabel: string
}
-1
View File
@@ -1 +0,0 @@
/// <reference types="vite/client" />
-6
View File
@@ -1,6 +0,0 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: { extend: {} },
plugins: [],
}
-15
View File
@@ -1,15 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true
},
"include": ["src", "vite.config.ts"]
}
-1
View File
@@ -1 +0,0 @@
{"root":["./src/App.tsx","./src/ContactForm.tsx","./src/Faq.tsx","./src/Staff.tsx","./src/VideoBackground.tsx","./src/main.tsx","./src/storage.ts","./src/types.ts","./src/vite-env.d.ts","./vite.config.ts"],"version":"5.6.3"}
-8
View File
@@ -1,8 +0,0 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: './',
server: { proxy: { '/api': 'http://localhost:3001' } },
})
-11
View File
@@ -1,11 +0,0 @@
{
"name": "cycle-atlas-root",
"private": true,
"version": "1.0.0",
"description": "Root wrapper so hosts can build and start the IT Support site in it-support/",
"engines": { "node": ">=22.13" },
"scripts": {
"build": "npm --prefix it-support install --include=dev && npm --prefix it-support run build",
"start": "NODE_ENV=production node it-support/server/index.js"
}
}
+151
View File
@@ -0,0 +1,151 @@
/* CycleWise AU - 3D cycle ring (Step 2).
Draws the same four phase arcs as the flat SVG ring, in 3D.
The page code sends the numbers via the "cycle:ring" event.
If WebGL is missing or anything fails, the flat ring stays visible. */
(function(){
"use strict";
function start(){
try {
if (!window.THREE) return;
var art = document.getElementById("phase-arc-menstrual");
art = art && art.closest(".hero-art");
if (!art) return;
var reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
var svg = art.querySelector("svg");
var canvas = document.createElement("canvas");
canvas.setAttribute("aria-hidden", "true");
canvas.className = "ring3d";
var renderer;
try { renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true, alpha: true}); }
catch(e){ return; } // no WebGL: keep the flat ring
var R = 1, TUBE = 0.085;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(30, 1, 0.1, 20);
camera.position.set(0, 0, 5.2);
scene.add(new THREE.AmbientLight(0xffffff, 0.75));
var sun = new THREE.DirectionalLight(0xffffff, 1.1);
sun.position.set(2, 3, 4);
scene.add(sun);
var group = new THREE.Group();
scene.add(group);
function cssColor(name){
var v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return new THREE.Color(v || "#888888");
}
function point(deg, r){
var a = deg * Math.PI / 180; // 0 deg = top, clockwise
return new THREE.Vector3(Math.sin(a) * r, Math.cos(a) * r, 0);
}
class ArcCurve extends THREE.Curve {
constructor(a0, a1){ super(); this.a0 = a0; this.a1 = a1; }
getPoint(t, target){
return (target || new THREE.Vector3()).copy(point(this.a0 + (this.a1 - this.a0) * t, R));
}
}
var data = window.cycleRingData || null;
var meshes = [];
function clear(){
meshes.forEach(function(m){
group.remove(m); m.geometry.dispose(); m.material.dispose();
});
meshes = [];
}
function add(mesh){ group.add(mesh); meshes.push(mesh); }
function mat(c){ return new THREE.MeshStandardMaterial({color: c, roughness: 0.45, metalness: 0.05}); }
function build(){
clear();
if (!data) return;
var cols = {
menstrual: cssColor("--period"),
follicular: cssColor("--ovulation-soft"),
fertile: cssColor("--fertile"),
luteal: cssColor("--pregnancy-soft"),
ink: cssColor("--ink")
};
var arcs = [
[0, data.perEnd, cols.menstrual],
[data.perEnd, data.fertStart, cols.follicular],
[data.fertStart, data.fertEnd, cols.fertile],
[data.lutStart, 360, cols.luteal]
];
arcs.forEach(function(a){
var end = Math.max(a[1], a[0] + 0.5);
var tube = new THREE.Mesh(new THREE.TubeGeometry(new ArcCurve(a[0], end), 48, TUBE, 16, false), mat(a[2]));
add(tube);
[a[0], end].forEach(function(deg){ // round end caps
var cap = new THREE.Mesh(new THREE.SphereGeometry(TUBE, 16, 12), mat(a[2]));
cap.position.copy(point(deg, R));
add(cap);
});
});
var marker = new THREE.Mesh(new THREE.SphereGeometry(TUBE * 1.9, 24, 16), mat(cols.ink));
marker.position.copy(point(data.todayAngle, R));
marker.position.z = TUBE * 0.6;
add(marker);
}
function resize(){
var w = svg.getBoundingClientRect().width || 220;
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(w, w, false);
canvas.style.width = canvas.style.height = w + "px";
}
var visible = false, raf = 0;
function frame(t){
raf = 0;
var s = t / 1000;
group.rotation.x = -0.55 + (reduce ? 0 : Math.sin(s * 0.6) * 0.12);
group.rotation.y = reduce ? 0.25 : Math.sin(s * 0.4) * 0.45;
renderer.render(scene, camera);
if (visible && !reduce) raf = requestAnimationFrame(frame);
}
function kick(){ if (!raf) raf = requestAnimationFrame(frame); }
// Show the 3D ring; hide the flat arcs but keep the "CYCLE DAY" text.
art.classList.add("has-3d");
art.insertBefore(canvas, svg);
resize();
build();
kick();
window.addEventListener("cycle:ring", function(e){ data = e.detail; build(); kick(); });
window.addEventListener("resize", function(){ resize(); kick(); });
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", function(){ build(); kick(); });
// Only animate while the ring is actually on screen (saves battery).
new IntersectionObserver(function(entries){
visible = entries[0].isIntersecting;
if (visible) { resize(); kick(); }
}).observe(canvas);
} catch(err) {
// Anything went wrong: leave the flat ring alone.
var c = document.querySelector(".ring3d"); if (c) c.remove();
var h = document.querySelector(".hero-art.has-3d"); if (h) h.classList.remove("has-3d");
if (window.console) console.warn("3D ring disabled:", err && err.message);
}
}
// three.js is big: fetch it only after the page is up, so the page shows first.
function loadThree(){
var tag = document.createElement("script");
tag.src = "vendor/three.min.js";
tag.onload = start;
document.head.appendChild(tag);
}
function schedule(){
if (window.THREE) { start(); }
else if (window.requestIdleCallback) { requestIdleCallback(loadThree, {timeout: 2000}); }
else { setTimeout(loadThree, 300); }
}
if (document.readyState === "complete") schedule();
else window.addEventListener("load", schedule);
})();
+68
View File
@@ -0,0 +1,68 @@
/* CycleWise AU - pregnancy timeline motion (Step 3).
- The week slider's track fills with colour up to the current week.
It grows the first time you scroll to it, then follows every week change.
- The baby-size picture pops a little when the week changes.
- The 40 week buttons wave in the first time they appear.
Cosmetic only: without GSAP the slider simply shows its normal look. */
(function(){
"use strict";
var slider = document.getElementById("week-slider");
var badge = document.getElementById("wk-badge");
if (!slider || !badge) return;
var hasGsap = !!window.gsap;
var reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
var animate = hasGsap && !reduce;
var fill = { f: 0 };
var target = 0;
var introDone = false;
function paint(){ slider.style.setProperty("--f", fill.f.toFixed(4)); }
function currentWeek(){
var n = parseInt((badge.textContent || "").replace(/\D/g, ""), 10);
return isNaN(n) ? (parseInt(slider.value, 10) || 1) : Math.max(1, Math.min(40, n));
}
function goTo(f){
target = f;
if (!introDone) return; // wait until the slider is on screen
if (!animate) { fill.f = f; paint(); return; }
gsap.to(fill, { f: f, duration: 0.6, ease: "power2.out", overwrite: true, onUpdate: paint });
}
// Follow every week change, whether from the slider, a week button or the calendar.
var lastWeek = currentWeek();
target = (lastWeek - 1) / 39;
new MutationObserver(function(){
var w = currentWeek();
if (w === lastWeek) return;
lastWeek = w;
goTo((w - 1) / 39);
var blob = document.querySelector("#wk-blob svg");
if (animate && blob) {
gsap.fromTo(blob, { scale: 0.8, transformOrigin: "50% 50%" },
{ scale: 1, duration: 0.5, ease: "back.out(2)", clearProps: "transform" });
}
}).observe(badge, { childList: true, characterData: true, subtree: true });
// First time the slider is visible: grow the fill from empty up to this week.
new IntersectionObserver(function(entries, obs){
if (!entries[0].isIntersecting) return;
obs.disconnect();
introDone = true;
if (!animate) { fill.f = target; paint(); return; }
gsap.to(fill, { f: target, duration: 1.2, ease: "power2.out", onUpdate: paint });
}).observe(slider);
// First time the week buttons are visible: wave them in.
var strip = document.getElementById("week-filmstrip");
if (strip && animate) {
new IntersectionObserver(function(entries, obs){
if (!entries[0].isIntersecting) return;
obs.disconnect();
gsap.from(strip.querySelectorAll(".film-item"), {
opacity: 0, scale: 0.8, duration: 0.4, stagger: 0.02, ease: "power2.out", clearProps: "all"
});
}).observe(strip);
}
})();
+11
View File
@@ -0,0 +1,11 @@
/*!
* ScrollTrigger 3.12.5
* https://gsap.com
*
* @license Copyright 2024, GreenSock. All rights reserved.
* Subject to the terms at https://gsap.com/standard-license or for Club GSAP members, the agreement issued with that membership.
* @author: Jack Doyle, jack@greensock.com
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).window=e.window||{})}(this,function(e){"use strict";function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function r(){return Ce||"undefined"!=typeof window&&(Ce=window.gsap)&&Ce.registerPlugin&&Ce}function z(e,t){return~Le.indexOf(e)&&Le[Le.indexOf(e)+1][t]}function A(e){return!!~t.indexOf(e)}function B(e,t,r,n,o){return e.addEventListener(t,r,{passive:!1!==n,capture:!!o})}function C(e,t,r,n){return e.removeEventListener(t,r,!!n)}function F(){return De&&De.isPressed||Ie.cache++}function G(r,n){function dd(e){if(e||0===e){o&&(Se.history.scrollRestoration="manual");var t=De&&De.isPressed;e=dd.v=Math.round(e)||(De&&De.iOS?1:0),r(e),dd.cacheID=Ie.cache,t&&i("ss",e)}else(n||Ie.cache!==dd.cacheID||i("ref"))&&(dd.cacheID=Ie.cache,dd.v=r());return dd.v+dd.offset}return dd.offset=0,r&&dd}function J(e,t){return(t&&t._ctx&&t._ctx.selector||Ce.utils.toArray)(e)[0]||("string"==typeof e&&!1!==Ce.config().nullTargetWarn?console.warn("Element not found:",e):null)}function K(t,e){var r=e.s,n=e.sc;A(t)&&(t=ke.scrollingElement||Pe);var o=Ie.indexOf(t),i=n===Fe.sc?1:2;~o||(o=Ie.push(t)-1),Ie[o+i]||B(t,"scroll",F);var a=Ie[o+i],s=a||(Ie[o+i]=G(z(t,r),!0)||(A(t)?n:G(function(e){return arguments.length?t[r]=e:t[r]})));return s.target=t,a||(s.smooth="smooth"===Ce.getProperty(t,"scrollBehavior")),s}function L(e,t,o){function Cd(e,t){var r=ze();t||n<r-s?(a=i,i=e,l=s,s=r):o?i+=e:i=a+(e-a)/(r-l)*(s-l)}var i=e,a=e,s=ze(),l=s,n=t||50,c=Math.max(500,3*n);return{update:Cd,reset:function reset(){a=i=o?0:i,l=s=0},getVelocity:function getVelocity(e){var t=l,r=a,n=ze();return!e&&0!==e||e===i||Cd(e),s===l||c<n-l?0:(i+(o?r:-r))/((o?n:s)-t)*1e3}}}function M(e,t){return t&&!e._gsapAllow&&e.preventDefault(),e.changedTouches?e.changedTouches[0]:e}function N(e){var t=Math.max.apply(Math,e),r=Math.min.apply(Math,e);return Math.abs(t)>=Math.abs(r)?t:r}function O(){(Ae=Ce.core.globals().ScrollTrigger)&&Ae.core&&function _integrate(){var e=Ae.core,r=e.bridge||{},t=e._scrollers,n=e._proxies;t.push.apply(t,Ie),n.push.apply(n,Le),Ie=t,Le=n,i=function _bridge(e,t){return r[e](t)}}()}function P(e){return Ce=e||r(),!Te&&Ce&&"undefined"!=typeof document&&document.body&&(Se=window,Pe=(ke=document).documentElement,Me=ke.body,t=[Se,ke,Pe,Me],Ce.utils.clamp,Be=Ce.core.context||function(){},Oe="onpointerenter"in Me?"pointer":"mouse",Ee=k.isTouch=Se.matchMedia&&Se.matchMedia("(hover: none), (pointer: coarse)").matches?1:"ontouchstart"in Se||0<navigator.maxTouchPoints||0<navigator.msMaxTouchPoints?2:0,Re=k.eventTypes=("ontouchstart"in Pe?"touchstart,touchmove,touchcancel,touchend":"onpointerdown"in Pe?"pointerdown,pointermove,pointercancel,pointerup":"mousedown,mousemove,mouseup,mouseup").split(","),setTimeout(function(){return o=0},500),O(),Te=1),Te}var Ce,Te,Se,ke,Pe,Me,Ee,Oe,Ae,t,De,Re,Be,o=1,qe=[],Ie=[],Le=[],ze=Date.now,i=function _bridge(e,t){return t},n="scrollLeft",a="scrollTop",Ye={s:n,p:"left",p2:"Left",os:"right",os2:"Right",d:"width",d2:"Width",a:"x",sc:G(function(e){return arguments.length?Se.scrollTo(e,Fe.sc()):Se.pageXOffset||ke[n]||Pe[n]||Me[n]||0})},Fe={s:a,p:"top",p2:"Top",os:"bottom",os2:"Bottom",d:"height",d2:"Height",a:"y",op:Ye,sc:G(function(e){return arguments.length?Se.scrollTo(Ye.sc(),e):Se.pageYOffset||ke[a]||Pe[a]||Me[a]||0})};Ye.op=Fe,Ie.cache=0;var k=(Observer.prototype.init=function init(e){Te||P(Ce)||console.warn("Please gsap.registerPlugin(Observer)"),Ae||O();var o=e.tolerance,a=e.dragMinimum,t=e.type,i=e.target,r=e.lineHeight,n=e.debounce,s=e.preventDefault,l=e.onStop,c=e.onStopDelay,u=e.ignore,f=e.wheelSpeed,d=e.event,p=e.onDragStart,g=e.onDragEnd,h=e.onDrag,v=e.onPress,b=e.onRelease,m=e.onRight,y=e.onLeft,x=e.onUp,w=e.onDown,_=e.onChangeX,T=e.onChangeY,S=e.onChange,k=e.onToggleX,E=e.onToggleY,D=e.onHover,R=e.onHoverEnd,q=e.onMove,I=e.ignoreCheck,z=e.isNormalizer,Y=e.onGestureStart,H=e.onGestureEnd,X=e.onWheel,W=e.onEnable,V=e.onDisable,U=e.onClick,j=e.scrollSpeed,G=e.capture,Q=e.allowClicks,Z=e.lockAxis,$=e.onLockAxis;function cf(){return xe=ze()}function df(e,t){return(se.event=e)&&u&&~u.indexOf(e.target)||t&&he&&"touch"!==e.pointerType||I&&I(e,t)}function ff(){var e=se.deltaX=N(me),t=se.deltaY=N(ye),r=Math.abs(e)>=o,n=Math.abs(t)>=o;S&&(r||n)&&S(se,e,t,me,ye),r&&(m&&0<se.deltaX&&m(se),y&&se.deltaX<0&&y(se),_&&_(se),k&&se.deltaX<0!=le<0&&k(se),le=se.deltaX,me[0]=me[1]=me[2]=0),n&&(w&&0<se.deltaY&&w(se),x&&se.deltaY<0&&x(se),T&&T(se),E&&se.deltaY<0!=ce<0&&E(se),ce=se.deltaY,ye[0]=ye[1]=ye[2]=0),(ne||re)&&(q&&q(se),re&&(h(se),re=!1),ne=!1),ie&&!(ie=!1)&&$&&$(se),oe&&(X(se),oe=!1),ee=0}function gf(e,t,r){me[r]+=e,ye[r]+=t,se._vx.update(e),se._vy.update(t),n?ee=ee||requestAnimationFrame(ff):ff()}function hf(e,t){Z&&!ae&&(se.axis=ae=Math.abs(e)>Math.abs(t)?"xLine truncated
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2023 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+11
View File
@@ -0,0 +1,11 @@
/*!
* GSAP 3.12.5
* https://gsap.com
*
* @license Copyright 2024, GreenSock. All rights reserved.
* Subject to the terms at https://gsap.com/standard-license or for Club GSAP members, the agreement issued with that membership.
* @author: Jack Doyle, jack@greensock.com
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).window=t.window||{})}(this,function(e){"use strict";function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),(t.prototype.constructor=t).__proto__=e}function _assertThisInitialized(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function r(t){return"string"==typeof t}function s(t){return"function"==typeof t}function t(t){return"number"==typeof t}function u(t){return void 0===t}function v(t){return"object"==typeof t}function w(t){return!1!==t}function x(){return"undefined"!=typeof window}function y(t){return s(t)||r(t)}function P(t){return(i=yt(t,ot))&&ze}function Q(t,e){return console.warn("Invalid property",t,"set to",e,"Missing plugin? gsap.registerPlugin()")}function R(t,e){return!e&&console.warn(t)}function S(t,e){return t&&(ot[t]=e)&&i&&(i[t]=e)||ot}function T(){return 0}function ea(t){var e,r,i=t[0];if(v(i)||s(i)||(t=[t]),!(e=(i._gsap||{}).harness)){for(r=gt.length;r--&&!gt[r].targetTest(i););e=gt[r]}for(r=t.length;r--;)t[r]&&(t[r]._gsap||(t[r]._gsap=new Vt(t[r],e)))||t.splice(r,1);return t}function fa(t){return t._gsap||ea(Mt(t))[0]._gsap}function ga(t,e,r){return(r=t[e])&&s(r)?t[e]():u(r)&&t.getAttribute&&t.getAttribute(e)||r}function ha(t,e){return(t=t.split(",")).forEach(e)||t}function ia(t){return Math.round(1e5*t)/1e5||0}function ja(t){return Math.round(1e7*t)/1e7||0}function ka(t,e){var r=e.charAt(0),i=parseFloat(e.substr(2));return t=parseFloat(t),"+"===r?t+i:"-"===r?t-i:"*"===r?t*i:t/i}function la(t,e){for(var r=e.length,i=0;t.indexOf(e[i])<0&&++i<r;);return i<r}function ma(){var t,e,r=dt.length,i=dt.slice(0);for(ct={},t=dt.length=0;t<r;t++)(e=i[t])&&e._lazy&&(e.render(e._lazy[0],e._lazy[1],!0)._lazy=0)}function na(t,e,r,i){dt.length&&!L&&ma(),t.render(e,r,i||L&&e<0&&(t._initted||t._startAt)),dt.length&&!L&&ma()}function oa(t){var e=parseFloat(t);return(e||0===e)&&(t+"").match(at).length<2?e:r(t)?t.trim():t}function pa(t){return t}function qa(t,e){for(var r in e)r in t||(t[r]=e[r]);return t}function ta(t,e){for(var r in e)"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&(t[r]=v(e[r])?ta(t[r]||(t[r]={}),e[r]):e[r]);return t}function ua(t,e){var r,i={};for(r in t)r in e||(i[r]=t[r]);return i}function va(t){var e=t.parent||I,r=t.keyframes?function _setKeyframeDefaults(i){return function(t,e){for(var r in e)r in t||"duration"===r&&i||"ease"===r||(t[r]=e[r])}}(Z(t.keyframes)):qa;if(w(t.inherit))for(;e;)r(t,e.vars.defaults),e=e.parent||e._dp;return t}function xa(t,e,r,i,n){void 0===r&&(r="_first"),void 0===i&&(i="_last");var a,s=t[i];if(n)for(a=e[n];s&&s[n]>a;)s=s._prev;return s?(e._next=s._next,s._next=e):(e._next=t[r],t[r]=e),e._next?e._next._prev=e:t[i]=e,e._prev=s,e.parent=e._dp=t,e}function ya(t,e,r,i){void 0===r&&(r="_first"),void 0===i&&(i="_last");var n=e._prev,a=e._next;n?n._next=a:t[r]===e&&(t[r]=a),a?a._prev=n:t[i]===e&&(t[i]=n),e._next=e._prev=e.parent=null}function za(t,e){t.parent&&(!e||t.parent.autoRemoveChildren)&&t.parent.remove&&t.parent.remove(t),t._act=0}function Aa(t,e){if(t&&(!e||e._end>t._dur||e._start<0))for(var r=t;r;)r._dirty=1,r=r.parent;return t}function Ca(t,e,r,i){return t._startAt&&(L?t._startAt.revert(ht):t.vars.immediateRender&&!t.vars.autoRevert||t._startAt.render(e,!0,i))}function Ea(t){return t._repeat?Tt(t._tTime,t=t.duration()+t._rDelay)*t:0}function Ga(t,e){return(t-e._start)*e._ts+(0<=e._ts?0:e._dirty?e.totalDuration():e._tDur)}function Ha(t){return t._end=ja(t._start+(t._tDur/Math.abs(t._ts||t._rts||X)||0))}function Ia(t,e){var r=t._dp;return r&&r.smoothChildTiming&&t._ts&&(t._start=ja(r._time-(0<t._ts?e/t._ts:((t._dirty?t.totalDuration():t._tDur)-e)/-t._ts)),Ha(t),r._dirty||Aa(r,t)),t}function Ja(t,e){var r;if((e._time||!e._dur&&e._initted||e._start<t._time&&(e._dur||!e.add))&&(r=Ga(t.rawTime(),e),(!e._dur||Ot(0,e.totalDuration(),r)-e._tTime>X)&&e.render(r,!0)),Aa(t,e)._dp&&t._initted&&t._time>=t._dur&&t._ts){if(t._dur<t.duration())for(r=t;r._dp;)0<=r.rawTime()&&r.totalTime(r._tTime),r=r._dp;t._zTime=-X}}function Ka(e,r,i,n){return r.parent&&za(r),r._start=ja((t(i)?i:i||e!==I?xt(e,i,r):e._time)+r._delay),r._end=ja(r._start+(r.totalDuration()/Math.abs(r.timeScale())||0)),xa(e,r,"_first","_last",e._sort?"_start":0),bt(r)||(e._recent=r),n||Ja(e,r),e._ts<0&&Ia(e,e._tTime),e}function La(t,e){return(ot.ScrollTrigger||Q("scrollTrigger",e))&&ot.ScrollTrigger.create(e,t)}function Ma(t,e,r,i,n){return Qt(t,e,n),t._initted?!r&&t._pt&&!L&&(t._dur&&!1!==t.vars.lazy||!t._dur&&t.vars.lazy)&&f!==Rt.frame?(dt.push(t),t._lazy=[n,i],1):void 0:1}function Ra(t,e,r,i){var n=t._repeat,a=ja(e)||0,s=t._tTime/t._tDur;return s&&!i&&(t._time*=a/t._dur),t._dur=a,t._tDur=n?n<0?1e10:ja(a*(n+1)+t._rDelay*n):a,0<s&&!i&&Ia(t,t._tTime=t._tDur*s),t.parent&&Ha(t),r||Aa(t.parent,t),t}function Sa(t){return t instanceof Xt?Aa(t):Ra(t,t._dur)}function Va(e,r,i){var n,aLine truncated
+7
View File
@@ -0,0 +1,7 @@
console.warn('Scripts "build/three.js" and "build/three.min.js" are deprecated with r150+, and will be removed with r160. Please use ES Modules or alternatives: https://threejs.org/docs/index.html#manual/en/introduction/Installation'),
/**
* @license
* Copyright 2010-2023 Three.js Authors
* SPDX-License-Identifier: MIT
*/
function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).THREE={})}(this,(function(t){"use strict";const e="160",n=1,i=2,r=3,s=0,a=1,o=100,l=204,c=205,h=0,u=1,d=2,p=0,m=1,f=2,g=3,_=4,v=5,x=6,y="attached",M="detached",S=300,b=301,T=302,E=303,w=304,A=306,R=1e3,C=1001,L=1002,P=1003,I=1004,U=1005,D=1006,N=1007,O=1008,F=1009,B=1012,z=1013,G=1014,H=1015,V=1016,k=1017,W=1018,X=1020,j=1023,q=1026,Y=1027,Z=1029,J=1031,K=1033,$=33776,Q=33777,tt=33778,et=33779,nt=35840,it=35841,rt=35842,st=35843,at=36196,ot=37492,lt=37496,ct=37808,ht=37809,ut=37810,dt=37811,pt=37812,mt=37813,ft=37814,gt=37815,_t=37816,vt=37817,xt=37818,yt=37819,Mt=37820,St=37821,bt=36492,Tt=36494,Et=36495,wt=36284,At=36285,Rt=36286,Ct=2300,Lt=2301,Pt=2302,It=2400,Ut=2401,Dt=2402,Nt=2500,Ot=2501,Ft=3e3,Bt=3001,zt="",Gt="srgb",Ht="srgb-linear",Vt="display-p3",kt="display-p3-linear",Wt="linear",Xt="srgb",jt="rec709",qt="p3",Yt=7680,Zt=35044,Jt="300 es",Kt=1035,$t=2e3,Qt=2001;class te{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e<i;e++)n[e].call(this,t);t.target=null}}}const ee=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let ne=1234567;const ie=Math.PI/180,re=180/Math.PI;function se(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(ee[255&t]+ee[t>>8&255]+ee[t>>16&255]+ee[t>>24&255]+"-"+ee[255&e]+ee[e>>8&255]+"-"+ee[e>>16&15|64]+ee[e>>24&255]+"-"+ee[63&n|128]+ee[n>>8&255]+"-"+ee[n>>16&255]+ee[n>>24&255]+ee[255&i]+ee[i>>8&255]+ee[i>>16&255]+ee[i>>24&255]).toLowerCase()}function ae(t,e,n){return Math.max(e,Math.min(n,t))}function oe(t,e){return(t%e+e)%e}function le(t,e,n){return(1-n)*t+n*e}function ce(t){return 0==(t&t-1)&&0!==t}function he(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function ue(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function de(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const pe={DEG2RAD:ie,RAD2DEG:re,generateUUID:se,clamp:ae,euclideanModulo:oe,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:le,damp:function(t,e,n,i){return le(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(oe(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatLine truncated