diff --git a/README.md b/README.md index 8572bfef..926916da 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - `account/account.js`: optional Google sign-in, added to every page with the shared top bar. Uses the `rumblekarts` Firebase project (same as the analytics and the Back Room games). Signed-in visitors get a row in Firestore `members/{uid}` (name, email, photo, first/last visit, page count and the analytics visitor IDs of their browsers), which the analytics dashboard shows under Signed-in visitors. The Back Room games reuse a signed-in account instead of switching to an anonymous one. - `site.css`: styles shared by the home, Web Development Projects and Productivity pages - `theme.js`: the site's light/dark switch, with three choices: Auto (follow the device's light or dark mode, the default), Light and Dark. Loaded with a plain `` in the ``, just before the stylesheet (not deferred, so it runs before the page is drawn and there's no flash), by every page that uses `site.css` and nothing else of its own for colours (home, Web Development Projects, Productivity, Engineering Projects, Marketplace, About, Project Daedalus, the Docket, Prompted, Boxed and Hype Cycle Exchange guides), by Docket and Prompted, the Back Room page, the phone page and the showcase landing page (which has no top bar, so no switch; it follows the choice made on any other page). **The switch** is one small button showing the current choice (half circle, sun or moon) that opens a menu with the three; theme.js puts it at the end of the page's `.topbar` by itself (its menu opens leftwards, or rightwards when the top bar has wrapped it to the left edge, as on a phone held sideways), right after the Sign in button (so `account/` is unchanged), which makes it the same place on every page with the top bar, the Back Room included; any other empty element with `data-theme-switch` is filled in too (the phone page has one in its header, since it has no top bar). **Storage:** localStorage `theme` (`light` or `dark`; removed for Auto), so the choice carries to every page; pages already open in other tabs, and pages inside frames (the home page's phone-version frame), follow a change straight away through the `storage` event. Nothing is stored online. **How the CSS follows it:** an explicit choice puts `data-theme="light"` or `data-theme="dark"` on ``, and Auto leaves it off. Each dark-mode block is written twice: inside `@media (prefers-color-scheme: dark)` as `:root:not([data-theme="light"])` (Auto, or Dark on a dark device), and again as `:root[data-theme="dark"]` (Dark on a light device). That's how `site.css`, `games.css`, Docket and Prompted do it; the phone page is dark by itself, so it does the opposite with its light look. A new page that uses `site.css` only needs the script line; a page with its own dark colours needs both blocks too. The shared Back Room scripts that add their own styles (party.js, avatar.js, miles.js, leaderboard.js, news.js, social.js, account-nudge.js, events.js, feedback.js and the rest) take their colours from the page's variables, so they follow without changes. `SiteTheme.get()` / `.set('auto'|'light'|'dark')` / `.wire(el)`, and a `site-theme` event on `window` after a change (seasons.js redoes its seasonal tint on it). **Pages that don't follow it** keep their own look: every game (each has its own fixed look, light or dark), the Daily Puzzles page, the admin page, and the pages that follow the device with their own CSS only: Boxed, Hype Cycle Exchange, the analytics dashboard and the privacy policy. -- `offline.js`, `sw.js`, `offline.html`: offline mode (version 2). `offline.js` (a deferred ` - - - - - - - - - - -
- - - -
-
- - -
-

Loading 36,000 films…

- -
- - - - -
- - - - diff --git a/movi/js/api/demo.js b/movi/js/api/demo.js deleted file mode 100644 index c53c63c8..00000000 --- a/movi/js/api/demo.js +++ /dev/null @@ -1,466 +0,0 @@ -// Demo backend: same contract as api/supabase.js, stored in this browser's localStorage. -// It seeds a small fictional community so the social side of Movi can be tried without a server. -import { allFilms, genres } from "../films.js"; -import { scoreFor, ORDER } from "../model.js"; -import { rng } from "../util.js"; - -const KEY = "movi.demo.world.v1"; -const SESSION = "movi.demo.session"; -const DAY = 86400000; - -const PEOPLE = [ - ["maya.watches", "Maya Ortiz", "Horror lifer. If it has a final girl, I've seen it.", 350, ["Horror", "Thriller", "Supernatural", "Slasher"], 0], - ["deshawn.films", "DeShawn Carter", "Big screen, big explosions, bigger popcorn.", 210, ["Action", "Superhero", "Adventure"], 0], - ["priya.reels", "Priya Nair", "Romance apologist. Will cry at anything with a good score.", 330, ["Romance", "Drama", "Musical"], 0], - ["theo.cinema", "Theo Lindqvist", "Mostly black and white. Occasionally color.", 30, ["Noir", "Drama", "Western", "Crime"], -1], - ["lucia.frames", "Lucía Romero", "Animation is cinema.", 280, ["Animated", "Family", "Fantasy"], 0], - ["kenji.screens", "Kenji Watanabe", "Space, time, and everything in between.", 190, ["Science Fiction", "Adventure", "Thriller"], 0], - ["amara.reviews", "Amara Okafor", "Tough grader. A 9 from me means something.", 0, ["Drama", "Biography", "Historical"], 1], - ["sam.popcorn", "Sam Rivera", "Here for a good laugh and a better snack.", 50, ["Comedy", "Teen", "Family"], 0], - ["noor.nightly", "Noor Haddad", "Whodunits, heists and slow-burn mysteries.", 260, ["Mystery", "Crime", "Thriller"], 0], - ["jules.indie", "Jules Moreau", "Private account. Festival circuit regular.", 160, ["Independent", "Drama", "Comedy"], 1, true], -]; - -const NOTES = { - loved: ["Instant all-timer.", "Rewatched and it hits even harder.", "The score alone is worth it.", "Couldn't stop thinking about it for days.", "Pure cinema.", "Every frame could be a painting.", "Saw it in a packed theater. Unforgettable.", "Better than I remembered."], - fine: ["Solid, but the third act dragged.", "Fun enough for a Sunday.", "Great cast, messy script.", "Some great scenes, didn't fully land for me.", "Worth it for the visuals alone."], - disliked: ["Not for me at all.", "Way too long.", "I wanted to like this so much.", "The hype did not match the movie."], -}; -const COMMENTS = ["Agreed, top tier.", "Ok I need to rewatch this.", "Bold ranking.", "Hard disagree, but respect.", "Adding this to my watchlist.", "That ending though.", "Finally someone said it.", "Where does it land vs the sequel?", "We should watch this together."]; -const PLACES = ["Theater", "Streaming", "Streaming", "Home", "TV"]; - -const clone = (x) => (x == null ? x : structuredClone(x)); -const iso = (t) => new Date(t).toISOString(); - -async function hashPw(pw) { - try { - const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode("movi:" + pw)); - return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); - } catch { - let h = 0; - for (const c of "movi:" + pw) h = (h * 33 + c.charCodeAt(0)) | 0; - return "w" + h; - } -} - -function seedWorld() { - const w = { v: 1, seq: 1, users: {}, rankings: {}, watch: {}, follows: [], activities: [], likes: [], comments: [], recs: [], notifications: [] }; - const now = Date.now(); - const pool = allFilms().slice(0, 900).filter((f) => f.g.length); - const ids = PEOPLE.map((_, i) => `demo-${i + 1}`); - const G = genres(); - - PEOPLE.forEach(([username, name, bio, hue, likes, harsh, priv], i) => { - const id = ids[i]; - const r = rng(1000 + i * 77); - w.users[id] = { - email: null, - profile: { id, username, display_name: name, bio, avatar_hue: hue, is_private: !!priv, yearly_goal: 52 + i * 8, ranked_count: 0, created_at: iso(now - (200 + i * 9) * DAY), demo: true }, - }; - const weighted = pool.map((f) => { - const match = f.g.filter((g) => likes.includes(G[g])).length; - const era = harsh === -1 ? (f.year < 1970 ? 3 : 0) : 0; - return [f, (1 + match * 4 + era) * (0.4 + r()) * (1 + f.pop / 120)]; - }); - const n = 28 + Math.floor(r() * 34); - const picked = []; - const avail = weighted.slice(); - while (picked.length < n && avail.length) { - const total = avail.reduce((t, x) => t + x[1], 0); - let x = r() * total, k = 0; - while (k < avail.length - 1 && (x -= avail[k][1]) > 0) k++; - const [f, wt] = avail.splice(k, 1)[0]; - picked.push([f, wt + r() * 3 - (harsh === 1 ? 1.5 : 0)]); - } - picked.sort((a, b) => b[1] - a[1]); - const split = harsh === 1 ? [0.35, 0.75] : [0.55, 0.85]; - const lists = { loved: [], fine: [], disliked: [] }; - picked.forEach(([f], k) => { - const p = k / picked.length; - lists[p < split[0] ? "loved" : p < split[1] ? "fine" : "disliked"].push(f.id); - }); - const rows = []; - for (const b of ORDER) { - lists[b].forEach((fid, pos) => { - const created = now - Math.floor(r() * 75 * DAY) - Math.floor(r() * DAY); - const note = r() < 0.35 ? NOTES[b][Math.floor(r() * NOTES[b].length)] : ""; - rows.push({ - user_id: id, film_id: fid, bucket: b, pos, score: scoreFor(b, pos, lists[b].length), note, - watched_on: iso(created).slice(0, 10), watched_where: PLACES[Math.floor(r() * PLACES.length)], watched_with: "", rewatch: r() < 0.12, - created_at: iso(created), updated_at: iso(created), - }); - }); - } - w.rankings[id] = rows; - w.users[id].profile.ranked_count = rows.length; - for (const row of rows) { - if (now - new Date(row.created_at).getTime() < 40 * DAY) { - w.activities.push({ id: w.seq++, user_id: id, kind: "ranked", film_id: row.film_id, bucket: row.bucket, score: row.score, note: row.note, created_at: row.created_at }); - } - } - const taken = new Set(rows.map((x) => x.film_id)); - w.watch[id] = []; - for (let k = 0; k < 8; k++) { - const f = pool[Math.floor(r() * 300)]; - if (taken.has(f.id) || w.watch[id].some((x) => x.film_id === f.id)) continue; - const created = iso(now - Math.floor(r() * 30 * DAY)); - w.watch[id].push({ film_id: f.id, from_user: null, created_at: created }); - if (k < 3) w.activities.push({ id: w.seq++, user_id: id, kind: "want", film_id: f.id, bucket: null, score: null, note: "", created_at: created }); - } - }); - - const r = rng(4242); - ids.forEach((a) => { - const others = ids.filter((b) => b !== a).sort(() => r() - 0.5).slice(0, 4 + Math.floor(r() * 4)); - for (const b of others) w.follows.push({ follower: a, followee: b, status: "accepted", created_at: iso(now - Math.floor(r() * 100) * DAY) }); - }); - for (const act of w.activities) { - const fans = w.follows.filter((f) => f.followee === act.user_id).map((f) => f.follower); - for (const u of fans) if (r() < 0.3) w.likes.push({ activity_id: act.id, user_id: u, created_at: act.created_at }); - if (act.kind === "ranked" && fans.length && r() < 0.14) { - const u = fans[Math.floor(r() * fans.length)]; - w.comments.push({ id: w.seq++, activity_id: act.id, user_id: u, body: COMMENTS[Math.floor(r() * COMMENTS.length)], created_at: iso(new Date(act.created_at).getTime() + 3600000) }); - } - } - return w; -} - -export async function createDemoApi() { - let w; - try { w = JSON.parse(localStorage.getItem(KEY)); } catch {} - if (!w || w.v !== 1) w = seedWorld(); - const save = () => { try { localStorage.setItem(KEY, JSON.stringify(w)); } catch {} }; - save(); - let uid = null; - try { uid = localStorage.getItem(SESSION); } catch {} - if (uid && !w.users[uid]) uid = null; - - const prof = (id) => w.users[id]?.profile || null; - const canView = (target) => { - const p = prof(target); - if (!p) return false; - return target === uid || !p.is_private || w.follows.some((f) => f.follower === uid && f.followee === target && f.status === "accepted"); - }; - const notify = (user_id, actor_id, kind, extra = {}) => { - if (user_id === actor_id) return; - w.notifications.push({ id: w.seq++, user_id, actor_id, kind, activity_id: null, film_id: null, body: "", read: false, created_at: iso(Date.now()), ...extra }); - }; - const requireUser = () => { if (!uid) throw new Error("Please sign in first"); }; - const isDemo = (id) => !!prof(id)?.demo; - const demoIds = () => Object.keys(w.users).filter(isDemo); - const later = (ms, fn) => setTimeout(() => { fn(); save(); api.onChange?.(); }, ms); - - const enrich = (a) => ({ - ...clone(a), - profile: clone(prof(a.user_id)), - likes: w.likes.filter((l) => l.activity_id === a.id).length, - comments: w.comments.filter((c) => c.activity_id === a.id).length, - liked: w.likes.some((l) => l.activity_id === a.id && l.user_id === uid), - }); - - const api = { - mode: "demo", - onChange: null, - get uid() { return uid; }, - - async signUp({ email, password, username, displayName }) { - email = email.trim().toLowerCase(); - if (Object.values(w.users).some((u) => u.email === email)) throw new Error("An account with that email already exists"); - if (!(await api.usernameAvailable(username))) throw new Error("That username is taken"); - if (password.length < 6) throw new Error("Password should be at least 6 characters"); - const id = "u-" + Math.random().toString(36).slice(2, 10); - w.users[id] = { - email, pw: await hashPw(password), - profile: { id, username, display_name: displayName || username, bio: "", avatar_hue: Math.floor(Math.random() * 360), is_private: false, yearly_goal: 52, ranked_count: 0, created_at: iso(Date.now()) }, - }; - w.rankings[id] = []; - w.watch[id] = []; - uid = id; - try { localStorage.setItem(SESSION, id); } catch {} - save(); - return { needsConfirm: false }; - }, - async signIn({ email, password }) { - email = email.trim().toLowerCase(); - const entry = Object.entries(w.users).find(([, u]) => u.email === email); - if (!entry || entry[1].pw !== (await hashPw(password))) throw new Error("Wrong email or password"); - uid = entry[0]; - try { localStorage.setItem(SESSION, uid); } catch {} - }, - supportsGoogle: false, - async signInWithGoogle() { throw new Error("Google sign-in needs the live server. Connect Supabase in config.js first."); }, - async userMeta() { return null; }, - async signOut() { uid = null; try { localStorage.removeItem(SESSION); } catch {} }, - async resetPassword() { throw new Error("Password reset needs a server. In demo mode, create a new account instead."); }, - async updatePassword(password) { - requireUser(); - if (password.length < 6) throw new Error("Password should be at least 6 characters"); - w.users[uid].pw = await hashPw(password); - save(); - }, - async usernameAvailable(name) { - return /^[a-z0-9_.]{3,20}$/.test(name) && !Object.values(w.users).some((u) => u.profile.username === name); - }, - async deleteAccount() { - requireUser(); - const id = uid; - delete w.users[id]; - delete w.rankings[id]; - delete w.watch[id]; - const acts = new Set(w.activities.filter((a) => a.user_id === id).map((a) => a.id)); - w.activities = w.activities.filter((a) => a.user_id !== id); - w.likes = w.likes.filter((l) => l.user_id !== id && !acts.has(l.activity_id)); - w.comments = w.comments.filter((c) => c.user_id !== id && !acts.has(c.activity_id)); - w.follows = w.follows.filter((f) => f.follower !== id && f.followee !== id); - w.recs = w.recs.filter((x) => x.from_user !== id && x.to_user !== id); - w.notifications = w.notifications.filter((n) => n.user_id !== id && n.actor_id !== id); - save(); - await api.signOut(); - }, - - async getProfile(id) { return clone(prof(id)); }, - async getProfileByUsername(username) { return clone(Object.values(w.users).find((u) => u.profile.username === username)?.profile || null); }, - async updateProfile(patch) { - requireUser(); - if (patch.username && patch.username !== prof(uid).username && !(await api.usernameAvailable(patch.username))) throw new Error("That username is taken"); - const allowed = ["username", "display_name", "bio", "avatar_hue", "is_private", "yearly_goal"]; - for (const k of allowed) if (k in patch) w.users[uid].profile[k] = patch[k]; - if (patch.is_private === false) w.follows.forEach((f) => { if (f.followee === uid && f.status === "pending") f.status = "accepted"; }); - save(); - return clone(prof(uid)); - }, - async searchUsers(q, limit = 20) { - const s = q.trim().toLowerCase(); - if (!s) return []; - return clone(Object.values(w.users).map((u) => u.profile).filter((p) => p.username.includes(s) || p.display_name.toLowerCase().includes(s)).slice(0, limit)); - }, - async listProfiles({ ids = null, limit = 50 } = {}) { - let ps = Object.values(w.users).map((u) => u.profile); - if (ids) ps = ps.filter((p) => ids.includes(p.id)); - return clone(ps.sort((a, b) => b.ranked_count - a.ranked_count).slice(0, limit)); - }, - - async getRankings(userId) { return canView(userId) ? clone(w.rankings[userId] || []) : []; }, - async rankingsOfUsers(ids) { - return ids.filter(canView).flatMap((id) => (w.rankings[id] || []).map(({ user_id, film_id, bucket, score, created_at }) => ({ user_id, film_id, bucket, score, created_at }))); - }, - async rankingsForFilm(filmId) { - const out = []; - for (const id of Object.keys(w.rankings)) { - if (!canView(id)) continue; - const r = w.rankings[id].find((x) => x.film_id === filmId); - if (r) out.push({ ...clone(r), profile: clone(prof(id)) }); - } - return out; - }, - async saveLists(lists) { - requireUser(); - const all = [...lists.loved, ...lists.fine, ...lists.disliked]; - if (new Set(all).size !== all.length) throw new Error("A film can only appear once"); - const old = new Map((w.rankings[uid] || []).map((r) => [r.film_id, r])); - const now = iso(Date.now()); - const rows = []; - for (const b of ORDER) { - lists[b].forEach((fid, pos) => { - const prev = old.get(fid); - rows.push({ - note: "", watched_on: null, watched_where: "", watched_with: "", rewatch: false, created_at: now, updated_at: now, - ...prev, user_id: uid, film_id: fid, bucket: b, pos, score: scoreFor(b, pos, lists[b].length), - ...(prev && prev.bucket !== b && { updated_at: now }), - }); - }); - } - w.rankings[uid] = rows; - w.users[uid].profile.ranked_count = rows.length; - save(); - }, - async updateEntry(filmId, patch) { - requireUser(); - const r = (w.rankings[uid] || []).find((x) => x.film_id === filmId); - if (!r) return; - for (const k of ["note", "watched_on", "watched_where", "watched_with", "rewatch"]) if (k in patch) r[k] = patch[k]; - save(); - }, - - async getWatchlist(userId) { - if (!canView(userId)) return []; - return clone([...(w.watch[userId] || [])].sort((a, b) => b.created_at.localeCompare(a.created_at))); - }, - async addWatch(filmId, fromUser = null) { - requireUser(); - const list = (w.watch[uid] ||= []); - if (!list.some((x) => x.film_id === filmId)) list.push({ film_id: filmId, from_user: fromUser, created_at: iso(Date.now()) }); - save(); - }, - async removeWatch(filmId) { - requireUser(); - w.watch[uid] = (w.watch[uid] || []).filter((x) => x.film_id !== filmId); - save(); - }, - - async follow(id) { - requireUser(); - if (id === uid) throw new Error("You can't follow yourself"); - let f = w.follows.find((x) => x.follower === uid && x.followee === id); - if (!f) { - f = { follower: uid, followee: id, status: prof(id).is_private ? "pending" : "accepted", created_at: iso(Date.now()) }; - w.follows.push(f); - notify(id, uid, f.status === "pending" ? "follow_request" : "follow"); - if (isDemo(id) && !isDemo(uid)) { - if (f.status === "pending") { - later(5000, () => { - const g = w.follows.find((x) => x.follower === uid && x.followee === id); - if (g && g.status === "pending") { g.status = "accepted"; notify(uid, id, "follow_accepted"); } - }); - } else if (Math.random() < 0.7) { - later(3500, () => { - if (w.users[uid] && !w.follows.some((x) => x.follower === id && x.followee === uid)) { - w.follows.push({ follower: id, followee: uid, status: prof(uid).is_private ? "pending" : "accepted", created_at: iso(Date.now()) }); - notify(uid, id, prof(uid).is_private ? "follow_request" : "follow"); - } - }); - } - } - save(); - } - return f.status; - }, - async unfollow(id) { w.follows = w.follows.filter((x) => !(x.follower === uid && x.followee === id)); save(); }, - async removeFollower(id) { w.follows = w.follows.filter((x) => !(x.follower === id && x.followee === uid)); save(); }, - async approveFollower(id) { - const f = w.follows.find((x) => x.follower === id && x.followee === uid); - if (f && f.status === "pending") { - f.status = "accepted"; - w.notifications = w.notifications.filter((n) => !(n.user_id === uid && n.actor_id === id && n.kind === "follow_request")); - notify(id, uid, "follow_accepted"); - save(); - } - }, - async getFollows(userId) { - const row = (id, f) => ({ id, status: f.status, created_at: f.created_at, profile: clone(prof(id)) }); - return { - following: w.follows.filter((f) => f.follower === userId && prof(f.followee)).map((f) => row(f.followee, f)), - followers: w.follows.filter((f) => f.followee === userId && prof(f.follower)).map((f) => row(f.follower, f)), - }; - }, - - async postActivity(a) { - requireUser(); - const act = { id: w.seq++, user_id: uid, kind: a.kind, film_id: a.film_id, bucket: a.bucket ?? null, score: a.score ?? null, note: a.note || "", created_at: iso(Date.now()) }; - w.activities.push(act); - save(); - if (!isDemo(uid) && act.kind === "ranked") { - const fans = w.follows.filter((f) => f.followee === uid && f.status === "accepted" && isDemo(f.follower)).map((f) => f.follower); - const pool = fans.length ? fans : demoIds().slice(0, 3); - const who = pool.sort(() => Math.random() - 0.5).slice(0, Math.min(2, pool.length)); - who.forEach((u, k) => later(4000 + k * 3000, () => { - if (!w.activities.some((x) => x.id === act.id) || w.likes.some((l) => l.activity_id === act.id && l.user_id === u)) return; - w.likes.push({ activity_id: act.id, user_id: u, created_at: iso(Date.now()) }); - notify(uid, u, "like", { activity_id: act.id, film_id: act.film_id }); - if (k === 0 && Math.random() < 0.5) { - const body = COMMENTS[Math.floor(Math.random() * COMMENTS.length)]; - w.comments.push({ id: w.seq++, activity_id: act.id, user_id: u, body, created_at: iso(Date.now()) }); - notify(uid, u, "comment", { activity_id: act.id, film_id: act.film_id, body }); - } - })); - } - return clone(act); - }, - async getFeed({ userIds = null, before = null, limit = 20 } = {}) { - return w.activities - .filter((a) => (userIds ? userIds.includes(a.user_id) : true) && canView(a.user_id) && (!before || a.created_at < before)) - .sort((a, b) => b.created_at.localeCompare(a.created_at)) - .slice(0, limit) - .map(enrich); - }, - async deleteActivity(id) { - const a = w.activities.find((x) => x.id === id); - if (!a || a.user_id !== uid) return; - w.activities = w.activities.filter((x) => x.id !== id); - w.likes = w.likes.filter((l) => l.activity_id !== id); - w.comments = w.comments.filter((c) => c.activity_id !== id); - w.notifications = w.notifications.filter((n) => n.activity_id !== id); - save(); - }, - async like(id) { - requireUser(); - const a = w.activities.find((x) => x.id === id); - if (!a || !canView(a.user_id) || w.likes.some((l) => l.activity_id === id && l.user_id === uid)) return; - w.likes.push({ activity_id: id, user_id: uid, created_at: iso(Date.now()) }); - notify(a.user_id, uid, "like", { activity_id: id, film_id: a.film_id }); - save(); - }, - async unlike(id) { w.likes = w.likes.filter((l) => !(l.activity_id === id && l.user_id === uid)); save(); }, - async getComments(activityId) { - return w.comments.filter((c) => c.activity_id === activityId).sort((a, b) => a.created_at.localeCompare(b.created_at)).map((c) => ({ ...clone(c), profile: clone(prof(c.user_id)) })); - }, - async addComment(activityId, body) { - requireUser(); - const a = w.activities.find((x) => x.id === activityId); - if (!a || !canView(a.user_id)) throw new Error("That post is no longer available"); - const c = { id: w.seq++, activity_id: activityId, user_id: uid, body: body.slice(0, 500), created_at: iso(Date.now()) }; - w.comments.push(c); - notify(a.user_id, uid, "comment", { activity_id: activityId, film_id: a.film_id, body: c.body.slice(0, 140) }); - save(); - return { ...clone(c), profile: clone(prof(uid)) }; - }, - async deleteComment(id) { - const c = w.comments.find((x) => x.id === id); - const a = c && w.activities.find((x) => x.id === c.activity_id); - if (c && (c.user_id === uid || a?.user_id === uid)) { w.comments = w.comments.filter((x) => x.id !== id); save(); } - }, - - async getNotifications(limit = 50) { - return w.notifications.filter((n) => n.user_id === uid).sort((a, b) => b.created_at.localeCompare(a.created_at)).slice(0, limit).map((n) => ({ ...clone(n), actor: clone(prof(n.actor_id)) })); - }, - async unreadCount() { return w.notifications.filter((n) => n.user_id === uid && !n.read).length; }, - async markNotificationsRead() { w.notifications.forEach((n) => { if (n.user_id === uid) n.read = true; }); save(); }, - - async sendRec(toId, filmId, message) { - requireUser(); - w.recs.push({ id: w.seq++, from_user: uid, to_user: toId, film_id: filmId, message: message.slice(0, 280), created_at: iso(Date.now()) }); - notify(toId, uid, "rec", { film_id: filmId, body: message.slice(0, 140) }); - save(); - }, - async getRecsForMe() { - return w.recs.filter((x) => x.to_user === uid).sort((a, b) => b.created_at.localeCompare(a.created_at)).map((x) => ({ ...clone(x), profile: clone(prof(x.from_user)) })); - }, - async deleteRec(id) { w.recs = w.recs.filter((x) => !(x.id === id && (x.to_user === uid || x.from_user === uid))); save(); }, - - async filmStats(ids) { - const set = new Set(ids); - const acc = new Map(); - for (const rows of Object.values(w.rankings)) for (const r of rows) { - if (!set.has(r.film_id)) continue; - const e = acc.get(r.film_id) || { film_id: r.film_id, sum: 0, n: 0 }; - e.sum += r.score; e.n++; - acc.set(r.film_id, e); - } - return new Map([...acc.values()].map((e) => [e.film_id, { film_id: e.film_id, avg_score: Math.round((e.sum / e.n) * 10) / 10, n: e.n }])); - }, - async topFilms(minCount = 2, limit = 30) { - const all = await api.filmStats([...new Set(Object.values(w.rankings).flat().map((r) => r.film_id))]); - return [...all.values()].filter((e) => e.n >= minCount).sort((a, b) => b.avg_score - a.avg_score || b.n - a.n).slice(0, limit); - }, - - async getBacklog() { return clone(((w.backlog ||= {})[uid] || []).slice()); }, - async addBacklog(ids) { - requireUser(); - const list = ((w.backlog ||= {})[uid] ||= []); - const have = new Set(list.map((r) => r.film_id)); - const now = Date.now(); - ids.forEach((film_id, i) => { if (!have.has(film_id)) list.unshift({ film_id, created_at: iso(now - i) }); }); - save(); - }, - async removeBacklog(id) { - const list = (w.backlog ||= {})[uid] || []; - w.backlog[uid] = list.filter((r) => r.film_id !== id); - save(); - }, - backlogLocal: false, - async matchTitles() { return null; }, - - resetDemo() { localStorage.removeItem(KEY); localStorage.removeItem(SESSION); }, - }; - return api; -} diff --git a/movi/js/api/index.js b/movi/js/api/index.js deleted file mode 100644 index bd762242..00000000 --- a/movi/js/api/index.js +++ /dev/null @@ -1,25 +0,0 @@ -// Picks the backend. Fill in docs/config.js to switch from demo mode to Supabase. -// -// Contract shared by api/demo.js and api/supabase.js (all methods async): -// auth: uid, signUp, signIn, signInWithGoogle, supportsGoogle, userMeta, signOut, resetPassword, updatePassword, usernameAvailable, deleteAccount -// profiles: getProfile, getProfileByUsername, updateProfile, searchUsers, listProfiles -// rankings: getRankings, rankingsOfUsers, rankingsForFilm, saveLists, updateEntry -// watch: getWatchlist, addWatch, removeWatch -// social: follow, unfollow, removeFollower, approveFollower, getFollows -// feed: postActivity, deleteActivity, getFeed, like, unlike, getComments, addComment, deleteComment -// inbox: getNotifications, unreadCount, markNotificationsRead, sendRec, getRecsForMe, deleteRec -// stats: filmStats, topFilms -// to rank: getBacklog, addBacklog, removeBacklog, backlogLocal, matchTitles (AI; null when unavailable) -export let api = null; - -export async function initApi() { - const cfg = window.MOVI_CONFIG || {}; - if (cfg.supabaseUrl && cfg.supabaseAnonKey) { - const { createSupabaseApi } = await import("./supabase.js"); - api = await createSupabaseApi({ url: cfg.supabaseUrl, anonKey: cfg.supabaseAnonKey }); - } else { - const { createDemoApi } = await import("./demo.js"); - api = await createDemoApi(); - } - return api; -} diff --git a/movi/js/api/supabase.js b/movi/js/api/supabase.js deleted file mode 100644 index 7cf70f62..00000000 --- a/movi/js/api/supabase.js +++ /dev/null @@ -1,235 +0,0 @@ -// Supabase backend. Every method mirrors api/demo.js; see api/index.js for the contract. -const PROFILE = "id,username,display_name,bio,avatar_hue,is_private,yearly_goal,ranked_count,created_at"; -const RANKING = "user_id,film_id,bucket,pos,score,note,watched_on,watched_where,watched_with,rewatch,created_at,updated_at"; - -const missingTable = (e) => e.code === "42P01" || e.code === "PGRST205" || /backlog/.test(e.message || "") && /exist|schema cache/.test(e.message || ""); - -export function localBacklog(uid) { - const key = `movi.backlog.${uid}`; - const read = () => { try { return JSON.parse(localStorage.getItem(key) || "[]"); } catch { return []; } }; - const write = (rows) => { try { localStorage.setItem(key, JSON.stringify(rows)); } catch {} }; - return { - get: () => read(), - add: (ids) => { - const rows = read(); - const have = new Set(rows.map((r) => r.film_id)); - const now = Date.now(); - ids.forEach((film_id, i) => { if (!have.has(film_id)) rows.unshift({ film_id, created_at: new Date(now - i).toISOString() }); }); - write(rows); - }, - remove: (id) => write(read().filter((r) => r.film_id !== id)), - }; -} - -function check({ data, error }) { - if (error) throw new Error(error.message); - return data; -} -const num = (r) => ({ ...r, score: r.score == null ? null : Number(r.score) }); - -export async function createSupabaseApi({ url, anonKey }) { - const { createClient } = await import("https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2.45.4/+esm"); - const sb = createClient(url, anonKey, { auth: { persistSession: true, autoRefreshToken: true } }); - // Which sign-in providers are switched on in the Supabase dashboard (the Google button only shows if it is). - // Fetched alongside the session, with a time limit so a slow network never holds up startup. - const [providers, session] = await Promise.all([ - fetch(`${url}/auth/v1/settings`, { headers: { apikey: anonKey }, signal: AbortSignal.timeout(4000) }) - .then((r) => (r.ok ? r.json() : {})) - .then((s) => s.external || {}) - .catch(() => ({})), - sb.auth.getSession(), - ]); - let uid = session.data.session?.user?.id ?? null; - let recovery = false; - let backlogLocal = false; - sb.auth.onAuthStateChange((event, session) => { - uid = session?.user?.id ?? null; - if (event === "PASSWORD_RECOVERY") recovery = true; - }); - - const withProfiles = async (rows, key = "user_id") => { - const ids = [...new Set(rows.map((r) => r[key]).filter(Boolean))]; - if (!ids.length) return rows; - const ps = check(await sb.from("profiles").select(PROFILE).in("id", ids)); - const map = new Map(ps.map((p) => [p.id, p])); - return rows.map((r) => ({ ...r, profile: map.get(r[key]) || null })); - }; - - const enrichActivities = async (rows) => { - if (!rows.length) return []; - const ids = rows.map((r) => r.id); - const mine = uid ? check(await sb.from("likes").select("activity_id").eq("user_id", uid).in("activity_id", ids)) : []; - const liked = new Set(mine.map((l) => l.activity_id)); - return rows.map(({ profiles, likes, comments, ...a }) => ({ - ...num(a), - profile: profiles, - likes: likes?.[0]?.count ?? 0, - comments: comments?.[0]?.count ?? 0, - liked: liked.has(a.id), - })); - }; - const ACTIVITY = "*, profiles!activities_user_id_fkey(" + PROFILE + "), likes(count), comments(count)"; - - return { - mode: "supabase", - get uid() { return uid; }, - takeRecovery() { const r = recovery; recovery = false; return r; }, - - async signUp({ email, password, username, displayName }) { - const { data, error } = await sb.auth.signUp({ - email, password, - options: { data: { username, display_name: displayName }, emailRedirectTo: location.origin + location.pathname }, - }); - if (error) throw new Error(error.message); - uid = data.session?.user?.id ?? null; - return { needsConfirm: !data.session }; - }, - async signIn({ email, password }) { - const { data, error } = await sb.auth.signInWithPassword({ email, password }); - if (error) throw new Error(error.message === "Invalid login credentials" ? "Wrong email or password" : error.message); - uid = data.user.id; - }, - supportsGoogle: !!providers.google, - async signInWithGoogle() { - if (!providers.google) throw new Error("Google sign-in isn't switched on yet. Use email for now."); - const { error } = await sb.auth.signInWithOAuth({ provider: "google", options: { redirectTo: location.origin + location.pathname } }); - if (error) throw new Error(error.message); - }, - async userMeta() { return (await sb.auth.getUser()).data.user?.user_metadata ?? null; }, - async signOut() { await sb.auth.signOut(); uid = null; }, - async resetPassword(email) { - check(await sb.auth.resetPasswordForEmail(email, { redirectTo: location.origin + location.pathname + "#/settings" })); - }, - async updatePassword(password) { check(await sb.auth.updateUser({ password })); }, - async usernameAvailable(name) { return check(await sb.rpc("username_available", { name })); }, - async deleteAccount() { check(await sb.rpc("delete_me")); await sb.auth.signOut(); uid = null; }, - - async getProfile(id) { return check(await sb.from("profiles").select(PROFILE).eq("id", id).maybeSingle()); }, - async getProfileByUsername(username) { return check(await sb.from("profiles").select(PROFILE).eq("username", username).maybeSingle()); }, - async updateProfile(patch) { return check(await sb.from("profiles").update(patch).eq("id", uid).select(PROFILE).single()); }, - async searchUsers(q, limit = 20) { - const s = q.replace(/[%_,()]/g, "").trim(); - if (!s) return []; - return check(await sb.from("profiles").select(PROFILE).or(`username.ilike.%${s}%,display_name.ilike.%${s}%`).order("ranked_count", { ascending: false }).limit(limit)); - }, - async listProfiles({ ids = null, limit = 50 } = {}) { - let q = sb.from("profiles").select(PROFILE).order("ranked_count", { ascending: false }).limit(limit); - if (ids) q = q.in("id", ids.length ? ids : ["00000000-0000-0000-0000-000000000000"]); - return check(await q); - }, - - async getRankings(userId) { return check(await sb.from("rankings").select(RANKING).eq("user_id", userId)).map(num); }, - async rankingsOfUsers(ids) { - if (!ids.length) return []; - return check(await sb.from("rankings").select("user_id,film_id,bucket,score,created_at").in("user_id", ids).limit(10000)).map(num); - }, - async rankingsForFilm(filmId) { - return (await withProfiles(check(await sb.from("rankings").select(RANKING).eq("film_id", filmId).limit(200)))).map(num); - }, - async saveLists(lists) { check(await sb.rpc("save_lists", lists)); }, - async updateEntry(filmId, patch) { check(await sb.from("rankings").update(patch).eq("user_id", uid).eq("film_id", filmId)); }, - - async getWatchlist(userId) { return check(await sb.from("watchlist").select("film_id,from_user,created_at").eq("user_id", userId).order("created_at", { ascending: false })); }, - async addWatch(filmId, fromUser = null) { - const { error } = await sb.from("watchlist").insert({ film_id: filmId, from_user: fromUser }); - if (error && error.code !== "23505") throw new Error(error.message); - }, - async removeWatch(filmId) { check(await sb.from("watchlist").delete().eq("user_id", uid).eq("film_id", filmId)); }, - - async follow(id) { - const { data, error } = await sb.from("follows").insert({ followee: id }).select("status").single(); - if (!error) return data.status; - if (error.code !== "23505") throw new Error(error.message); - // Already following or requested: report the existing status. - return check(await sb.from("follows").select("status").eq("follower", uid).eq("followee", id).single()).status; - }, - async unfollow(id) { check(await sb.from("follows").delete().eq("follower", uid).eq("followee", id)); }, - async removeFollower(id) { check(await sb.from("follows").delete().eq("follower", id).eq("followee", uid)); }, - async approveFollower(id) { check(await sb.from("follows").update({ status: "accepted" }).eq("follower", id).eq("followee", uid)); }, - async getFollows(userId) { - const [out, inc] = await Promise.all([ - sb.from("follows").select("followee,status,created_at").eq("follower", userId), - sb.from("follows").select("follower,status,created_at").eq("followee", userId), - ]); - const following = await withProfiles(check(out).map((r) => ({ id: r.followee, status: r.status, created_at: r.created_at })), "id"); - const followers = await withProfiles(check(inc).map((r) => ({ id: r.follower, status: r.status, created_at: r.created_at })), "id"); - return { following: following.filter((r) => r.profile), followers: followers.filter((r) => r.profile) }; - }, - - async postActivity(a) { return num(check(await sb.from("activities").insert(a).select().single())); }, - async getFeed({ userIds = null, before = null, limit = 20 } = {}) { - let q = sb.from("activities").select(ACTIVITY).order("created_at", { ascending: false }).limit(limit); - if (userIds) q = q.in("user_id", userIds.length ? userIds : ["00000000-0000-0000-0000-000000000000"]); - if (before) q = q.lt("created_at", before); - return enrichActivities(check(await q)); - }, - async deleteActivity(id) { check(await sb.from("activities").delete().eq("id", id).eq("user_id", uid)); }, - async like(id) { - const { error } = await sb.from("likes").insert({ activity_id: id }); - if (error && error.code !== "23505") throw new Error(error.message); - }, - async unlike(id) { check(await sb.from("likes").delete().eq("activity_id", id).eq("user_id", uid)); }, - async getComments(activityId) { - return withProfiles(check(await sb.from("comments").select("*").eq("activity_id", activityId).order("created_at"))); - }, - async addComment(activityId, body) { - const c = check(await sb.from("comments").insert({ activity_id: activityId, body }).select().single()); - return (await withProfiles([c]))[0]; - }, - async deleteComment(id) { check(await sb.from("comments").delete().eq("id", id)); }, - - async getNotifications(limit = 50) { - const rows = check(await sb.from("notifications").select("*").eq("user_id", uid).order("created_at", { ascending: false }).limit(limit)); - return (await withProfiles(rows, "actor_id")).map((n) => ({ ...n, actor: n.profile })); - }, - async unreadCount() { - const { count, error } = await sb.from("notifications").select("id", { count: "exact", head: true }).eq("user_id", uid).eq("read", false); - if (error) throw new Error(error.message); - return count || 0; - }, - async markNotificationsRead() { check(await sb.from("notifications").update({ read: true }).eq("user_id", uid).eq("read", false)); }, - - async sendRec(toId, filmId, message) { check(await sb.from("recommendations").insert({ to_user: toId, film_id: filmId, message })); }, - async getRecsForMe() { - return withProfiles(check(await sb.from("recommendations").select("*").eq("to_user", uid).order("created_at", { ascending: false }).limit(100)), "from_user"); - }, - async deleteRec(id) { check(await sb.from("recommendations").delete().eq("id", id)); }, - - async filmStats(ids) { - if (!ids.length) return new Map(); - return new Map(check(await sb.rpc("film_stats", { ids })).map((r) => [r.film_id, r])); - }, - async topFilms(minCount = 2, limit = 30) { return check(await sb.rpc("top_films", { min_count: minCount, lim: limit })); }, - - // "To rank" list. Falls back to this device if the backlog table hasn't been created yet. - async getBacklog() { - const { data, error } = await sb.from("backlog").select("film_id,created_at").eq("user_id", uid).order("created_at", { ascending: false }); - if (error) { - if (missingTable(error)) { backlogLocal = true; return localBacklog(uid).get(); } - throw new Error(error.message); - } - backlogLocal = false; - return data; - }, - async addBacklog(ids) { - if (!ids.length) return; - if (backlogLocal) return localBacklog(uid).add(ids); - const now = Date.now(); - const rows = ids.map((film_id, i) => ({ film_id, created_at: new Date(now - i).toISOString() })); - const { error } = await sb.from("backlog").upsert(rows, { onConflict: "user_id,film_id", ignoreDuplicates: true }); - if (error) throw new Error(error.message); - }, - async removeBacklog(id) { - if (backlogLocal) return localBacklog(uid).remove(id); - check(await sb.from("backlog").delete().eq("user_id", uid).eq("film_id", id)); - }, - get backlogLocal() { return backlogLocal; }, - - // AI title matching through the match-films Edge Function. Returns null when it isn't set up. - async matchTitles(lines) { - const { data, error } = await sb.functions.invoke("match-films", { body: { lines } }); - if (error || !data?.results) return null; - return data.results; - }, - }; -} diff --git a/movi/js/app.js b/movi/js/app.js deleted file mode 100644 index 8308cebd..00000000 --- a/movi/js/app.js +++ /dev/null @@ -1,371 +0,0 @@ -import { $, esc, ICON, toast } from "./util.js"; -import { loadFilms, film, isFilmId } from "./films.js"; -import { initApi, api } from "./api/index.js"; -import { S, rankedIds, removeBacklog, updateMe, loadSession, clearSession, signedIn, addWatch, removeWatch, skipFilm, removeRanking, follow, unfollow, removeFollower, refreshUnread } from "./state.js"; -import { fillMissingPosters, avatarHTML, closeModal, modalOpen, confirmDialog, spinnerHTML, emptyHTML, withTransition } from "./ui.js"; -import { openFilm, closeFilm, refreshFilm, refreshFilmPoster, recommendDialog, shareFilm, sheetFilmId } from "./film-sheet.js"; -import { startRank, startQueue, cancelRank, flowActive, flowAction, flowKey, quickAdd, quickPick, requireMe, setFlowDoneHandler } from "./rank-flow.js"; -import { runMatch, addReviewed, clearReview } from "./views/torank.js"; -import { renderFeed, feedMore, toggleLike, toggleComments, deleteComment, followBtnHTML } from "./views/feed.js"; -import { renderDiscover, renderSearch, drawResults, moreResults, refreshQuick, shuffleQuick } from "./views/discover.js"; -import { renderLists, shareList } from "./views/lists.js"; -import { renderProfile, showFollows, shareProfile } from "./views/profile.js"; -import { renderLeaderboard, renderNotifications, renderPeople, renderTogether, handleRequest } from "./views/social.js"; -import { signInWithGoogle, shuffleOnboarding, renderWelcome, renderOnboarding, onboardingNext, onboardingDone, renderSettings, exportData, deleteAccount, forgotPassword, needsOnboarding } from "./views/account.js"; - -const view = () => $("#view"); - -// ---------------- Router ---------------- -const ROUTES = { - feed: { auth: true, nav: "feed", render: (v) => renderFeed(v) }, - discover: { nav: "discover", render: (v) => renderDiscover(v) }, - search: { nav: "search", render: (v, a, p) => renderSearch(v, p) }, - lists: { auth: true, nav: "lists", render: (v, a) => renderLists(v, a[0] || "been") }, - leaderboard: { nav: "leaderboard", render: (v) => renderLeaderboard(v) }, - notifications: { auth: true, nav: "notifications", render: (v) => renderNotifications(v) }, - people: { auth: true, nav: "feed", render: (v) => renderPeople(v) }, - together: { auth: true, nav: "discover", render: (v) => renderTogether(v) }, - settings: { auth: true, nav: "profile", render: (v) => renderSettings(v) }, - onboarding: { auth: true, nav: "", render: (v) => renderOnboarding(v) }, - welcome: { guest: true, nav: "", render: (v) => renderWelcome(v) }, - u: { nav: "profile", render: (v, a) => renderProfile(v, decodeURIComponent(a[0] || ""), a[1]) }, -}; - -function parse() { - const raw = location.hash.replace(/^#\/?/, ""); - const [path, qs = ""] = raw.split("?"); - const parts = path.split("/").filter(Boolean); - return { name: parts[0] || "", args: parts.slice(1), params: new URLSearchParams(qs), raw }; -} - -let current = null; -async function route() { - let { name, args, params } = parse(); - if (name === "film") { - const id = Number(args[0]); - if (!current) { - current = { name: signedIn() ? "feed" : "discover", args: [], params: new URLSearchParams() }; - await draw(current); - } - if (isFilmId(id)) openFilm(id); - return; - } - if (!ROUTES[name]) name = signedIn() ? "feed" : "welcome"; - const r = ROUTES[name]; - if (r.auth && !signedIn()) return go("#/welcome"); - if (r.guest && signedIn()) return go("#/feed"); - if (name === "u" && !args[0] && signedIn()) args = [S.me.username]; - if (name === "u" && !args[0]) return go("#/welcome"); - current = { name, args, params }; - await draw(current); -} - -// Switching tabs within one screen (My Lists tabs, a profile's tabs) swaps content in place. -let drawn = null; -const isTabSwitch = (a, b) => a && a.name === b.name && ["lists", "u"].includes(b.name) && (b.name !== "u" || a.args[0] === b.args[0]); - -async function draw(c, keepScroll = false) { - const r = ROUTES[c.name]; - const y = scrollY; - const tabSwitch = !keepScroll && isTabSwitch(drawn, c); - drawn = c; - document.body.dataset.route = c.name; - renderShell(r.nav); - const v = view(); - const render = async () => { - try { - await r.render(v, c.args, c.params); - } catch (e) { - console.error(e); - v.innerHTML = emptyHTML({ title: "Something went wrong", text: esc(e.message), action: `` }); - } - }; - if (tabSwitch) return withTransition(render); - if (!keepScroll) v.innerHTML = spinnerHTML(); - await render(); - if (keepScroll) scrollTo(0, y); - else { - // A short fade-up when switching screens; soft refreshes keep content still. - v.classList.remove("enter"); - void v.offsetWidth; - v.classList.add("enter"); - } -} - -const go = (hash) => { if (location.hash === hash) route(); else location.hash = hash; }; -const rerender = () => current && draw(current, true); - -// Navigation before startup finishes is picked up by boot()'s own route() call, once the session is known. -let booted = false; -// Pages visited inside the app this session, so the back arrow knows whether "back" stays in Movi. -let inAppSteps = 0; -window.addEventListener("hashchange", () => { - if (!booted) return; - inAppSteps++; - if (flowActive()) cancelRank(); - closeModal(); - if (!location.hash.startsWith("#/film/")) { - if (sheetFilmId() != null) closeFilm(); - scrollTo(0, 0); - } - route(); -}); - -// ---------------- Shell ---------------- -// Main tabs have their own button in the tab bar; every other page gets a back arrow on phones, -// which matters most for the home-screen app, where there is no browser back button. -function isSubPage() { - if (!current) return false; - if (["feed", "discover", "lists", "welcome", "onboarding"].includes(current.name)) return false; - if (current.name === "u" && S.me && current.args[0] === S.me.username) return false; - return true; -} -function goBack() { - if (inAppSteps > 0) history.back(); - else location.hash = S.me ? "#/feed" : "#/discover"; -} - -function renderShell(active) { - const me = S.me; - const back = $("#backbtn"); - if (back) back.hidden = !isSubPage(); - const tab = (key, href, icon, label) => `${icon}${label}`; - const bell = `${ICON.bell}${S.unread ? `${S.unread > 9 ? "9+" : S.unread}` : ""}`; - $("#topnav").innerHTML = me - ? `${tab("feed", "#/feed", ICON.home, "Feed")}${tab("discover", "#/discover", ICON.compass, "Discover")}${tab("lists", "#/lists", ICON.list, "My Lists")}${tab("leaderboard", "#/leaderboard", ICON.trophy, "Leaderboard")}` - : `${tab("discover", "#/discover", ICON.compass, "Discover")}${tab("search", "#/search", ICON.search, "Search")}${tab("leaderboard", "#/leaderboard", ICON.trophy, "Leaderboard")}`; - $("#topright").innerHTML = me - ? `${ICON.search} - ${ICON.trophy} - ${bell} - - ${avatarHTML(me, 34)}` - : `Sign in`; - $("#tabbar").innerHTML = me - ? `${tab("feed", "#/feed", ICON.home, "Feed")}${tab("discover", "#/discover", ICON.compass, "Discover")} - - ${tab("lists", "#/lists", ICON.list, "Lists")}${tab("profile", `#/u/${encodeURIComponent(me.username)}`, ICON.user, "Profile")}` - : ""; - document.body.classList.toggle("guest", !me); -} -document.addEventListener("movi:posters", () => { fillMissingPosters(); refreshFilmPoster(); }); -document.addEventListener("movi:unread", () => current && renderShell(ROUTES[current.name]?.nav)); -document.addEventListener("movi:auth", () => current && renderShell(ROUTES[current.name]?.nav)); -document.addEventListener("movi:signedout", () => { clearSession(); go("#/welcome"); }); - -// ---------------- Refresh after changes ---------------- -// Removed items shrink away while their neighbors slide into the gap. -const removeItem = (el) => el && withTransition(() => el.remove(), { cards: true }); - -function softRefresh() { - const n = current?.name; - if (n === "discover") { - refreshQuick(); - const gone = new Set([...rankedIds(), ...S.skip]); - document.querySelectorAll("#view .rail .card .hit").forEach((b) => { if (gone.has(Number(b.dataset.film))) b.closest(".card").remove(); }); - } else if (n === "search") drawResults(); - else if (["lists", "onboarding", "together"].includes(n) || (n === "u" && current.args[0] === S.me?.username)) rerender(); - refreshFilm(); -} -setFlowDoneHandler(() => { - softRefresh(); - if (current?.name === "feed") rerender(); -}); - -function swapFollowButtons(uid) { - document.querySelectorAll(`[data-uid="${CSS.escape(uid)}"][data-act="follow"], [data-uid="${CSS.escape(uid)}"][data-act="unfollow"]`).forEach((b) => { - const p = { id: uid }; - const size = b.classList.contains("sm") ? "sm" : ""; - b.outerHTML = followBtnHTML(p, size); - }); -} - -// ---------------- Actions ---------------- -async function act(name, el) { - const id = el.dataset.id != null ? Number(el.dataset.id) : null; - const uid = el.dataset.uid; - switch (name) { - case "rank": if (requireMe()) startRank(id); return; - case "quick-add": if (requireMe()) quickAdd(); return; - case "qa-pick": return quickPick(id); - case "watch": - case "watch-from": - if (!requireMe()) return; - await addWatch(id, el.dataset.from || null); - toast(`Saved ${film(id).title} to your watchlist`); - document.querySelectorAll(`.pbtn[data-id="${id}"][data-act="watch"]`).forEach((b) => { b.dataset.act = "unwatch"; b.classList.add("on"); b.querySelector("span").textContent = "Saved"; }); - return softRefresh(); - case "unwatch": - await removeWatch(id); - toast("Removed from watchlist"); - document.querySelectorAll(`.pbtn[data-id="${id}"][data-act="unwatch"]`).forEach((b) => { b.dataset.act = "watch"; b.classList.remove("on"); b.querySelector("span").textContent = "Save"; }); - return softRefresh(); - case "skip": skipFilm(id); return softRefresh(); - case "remove": { - const ok = await confirmDialog({ title: `Remove ${film(id).title}?`, text: "It comes off your list and the scores of everything below it shift up.", ok: "Remove", danger: true }); - if (!ok) return; - await removeRanking(id); - toast("Removed from your list"); - return softRefresh(); - } - case "close-film": return closeFilmView(); - case "modal-close": return closeModal(); - case "recommend": if (requireMe()) recommendDialog(id); return; - case "share-film": return shareFilm(id); - case "share-list": return shareList(); - case "share-profile": return shareProfile(el.dataset.username); - case "like": if (requireMe()) toggleLike(el); return; - case "comments": return toggleComments(el); - case "del-comment": return deleteComment(el); - case "delete-post": { - if (!(await confirmDialog({ title: "Delete this post?", text: "It's removed from feeds along with its likes and comments. Your ranking stays.", ok: "Delete", danger: true }))) return; - await api.deleteActivity(id); - removeItem(el.closest(".post")); - return; - } - case "skip-main": return $("#view").focus(); - case "back": return goBack(); - case "shuffle-quick": return shuffleQuick(); - case "bulk-match": { - el.disabled = true; - try { await runMatch(); } finally { el.disabled = false; } - return; - } - case "bulk-add": await addReviewed(); return rerender(); - case "bulk-clear": clearReview(); return rerender(); - case "unbacklog": - await removeBacklog(id); - toast("Removed from To rank"); - await removeItem(el.closest(".card")); - return rerender(); - case "rank-queue": if (requireMe()) startQueue(S.backlog.map((b) => b.film_id)); return; - case "feed-more": return feedMore(); - case "more": return moreResults(); - case "follow": { - if (!requireMe()) return; - el.disabled = true; - try { - const st = await follow(uid); - toast(st === "pending" ? "Follow request sent" : "Following"); - } catch (e) { toast(e.message); } - swapFollowButtons(uid); - if (current?.name === "u") rerender(); - return; - } - case "unfollow": { - const st = S.following.get(uid); - if (st === "accepted" && !(await confirmDialog({ title: "Unfollow?", text: "Their activity leaves your feed and rec scores.", ok: "Unfollow" }))) return; - try { await unfollow(uid); } catch (e) { toast(e.message); } - swapFollowButtons(uid); - if (current?.name === "u") rerender(); - return; - } - case "remove-follower": - await removeFollower(uid); - removeItem(el.closest(".urow")); - toast("Follower removed"); - return; - case "approve": - case "decline": - await handleRequest(uid, name === "approve"); - removeItem(el.closest(".urow")); - return; - case "show-follows": return showFollows(uid, el.dataset.kind); - case "dismiss-rec": - await api.deleteRec(id); - removeItem(el.closest(".rec")); - return; - case "ob-shuffle": return shuffleOnboarding(); - case "ob-next": return onboardingNext(); - case "ob-done": return onboardingDone(); - case "export": return exportData(); - case "forgot": return forgotPassword(); - case "google": return signInWithGoogle(el); - case "sign-out": - await api.signOut(); - clearSession(); - clearReview(); - toast("Signed out"); - return go("#/welcome"); - case "delete-account": return deleteAccount(); - case "reset-demo": - if (!(await confirmDialog({ title: "Reset demo data?", text: "Deletes every demo account and ranking in this browser and starts fresh.", ok: "Reset", danger: true }))) return; - api.resetDemo(); - location.hash = "#/welcome"; - location.reload(); - return; - default: - return flowAction(name, el); - } -} - -document.addEventListener("click", (e) => { - const a = e.target.closest("[data-act]"); - if (a && !a.disabled) { - e.preventDefault(); - if (a.dataset.act === "modal-close-nav") { closeModal(); closeFilmView(); location.hash = a.getAttribute("href"); return; } - act(a.dataset.act, a).catch((err) => toast(err.message)); - return; - } - const f = e.target.closest("[data-film]"); - if (f) { - e.preventDefault(); - closeModal(); - openFilm(Number(f.dataset.film)); - return; - } - const q = e.target.closest('a[href="#quick"]'); - if (q) { e.preventDefault(); $("#quick")?.scrollIntoView({ behavior: "smooth" }); } -}); - -document.addEventListener("keydown", (e) => { - if (flowKey(e)) return; - if (e.key !== "Escape") return; - if (modalOpen()) closeModal(); - else if (sheetFilmId() != null) closeFilmView(); -}); - -function closeFilmView() { - closeFilm(); - if (location.hash.startsWith("#/film/")) history.replaceState(null, "", "#/" + (current ? [current.name, ...current.args].join("/") : "discover")); -} - -// ---------------- Boot ---------------- -async function boot() { - try { - await loadFilms(); - } catch { - view().innerHTML = emptyHTML({ title: "Couldn't load the film database", text: "If you opened index.html directly from disk, run a local server instead: python3 -m http.server inside the docs folder, then visit localhost:8000." }); - return; - } - try { - await initApi(); - } catch (e) { - view().innerHTML = emptyHTML({ title: "Couldn't connect to the server", text: `Check the Supabase settings in config.js. (${esc(e.message)})` }); - return; - } - api.onChange = () => refreshUnread(); - // A failed Google sign-in comes back as #error=...&error_description=... - const authError = new URLSearchParams(location.hash.replace(/^#/, "")).get("error_description"); - if (authError) { - history.replaceState(null, "", location.pathname); - toast(/provider is not enabled/i.test(authError) ? "Google sign-in isn't switched on yet" : `Sign-in failed: ${authError.replace(/\+/g, " ")}`); - } - await loadSession().catch(() => clearSession()); - if (S.me && S.me.display_name === S.me.username) { - const meta = await api.userMeta().catch(() => null); - const name = (meta?.full_name || meta?.name || "").trim().slice(0, 40); - if (name) await updateMe({ display_name: name }).catch(() => {}); - } - // New members land on onboarding from the home page only; a link to a specific page is respected. - const atHome = ["", "#", "#/", "#/feed"].includes(location.hash); - if (S.me && atHome && needsOnboarding() && S.me.ranked_count === 0 && !S.backlog.length) location.hash = "#/onboarding"; - if (api.takeRecovery?.() && S.me) { - location.hash = "#/settings"; - toast("Choose a new password below"); - } - booted = true; - await route(); - setInterval(() => { if (document.visibilityState === "visible") refreshUnread(); }, 40000); -} -boot(); diff --git a/movi/js/data-version.js b/movi/js/data-version.js deleted file mode 100644 index e7864cdf..00000000 --- a/movi/js/data-version.js +++ /dev/null @@ -1,2 +0,0 @@ -// Written by tools/build_movie_db.py. Changes whenever the film data changes. -export const DATA_VERSION = "e3d85a42cf55"; diff --git a/movi/js/film-sheet.js b/movi/js/film-sheet.js deleted file mode 100644 index ae1e6d0c..00000000 --- a/movi/js/film-sheet.js +++ /dev/null @@ -1,241 +0,0 @@ -import { $, esc, ICON, toast, copyText, today } from "./util.js"; -import { film, details, genreNames, posterUrl, allFilms } from "./films.js"; -import { BUCKETS, recScore, genreAffinity } from "./model.js"; -import { api } from "./api/index.js"; -import { sample, softmax } from "./variety.js"; -import { S, scoreOf, isWatch, rankedCount, followingIds, loadFriendRows, friendRowsFor, myRows, updateDetails, rankedIds } from "./state.js"; -import { posterHTML, railHTML, avatarHTML, userHref, scoreHTML, openLayer, closeLayer, openModal, closeModal, demoTag } from "./ui.js"; - -export const PLACES = ["Theater", "Streaming", "Home", "TV", "Plane", "Other"]; - -let current = null; - -export function similarFilms(seed, limit = 14, { vary = false } = {}) { - const taken = new Set([seed.id, ...(S.me ? [...rankedIds(), ...S.skip] : [])]); - const out = []; - const films = allFilms(); - for (let i = 0; i < Math.min(films.length, 6000); i++) { - const f = films[i]; - if (taken.has(f.id) || !f.g.length) continue; - const overlap = f.g.filter((g) => seed.g.includes(g)).length; - if (!overlap) continue; - out.push([f.pop / 20 + overlap * 2.5 - Math.abs(f.year - seed.year) / 12, f]); - } - out.sort((a, b) => b[0] - a[0]); - if (vary) return sample(softmax(out.slice(0, limit * 6)), limit); - return out.slice(0, limit).map((x) => x[1]); -} - -export function recommendFor(limit = 18) { - const rows = myRows(); - const aff = genreAffinity(rows, 64); - const taken = new Set([...rankedIds(), ...S.skip, ...S.watch.map((w) => w.film_id)]); - const films = allFilms(); - const out = []; - for (let i = 0; i < Math.min(films.length, 6000); i++) { - const f = films[i]; - if (taken.has(f.id) || !f.g.length) continue; - out.push([f.pop / 20 + f.g.reduce((t, g) => t + aff[g], 0) / Math.sqrt(f.g.length), f]); - } - out.sort((a, b) => b[0] - a[0]); - return sample(softmax(out.slice(0, limit * 10)), limit); -} - -export async function openFilm(id) { - const f = film(id); - if (!f) return; - current = { id, det: null, stats: null, others: null }; - openLayer("#sheet", sheetHTML(f)); - $("#sheet .panel").scrollTop = 0; - const token = current; - const [det, stats, others] = await Promise.all([ - details(id), - api.filmStats([id]).catch(() => new Map()), - api.rankingsForFilm(id).catch(() => []), - S.me ? loadFriendRows().catch(() => []) : null, - ]); - if (current !== token) return; - Object.assign(current, { det, stats: stats.get(id) || null, others }); - rerender(); -} - -export function refreshFilm() { - if (current && !$("#sheet").hidden) rerender(); -} -// Background posters arrived: redraw the open film page only if its poster was missing. -export function refreshFilmPoster() { - if (current && !$("#sheet").hidden && film(current.id).poster && !$("#sheet .film .poster img")) rerender(); -} -export const sheetFilmId = () => (!$("#sheet").hidden && current ? current.id : null); - -function rerender() { - const panel = $("#sheet .panel"); - const top = panel ? panel.scrollTop : 0; - // Redrawing replaces every element; put keyboard focus back on the equivalent one. - const active = document.activeElement; - const hadFocus = $("#sheet").contains(active); - const focusKey = hadFocus ? (active.id ? `#${active.id}` : active.dataset.act ? `[data-act="${active.dataset.act}"]` : active.name ? `[name="${active.name}"]` : null) : null; - $("#sheet").innerHTML = sheetHTML(film(current.id), current, false); - $("#sheet .panel").scrollTop = top; - bindDetails(current.id); - if (hadFocus) ((focusKey && $(`#sheet .panel ${focusKey}`)) || $("#sheet .close"))?.focus({ preventScroll: true }); -} - -export function closeFilm() { - current = null; - closeLayer("#sheet"); -} - -function sheetHTML(f, data = null, animate = true) { - const det = data?.det; - const s = S.me ? scoreOf(f.id) : null; - const img = posterUrl(f, "s"); - const anim = animate ? "" : ' style="animation:none"'; - const entry = S.me ? S.entries.get(f.id) : null; - - let yours = ""; - if (s) { - yours = `
${scoreHTML(s.score, "lg")} -
#${s.overall} of ${rankedCount()} in your list${BUCKETS[s.b].short} · #${s.i + 1} of ${s.n} in that group
- ${detailsFormHTML(entry)}`; - } else if (data && S.me) { - const fr = friendRowsFor(f.id); - const rec = recScore(fr, S.matches, data.stats); - if (rec) { - yours = `
${scoreHTML(rec.score, "lg")}
Rec score${ - rec.basis === "friends" ? `Predicted for you from ${rec.n} friend${rec.n === 1 ? "" : "s"}, weighted by taste match` : `Average from ${rec.n} member${rec.n === 1 ? "" : "s"}. Follow people to personalize it.` - }
`; - } - } - - const acts = !S.me - ? `${ICON.rank} Join Movi to rank it` - : s - ? ` - - - ` - : ` - - - `; - - const plot = det ? (det.plot ? `

${esc(det.plot)}

` : `

No summary available.

`) : `

Loading details…

`; - const cast = det?.cast?.length ? `

Starring ${esc(det.cast.slice(0, 8).join(", "))}

` : ""; - const wiki = det?.href ? `Read more on Wikipedia` : ""; - const global = data?.stats - ? `
${ICON.globe}${Number(data.stats.avg_score).toFixed(1)} average from ${data.stats.n} member${data.stats.n == 1 ? "" : "s"}
` - : data ? `
${ICON.globe}No one on Movi has ranked this yet${S.me && !s ? " — be the first" : ""}.
` : ""; - - let people = ""; - if (data?.others?.length) { - const fset = new Set(S.me ? followingIds() : []); - const others = data.others.filter((r) => r.profile && r.user_id !== S.me?.id); - const friends = others.filter((r) => fset.has(r.user_id)); - const rest = others.filter((r) => !fset.has(r.user_id)); - const row = (r) => `${avatarHTML(r.profile, 36)}${esc(r.profile.display_name || r.profile.username)}${demoTag(r.profile)}${r.note ? `“${esc(r.note.slice(0, 90))}${r.note.length > 90 ? "…" : ""}”` : `@${esc(r.profile.username)}`}${scoreHTML(r.score)}`; - if (friends.length) people += `

Friends who ranked it

${friends.slice(0, 12).map(row).join("")}
`; - if (rest.length) people += `

${friends.length ? "Others on Movi" : "On Movi"}

${rest.slice(0, 8).map(row).join("")}
`; - } - - const more = data ? (data.more ||= similarFilms(f, 14, { vary: true })) : []; - return `
- `; -} - -export function detailsFormHTML(e, { compact = false } = {}) { - e = e || {}; - return `
-
-
-
${PLACES.map((p) => ``).join("")}
- - -
`; -} - -export function readDetails(form) { - const fd = new FormData(form); - return { - watched_on: fd.get("watched_on") || null, - rewatch: fd.get("rewatch") === "on", - watched_where: form.querySelector("[data-where].on")?.dataset.where || "", - watched_with: String(fd.get("watched_with") || "").trim(), - note: String(fd.get("note") || "").trim(), - }; -} - -export function bindWhereChips(form, onChange) { - form.querySelectorAll("[data-where]").forEach((b) => - b.addEventListener("click", () => { - const on = !b.classList.contains("on"); - form.querySelectorAll("[data-where]").forEach((x) => x.classList.remove("on")); - if (on) b.classList.add("on"); - onChange?.(); - }), - ); -} - -function bindDetails(id) { - const form = $("#sheet #details"); - if (!form) return; - let t; - const saveSoon = () => { - clearTimeout(t); - t = setTimeout(() => updateDetails(id, readDetails(form)), 400); - }; - form.addEventListener("input", saveSoon); - form.addEventListener("change", saveSoon); - form.addEventListener("submit", (e) => e.preventDefault()); - bindWhereChips(form, saveSoon); -} - -export async function recommendDialog(filmId) { - const f = film(filmId); - const { following, followers } = await api.getFollows(S.me.id); - const seen = new Set(); - const people = [...following, ...followers].filter((x) => x.status === "accepted" && x.profile && !seen.has(x.id) && seen.add(x.id)); - if (!people.length) { - openModal(`

Recommend ${esc(f.title)}

Follow some people first, then you can send them films.

Find people
`); - return; - } - const dlg = openModal(`

Recommend ${esc(f.title)}

-

They'll get a notification and it'll show up in their Recs.

-
${people.map((x) => ``).join("")}
- -
`); - dlg.querySelector("#rec-send").addEventListener("click", async () => { - const ids = [...dlg.querySelectorAll("input[type=checkbox]:checked")].map((c) => c.value); - if (!ids.length) return toast("Pick at least one person"); - const msg = dlg.querySelector("#rec-msg").value.trim(); - try { - await Promise.all(ids.map((id) => api.sendRec(id, filmId, msg))); - closeModal(); - toast(`Sent to ${ids.length} ${ids.length === 1 ? "person" : "people"}`); - } catch (e) { - toast("Couldn't send: " + e.message); - } - }); -} - -export async function shareFilm(filmId) { - const f = film(filmId); - const s = S.me ? scoreOf(filmId) : null; - const url = `${location.origin}${location.pathname}#/film/${filmId}`; - const text = s ? `I gave ${f.title} (${f.year}) a ${s.score.toFixed(1)} on Movi` : `${f.title} (${f.year}) on Movi`; - try { - if (navigator.share) return await navigator.share({ title: f.title, text, url }); - } catch (e) { - if (e.name === "AbortError") return; - } - toast((await copyText(`${text} ${url}`)) ? "Link copied" : url); -} diff --git a/movi/js/films.js b/movi/js/films.js deleted file mode 100644 index b52af694..00000000 --- a/movi/js/films.js +++ /dev/null @@ -1,113 +0,0 @@ -import { norm } from "./util.js"; -import { DATA_VERSION } from "./data-version.js"; - -// Versioned URLs: the browser may reuse its copy without asking the server, until the data changes. -const dataUrl = (path) => fetch(`data/${path}?v=${DATA_VERSION}`, { cache: "force-cache" }); - -let DB = null; -const shardCache = new Map(); - -export async function loadFilms() { - const res = await dataUrl("index.json"); - if (!res.ok) throw new Error(`index.json ${res.status}`); - const raw = await res.json(); - DB = { - genres: raw.genres, - shard: raw.shard, - posterBase: raw.posterBase, - films: raw.films.map(([title, year, g, poster, pop], id) => ({ id, title, year, g, poster, pop, n: norm(title) })), - }; - const counts = new Array(DB.genres.length).fill(0); - DB.films.slice(0, 3000).forEach((f) => f.g.forEach((g) => counts[g]++)); - DB.genreFreq = counts.map((c) => Math.max(c, 1) / 3000); - DB.postersReady = loadRestPosters(raw.corePosters ?? DB.films.length); - return DB; -} - -// Posters beyond the most popular films arrive a moment after the first screen. -async function loadRestPosters(core) { - if (core >= DB.films.length) return; - try { - const rest = await (await dataUrl("posters.json")).json(); - rest.forEach((p, i) => { if (p && DB.films[core + i]) DB.films[core + i].poster = p; }); - document.dispatchEvent(new CustomEvent("movi:posters")); - } catch {} -} - -export const genreFreq = (name) => DB.genreFreq[DB.genres.indexOf(name)] ?? 0.05; - -export const filmCount = () => DB.films.length; -export const allFilms = () => DB.films; -export const genres = () => DB.genres; -export const film = (id) => DB.films[id]; -export const isFilmId = (id) => Number.isInteger(id) && id >= 0 && id < DB.films.length; -// TMDB serves fixed widths; pick the smallest that stays sharp at 2x for where the poster is shown. -const TMDB_SIZES = { s: "w185", m: "w342", l: "w500" }; -export const posterUrl = (f, size = "m") => - !f.poster ? "" : f.poster[0] === "~" ? `https://image.tmdb.org/t/p/${TMDB_SIZES[size] || "w342"}${f.poster.slice(1)}` : f.poster.startsWith("http") ? f.poster : DB.posterBase + f.poster; -export const genreNames = (f) => f.g.map((i) => DB.genres[i]); -export const genreIndex = (name) => DB.genres.indexOf(name); - -export function details(id) { - const n = Math.floor(id / DB.shard); - if (!shardCache.has(n)) { - shardCache.set( - n, - dataUrl(`details/${n}.json`) - .then((r) => r.json()) - .catch(() => { - shardCache.delete(n); - return []; - }), - ); - } - return shardCache.get(n).then((rows) => { - const [cast = [], plot = "", href = ""] = rows[id % DB.shard] || []; - return { cast, plot, href }; - }); -} - -const YEAR = /^(19|20)\d\d$/; - -export function searchFilms({ q = "", genre = "", decade = "", sort = "pop", exclude = null } = {}) { - const tokens = norm(q).split(" ").filter(Boolean); - const years = tokens.filter((t) => YEAR.test(t)).map(Number); - const words = tokens.filter((t) => !YEAR.test(t)); - const g = genre ? DB.genres.indexOf(genre) : -1; - const dec = decade ? Number(decade) : null; - const phrase = words.join(" "); - const out = []; - for (const f of DB.films) { - if (exclude && exclude.has(f.id)) continue; - if (g >= 0 && !f.g.includes(g)) continue; - if (dec !== null && (f.year < dec || f.year >= dec + 10)) continue; - let rel = 0; - if (years.length) { - const titleHasYear = years.every((y) => ` ${f.n} `.includes(` ${y} `)); - if (!years.includes(f.year) && !titleHasYear) continue; - if (titleHasYear) rel += 2; - } - if (words.length) { - if (!words.every((w) => f.n.includes(w))) continue; - rel += f.n === phrase ? 3 : f.n.startsWith(phrase) ? 2 : ` ${f.n}`.includes(` ${words[0]}`) ? 1 : 0; - } - out.push([rel, f]); - } - const sorters = { - pop: (a, b) => b[0] - a[0] || a[1].id - b[1].id, - new: (a, b) => b[0] - a[0] || b[1].year - a[1].year || a[1].id - b[1].id, - old: (a, b) => b[0] - a[0] || a[1].year - b[1].year || a[1].id - b[1].id, - az: (a, b) => a[1].n.localeCompare(b[1].n), - }; - return out.sort(sorters[sort] || sorters.pop).map((x) => x[1]); -} - -export function topByGenre(name, limit = 20, exclude = null) { - const g = DB.genres.indexOf(name); - const out = []; - for (const f of DB.films) { - if (f.g.includes(g) && !(exclude && exclude.has(f.id))) out.push(f); - if (out.length >= limit) break; - } - return out; -} diff --git a/movi/js/matcher.js b/movi/js/matcher.js deleted file mode 100644 index 2199a58c..00000000 --- a/movi/js/matcher.js +++ /dev/null @@ -1,170 +0,0 @@ -// Turns a typed list of watched movies ("karate kid, star wars 1, harry potter") into films. -// A local matcher always runs; when the match-films Edge Function is set up, Claude resolves -// nicknames, numbering and franchises, and its answers are mapped back onto the local database. -import { allFilms } from "./films.js"; -import { api } from "./api/index.js"; -import { norm } from "./util.js"; - -const ROMAN = ["", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x"]; -const WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }; -const AI_CHUNK = 60; - -let titleIndex = null; -function exactTitles() { - if (!titleIndex) { - titleIndex = new Map(); - for (const f of allFilms()) (titleIndex.get(f.n) || titleIndex.set(f.n, []).get(f.n)).push(f); - } - return titleIndex; -} - -const numberOf = (word) => { - if (/^\d{1,2}$/.test(word)) return Number(word); - if (WORDS[word]) return WORDS[word]; - const r = ROMAN.indexOf(word); - return r > 0 ? r : 0; -}; -const titleNumbers = (n) => n.split(" ").map(numberOf).filter(Boolean); - -export function splitInput(text) { - const out = []; - for (let line of text.split(/\r?\n/)) { - line = line.replace(/^\s*(?:[-*•·]|\d{1,3}[.)])\s+/, "").trim(); - if (!line) continue; - if (exactTitles().has(norm(line))) { out.push(line); continue; } - // Split on commas, but rejoin neighbors that together form a known title ("Crouching Tiger, Hidden Dragon"). - const parts = line.split(/\s*[,;|]\s*|\s+\/\s+/).filter((p) => p.trim()); - for (let i = 0; i < parts.length; ) { - let take = 1; - for (let j = Math.min(parts.length, i + 4); j > i + 1; j--) { - if (exactTitles().has(norm(parts.slice(i, j).join(", ")))) { take = j - i; break; } - } - out.push(parts.slice(i, i + take).join(", ").trim()); - i += take; - } - } - const seen = new Set(); - return out.filter((t) => !seen.has(norm(t)) && seen.add(norm(t))); -} - -function parse(raw) { - let n = norm(raw); - let year = null; - const ym = n.match(/\b(19[0-9]{2}|20[0-4][0-9])\b/); - if (ym && n !== ym[1]) { - year = Number(ym[1]); - n = n.replace(ym[0], " ").replace(/\s+/g, " ").trim(); - } - let part = 0; - const pm = n.match(/\b(?:part|episode|ep|chapter|vol|volume)\s+(\w+)\b/); - if (pm && numberOf(pm[1])) { - part = numberOf(pm[1]); - n = n.replace(pm[0], " ").replace(/\s+/g, " ").trim(); - } else { - const words = n.split(" "); - const last = words[words.length - 1]; - if (words.length > 1 && numberOf(last) && !exactTitles().has(n)) { - part = numberOf(last); - n = words.slice(0, -1).join(" "); - } - } - return { raw, base: n.replace(/^the /, ""), year, part }; -} - -function scoreFilm(f, q, words) { - const t = f.n.replace(/^the /, ""); - let s = f.pop / 5; - if (t === q.base) s += 100; - else if (t.startsWith(q.base)) s += 30; - s -= Math.max(0, t.split(" ").length - words.length) * 3; - const nums = titleNumbers(t); - if (q.part) { - if (nums.includes(q.part)) s += 150; - else if (q.part === 1 && !nums.length) s += 40; - else s -= nums.length ? 40 : 30; - } else if (nums.length && t !== q.base) s -= 15; - if (q.year) { - // A number like 2049 may be part of the title ("Blade Runner 2049") rather than a release year. - if (` ${t} `.includes(` ${q.year} `)) s += 150; - else s += f.year === q.year ? 80 : Math.abs(f.year - q.year) === 1 ? 40 : -20; - } - return s; -} - -function localMatch(raw) { - const q = parse(raw); - const words = q.base.split(" ").filter(Boolean); - if (!words.length) return { text: raw, film: null, alts: [], series: [], hints: [] }; - const squashed = q.base.replace(/ /g, ""); - const cands = []; - for (const f of allFilms()) { - const padded = ` ${f.n} `; - // "spiderman" should find "Spider-Man": also compare with spaces removed. - if (words.every((w) => padded.includes(` ${w}`)) || (squashed.length >= 5 && f.n.replace(/ /g, "").includes(squashed))) { - cands.push([scoreFilm(f, q, words), f]); - } - } - cands.sort((a, b) => b[0] - a[0]); - const top = cands.slice(0, 8).map((c) => c[1]); - let best = cands.length && (cands[0][0] >= 40 || cands.length === 1) ? cands[0][1] : null; - let series = []; - if (!q.part && !q.year) { - // A franchise name on its own ("harry potter"): suggest the first film and offer the rest. - const family = cands.filter(([, f]) => f.n.replace(/^the /, "").startsWith(q.base) && f.pop >= 15).map((c) => c[1]); - const exact = family.find((f) => f.n.replace(/^the /, "") === q.base); - if (family.length >= 3 || (family.length >= 2 && !exact)) { - const ordered = [...family].sort((a, b) => a.year - b.year); - if (!best || !exact) best = ordered[0]; - series = ordered.filter((f) => f.id !== best.id); - } - } - return { text: raw, film: best?.id ?? null, alts: top.filter((f) => f.id !== best?.id).slice(0, 6).map((f) => f.id), series: series.slice(0, 11).map((f) => f.id), hints: top }; -} - -function lookup(title, year) { - const n = norm(title); - const exact = (exactTitles().get(n) || []).concat(n.startsWith("the ") ? [] : exactTitles().get("the " + n) || []); - const byYear = exact.filter((f) => Math.abs(f.year - year) <= 1).sort((a, b) => Math.abs(a.year - year) - Math.abs(b.year - year)); - if (byYear.length) return byYear[0].id; - if (exact.length === 1) return exact[0].id; - const m = localMatch(`${title} ${year}`); - return m.film; -} - -export async function matchTitles(text, { useAi = true } = {}) { - const lines = splitInput(text); - const local = lines.map(localMatch); - let usedAi = false; - if (useAi && lines.length) { - const results = []; - for (let i = 0; i < lines.length; i += AI_CHUNK) { - const chunk = local.slice(i, i + AI_CHUNK).map((m) => ({ text: m.text, hints: m.hints.map((f) => ({ title: f.title, year: f.year })) })); - let res = null; - try { res = await api.matchTitles(chunk); } catch { res = null; } - if (!res) break; - res.forEach((r) => results.push({ ...r, line: r.line + i })); - } - if (results.length) { - usedAi = true; - for (const r of results) { - const m = local[r.line]; - if (!m) continue; - const ids = (r.films || []).map((f) => lookup(f.title, f.year)).filter((id) => id != null); - if (ids.length) { - m.film = ids[0]; - m.extra = ids.slice(1); - m.alts = m.alts.filter((id) => !ids.includes(id)); - } - const series = (r.series || []).map((f) => lookup(f.title, f.year)).filter((id) => id != null && !ids.includes(id)); - if (series.length) m.series = series; - else if (ids.length) m.series = m.series.filter((id) => !ids.includes(id)); - } - } - } - const items = []; - for (const m of local) { - items.push({ text: m.text, film: m.film, alts: m.alts, series: m.series, include: m.film != null, addSeries: false }); - for (const id of m.extra || []) items.push({ text: m.text, film: id, alts: [], series: [], include: true, addSeries: false }); - } - return { items, usedAi }; -} diff --git a/movi/js/model.js b/movi/js/model.js deleted file mode 100644 index 1b611a0e..00000000 --- a/movi/js/model.js +++ /dev/null @@ -1,156 +0,0 @@ -import { ICON } from "./util.js"; -import { film, genreNames, genreFreq } from "./films.js"; - -export const BUCKETS = { - loved: { label: "I loved it", short: "Loved", lo: 6.8, hi: 10, icon: ICON.heart, hint: "Scores 6.8 – 10" }, - fine: { label: "It was fine", short: "Fine", lo: 3.4, hi: 6.7, icon: ICON.meh, hint: "Scores 3.4 – 6.7" }, - disliked: { label: "Didn't like it", short: "Didn't like", lo: 0, hi: 3.3, icon: ICON.down, hint: "Scores 0 – 3.3" }, -}; -export const ORDER = ["loved", "fine", "disliked"]; - -// Keep in sync with public.movi_score() in supabase/migrations. -export function scoreFor(bucket, i, n) { - const { lo, hi } = BUCKETS[bucket]; - const s = n <= 1 ? lo + (hi - lo) * 0.75 : hi - (hi - lo) * (i / (n - 1)); - return Math.round(s * 10) / 10; -} - -export const bucketForScore = (s) => (s >= 6.8 ? "loved" : s >= 3.4 ? "fine" : "disliked"); - -export function listsFromRows(rows) { - const lists = { loved: [], fine: [], disliked: [] }; - for (const r of [...rows].sort((a, b) => a.pos - b.pos)) lists[r.bucket]?.push(r.film_id); - return lists; -} - -export function rowsWithScores(rows) { - const lists = listsFromRows(rows); - const byId = new Map(rows.map((r) => [r.film_id, r])); - let offset = 0; - const out = []; - for (const b of ORDER) { - lists[b].forEach((id, i) => out.push({ ...byId.get(id), bucket: b, pos: i, score: scoreFor(b, i, lists[b].length), overall: offset + i + 1 })); - offset += lists[b].length; - } - return out; -} - -export function tasteMatch(rowsA, rowsB) { - const a = new Map(rowsA.map((r) => [r.film_id, Number(r.score)])); - const common = []; - for (const r of rowsB) if (a.has(r.film_id)) common.push([r.film_id, a.get(r.film_id), Number(r.score)]); - if (common.length < 3) return { pct: null, common }; - const diff = common.reduce((t, [, x, y]) => t + Math.abs(x - y), 0) / common.length; - return { pct: Math.max(0, Math.min(100, Math.round(100 - diff * 11))), common }; -} - -export function recScore(friendRows, matches, global) { - if (friendRows.length) { - let w = 0, s = 0; - for (const r of friendRows) { - const m = matches.get(r.user_id); - const wt = Math.pow((m ?? 60) / 100, 2) + 0.05; - w += wt; - s += wt * Number(r.score); - } - let score = s / w; - if (global && global.n > friendRows.length && friendRows.length < 3) score = score * 0.7 + Number(global.avg_score) * 0.3; - return { score: Math.round(score * 10) / 10, basis: "friends", n: friendRows.length }; - } - if (global && global.n) return { score: Number(global.avg_score), basis: "everyone", n: Number(global.n) }; - return null; -} - -export function genreAffinity(rows, genreCount) { - const a = new Array(genreCount).fill(0); - for (const r of rows) { - const w = (Number(r.score) - 5) / 5; - for (const g of film(r.film_id).g) a[g] += w; - } - return a; -} - -export function tasteStats(rows) { - const stats = new Map(); - for (const r of rows) { - for (const g of genreNames(film(r.film_id))) { - const e = stats.get(g) || { g, n: 0, sum: 0 }; - e.n++; - e.sum += Number(r.score); - stats.set(g, e); - } - } - return [...stats.values()].sort((a, b) => b.n - a.n || b.sum - a.sum); -} - -const ARCHETYPES = { - Horror: "The Night Owl", "Science Fiction": "The Futurist", Animated: "The Dreamer", Drama: "The Auteur", - Comedy: "The Jester", Action: "The Thrill Seeker", Romance: "The Romantic", Crime: "The Detective", - Thriller: "The Detective", Mystery: "The Detective", Noir: "The Detective", Western: "The Drifter", - War: "The Historian", Historical: "The Historian", Biography: "The Historian", Musical: "The Showstopper", - Superhero: "The Hero Collector", Fantasy: "The Myth Maker", Adventure: "The Explorer", Documentary: "The Truth Seeker", -}; -export function archetype(rows) { - if (rows.length < 3) return "Just getting started"; - const min = rows.length >= 12 ? 3 : 2; - const top = tasteStats(rows) - .filter((e) => ARCHETYPES[e.g] && e.n >= min) - .map((e) => ({ ...e, lift: (e.n / rows.length / Math.sqrt(genreFreq(e.g))) * (e.sum / e.n / 10) })) - .sort((a, b) => b.lift - a.lift)[0]; - const base = top ? ARCHETYPES[top.g] : "The Explorer"; - const avg = rows.reduce((t, r) => t + Number(r.score), 0) / rows.length; - return avg >= 7.5 ? `${base} · easy to please` : avg <= 4.5 ? `${base} · tough critic` : base; -} - -const WEEK = 7 * 86400000; -const MONDAY = Date.UTC(1970, 0, 5); -const weekOf = (t) => Math.floor((t - MONDAY) / WEEK); - -export function streaks(rows) { - const weeks = new Set(rows.map((r) => weekOf(new Date(r.created_at).getTime()))); - const now = weekOf(Date.now()); - let cur = 0; - let w = weeks.has(now) ? now : now - 1; - while (weeks.has(w)) { cur++; w--; } - let longest = 0, run = 0, prev = null; - for (const x of [...weeks].sort((a, b) => a - b)) { - run = prev !== null && x === prev + 1 ? run + 1 : 1; - longest = Math.max(longest, run); - prev = x; - } - return { current: cur, longest, activeThisWeek: weeks.has(now) }; -} - -export function goalProgress(rows, goal) { - const year = new Date().getFullYear(); - const done = rows.filter((r) => new Date(r.watched_on || r.created_at).getFullYear() === year).length; - return { year, done, goal, pct: Math.min(100, Math.round((done / goal) * 100)) }; -} - -export function badges({ rows, followers = 0, following = 0 }) { - const n = rows.length; - const genreSet = new Set(rows.flatMap((r) => genreNames(film(r.film_id)))); - const decades = new Set(rows.map((r) => Math.floor(film(r.film_id).year / 10))); - const count = (fn) => rows.filter(fn).length; - const st = streaks(rows); - const defs = [ - ["first", "First Take", "Rank your first film", n, 1], - ["ten", "Getting Into It", "Rank 10 films", n, 10], - ["fifty", "Cinephile", "Rank 50 films", n, 50], - ["hundred", "Film Buff", "Rank 100 films", n, 100], - ["twofifty", "Archivist", "Rank 250 films", n, 250], - ["fivehundred", "Projectionist", "Rank 500 films", n, 500], - ["genres", "Genre Hopper", "Rank films in 10 genres", genreSet.size, 10], - ["decades", "Time Traveler", "Rank films from 6 decades", decades.size, 6], - ["classics", "Golden Age", "Rank 10 films from before 1960", count((r) => film(r.film_id).year < 1960), 10], - ["loved", "Superfan", "Love 25 films", count((r) => r.bucket === "loved"), 25], - ["critic", "Tough Crowd", "Dislike 10 films", count((r) => r.bucket === "disliked"), 10], - ["notes", "Critic's Notebook", "Write 10 notes", count((r) => (r.note || "").trim()), 10], - ["rewatch", "Rewatcher", "Log 5 rewatches", count((r) => r.rewatch), 5], - ["theater", "Front Row", "Watch 5 films in a theater", count((r) => r.watched_where === "Theater"), 5], - ["streak", "On a Roll", "Rank films 4 weeks in a row", st.longest, 4], - ["social", "Social Butterfly", "Follow 5 people", following, 5], - ["tastemaker", "Tastemaker", "Get 5 followers", followers, 5], - ]; - return defs.map(([id, name, desc, value, target]) => ({ id, name, desc, value: Math.min(value, target), target, earned: value >= target })); -} diff --git a/movi/js/rank-flow.js b/movi/js/rank-flow.js deleted file mode 100644 index 547b9c31..00000000 --- a/movi/js/rank-flow.js +++ /dev/null @@ -1,258 +0,0 @@ -import { $, esc, ICON, toast, debounce, today } from "./util.js"; -import { film, searchFilms, filmCount } from "./films.js"; -import { BUCKETS, ORDER } from "./model.js"; -import { api } from "./api/index.js"; -import { S, scoreOf, rankedCount, detachRanking, restoreLists, commitRanking, updateDetails } from "./state.js"; -import { posterHTML, openLayer, closeLayer, openModal, closeModal, scoreHTML, reduceMotion } from "./ui.js"; -import { detailsFormHTML, readDetails, bindWhereChips, recommendFor } from "./film-sheet.js"; - -let F = null; -// "Rank all, one by one": films still waiting after the current one, and how many the run started with. -let queue = []; -let queueTotal = 0; - -export function startQueue(ids) { - if (!ids.length) return; - queue = ids.slice(1); - queueTotal = ids.length; - startRank(ids[0]); -} - -let onDone = null; - -export const flowActive = () => !!F; -export function setFlowDoneHandler(fn) { onDone = fn; } - -export function startRank(id) { - const { prev, place } = detachRanking(id); - F = { id, prev, wasRanked: !!place, prevBucket: place?.b ?? null, step: "feel", bucket: null, lo: 0, hi: 0, history: [], comps: 0, max: 0, busy: false, against: [] }; - openLayer("#flow", ""); - render(); -} - -export function cancelRank() { - if (!F || F.step === "saving") return; - if (F.step !== "done") restoreLists(F.prev); - F = null; - queue = []; - queueTotal = 0; - closeLayer("#flow"); -} - -// Leaves this film for later and moves on to the next one in the queue. -function skipInQueue() { - if (!F) return; - restoreLists(F.prev); - F = null; - if (queue.length) return startRank(queue.shift()); - queueTotal = 0; - closeLayer("#flow"); -} - -function chooseBucket(b) { - F.bucket = b; - F.lo = 0; - F.hi = S.lists[b].length; - F.max = Math.ceil(Math.log2(F.hi + 1)); - F.step = "duel"; - if (F.lo >= F.hi) return finish(); - render(); -} - -function pick(newIsBetter, tie = false) { - if (!F || F.busy || F.step !== "duel") return; - const mid = (F.lo + F.hi) >> 1; - F.history.push([F.lo, F.hi]); - F.against.push(S.lists[F.bucket][mid]); - F.comps++; - if (tie) F.lo = F.hi = mid + 1; - else if (newIsBetter) F.hi = mid; - else F.lo = mid + 1; - const next = () => (F.lo >= F.hi ? finish() : render()); - if (tie) return next(); - const flow = F; - F.busy = true; - navigator.vibrate?.(8); - $(newIsBetter ? "#pick-new" : "#pick-old")?.classList.add("chosen"); - $(newIsBetter ? "#pick-old" : "#pick-new")?.classList.add("lost"); - // Only continue if this is still the same ranking (it may have been closed in the meantime). - setTimeout(() => { if (F === flow) { F.busy = false; next(); } }, 260); -} - -function undo() { - if (!F.history.length) { - F.step = "feel"; - return render(); - } - [F.lo, F.hi] = F.history.pop(); - F.against.pop(); - F.comps--; - render(); -} - -async function finish() { - const flow = F; - F.step = "saving"; - render(); - try { - await commitRanking({ filmId: F.id, bucket: F.bucket, index: F.lo, prev: F.prev }); - } catch { - F = null; - queue = []; - queueTotal = 0; - closeLayer("#flow"); - return; - } - if (F !== flow) return; - F.step = "done"; - const e = S.entries.get(F.id); - if (!e.watched_on && !F.wasRanked) e.watched_on = today(); - render(); - sparks(); -} - -async function complete(next = null) { - if (!F) return; - const f = F; - const form = $("#flow #details"); - const det = form ? readDetails(form) : null; - // In "Rank all, one by one" the ranking screen stays open and moves straight to the next film. - const continuing = next !== "another" && queue.length > 0; - F = null; - if (!continuing) closeLayer("#flow"); - if (det) await updateDetails(f.id, det); - if (!f.wasRanked || f.prevBucket !== f.bucket) { - const s = scoreOf(f.id); - api.postActivity({ kind: "ranked", film_id: f.id, bucket: s.b, score: s.score, note: det?.note || "" }).catch(() => {}); - } - onDone?.(f.id); - if (next === "another") { queue = []; queueTotal = 0; quickAdd(); } - else if (continuing) startRank(queue.shift()); - else queueTotal = 0; -} - -function render() { - const el = $("#flow"); - if (!F) return; - const f = film(F.id); - const stepLabel = (queueTotal ? `Film ${queueTotal - queue.length} of ${queueTotal} · ` : "") + { feel: "Step 1 of 2", duel: "Step 2 of 2", saving: "Saving…", done: "Ranked" }[F.step]; - const top = `
${stepLabel} - ${F.step === "saving" ? "" : ``}
`; - let body = ""; - if (F.step === "feel") { - body = `
${posterHTML(f)}

How was ${esc(f.title)}?

-

${F.wasRanked ? "Re-ranking from scratch. " : ""}Go with your gut — you'll fine-tune it next.

-
${ORDER.map((b, i) => ``).join("")}
- ${queueTotal ? `
` : ""}`; - } else if (F.step === "duel") { - const mid = (F.lo + F.hi) >> 1; - const opp = film(S.lists[F.bucket][mid]); - const dots = Array.from({ length: F.max }, (_, i) => ``).join(""); - body = `

Which did you like more?

Tap one, or use ← and →

-
- -
VS
- -
${dots}
-
`; - } else if (F.step === "saving") { - body = `
`; - } else { - const s = scoreOf(F.id); - const beat = F.against.filter((id) => scoreOf(id).overall > s.overall).map((id) => film(id).title); - body = `
-
${s.score.toFixed(1)}
-

${esc(f.title)}

-

#${s.overall} of ${rankedCount()} in your list · ${BUCKETS[s.b].short}${F.comps ? ` · ${F.comps} pick${F.comps === 1 ? "" : "s"}` : ""}

- ${beat.length ? `

Ranked above ${beat.slice(0, 2).map(esc).join(" and ")}${beat.length > 2 ? ` and ${beat.length - 2} more` : ""}

` : ""} -
${detailsFormHTML(S.entries.get(F.id))}
-
`; - } - el.innerHTML = `
${top}${body}
`; - el.scrollTop = 0; - // Each step replaces the screen; put keyboard focus on its first choice. - el.querySelector(".feel, #pick-new, .flow-foot .btn.primary")?.focus({ preventScroll: true }); - if (F.step === "done") { - const form = $("#flow #details"); - bindWhereChips(form); - form.addEventListener("submit", (e) => e.preventDefault()); - } -} - -function sparks() { - navigator.vibrate?.([12, 40, 18]); - if (reduceMotion()) return; - const colors = ["#e5484d", "#ff8589", "#f2f0ee", "#6fdcb0"]; - for (let i = 0; i < 28; i++) { - const s = document.createElement("i"); - s.className = "spark"; - const a = (Math.PI * 2 * i) / 28; - const r = 130 + Math.random() * 120; - s.style.cssText = `background:${colors[i % 4]};--dx:${Math.cos(a) * r}px;--dy:${Math.sin(a) * r}px`; - $("#flow").appendChild(s); - setTimeout(() => s.remove(), 1100); - } -} - -export function flowAction(name, el) { - switch (name) { - case "feel": return chooseBucket(el.dataset.b); - case "pick-new": return pick(true); - case "pick-old": return pick(false); - case "tie": return pick(false, true); - case "undo": return undo(); - case "flow-cancel": return cancelRank(); - case "flow-done": return complete(); - case "flow-another": return complete("another"); - case "queue-skip": return skipInQueue(); - } -} - -export function flowKey(e) { - if (!F) return false; - if (e.key === "Escape") { F.step === "done" ? complete() : cancelRank(); return true; } - if (["INPUT", "TEXTAREA"].includes(e.target.tagName)) return true; - if (F.step === "feel" && ["1", "2", "3"].includes(e.key)) chooseBucket(ORDER[Number(e.key) - 1]); - else if (F.step === "duel" && e.key === "ArrowLeft") pick(true); - else if (F.step === "duel" && e.key === "ArrowRight") pick(false); - return true; -} - -// ---------- Quick add: search any film and rank it ---------- -export function quickAdd() { - const dlg = openModal(`

Rank a film

- -
- ${ICON.list}Seen a lot of movies?Type them all at once and rank them later${ICON.chevron}`, { wide: true }); - const input = dlg.querySelector("#qa"); - const out = dlg.querySelector("#qa-results"); - // Before typing: a fresh, personalized set every time the box opens (and on Shuffle). - let suggestions = recommendFor(12); - const draw = () => { - const q = input.value.trim(); - const films = q ? searchFilms({ q }).slice(0, 30) : suggestions; - out.innerHTML = (q ? "" : `

Suggested for you · seen any?

`) + (films.length - ? films.map((f) => { - const s = scoreOf(f.id); - return ``; - }).join("") - : `

No films match “${esc(q)}”.

`); - }; - input.addEventListener("input", debounce(draw, 120)); - out.addEventListener("click", (e) => { - if (!e.target.closest("#qa-shuffle")) return; - suggestions = recommendFor(12); - draw(); - }); - draw(); -} - -export function quickPick(id) { - closeModal(); - startRank(id); -} - -export function requireMe() { - if (!S.me) { toast("Sign in to rank films"); location.hash = "#/welcome"; return false; } - return true; -} diff --git a/movi/js/state.js b/movi/js/state.js deleted file mode 100644 index 460707b3..00000000 --- a/movi/js/state.js +++ /dev/null @@ -1,219 +0,0 @@ -// The signed-in user's data, cached in memory, plus the actions that change it. -import { api } from "./api/index.js"; -import { ORDER, scoreFor, listsFromRows, rowsWithScores, tasteMatch } from "./model.js"; -import { toast } from "./util.js"; - -const blankLists = () => ({ loved: [], fine: [], disliked: [] }); - -export const S = { - me: null, - lists: blankLists(), - entries: new Map(), - watch: [], - backlog: [], - following: new Map(), - followers: [], - friendRows: null, - matches: new Map(), - unread: 0, - skip: new Set(), -}; - -const skipKey = () => `movi.skip.${S.me?.id}`; - -export async function loadSession() { - if (!api.uid) return clearSession(); - const uid = api.uid; - const [me, rows, watch, follows] = await Promise.all([api.getProfile(uid), api.getRankings(uid), api.getWatchlist(uid), api.getFollows(uid)]); - if (!me) { - await api.signOut(); - return clearSession(); - } - S.me = me; - S.lists = listsFromRows(rows); - S.entries = new Map(rows.map((r) => [r.film_id, r])); - S.watch = watch; - S.backlog = await api.getBacklog().catch(() => []); - S.following = new Map(follows.following.map((f) => [f.id, f.status])); - S.followers = follows.followers; - S.friendRows = null; - S.matches = new Map(); - try { S.skip = new Set(JSON.parse(localStorage.getItem(skipKey()) || "[]")); } catch { S.skip = new Set(); } - refreshUnread(); - return me; -} - -export function clearSession() { - Object.assign(S, { me: null, lists: blankLists(), entries: new Map(), watch: [], backlog: [], following: new Map(), followers: [], friendRows: null, matches: new Map(), unread: 0, skip: new Set() }); - return null; -} - -export const signedIn = () => !!S.me; -export const rankedIds = () => ORDER.flatMap((b) => S.lists[b]); -export const rankedCount = () => rankedIds().length; -export const myRows = () => rowsWithScores([...S.entries.values()].filter((r) => findBucket(r.film_id)).map((r) => ({ ...r, ...placement(r.film_id) }))); -export const isWatch = (id) => S.watch.some((w) => w.film_id === id); -export const followingIds = () => [...S.following].filter(([, s]) => s === "accepted").map(([id]) => id); -export const followStatus = (id) => S.following.get(id) || null; -export const acceptedFollowers = () => S.followers.filter((f) => f.status === "accepted"); -export const pendingRequests = () => S.followers.filter((f) => f.status === "pending"); - -function findBucket(id) { - for (const b of ORDER) if (S.lists[b].includes(id)) return b; - return null; -} -function placement(id) { - const b = findBucket(id); - return { bucket: b, pos: S.lists[b].indexOf(id) }; -} - -export function scoreOf(id) { - let offset = 0; - for (const b of ORDER) { - const list = S.lists[b]; - const i = list.indexOf(id); - if (i >= 0) return { b, i, n: list.length, score: scoreFor(b, i, list.length), overall: offset + i + 1 }; - offset += list.length; - } - return null; -} - -export const avgScore = () => { - const ids = rankedIds(); - return ids.length ? ids.reduce((t, id) => t + scoreOf(id).score, 0) / ids.length : 0; -}; - -async function persistLists(prev) { - try { - await api.saveLists(S.lists); - S.me.ranked_count = rankedCount(); - recomputeMatches(); - } catch (e) { - S.lists = prev; - toast("Couldn't save your ranking: " + e.message); - throw e; - } -} -const copyLists = () => ({ loved: [...S.lists.loved], fine: [...S.lists.fine], disliked: [...S.lists.disliked] }); - -export function detachRanking(id) { - const prev = copyLists(); - const place = scoreOf(id); - for (const b of ORDER) S.lists[b] = S.lists[b].filter((x) => x !== id); - return { prev, place }; -} -export function restoreLists(prev) { S.lists = prev; } - -export async function commitRanking({ filmId, bucket, index, prev }) { - S.lists[bucket].splice(index, 0, filmId); - await persistLists(prev); - const now = new Date().toISOString(); - const entry = { note: "", watched_on: null, watched_where: "", watched_with: "", rewatch: false, created_at: now, ...S.entries.get(filmId), film_id: filmId }; - S.entries.set(filmId, entry); - if (isWatch(filmId)) await removeWatch(filmId, true); - if (inBacklog(filmId)) await removeBacklog(filmId); - S.skip.delete(filmId); - saveSkip(); -} - -export async function removeRanking(id) { - const { prev } = detachRanking(id); - await persistLists(prev); - S.entries.delete(id); -} - -export async function updateDetails(id, patch) { - const e = S.entries.get(id); - if (!e) return; - Object.assign(e, patch); - try { await api.updateEntry(id, patch); } catch (err) { toast("Couldn't save details: " + err.message); } -} - -export async function addWatch(id, fromUser = null) { - if (isWatch(id)) return; - S.watch.unshift({ film_id: id, from_user: fromUser, created_at: new Date().toISOString() }); - try { - await api.addWatch(id, fromUser); - api.postActivity({ kind: "want", film_id: id }).catch(() => {}); - } catch (e) { - S.watch = S.watch.filter((w) => w.film_id !== id); - toast("Couldn't save: " + e.message); - } -} -export async function removeWatch(id, quiet = false) { - const prev = S.watch; - S.watch = S.watch.filter((w) => w.film_id !== id); - try { await api.removeWatch(id); } catch (e) { S.watch = prev; if (!quiet) toast("Couldn't remove: " + e.message); } -} - -export function skipFilm(id) { S.skip.add(id); saveSkip(); } -function saveSkip() { try { localStorage.setItem(skipKey(), JSON.stringify([...S.skip])); } catch {} } - -export async function follow(id) { - const status = await api.follow(id); - S.following.set(id, status); - S.friendRows = null; - return status; -} -export async function unfollow(id) { - await api.unfollow(id); - S.following.delete(id); - S.friendRows = null; -} -export async function approveFollower(id) { - await api.approveFollower(id); - const f = S.followers.find((x) => x.id === id); - if (f) f.status = "accepted"; -} -export async function removeFollower(id) { - await api.removeFollower(id); - S.followers = S.followers.filter((x) => x.id !== id); -} -export async function reloadFollows() { - const f = await api.getFollows(S.me.id); - S.following = new Map(f.following.map((x) => [x.id, x.status])); - S.followers = f.followers; -} - -export async function loadFriendRows() { - if (S.friendRows) return S.friendRows; - S.friendRows = await api.rankingsOfUsers(followingIds()); - recomputeMatches(); - return S.friendRows; -} -function recomputeMatches() { - if (!S.friendRows) return; - const mine = myRows(); - const byUser = new Map(); - for (const r of S.friendRows) (byUser.get(r.user_id) || byUser.set(r.user_id, []).get(r.user_id)).push(r); - S.matches = new Map([...byUser].map(([u, rows]) => [u, tasteMatch(mine, rows).pct])); -} -export const friendRowsFor = (filmId) => (S.friendRows || []).filter((r) => r.film_id === filmId); - -export async function refreshUnread() { - if (!S.me) return 0; - try { S.unread = await api.unreadCount(); } catch {} - document.dispatchEvent(new CustomEvent("movi:unread")); - return S.unread; -} - -export async function updateMe(patch) { - S.me = await api.updateProfile(patch); - return S.me; -} - -export const inBacklog = (id) => S.backlog.some((b) => b.film_id === id); - -export async function addBacklog(ids) { - const fresh = [...new Set(ids)].filter((id) => !inBacklog(id) && !scoreOf(id)); - if (!fresh.length) return 0; - await api.addBacklog(fresh); - const now = Date.now(); - S.backlog = [...fresh.map((film_id, i) => ({ film_id, created_at: new Date(now - i).toISOString() })), ...S.backlog]; - return fresh.length; -} - -export async function removeBacklog(id) { - S.backlog = S.backlog.filter((b) => b.film_id !== id); - try { await api.removeBacklog(id); } catch (e) { toast("Couldn't update your To rank list: " + e.message); } -} diff --git a/movi/js/ui.js b/movi/js/ui.js deleted file mode 100644 index 46c6b243..00000000 --- a/movi/js/ui.js +++ /dev/null @@ -1,161 +0,0 @@ -import { $, esc, hash, ICON } from "./util.js"; -import { film, posterUrl } from "./films.js"; -import { bucketForScore } from "./model.js"; -import { S, scoreOf, isWatch } from "./state.js"; - -export function posterHTML(f, size = "m") { - const h = hash(f.title) % 360; - const img = f.poster ? `` : ""; - return `
${img}
`; -} - -export function scoreHTML(score, cls = "") { - if (score == null) return ""; - return `${Number(score).toFixed(1)}`; -} - -export function cardHTML(f, { acts = "", label = "" } = {}) { - const s = S.me ? scoreOf(f.id) : null; - const badge = s ? `${s.score.toFixed(1)}` : ""; - const rib = !s && S.me && isWatch(f.id) ? `${ICON.bookmark}` : ""; - return `
${badge}${rib}${acts}
`; -} - -export const railHTML = (films, opts) => `
${films.map((f) => cardHTML(f, opts?.(f))).join("")}
`; - -export const sectionHTML = (title, sub, body, link = "") => - `

${title}

${sub ? `

${sub}

` : ""}
${link}
${body}
`; - -export const emptyHTML = ({ title, text = "", action = "" }) => `

${title}

${text ? `

${text}

` : ""}${action}
`; - -export function avatarHTML(p, size = 40) { - if (!p) return ``; - const h = p.avatar_hue ?? 40; - const ch = (p.display_name || p.username || "?").trim()[0]?.toUpperCase() || "?"; - return ``; -} - -export const userHref = (p) => `#/u/${encodeURIComponent(p.username)}`; -export const nameHTML = (p) => `${esc(p.display_name || p.username)}`; -export const demoTag = (p) => (p?.demo ? `Demo` : ""); - -export function userRowHTML(p, right = "", sub = "") { - return `
${avatarHTML(p, 44)}${esc(p.display_name || p.username)}${p.is_private ? `${ICON.lock}` : ""}${demoTag(p)}@${esc(p.username)}${sub ? " · " + sub : ""}${right}
`; -} - -// ---------- Layers: film sheet (#sheet), dialog (#modal), ranking flow (#flow) ---------- -function lock() { document.body.classList.add("locked"); } -export { reduceMotion }; -// Runs a DOM update as a View Transition where supported: tab switches cross-fade with the -// highlight sliding across, and with { cards: true } list items glide into place as others leave. -export function withTransition(update, { cards = false } = {}) { - if (!document.startViewTransition || reduceMotion()) return Promise.resolve(update()); - const root = document.documentElement; - if (cards) root.classList.add("vt-cards"); - const t = document.startViewTransition(update); - t.finished.catch(() => {}).finally(() => root.classList.remove("vt-cards")); - return t.updateCallbackDone; -} -export function unlockIfClear() { - if ($("#sheet").hidden && $("#modal").hidden && $("#flow").hidden) document.body.classList.remove("locked"); -} - -// Focus goes back to whatever opened a layer once it closes, so keyboard users keep their place. -const returnFocus = new Map(); -function rememberFocus(id) { - if (!returnFocus.has(id) && document.activeElement && document.activeElement !== document.body) returnFocus.set(id, document.activeElement); -} -function restoreFocus(id) { - const el = returnFocus.get(id); - returnFocus.delete(id); - if (el && el.isConnected) el.focus({ preventScroll: true }); -} - -// Layers slide out briefly before they hide; reopening during that moment cancels it. -const closing = new Map(); -const reduceMotion = () => matchMedia("(prefers-reduced-motion: reduce)").matches; -function hideLayer(el, after) { - const finish = () => { - closing.delete(el.id); - el.classList.remove("closing"); - el.hidden = true; - el.innerHTML = ""; - after?.(); - }; - if (reduceMotion()) return finish(); - el.classList.add("closing"); - closing.set(el.id, setTimeout(finish, 180)); -} -function cancelHide(el) { - clearTimeout(closing.get(el.id)); - closing.delete(el.id); - el.classList.remove("closing"); -} - -let modalClose = null; -export function openModal(html, { onClose = null, wide = false } = {}) { - rememberFocus("#modal"); - const el = $("#modal"); - cancelHide(el); - el.hidden = false; - el.innerHTML = `
`; - modalClose = onClose; - lock(); - setTimeout(() => el.querySelector("input:not([type=hidden]),textarea")?.focus(), 30); - return el.querySelector(".dialog"); -} -export function closeModal() { - const el = $("#modal"); - if (el.hidden || closing.has(el.id)) return; - const fn = modalClose; - modalClose = null; - hideLayer(el, unlockIfClear); - restoreFocus("#modal"); - fn?.(); -} -export const modalOpen = () => !$("#modal").hidden && !closing.has("modal"); - -export function openLayer(id, html) { - rememberFocus(id); - const el = $(id); - cancelHide(el); - el.hidden = false; - el.innerHTML = html; - lock(); - setTimeout(() => el.querySelector(".close, button")?.focus({ preventScroll: true }), 30); - return el; -} -export function closeLayer(id) { - const el = $(id); - if (el.hidden || closing.has(el.id)) return; - hideLayer(el, unlockIfClear); - restoreFocus(id); -} - -export function spinnerHTML(text = "") { - return `
${text ? `

${esc(text)}

` : ""}
`; -} - -export function confirmDialog({ title, text, ok = "Confirm", danger = false }) { - return new Promise((resolve) => { - let answered = false; - openModal( - `

${esc(title)}

${esc(text)}

-
`, - { onClose: () => { if (!answered) resolve(false); } }, - ); - $("#dlg-ok").addEventListener("click", () => { answered = true; closeModal(); resolve(true); }); - }); -} - -// Fills in posters that arrived after a card was drawn (see films.js loadRestPosters). -export function fillMissingPosters() { - document.querySelectorAll(".poster:not(:has(img))").forEach((el) => { - const host = el.closest("[data-film],[data-id]"); - const id = Number(host?.dataset.film ?? host?.dataset.id); - const f = Number.isInteger(id) ? film(id) : null; - if (!f?.poster) return; - const small = el.closest(".rowi,.qa-row,.nposter,.crow,.mposter,.pposter"); - el.insertAdjacentHTML("beforeend", ``); - }); -} diff --git a/movi/js/util.js b/movi/js/util.js deleted file mode 100644 index 101d5442..00000000 --- a/movi/js/util.js +++ /dev/null @@ -1,106 +0,0 @@ -export const $ = (sel, root = document) => root.querySelector(sel); -export const $$ = (sel, root = document) => [...root.querySelectorAll(sel)]; - -export const esc = (s) => - String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); - -export const norm = (s) => - s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim(); - -export const hash = (s) => { - let h = 0; - for (const c of String(s)) h = (h * 31 + c.charCodeAt(0)) | 0; - return Math.abs(h); -}; - -export function rng(seed) { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) | 0; - let t = Math.imul(a ^ (a >>> 15), 1 | a); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -export function debounce(fn, ms) { - let t; - return (...args) => { - clearTimeout(t); - t = setTimeout(() => fn(...args), ms); - }; -} - -export function timeAgo(iso) { - const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000); - if (s < 60) return "just now"; - if (s < 3600) return `${Math.floor(s / 60)}m`; - if (s < 86400) return `${Math.floor(s / 3600)}h`; - if (s < 86400 * 7) return `${Math.floor(s / 86400)}d`; - const d = new Date(iso); - return d.toLocaleDateString(undefined, { month: "short", day: "numeric", ...(d.getFullYear() !== new Date().getFullYear() && { year: "numeric" }) }); -} - -export const plural = (n, word, many = word + "s") => `${n.toLocaleString()} ${n === 1 ? word : many}`; - -export const today = () => { - const d = new Date(); - return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; -}; - -const svg = (d) => ``; -export const ICON = { - heart: svg(''), - meh: svg(''), - down: svg(''), - bookmark: svg(''), - plus: svg(''), - check: svg(''), - close: svg(''), - rank: svg(''), - share: svg(''), - undo: svg(''), - search: svg(''), - home: svg(''), - compass: svg(''), - list: svg(''), - user: svg(''), - users: svg(''), - bell: svg(''), - trophy: svg(''), - gear: svg(''), - comment: svg(''), - send: svg(''), - lock: svg(''), - link: svg(''), - flame: svg(''), - target: svg(''), - popcorn: svg(''), - sparkle: svg(''), - logout: svg(''), - trash: svg(''), - chevron: svg(''), - back: svg(''), - ticket: svg(''), - globe: svg(''), - repeat: svg(''), - copy: svg(''), -}; - -let toastTimer; -export function toast(msg) { - const t = $("#toast"); - t.textContent = msg; - t.classList.add("show"); - clearTimeout(toastTimer); - toastTimer = setTimeout(() => t.classList.remove("show"), 2400); -} - -export async function copyText(text) { - try { - await navigator.clipboard.writeText(text); - return true; - } catch { - return false; - } -} diff --git a/movi/js/variety.js b/movi/js/variety.js deleted file mode 100644 index 8c7d8e8c..00000000 --- a/movi/js/variety.js +++ /dev/null @@ -1,59 +0,0 @@ -// Keeps suggestion rows fresh: weighted random picks from a large pool of good matches, -// with films shown in the last few hours pushed back and no repeats within one page. -const KEY = "movi.recentShown"; -const FRESH_HOURS = 6; - -let recent = loadRecent(); -let usedOnPage = new Set(); - -function loadRecent() { - try { - const cutoff = Date.now() - FRESH_HOURS * 3600000; - const saved = JSON.parse(localStorage.getItem(KEY) || "{}"); - return Object.fromEntries(Object.entries(saved).filter(([, t]) => t > cutoff)); - } catch { - return {}; - } -} - -function saveRecent() { - try { localStorage.setItem(KEY, JSON.stringify(recent)); } catch {} -} - -export function beginPage() { - usedOnPage = new Set(); - recent = loadRecent(); -} - -// candidates: [weight, film][]; returns up to n films, sampled without replacement by weight. -export function sample(candidates, n) { - const pool = []; - for (const [w, f] of candidates) { - if (usedOnPage.has(f.id)) continue; - pool.push([Math.max(w, 1e-6) * (recent[f.id] ? 0.12 : 1), f]); - } - const out = []; - let total = pool.reduce((t, x) => t + x[0], 0); - while (out.length < n && pool.length) { - let r = Math.random() * total; - let k = 0; - while (k < pool.length - 1 && (r -= pool[k][0]) > 0) k++; - const [w, f] = pool.splice(k, 1)[0]; - total -= w; - out.push(f); - } - const now = Date.now(); - for (const f of out) { - usedOnPage.add(f.id); - recent[f.id] = now; - } - saveRecent(); - return out; -} - -// Turns a best-first score list into sampling weights that still favor the strongest matches. -export const softmax = (scored, temp = 1.5) => { - const max = scored.length ? Math.max(...scored.map((x) => x[0])) : 0; - return scored.map(([s, f]) => [Math.exp((s - max) / temp), f]); -}; -export const byPopularity = (films, power = 1.6) => films.map((f) => [Math.pow(f.pop / 100, power) + 0.02, f]); diff --git a/movi/js/views/account.js b/movi/js/views/account.js deleted file mode 100644 index 25ba6f00..00000000 --- a/movi/js/views/account.js +++ /dev/null @@ -1,262 +0,0 @@ -import { $, esc, ICON, toast, debounce } from "../util.js"; -import { film, filmCount, searchFilms } from "../films.js"; -import { api } from "../api/index.js"; -import { S, loadSession, rankedCount, updateMe, rankedIds, myRows } from "../state.js"; -import { cardHTML, userRowHTML, avatarHTML, confirmDialog } from "../ui.js"; -import { followBtnHTML } from "./feed.js"; -import { sample, byPopularity } from "../variety.js"; - -const onboardKey = () => `movi.onboarded.${S.me?.id}`; -export const needsOnboarding = () => { try { return !localStorage.getItem(onboardKey()); } catch { return false; } }; -const finishOnboarding = () => { try { localStorage.setItem(onboardKey(), "1"); } catch {} }; - -let authTab = "signup"; - -// Google's multicolor "G", as Google's sign-in branding guidelines ask for on Google sign-in buttons. -const GOOGLE_G = ``; - -export async function signInWithGoogle(btn) { - btn.disabled = true; - try { - await api.signInWithGoogle(); - } catch (e) { - btn.disabled = false; - toast(e.message); - } -} - -export function renderWelcome(view) { - const demo = api.mode === "demo"; - view.innerHTML = ` -
-
- -

Rank every movie you've ever seen.

-

No more stars. Pick which film you liked more, a few times, and Movi builds your personal 0–10 scores and a ranked list that's truly yours.

-
    -
  • ${ICON.rank}Head-to-head ranking — about 5 quick picks per film
  • -
  • ${ICON.users}Friends & feed — see what they watch, like and comment
  • -
  • ${ICON.sparkle}Rec scores — predicted scores from friends with your taste
  • -
  • ${ICON.trophy}Leaderboards, streaks & badges — make watching a habit
  • -
-

${filmCount().toLocaleString()} films · Watchlist · Taste match · Watch together

-
-
- ${api.supportsGoogle ? `
or use email
` : ""} -
- ${authTab === "signup" ? ` -
- - - - - - -
` : ` -
- - - - - ${demo ? "" : ``} -
`} - ${demo ? `
${ICON.lock}Demo mode. Accounts and rankings are saved only in this browser, alongside a sample community. Connect Supabase in config.js to go live.
` : ""} - Browse without an account - -
-
`; - view.querySelectorAll("[data-atab]").forEach((b) => b.addEventListener("click", () => { authTab = b.dataset.atab; renderWelcome(view); })); - const form = $("#auth-form"); - const err = $("#auth-err"); - const u = form.username; - if (u) { - u.addEventListener("input", () => { u.value = u.value.toLowerCase().replace(/[^a-z0-9_.]/g, ""); checkName(); }); - const nameField = form.display_name; - nameField.addEventListener("input", () => { - if (!u.dataset.touched) { u.value = nameField.value.toLowerCase().replace(/[^a-z0-9]+/g, "").slice(0, 20); checkName(); } - }); - u.addEventListener("keydown", () => { u.dataset.touched = "1"; }); - } - const checkName = debounce(async () => { - const hint = $("#u-hint"); - if (!hint || !u.value) return; - if (!/^[a-z0-9_.]{3,20}$/.test(u.value)) { hint.textContent = "3–20 characters: lowercase letters, numbers, _ and ."; hint.className = "hint"; return; } - const ok = await api.usernameAvailable(u.value).catch(() => true); - hint.textContent = ok ? `@${u.value} is available` : `@${u.value} is taken`; - hint.className = ok ? "hint good" : "hint bad"; - }, 300); - - form.addEventListener("submit", async (e) => { - e.preventDefault(); - err.textContent = ""; - const fd = Object.fromEntries(new FormData(form)); - if (authTab === "signup") { - if (!fd.display_name.trim()) return (err.textContent = "Tell us your name"); - if (!/^[a-z0-9_.]{3,20}$/.test(fd.username)) return (err.textContent = "Pick a username with 3–20 lowercase letters, numbers, _ or ."); - if (!/^\S+@\S+\.\S+$/.test(fd.email)) return (err.textContent = "Enter a valid email"); - if ((fd.password || "").length < 6) return (err.textContent = "Password should be at least 6 characters"); - } else if (!fd.email || !fd.password) return (err.textContent = "Enter your email and password"); - const btn = $("#auth-go"); - btn.disabled = true; - btn.textContent = authTab === "signup" ? "Creating account…" : "Signing in…"; - try { - if (authTab === "signup") { - if (!(await api.usernameAvailable(fd.username))) throw new Error("That username is taken"); - const res = await api.signUp({ email: fd.email, password: fd.password, username: fd.username, displayName: fd.display_name.trim() }); - if (res.needsConfirm) { - view.querySelector(".auth").innerHTML = `

Check your email

We sent a confirmation link to ${esc(fd.email)}. Open it to finish creating your account, then sign in.

`; - view.querySelector("[data-atab-reset]").addEventListener("click", () => { authTab = "signin"; renderWelcome(view); }); - return; - } - } else { - await api.signIn({ email: fd.email, password: fd.password }); - } - await loadSession(); - document.dispatchEvent(new CustomEvent("movi:auth")); - location.hash = needsOnboarding() && rankedCount() === 0 ? "#/onboarding" : "#/feed"; - } catch (ex) { - err.textContent = ex.message; - btn.disabled = false; - btn.textContent = authTab === "signup" ? "Create account" : "Sign in"; - } - }); -} - -export async function forgotPassword() { - const email = $("#auth-form")?.email?.value?.trim() || prompt("Your account email:"); - if (!email) return; - try { - await api.resetPassword(email); - toast("Check your email for a reset link"); - } catch (e) { toast(e.message); } -} - -// ---------- Onboarding ---------- -let obStep = 1; -// Well-known films to start with: a fresh set each visit, kept steady while you work through it. -let obPicks = null; -function onboardingPicks(fresh = false) { - const taken = new Set([...rankedIds(), ...S.skip]); - const keep = fresh || !obPicks ? [] : obPicks.filter((id) => !taken.has(id)); - const pool = searchFilms({}).filter((f) => !taken.has(f.id) && !keep.includes(f.id)).slice(0, 400); - obPicks = [...keep, ...sample(byPopularity(pool, 2.2), 18 - keep.length).map((f) => f.id)]; - return obPicks.map(film); -} -export function shuffleOnboarding() { - onboardingPicks(true); - renderOnboarding(document.querySelector("#view")); -} -export async function renderOnboarding(view) { - const n = rankedCount(); - const steps = `
${[1, 2].map((i) => ``).join("")}
`; - if (obStep === 1) { - const picks = onboardingPicks(); - view.innerHTML = `
${steps} -

Rank 3 films you've seen

-

Pick films you know well. ${n ? `${Math.min(n, 3)} of 3 done.` : "It takes a few seconds each."}

-
${ICON.list} Paste a list of movies${n >= 3 ? `` : ``}
-
${picks.map((f) => cardHTML(f, { acts: `
` })).join("")}
`; - return; - } - view.innerHTML = `
${steps}

Follow people

Their rankings power your feed, rec scores and leaderboard.

-
`; - const ps = (await api.listProfiles({ limit: 30 })).filter((p) => p.id !== S.me.id); - $("#ob-people").innerHTML = ps.map((p) => userRowHTML(p, followBtnHTML(p), `${p.ranked_count} ranked`)).join("") || `

No one else is here yet — invite your friends from your profile.

`; -} -export function onboardingNext() { obStep = 2; renderOnboarding($("#view")); } -export function onboardingDone() { finishOnboarding(); obStep = 1; location.hash = "#/feed"; } - -// ---------- Settings ---------- -export function renderSettings(view) { - const me = S.me; - const demo = api.mode === "demo"; - view.innerHTML = `

Settings

-
-

Profile

-
${avatarHTML(me, 72)}
- - - - - - - -
-
-

Password

- - -
-
-

Your data

-

Download everything you've ranked, noted and saved.

-
- -
-
-

Account

-

${demo ? "Demo mode: this account lives only in this browser." : "Signed in to Movi."}

-
- ${demo ? `` : ""}
-
-

Film data from Wikipedia (CC BY-SA). Posters from TMDB. This product uses the TMDB API but is not endorsed or certified by TMDB. ${demo ? "Running in demo mode." : "Connected to Supabase."}

`; - const pf = $("#prof-form"); - pf.avatar_hue.addEventListener("input", () => { $("#av-prev").innerHTML = avatarHTML({ ...me, display_name: pf.display_name.value, avatar_hue: Number(pf.avatar_hue.value) }, 72); }); - pf.username.addEventListener("input", () => { pf.username.value = pf.username.value.toLowerCase().replace(/[^a-z0-9_.]/g, ""); }); - pf.addEventListener("submit", async (e) => { - e.preventDefault(); - const err = $("#prof-err"); - err.textContent = ""; - const fd = new FormData(pf); - const patch = { - display_name: String(fd.get("display_name")).trim().slice(0, 40), - username: String(fd.get("username")).trim(), - bio: String(fd.get("bio")).trim().slice(0, 160), - avatar_hue: Number(fd.get("avatar_hue")), - yearly_goal: Math.max(1, Math.min(1000, Number(fd.get("yearly_goal")) || 52)), - is_private: fd.get("is_private") === "on", - }; - if (!patch.display_name) return (err.textContent = "Name can't be empty"); - if (!/^[a-z0-9_.]{3,20}$/.test(patch.username)) return (err.textContent = "Username needs 3–20 lowercase letters, numbers, _ or ."); - try { - if (patch.username !== me.username && !(await api.usernameAvailable(patch.username))) throw new Error("That username is taken"); - await updateMe(patch); - document.dispatchEvent(new CustomEvent("movi:auth")); - toast("Profile saved"); - } catch (ex) { - err.textContent = /duplicate|unique/i.test(ex.message) ? "That username is taken" : ex.message; - } - }); - $("#pw-form").addEventListener("submit", async (e) => { - e.preventDefault(); - try { - await api.updatePassword(e.target.password.value); - e.target.reset(); - toast("Password updated"); - } catch (ex) { toast(ex.message); } - }); -} - -export function exportData() { - const data = { - exported_at: new Date().toISOString(), - profile: S.me, - rankings: myRows().map((r) => ({ ...r, title: film(r.film_id).title, year: film(r.film_id).year })), - watchlist: S.watch.map((w) => ({ ...w, title: film(w.film_id).title, year: film(w.film_id).year })), - }; - const a = document.createElement("a"); - a.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: "application/json" })); - a.download = `movi-${S.me.username}.json`; - a.click(); - setTimeout(() => URL.revokeObjectURL(a.href), 1000); -} - -export async function deleteAccount() { - const ok = await confirmDialog({ title: "Delete your account?", text: "This permanently deletes your profile, rankings, notes, watchlist, follows and activity. This can't be undone.", ok: "Delete forever", danger: true }); - if (!ok) return; - try { - await api.deleteAccount(); - toast("Account deleted"); - document.dispatchEvent(new CustomEvent("movi:signedout")); - } catch (e) { toast(e.message); } -} diff --git a/movi/js/views/discover.js b/movi/js/views/discover.js deleted file mode 100644 index f260c4cb..00000000 --- a/movi/js/views/discover.js +++ /dev/null @@ -1,186 +0,0 @@ -import { $, esc, ICON, debounce } from "../util.js"; -import { film, filmCount, genres, searchFilms, topByGenre } from "../films.js"; -import { api } from "../api/index.js"; -import { S, rankedIds, rankedCount, avgScore, loadFriendRows, followingIds, myRows } from "../state.js"; -import { cardHTML, railHTML, sectionHTML, emptyHTML, userRowHTML, spinnerHTML, withTransition } from "../ui.js"; -import { recommendFor, similarFilms } from "../film-sheet.js"; -import { beginPage, sample, byPopularity } from "../variety.js"; -import { genreAffinity } from "../model.js"; -import { followBtnHTML } from "./feed.js"; - -const GENRE_RAILS = [ - ["Science Fiction", "Sci-fi to rank"], ["Animated", "Animation favorites"], ["Horror", "Horror"], ["Comedy", "Comedies"], - ["Crime", "Crime & gangsters"], ["Romance", "Romance"], ["Superhero", "Superheroes"], ["Western", "Westerns"], - ["Thriller", "Thrillers"], ["Drama", "Dramas"], ["Action", "Action"], ["Adventure", "Adventures"], ["Fantasy", "Fantasy"], - ["Mystery", "Mysteries"], ["Musical", "Musicals"], ["War", "War films"], ["Noir", "Film noir"], ["Biography", "True stories"], - ["Family", "Family night"], ["Sports", "Sports films"], -]; -const RAILS_PER_VISIT = 6; - -// A different set of genre rows each visit, leaning toward genres the user scores highly. -function pickGenreRails() { - const aff = S.me ? genreAffinity(myRows(), genres().length) : []; - const weighted = GENRE_RAILS.map((r) => [Math.exp(Math.max(-2, Math.min(3, (aff[genres().indexOf(r[0])] || 0) / 2))) * (0.5 + Math.random()), r]); - return weighted.sort((a, b) => b[0] - a[0]).slice(0, RAILS_PER_VISIT).map((x) => x[1]); -} - -export async function renderDiscover(view) { - const me = S.me; - const n = me ? rankedCount() : 0; - const hero = !me - ? `

Stop rating movies.
Start ranking them.

-

Pick which film you liked more, a few times, and Movi builds your 0–10 scores and ranked list. See what your friends think, compare taste, and find what to watch next.

-
` - : n === 0 - ? `

Let's build your list, ${esc(me.display_name || me.username)}.

-

Start with films you know well. Each one takes a few seconds: a gut check, then a couple of head-to-heads.

-
${ICON.list} Add movies you've seen
` - : `

Discover

${rankedCount()} ranked · ${avgScore().toFixed(1)} average. Find your next favorite.

-
`; - - beginPage(); - if (me) pickQuick(); - const favorites = me ? S.lists.loved.slice(0, 6) : []; - const topLoved = favorites.length ? film(favorites[Math.floor(Math.random() * favorites.length)]) : null; - const exclude = me ? notNewIds() : null; - view.innerHTML = `${hero} - ${ICON.search}Search films or people - ${me ? `
` : ""} - ${me && n >= 3 ? sectionHTML("Recommended for you", "Based on the genres you score highest", railHTML(recommendFor(18))) : ""} - -
- ${topLoved ? sectionHTML(`Because you loved ${esc(topLoved.title)}`, "Similar genres and era", railHTML(similarFilms(topLoved, 16, { vary: true }))) : ""} - ${pickGenreRails().map(([g, t]) => sectionHTML(t, "", railHTML(sample(byPopularity(topByGenre(g, 160, exclude), 1.3), 20)), `See all`)).join("")}`; - if (me) drawQuick(); - loadTrending(); -} - -// Films the user has ranked or said they're not interested in never appear as suggestions. -const notNewIds = () => new Set([...rankedIds(), ...S.skip]); - -let quickIds = []; -const QUICK_COUNT = 12; -const quickTaken = () => new Set([...rankedIds(), ...S.watch.map((w) => w.film_id), ...S.skip]); -const quickPool = (taken) => byPopularity(searchFilms({}).filter((f) => !taken.has(f.id)).slice(0, 450)); - -function pickQuick() { - quickIds = sample(quickPool(quickTaken()), QUICK_COUNT).map((f) => f.id); -} - -function drawQuick() { - const el = $("#quick"); - if (!el) return; - const acts = (f) => ({ acts: `
` }); - el.innerHTML = `

Seen any of these?

Rank what you've watched, save what you want to. The fastest way to build your list.

-
-
${quickIds.map((id) => cardHTML(film(id), acts(film(id)))).join("")}
`; -} - -export function shuffleQuick() { - pickQuick(); - drawQuick(); -} - -// After Save / Skip / ranking: swap out only the cards that no longer belong, keeping the rest in place. -export function refreshQuick() { - const taken = quickTaken(); - const keep = new Set(quickIds.filter((id) => !taken.has(id))); - const fresh = sample(quickPool(new Set([...taken, ...keep])), QUICK_COUNT - keep.size).map((f) => f.id); - quickIds = quickIds.map((id) => (keep.has(id) ? id : fresh.shift())).filter((id) => id != null); - drawQuick(); -} - -async function loadTrending() { - const [top, friendRows] = await Promise.all([ - api.topFilms(2, 100).catch(() => []), - S.me ? loadFriendRows().catch(() => []) : [], - ]); - const hide = S.me ? notNewIds() : new Set(); - const topNew = top.filter((t) => !hide.has(t.film_id)); - const tbox = $("#top-movi"); - if (tbox && topNew.length) { - tbox.innerHTML = sectionHTML("Top rated on Movi", "Highest average score across members", railHTML(sample(topNew.filter((t) => film(t.film_id)).map((t) => [Math.exp((Number(t.avg_score) - Number(topNew[0].avg_score)) / 1.2) * Math.log2(1 + Number(t.n)), film(t.film_id)]), 18), (f) => { - const t = top.find((x) => x.film_id === f.id); - return { label: `${Number(t.avg_score).toFixed(1)} avg · ${t.n} members` }; - })); - } - const fbox = $("#friends-trending"); - if (!fbox || !friendRows.length) return; - const since = Date.now() - 45 * 86400000; - const agg = new Map(); - for (const r of friendRows) { - if (new Date(r.created_at).getTime() < since || hide.has(r.film_id)) continue; - const e = agg.get(r.film_id) || { id: r.film_id, n: 0, sum: 0 }; - e.n++; e.sum += Number(r.score); - agg.set(r.film_id, e); - } - const list = [...agg.values()].sort((a, b) => b.n - a.n || b.sum / b.n - a.sum / a.n).slice(0, 120); - if (list.length) { - fbox.innerHTML = sectionHTML("Trending with friends", `What the ${followingIds().length} people you follow ranked lately`, railHTML(sample(list.map((e) => [Math.pow(e.n, 1.3) * (e.sum / e.n / 10 + 0.3), film(e.id)]), 16), (f) => { - const e = agg.get(f.id); - return { label: `${e.n} friend${e.n === 1 ? "" : "s"} · ${(e.sum / e.n).toFixed(1)} avg` }; - })); - } -} - -// ---------- Search ---------- -const SQ = { q: "", genre: "", decade: "", sort: "pop", page: 1, tab: "films" }; - -export function renderSearch(view, params) { - if (params.get("genre") !== null) { SQ.genre = params.get("genre"); SQ.q = ""; SQ.page = 1; SQ.tab = "films"; } - if (params.get("tab")) SQ.tab = params.get("tab"); - const decades = []; - for (let d = 2020; d >= 1900; d -= 10) decades.push(d); - view.innerHTML = ` -

Search

-
${["films", "people"].map((t) => ``).join("")}
- ${SQ.tab === "films" ? `
- - -
-
${genres().filter((g) => g !== "Short").map((g) => ``).join("")}
` : ""} -
`; - const q = $("#q"); - q.addEventListener("input", debounce(() => { SQ.q = q.value; SQ.page = 1; drawResults(); }, 140)); - view.querySelectorAll("[data-stab]").forEach((b) => b.addEventListener("click", () => { SQ.tab = b.dataset.stab; withTransition(() => renderSearch(view, new URLSearchParams())); })); - if (SQ.tab === "films") { - $("#sort").value = SQ.sort; - $("#decade").addEventListener("change", (e) => { SQ.decade = e.target.value; SQ.page = 1; drawResults(); }); - $("#sort").addEventListener("change", (e) => { SQ.sort = e.target.value; SQ.page = 1; drawResults(); }); - $("#gchips").addEventListener("click", (e) => { - const b = e.target.closest("[data-g]"); - if (!b) return; - SQ.genre = b.dataset.g; SQ.page = 1; - $("#gchips").querySelectorAll(".chip").forEach((c) => c.classList.toggle("on", c === b)); - drawResults(); - }); - $("#gchips .chip.on")?.scrollIntoView({ inline: "center", block: "nearest" }); - } - drawResults(); - if (matchMedia("(hover: hover)").matches) q.focus(); -} - -let peopleSeq = 0; -export async function drawResults() { - const el = $("#results"); - if (!el) return; - if (SQ.tab === "people") { - const seq = ++peopleSeq; - el.innerHTML = spinnerHTML(); - const list = SQ.q.trim() ? await api.searchUsers(SQ.q.trim().toLowerCase(), 30) : await api.listProfiles({ limit: 30 }); - if (seq !== peopleSeq) return; - el.innerHTML = list.length - ? `
${SQ.q.trim() ? `${list.length} match${list.length === 1 ? "" : "es"}` : "Most active members"}
${list.map((p) => userRowHTML(p, followBtnHTML(p), `${p.ranked_count} ranked`)).join("")}
` - : emptyHTML({ title: "No one found", text: "Try a different name or username." }); - return; - } - const all = searchFilms(SQ); - const shown = all.slice(0, SQ.page * 60); - el.innerHTML = all.length - ? `
${all.length.toLocaleString()} film${all.length === 1 ? "" : "s"}
-
${shown.map((f) => cardHTML(f)).join("")}
- ${shown.length < all.length ? `
` : ""}` - : emptyHTML({ title: "No films found", text: "Try a shorter title, or clear the genre and decade filters." }); -} -export function moreResults() { SQ.page++; drawResults(); } - diff --git a/movi/js/views/feed.js b/movi/js/views/feed.js deleted file mode 100644 index a94fc95b..00000000 --- a/movi/js/views/feed.js +++ /dev/null @@ -1,176 +0,0 @@ -import { $, esc, ICON, timeAgo, toast } from "../util.js"; -import { film } from "../films.js"; -import { BUCKETS, streaks, goalProgress } from "../model.js"; -import { api } from "../api/index.js"; -import { S, followingIds, myRows, scoreOf, isWatch } from "../state.js"; -import { posterHTML, avatarHTML, nameHTML, scoreHTML, emptyHTML, spinnerHTML, userRowHTML, demoTag, withTransition } from "../ui.js"; - -let feedTab = "following"; -let cursor = null; -let loading = false; - -export async function renderFeed(view) { - const rows = myRows(); - const st = streaks(rows); - const goal = goalProgress(rows, S.me.yearly_goal); - const ring = (pct) => ``; - view.innerHTML = ` -
-
-

Feed

-
${["following", "everyone"].map((t) => ``).join("")}
-
${spinnerHTML()}
-
-
- -
`; - view.querySelectorAll("[data-feedtab]").forEach((b) => b.addEventListener("click", () => { feedTab = b.dataset.feedtab; withTransition(() => renderFeed(view)); })); - cursor = null; - await loadPosts(true); - loadSuggestions(); -} - -async function loadPosts(reset) { - if (loading) return; - loading = true; - const box = $("#posts"); - const ids = feedTab === "following" ? [...followingIds(), S.me.id] : null; - let items = []; - try { - items = await api.getFeed({ userIds: ids, before: reset ? null : cursor, limit: 15 }); - } catch (e) { - loading = false; - if (box) box.innerHTML = emptyHTML({ title: "Couldn't load the feed", text: esc(e.message) }); - return; - } - loading = false; - if (!box) return; - if (reset) box.innerHTML = ""; - if (reset && !items.length) { - box.innerHTML = feedTab === "following" - ? emptyHTML({ title: "Your feed is quiet", text: followingIds().length ? "The people you follow haven't ranked anything yet." : "Follow people to see what they're watching and how they rank it.", action: `` }) - : emptyHTML({ title: "Nothing here yet", text: "Be the first to rank something.", action: `` }); - box.querySelector("[data-feedtab-go]")?.addEventListener("click", () => { feedTab = "everyone"; renderFeed($("#view")); }); - } - box.insertAdjacentHTML("beforeend", items.map(postHTML).join("")); - cursor = items.length ? items[items.length - 1].created_at : cursor; - const more = $("#feed-more"); - if (more) more.innerHTML = items.length === 15 ? `` : ""; -} - -export function feedMore() { loadPosts(false); } - -export function postHTML(a) { - const f = film(a.film_id); - const p = a.profile; - if (!f || !p) return ""; - const mine = a.user_id === S.me?.id; - const verb = a.kind === "ranked" - ? `ranked ${esc(f.title)}` - : `wants to watch ${esc(f.title)}`; - const meta = a.kind === "ranked" && a.bucket ? `${BUCKETS[a.bucket].short} · ${f.year}` : `${f.year}`; - const myS = S.me ? scoreOf(f.id) : null; - const saveBtn = S.me && !mine && !myS - ? `` - : myS && !mine ? `You: ${scoreHTML(myS.score)}` : ""; - return `
-
${avatarHTML(p, 42)}
${nameHTML(p)} ${demoTag(p)}${verb}${meta}
- ${timeAgo(a.created_at)}
-
- -
${a.kind === "ranked" ? `
${scoreHTML(a.score, "lg")}
` : ""}${a.note ? `

“${esc(a.note)}”

` : ""}
-
-
- - - ${saveBtn} - ${mine ? `` : ""} -
- -
`; -} - -export async function toggleLike(btn) { - const id = Number(btn.dataset.id); - const on = !btn.classList.contains("on"); - const span = btn.querySelector("span"); - const n = Number(span.textContent || 0) + (on ? 1 : -1); - btn.classList.toggle("on", on); - btn.setAttribute("aria-pressed", on); - span.textContent = n || ""; - btn.setAttribute("aria-label", `Like (${n})`); - try { await (on ? api.like(id) : api.unlike(id)); } catch (e) { - btn.classList.toggle("on", !on); - span.textContent = n - (on ? 1 : -1) || ""; - toast("Couldn't update like: " + e.message); - } -} - -export async function toggleComments(btn) { - const post = btn.closest(".post"); - const box = post.querySelector(".cmts"); - if (!box.hidden) { box.hidden = true; return; } - box.hidden = false; - box.innerHTML = `
Loading…
`; - await drawComments(post); -} - -async function drawComments(post) { - const id = Number(post.dataset.post); - const box = post.querySelector(".cmts"); - const list = await api.getComments(id); - const owner = post.querySelector(".delete-post, [data-act=delete-post]") !== null; - box.innerHTML = list.map((c) => `
${avatarHTML(c.profile, 28)}
${c.profile ? nameHTML(c.profile) : "Someone"} ${esc(c.body)}${timeAgo(c.created_at)}${c.user_id === S.me?.id || owner ? ` · ` : ""}
`).join("") - + (S.me ? `
` : `

Sign in to comment.

`); - const form = box.querySelector("form"); - form?.addEventListener("submit", async (e) => { - e.preventDefault(); - const body = form.body.value.trim(); - if (!body) return; - form.querySelector("button").disabled = true; - try { - await api.addComment(id, body); - const counter = post.querySelector('[data-act="comments"] span'); - counter.textContent = Number(counter.textContent || 0) + 1; - await drawComments(post); - post.querySelector(".cmt-form input")?.focus(); - } catch (err) { - toast("Couldn't post: " + err.message); - form.querySelector("button").disabled = false; - } - }); -} - -export async function deleteComment(btn) { - const post = btn.closest(".post"); - await api.deleteComment(Number(btn.dataset.id)); - const counter = post.querySelector('[data-act="comments"] span'); - counter.textContent = Math.max(0, Number(counter.textContent || 0) - 1) || ""; - await drawComments(post); -} - -async function loadSuggestions() { - const box = $("#suggest"); - if (!box) return; - const exclude = new Set([S.me.id, ...S.following.keys()]); - const ps = (await api.listProfiles({ limit: 40 })).filter((p) => !exclude.has(p.id)).slice(0, 5); - box.innerHTML = `

People to follow

${ps.length ? ps.map((p) => userRowHTML(p, followBtnHTML(p), `${p.ranked_count} ranked`)).join("") : `

You're following everyone. Invite friends to Movi!

`} - See all`; -} - -export function followBtnHTML(p, size = "sm") { - if (!S.me || p.id === S.me.id) return ""; - const st = S.following.get(p.id); - if (st === "accepted") return ``; - if (st === "pending") return ``; - return ``; -} - diff --git a/movi/js/views/lists.js b/movi/js/views/lists.js deleted file mode 100644 index f846b405..00000000 --- a/movi/js/views/lists.js +++ /dev/null @@ -1,142 +0,0 @@ -import { $, esc, ICON, norm, timeAgo, toast, copyText } from "../util.js"; -import { film, genres, genreNames } from "../films.js"; -import { BUCKETS } from "../model.js"; -import { api } from "../api/index.js"; -import { S, myRows, rankedCount, scoreOf } from "../state.js"; -import { renderToRank } from "./torank.js"; -import { posterHTML, cardHTML, scoreHTML, emptyHTML, avatarHTML, nameHTML, spinnerHTML } from "../ui.js"; - -const LQ = { bucket: "all", genre: "", decade: "", sort: "rank", q: "", year: "" }; - -export function listRowsHTML(rows, { showNote = true, owner = true } = {}) { - return rows.map((r) => { - const f = film(r.film_id); - const bits = [f.year, ...genreNames(f).slice(0, 2)]; - if (r.watched_where) bits.push(r.watched_where); - if (r.rewatch) bits.push("Rewatch"); - return ``; - }).join("") || emptyHTML({ title: owner ? "No matches" : "Nothing here", text: owner ? "Try clearing a filter." : "" }); -} - -export function filterRows(rows, Q) { - const g = Q.genre ? genres().indexOf(Q.genre) : -1; - const words = norm(Q.q || "").split(" ").filter(Boolean); - let out = rows.filter((r) => { - const f = film(r.film_id); - if (Q.bucket !== "all" && r.bucket !== Q.bucket) return false; - if (g >= 0 && !f.g.includes(g)) return false; - if (Q.decade && Math.floor(f.year / 10) * 10 !== Number(Q.decade)) return false; - if (Q.year && new Date(r.watched_on || r.created_at).getFullYear() !== Number(Q.year)) return false; - if (words.length && !words.every((w) => f.n.includes(w))) return false; - return true; - }); - const by = { - rank: (a, b) => a.overall - b.overall, - recent: (a, b) => String(b.created_at).localeCompare(String(a.created_at)), - watched: (a, b) => String(b.watched_on || b.created_at).localeCompare(String(a.watched_on || a.created_at)), - release: (a, b) => film(b.film_id).year - film(a.film_id).year, - title: (a, b) => film(a.film_id).n.localeCompare(film(b.film_id).n), - }; - return out.sort(by[Q.sort] || by.rank); -} - -export function listControlsHTML(rows, Q, id = "lc") { - const decs = [...new Set(rows.map((r) => Math.floor(film(r.film_id).year / 10) * 10))].sort((a, b) => b - a); - const years = [...new Set(rows.map((r) => new Date(r.watched_on || r.created_at).getFullYear()))].sort((a, b) => b - a); - const gs = [...new Set(rows.flatMap((r) => genreNames(film(r.film_id))))].sort(); - const counts = { all: rows.length, loved: 0, fine: 0, disliked: 0 }; - rows.forEach((r) => counts[r.bucket]++); - return `
-
${["all", "loved", "fine", "disliked"].map((k) => ``).join("")}
-
- - - - - -
`; -} - -export function bindListControls(root, Q, redraw) { - root.querySelector('[data-ctl="sort"]').value = Q.sort; - root.querySelector('[data-ctl="bucket"]').addEventListener("click", (e) => { - const b = e.target.closest("[data-v]"); - if (!b) return; - Q.bucket = b.dataset.v; - root.querySelectorAll('[data-ctl="bucket"] .chip').forEach((c) => c.classList.toggle("on", c === b)); - redraw(); - }); - root.querySelectorAll("select[data-ctl], input[data-ctl]").forEach((el) => el.addEventListener(el.tagName === "INPUT" ? "input" : "change", () => { Q[el.dataset.ctl] = el.value; redraw(); })); -} - -export async function renderLists(view, tab = "been") { - const tabs = { been: `Been · ${rankedCount()}`, torank: `To rank · ${S.backlog.length}`, want: `Want to watch · ${S.watch.length}`, recs: "Recs for you" }; - view.innerHTML = `

My Lists

-
-
${Object.entries(tabs).map(([k, v]) => `${v}`).join("")}
-
`; - const body = $("#list-body"); - if (tab === "torank") return renderToRank(body); - if (tab === "want") return renderWant(body); - if (tab === "recs") return renderRecs(body); - const rows = myRows(); - if (!rows.length) { - body.innerHTML = emptyHTML({ title: "Your list is empty", text: "Rank a film you've seen and it lands here with a score. Seen a lot? Add them all at once and rank later.", action: `
Add many at once
` }); - return; - } - body.innerHTML = listControlsHTML(rows, LQ) + `
`; - const draw = () => { $("#rows").innerHTML = listRowsHTML(filterRows(rows, LQ)); }; - bindListControls(body, LQ, draw); - draw(); -} - -function renderWant(body) { - if (!S.watch.length) { - body.innerHTML = emptyHTML({ title: "Nothing saved yet", text: "Tap “Save” or the bookmark on any film to keep it here.", action: `Find films` }); - return; - } - body.innerHTML = `

Watched one? Tap “Watched” to rank it.

-
${S.watch.map((w) => cardHTML(film(w.film_id), { - label: w.from_user ? "Recommended" : `Saved ${timeAgo(w.created_at)}`, - acts: `
`, - })).join("")}
`; -} - -async function renderRecs(body) { - body.innerHTML = spinnerHTML(); - let recs = []; - try { recs = await api.getRecsForMe(); } catch (e) { body.innerHTML = emptyHTML({ title: "Couldn't load recs", text: esc(e.message) }); return; } - if (!recs.length) { - body.innerHTML = emptyHTML({ title: "No recommendations yet", text: "When friends send you a film, it shows up here. You can send them one from any film page." }); - return; - } - body.innerHTML = `
${recs.map((r) => { - const f = film(r.film_id); - if (!f) return ""; - const s = scoreOf(f.id); - return `
- -
-
${avatarHTML(r.profile, 28)} ${r.profile ? nameHTML(r.profile) : "Someone"} recommended · ${timeAgo(r.created_at)}
- - ${r.message ? `

“${esc(r.message)}”

` : ""} -
${s ? `You ranked it ${scoreHTML(s.score)}` : ``} -
-
`; - }).join("")}
`; -} - -export async function shareList() { - const rows = myRows().slice(0, 10); - if (!rows.length) return toast("Rank some films first"); - const url = `${location.origin}${location.pathname}#/u/${encodeURIComponent(S.me.username)}`; - const text = `My Movi top ${rows.length}:\n` + rows.map((r, i) => `${i + 1}. ${film(r.film_id).title} (${film(r.film_id).year}) — ${r.score.toFixed(1)}`).join("\n") + `\n${url}`; - try { - if (navigator.share) return await navigator.share({ text }); - } catch (e) { - if (e.name === "AbortError") return; - } - toast((await copyText(text)) ? "Top 10 copied to clipboard" : "Couldn't copy — try again"); -} diff --git a/movi/js/views/profile.js b/movi/js/views/profile.js deleted file mode 100644 index 64e7c752..00000000 --- a/movi/js/views/profile.js +++ /dev/null @@ -1,163 +0,0 @@ -import { $, esc, ICON, toast, copyText } from "../util.js"; -import { film } from "../films.js"; -import { rowsWithScores, tasteMatch, tasteStats, archetype, streaks, goalProgress, badges } from "../model.js"; -import { api } from "../api/index.js"; -import { S, myRows } from "../state.js"; -import { avatarHTML, cardHTML, emptyHTML, spinnerHTML, sectionHTML, scoreHTML, posterHTML, railHTML, userRowHTML, openModal, demoTag } from "../ui.js"; -import { postHTML, followBtnHTML } from "./feed.js"; -import { listRowsHTML, filterRows, listControlsHTML, bindListControls } from "./lists.js"; - -const PQ = { bucket: "all", genre: "", decade: "", sort: "rank", q: "", year: "" }; - -export async function renderProfile(view, username, tab = "rankings") { - view.innerHTML = spinnerHTML(); - const p = await api.getProfileByUsername(username); - if (!p) { - view.innerHTML = emptyHTML({ title: "No one by that name", text: `There's no member called @${esc(username)}.`, action: `Search people` }); - return; - } - const own = S.me?.id === p.id; - const follows = await api.getFollows(p.id); - const st = S.me ? follows.followers.find((f) => f.id === S.me.id)?.status || null : null; - if (S.me && !own) { - if (st) S.following.set(p.id, st); - else S.following.delete(p.id); - } - const canSee = own || !p.is_private || st === "accepted"; - const [rowsRaw, watch, board] = await Promise.all([ - own ? myRows() : canSee ? api.getRankings(p.id) : [], - own ? S.watch : canSee ? api.getWatchlist(p.id) : [], - api.listProfiles({ limit: 1000 }).catch(() => []), - ]); - const rows = own ? rowsRaw : rowsWithScores(rowsRaw); - const followers = follows.followers.filter((f) => f.status === "accepted"); - const following = follows.following.filter((f) => f.status === "accepted"); - const place = board.findIndex((x) => x.id === p.id) + 1; - const match = !own && S.me && rows.length ? tasteMatch(myRows(), rows) : null; - - const tabs = [["rankings", `Rankings · ${rows.length}`], ["want", `Watchlist · ${watch.length}`], ["activity", "Activity"], ["taste", "Taste"]]; - if (!own && S.me && canSee) tabs.push(["compare", "Compare"]); - if (!tabs.some(([k]) => k === tab)) tab = "rankings"; - const base = `#/u/${encodeURIComponent(p.username)}`; - - view.innerHTML = ` -
- ${avatarHTML(p, 92)} -
-

${esc(p.display_name || p.username)} ${p.is_private ? `${ICON.lock}` : ""}${demoTag(p)}

-
@${esc(p.username)} · ${esc(archetype(rows))}
- ${p.bio ? `

${esc(p.bio)}

` : ""} -
- ${p.ranked_count} ranked - - - ${place ? `#${place} on Movi` : ""} -
- ${match?.pct != null ? `
${match.pct}% taste match · ${match.common.length} films in common
` : match ? `
Rank more of the same films to see your taste match (${match.common.length} in common so far)
` : ""} -
-
- ${own ? `${ICON.gear} Edit profile` : followBtnHTML(p, "")} - -
-
- ${own && S.followers.some((f) => f.status === "pending") ? `` : ""} -
${tabs.map(([k, v]) => `${v}`).join("")}
-
`; - - const box = $("#ptab"); - if (!canSee) { - box.innerHTML = emptyHTML({ title: "This account is private", text: st === "pending" ? "Your follow request is waiting for approval." : `Follow @${esc(p.username)} to see their rankings and activity.`, action: S.me ? followBtnHTML(p, "") : `Join Movi` }); - return; - } - if (tab === "rankings") { - if (!rows.length) { box.innerHTML = emptyHTML({ title: own ? "You haven't ranked anything yet" : "No rankings yet", action: own ? `` : "" }); return; } - box.innerHTML = listControlsHTML(rows, PQ, "plc") + `
`; - const draw = () => { $("#prow").innerHTML = listRowsHTML(filterRows(rows, PQ), { owner: true }); }; - bindListControls(box, PQ, draw); - draw(); - } else if (tab === "want") { - box.innerHTML = watch.length ? `
${watch.map((w) => cardHTML(film(w.film_id))).join("")}
` : emptyHTML({ title: "Watchlist is empty" }); - } else if (tab === "activity") { - const items = await api.getFeed({ userIds: [p.id], limit: 30 }); - box.innerHTML = items.length ? `
${items.map(postHTML).join("")}
` : emptyHTML({ title: "No activity yet" }); - } else if (tab === "taste") { - box.innerHTML = tasteHTML(rows, p, { followers: followers.length, following: following.length, own }); - } else if (tab === "compare") { - box.innerHTML = compareHTML(rows, p, match); - } -} - -function bars(items, max) { - return `
${items.map(([label, val, right]) => `
${esc(label)}
${right}
`).join("")}
`; -} - -function tasteHTML(rows, p, { followers, following, own }) { - if (!rows.length) return emptyHTML({ title: "No taste profile yet", text: own ? "Rank a few films to see your genres, decades and movie personality." : "" }); - const avg = rows.reduce((t, r) => t + Number(r.score), 0) / rows.length; - const st = streaks(rows); - const goal = goalProgress(rows, p.yearly_goal); - const stats = tasteStats(rows); - const maxG = Math.max(1, ...stats.map((e) => e.n)); - const dec = new Map(); - rows.forEach((r) => { const d = Math.floor(film(r.film_id).year / 10) * 10; dec.set(d, (dec.get(d) || 0) + 1); }); - const decs = [...dec].sort((a, b) => b[0] - a[0]); - const maxD = Math.max(1, ...decs.map((d) => d[1])); - const places = new Map(); - rows.forEach((r) => r.watched_where && places.set(r.watched_where, (places.get(r.watched_where) || 0) + 1)); - const bs = badges({ rows, followers, following }); - const earned = bs.filter((b) => b.earned).length; - const top4 = [...rows].sort((a, b) => a.overall - b.overall).slice(0, 4).map((r) => film(r.film_id)); - const ring = ``; - return ` -
-
${avg.toFixed(1)}Avg score
-
${rows.filter((r) => r.bucket === "loved").length}Loved
-
${st.current}wkStreak · best ${st.longest}
-
${ring}${goal.pct}%
${goal.done}/${goal.goal}${goal.year} goal
-
- ${sectionHTML("Top 4", "The very top of the list", `
${top4.map((f) => cardHTML(f)).join("")}
`)} -
- ${sectionHTML("Genres", "Films ranked · average score", bars(stats.slice(0, 8).map((e) => [e.g, e.n, `${e.n} · ${(e.sum / e.n).toFixed(1)}`]), maxG))} - ${sectionHTML("Decades", "When the films came out", bars(decs.slice(0, 8).map(([d, c]) => [`${d}s`, c, c]), maxD))} -
- ${places.size ? sectionHTML("Where they watch", "", bars([...places].sort((a, b) => b[1] - a[1]).map(([k, v]) => [k, v, v]), Math.max(...places.values()))) : ""} - ${sectionHTML("Badges", `${earned} of ${bs.length} earned`, `
${bs.map((b) => `
${b.earned ? ICON.trophy : ICON.lock}${esc(b.name)}${esc(b.desc)}${b.earned ? "" : `
${b.value} / ${b.target}`}
`).join("")}
`)}`; -} - -function compareHTML(rows, p, match) { - const mine = new Map(myRows().map((r) => [r.film_id, r])); - const common = rows.filter((r) => mine.has(r.film_id)).map((r) => ({ id: r.film_id, them: Number(r.score), me: mine.get(r.film_id).score })); - const theirLoved = rows.filter((r) => r.bucket === "loved" && !mine.has(r.film_id)).sort((a, b) => a.overall - b.overall).slice(0, 16).map((r) => film(r.film_id)); - const name = esc(p.display_name || p.username); - const row = (c) => { - const f = film(c.id); - const d = Math.abs(c.them - c.me); - return ``; - }; - const agree = [...common].sort((a, b) => Math.abs(a.them - a.me) - Math.abs(b.them - b.me)).slice(0, 8); - const clash = [...common].sort((a, b) => Math.abs(b.them - b.me) - Math.abs(a.them - a.me)).filter((c) => Math.abs(c.them - c.me) >= 1.5).slice(0, 8); - return ` -
${avatarHTML(S.me, 56)}You
${match?.pct != null ? `${match.pct}%` : "–"}taste match
${avatarHTML(p, 56)}${name}
-

${common.length} film${common.length === 1 ? "" : "s"} you've both ranked

- ${theirLoved.length ? sectionHTML(`${name} loved these — you haven't ranked them`, "", railHTML(theirLoved)) : ""} - ${common.length ? sectionHTML("You agree on", "", `
${agree.map(row).join("")}
`) : emptyHTML({ title: "Nothing in common yet", text: "Rank some of the same films to compare." })} - ${clash.length ? sectionHTML("Where you disagree", "", `
${clash.map(row).join("")}
`) : ""}`; -} - -export async function showFollows(uid, kind) { - const { followers, following } = await api.getFollows(uid); - const list = (kind === "followers" ? followers : following).filter((x) => x.status === "accepted" && x.profile); - const own = uid === S.me?.id; - openModal(`

${kind === "followers" ? "Followers" : "Following"}

-
${list.length ? list.map((x) => userRowHTML(x.profile, own && kind === "followers" ? `${followBtnHTML(x.profile)}` : followBtnHTML(x.profile), `${x.profile.ranked_count} ranked`)).join("") : `

No one yet.

`}
`); -} - -export async function shareProfile(username) { - const url = `${location.origin}${location.pathname}#/u/${encodeURIComponent(username)}`; - try { - if (navigator.share) return await navigator.share({ title: `@${username} on Movi`, url }); - } catch (e) { - if (e.name === "AbortError") return; - } - toast((await copyText(url)) ? "Profile link copied" : url); -} diff --git a/movi/js/views/social.js b/movi/js/views/social.js deleted file mode 100644 index 19b2a98f..00000000 --- a/movi/js/views/social.js +++ /dev/null @@ -1,148 +0,0 @@ -import { $, esc, ICON, timeAgo, toast } from "../util.js"; -import { film, allFilms, genres } from "../films.js"; -import { genreAffinity } from "../model.js"; -import { api } from "../api/index.js"; -import { S, followingIds, myRows, pendingRequests, approveFollower, removeFollower, refreshUnread, reloadFollows } from "../state.js"; -import { avatarHTML, emptyHTML, spinnerHTML, userRowHTML, userHref, posterHTML, cardHTML, demoTag, withTransition } from "../ui.js"; -import { followBtnHTML } from "./feed.js"; -import { sample, softmax } from "../variety.js"; - -let boardTab = "following"; - -export async function renderLeaderboard(view) { - view.innerHTML = `

Leaderboard

Who's ranked the most films.

-
${["following", "everyone"].map((t) => ``).join("")}
-
${spinnerHTML()}
`; - view.querySelectorAll("[data-btab]").forEach((b) => b.addEventListener("click", () => { boardTab = b.dataset.btab; withTransition(() => renderLeaderboard(view)); })); - if (S.me) await reloadFollows().catch(() => {}); - const ids = boardTab === "following" && S.me ? [S.me.id, ...followingIds()] : null; - const list = await api.listProfiles({ ids, limit: 100 }); - const box = $("#board"); - if (!box) return; - if (boardTab === "following" && list.length <= 1) { - box.innerHTML = emptyHTML({ title: "Follow people to compete", text: "Your friends leaderboard shows you and everyone you follow.", action: `${ICON.users} Find people` }); - return; - } - const meIdx = list.findIndex((p) => p.id === S.me?.id); - box.innerHTML = `${meIdx >= 0 ? `` : ""} -
    ${list.map((p, i) => `
  1. ${i + 1} - ${avatarHTML(p, 42)}${esc(p.display_name || p.username)}${demoTag(p)}@${esc(p.username)} - ${p.ranked_count}ranked
  2. `).join("")}
`; -} - -const NOTE_TEXT = { - follow: () => "started following you", - follow_request: () => "wants to follow you", - follow_accepted: () => "accepted your follow request", - like: (n) => `liked your ranking of ${esc(film(n.film_id)?.title || "a film")}`, - comment: (n) => `commented on ${esc(film(n.film_id)?.title || "your post")}: “${esc(n.body)}”`, - rec: (n) => `recommended ${esc(film(n.film_id)?.title || "a film")}${n.body ? `: “${esc(n.body)}”` : ""}`, -}; - -export async function renderNotifications(view) { - view.innerHTML = `

Notifications

${spinnerHTML()}
`; - await reloadFollows().catch(() => {}); - const items = await api.getNotifications(60); - const reqs = pendingRequests(); - const box = $("#nbox"); - if (!box) return; - box.innerHTML = ` - ${reqs.length ? `

Follow requests

${reqs.map((r) => userRowHTML(r.profile, ``)).join("")}
` : ""} - ${items.length ? `
${items.map((n) => { - const a = n.actor; - if (!a) return ""; - const target = n.film_id != null ? `data-film="${n.film_id}"` : ""; - const right = ["follow", "follow_accepted"].includes(n.kind) ? followBtnHTML(a) : n.film_id != null && film(n.film_id) ? `` : ""; - return `
${avatarHTML(a, 40)} -
${esc(a.display_name || a.username)} ${NOTE_TEXT[n.kind]?.(n) || ""}${timeAgo(n.created_at)}
${right}
`; - }).join("")}
` : reqs.length ? "" : emptyHTML({ title: "No notifications yet", text: "Likes, comments, new followers and recommendations show up here." })}`; - if (items.some((n) => !n.read)) { - await api.markNotificationsRead().catch(() => {}); - refreshUnread(); - } -} - -export async function handleRequest(uid, approve) { - try { - if (approve) await approveFollower(uid); else await removeFollower(uid); - toast(approve ? "Request approved" : "Request declined"); - } catch (e) { toast(e.message); } -} - -export async function renderPeople(view) { - view.innerHTML = `

Find people

Follow friends to fill your feed, get rec scores and compare taste.

- ${ICON.search}Search by name or username -
Invite friends to MoviShare your profile link so they can follow you.
-
${spinnerHTML()}
`; - const all = await api.listProfiles({ limit: 100 }); - const mine = myRows(); - let theirRows = []; - try { theirRows = await api.rankingsOfUsers(all.filter((p) => p.id !== S.me.id && !p.is_private).map((p) => p.id).slice(0, 40)); } catch {} - const byUser = new Map(); - theirRows.forEach((r) => (byUser.get(r.user_id) || byUser.set(r.user_id, []).get(r.user_id)).push(r)); - const mineSet = new Set(mine.map((r) => r.film_id)); - const scored = all.filter((p) => p.id !== S.me.id).map((p) => { - const rows = byUser.get(p.id) || []; - const common = rows.filter((r) => mineSet.has(r.film_id)).length; - return { p, common }; - }); - const suggest = scored.filter((x) => !S.following.has(x.p.id)).sort((a, b) => b.common - a.common || b.p.ranked_count - a.p.ranked_count); - const box = $("#pbox"); - if (!box) return; - box.innerHTML = suggest.length - ? `

Suggested for you

${suggest.map(({ p, common }) => userRowHTML(p, followBtnHTML(p), common ? `${common} films in common` : `${p.ranked_count} ranked`)).join("")}
` - : emptyHTML({ title: "You're following everyone", text: "Invite friends to grow your feed." }); -} - -// ---------- Watch together ---------- -const picked = new Set(); -export async function renderTogether(view) { - view.innerHTML = `

Watch together

Pick who's watching. Movi finds films nobody has seen that the group is likely to love.

${spinnerHTML()}
`; - const { following } = await api.getFollows(S.me.id); - const friends = following.filter((f) => f.status === "accepted" && f.profile); - const box = $("#tbox"); - if (!box) return; - if (!friends.length) { - box.innerHTML = emptyHTML({ title: "Follow some friends first", text: "Watch together uses your friends' rankings and watchlists.", action: `${ICON.users} Find people` }); - return; - } - box.innerHTML = `
${friends.map((f) => ``).join("")}
-
-
`; - box.querySelectorAll(".pp input").forEach((c) => c.addEventListener("change", () => { - c.checked ? picked.add(c.value) : picked.delete(c.value); - c.closest(".pp").classList.toggle("on", c.checked); - })); - $("#t-go").addEventListener("click", () => suggestTogether()); - if (picked.size) suggestTogether(); -} - -async function suggestTogether() { - const out = $("#t-out"); - const ids = [...picked]; - if (!ids.length) { out.innerHTML = `

Pick at least one friend.

`; return; } - out.innerHTML = spinnerHTML("Comparing tastes…"); - const [rows, watches] = await Promise.all([api.rankingsOfUsers(ids), Promise.all(ids.map((id) => api.getWatchlist(id)))]); - const G = genres().length; - const members = [{ id: S.me.id, rows: myRows(), watch: S.watch }, ...ids.map((id, i) => ({ id, rows: rows.filter((r) => r.user_id === id), watch: watches[i] }))]; - const seen = new Set(members.flatMap((m) => m.rows.map((r) => r.film_id))); - const affs = members.map((m) => genreAffinity(m.rows, G)); - const wantCount = new Map(); - members.forEach((m) => m.watch.forEach((w) => wantCount.set(w.film_id, (wantCount.get(w.film_id) || 0) + 1))); - const films = allFilms(); - const scored = []; - for (let i = 0; i < Math.min(films.length, 5000); i++) { - const f = films[i]; - if (seen.has(f.id) || !f.g.length) continue; - const fit = affs.map((a) => f.g.reduce((t, g) => t + a[g], 0) / Math.sqrt(f.g.length)); - const minFit = Math.min(...fit); - const s = fit.reduce((a, b) => a + b, 0) / fit.length + minFit * 0.5 + f.pop / 25 + (wantCount.get(f.id) || 0) * 3; - scored.push([s, f, wantCount.get(f.id) || 0]); - } - scored.sort((a, b) => b[0] - a[0]); - // A varied pick from the group's best matches, so "Find films" gives new ideas each time. - const ideas = sample(softmax(scored.slice(0, 90).map(([sc, f]) => [sc, f]), 1.2), 18); - const top = ideas.map((f) => [0, f, wantCount.get(f.id) || 0]); - out.innerHTML = `

Tonight's picks for ${members.length} of you

-
${top.map(([, f, w]) => cardHTML(f, { label: w ? `On ${w} watchlist${w === 1 ? "" : "s"}` : `${f.year}` })).join("")}
`; -} diff --git a/movi/js/views/torank.js b/movi/js/views/torank.js deleted file mode 100644 index 03c6bfdb..00000000 --- a/movi/js/views/torank.js +++ /dev/null @@ -1,150 +0,0 @@ -// "To rank": paste every movie you've watched, confirm the matches, then rank them whenever you like. -import { $, esc, ICON, toast, timeAgo } from "../util.js"; -import { film, searchFilms } from "../films.js"; -import { api } from "../api/index.js"; -import { S, addBacklog, scoreOf } from "../state.js"; -import { posterHTML, cardHTML, emptyHTML, spinnerHTML } from "../ui.js"; -import { matchTitles } from "../matcher.js"; - -const EXAMPLE = "karate kid, star wars 1, star wars 2, harry potter"; -let draft = ""; -let review = null; -let usedAi = false; -let owner = null; - -export function renderToRank(body) { - // A typed list belongs to whoever typed it; start clean after a sign-out or account switch. - if (owner !== S.me?.id) { - owner = S.me?.id; - clearReview(); - } - const live = api.mode === "supabase"; - body.innerHTML = ` -
-

Add movies you've watched

-

Type or paste as many as you like — one per line or separated by commas. Rough titles are fine: “${esc(EXAMPLE)}”. ${live ? "Movi's AI figures out which films you mean." : ""} You can rank them later.

- -
-
-
- ${S.backlog.length ? `

Waiting to be ranked · ${S.backlog.length}

Rank them one at a time, or run through the whole list.

-
-
${S.backlog.map((b) => cardHTML(film(b.film_id), { - label: `Added ${timeAgo(b.created_at)}`, - acts: `
`, - })).join("")}
` - : `
${emptyHTML({ title: "Nothing waiting to be ranked", text: "Films you add above land here, so you can rank them whenever you have a minute." })}
`} - ${api.backlogLocal ? `

Your To rank list is saved on this device until the To rank database table is set up.

` : ""}`; - const ta = $("#bulk-text"); - const count = () => { const n = ta.value.split(/[\n,;]+/).filter((x) => x.trim()).length; $("#bulk-count").textContent = n ? `${n} title${n === 1 ? "" : "s"}` : ""; }; - ta.addEventListener("input", () => { draft = ta.value; count(); }); - count(); - if (review) drawReview(); -} - -export async function runMatch() { - const ta = $("#bulk-text"); - const text = ta?.value.trim(); - if (!text) { toast("Type at least one movie"); ta?.focus(); return; } - draft = text; - const box = $("#bulk-review"); - box.innerHTML = spinnerHTML("Finding your movies…"); - const res = await matchTitles(text, { useAi: api.mode === "supabase" }); - review = res.items; - usedAi = res.usedAi; - drawReview(); -} - -function drawReview() { - const box = $("#bulk-review"); - if (!box || !review) return; - const chosen = new Set(); - const rows = review.map((it, i) => { - const f = it.film != null ? film(it.film) : null; - const dup = f && chosen.has(f.id); - if (f && it.include) chosen.add(f.id); - const s = f ? scoreOf(f.id) : null; - const queued = f && S.backlog.some((b) => b.film_id === f.id); - const status = s ? `Already ranked ${s.score.toFixed(1)}` : queued ? `Already in To rank` : dup ? `Duplicate` : ""; - const alts = it.alts.map((id) => film(id)).filter(Boolean); - const series = it.series.map((id) => film(id)).filter(Boolean); - return `
- ${f ? `` : `?`} -
-
${f ? `${esc(f.title)} ${f.year} ${status}` : `No match yet — search below or leave it out`}
- You typed “${esc(it.text)}”${f ? ` · ` : ""} - ${!f || it.open ? `
- ${alts.length ? `` : ""} -
-
` : ""} - ${series.length ? `` : ""} -
- ${f ? `` : ""} -
`; - }); - const ids = collectIds(); - box.innerHTML = `
${review.filter((it) => it.film != null).length} of ${review.length} matched${usedAi ? `${ICON.sparkle} Matched with AI` : ""}
-
${rows.join("")}
-
`; - box.querySelectorAll("[data-change]").forEach((b) => b.addEventListener("click", () => { - const it = review[b.dataset.change]; - it.open = !it.open; - drawReview(); - if (it.open) box.querySelector(`.msq[data-i="${b.dataset.change}"]`)?.focus(); - })); - box.querySelectorAll("[data-include]").forEach((c) => c.addEventListener("change", () => { review[c.dataset.include].include = c.checked; drawReview(); })); - box.querySelectorAll("[data-series]").forEach((c) => c.addEventListener("change", () => { review[c.dataset.series].addSeries = c.checked; drawReview(); })); - box.querySelectorAll(".malt").forEach((sel) => sel.addEventListener("change", () => { - if (!sel.value) return; - const it = review[sel.dataset.i]; - const prev = it.film; - it.film = Number(sel.value); - it.alts = it.alts.filter((id) => id !== it.film).concat(prev != null ? [prev] : []); - it.include = true; - it.open = false; - drawReview(); - })); - box.querySelectorAll(".msq").forEach((inp) => inp.addEventListener("input", () => { - const out = box.querySelector(`.msr[data-i="${inp.dataset.i}"]`); - const q = inp.value.trim(); - out.innerHTML = q ? searchFilms({ q }).slice(0, 5).map((f) => ``).join("") : ""; - out.querySelectorAll("[data-pick]").forEach((b) => b.addEventListener("click", () => { - const [i, id] = b.dataset.pick.split(":").map(Number); - const it = review[i]; - if (it.film != null) it.alts = [it.film, ...it.alts.filter((x) => x !== Number(id))]; - it.film = id; - it.include = true; - it.open = false; - drawReview(); - })); - })); -} - -function collectIds() { - const out = []; - const seen = new Set(); - const ok = (id) => id != null && !seen.has(id) && !scoreOf(id) && !S.backlog.some((b) => b.film_id === id); - for (const it of review || []) { - if (it.include && ok(it.film)) { seen.add(it.film); out.push(it.film); } - if (it.addSeries) for (const id of it.series) if (ok(id)) { seen.add(id); out.push(id); } - } - return out; -} - -export async function addReviewed() { - const ids = collectIds(); - if (!ids.length) return; - try { - const n = await addBacklog(ids); - toast(`Added ${n} film${n === 1 ? "" : "s"} to To rank`); - review = null; - draft = ""; - } catch (e) { - toast("Couldn't save: " + e.message); - } -} - -export function clearReview() { - review = null; - draft = ""; -} diff --git a/movi/manifest.webmanifest b/movi/manifest.webmanifest deleted file mode 100644 index 30dcb765..00000000 --- a/movi/manifest.webmanifest +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "Movi", - "short_name": "Movi", - "description": "Rank every movie you've seen by picking which one you liked more.", - "id": "./", - "start_url": "./#/feed", - "scope": "./", - "display": "standalone", - "background_color": "#161616", - "theme_color": "#161616", - "icons": [ - { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, - { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" }, - { "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }, - { "src": "icon.svg", "sizes": "any", "type": "image/svg+xml" } - ] -} diff --git a/movi/og-image.jpg b/movi/og-image.jpg deleted file mode 100644 index c5dfade9..00000000 Binary files a/movi/og-image.jpg and /dev/null differ diff --git a/movi/preview.jpg b/movi/preview.jpg deleted file mode 100644 index 4475368b..00000000 Binary files a/movi/preview.jpg and /dev/null differ diff --git a/movi/privacy.html b/movi/privacy.html deleted file mode 100644 index e40efe11..00000000 --- a/movi/privacy.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - Privacy policy · Movi - - - - - - - - - - -
- -

Privacy policy

-

Last updated November 22, 2026

-

Movi is a free app for ranking the movies you've seen and sharing them with friends. We collect only what the app needs to work, we never sell your information, and there are no ads or tracking.

- -

Who this covers

-

This policy covers Movi at ngcoding10.github.io/claude and the same app at ascoding11.github.io/movi. Both addresses use the same accounts and the same data. "We" means the person who runs Movi.

- -

What we collect

-
    -
  • Account details: your email address, a username, a display name, and optionally a short bio, an avatar color and a yearly goal. If you sign in with Google, we receive your name and email address from Google. We never see your Google password.
  • -
  • What you do in Movi: your rankings and scores, notes you write about films, your watchlist and To rank list, who you follow and who follows you, posts, likes, comments, recommendations you send or receive, and notifications.
  • -
  • Lists of titles you type into To rank, which are used to find the matching films.
  • -
  • Settings saved in your browser: whether you've finished the welcome steps, films you've skipped, and which suggestions you've seen recently, so they don't repeat. These stay on your device.
  • -
-

We don't collect your location, contacts, payment details or browsing history, and Movi has no ads, analytics or tracking cookies.

- -

How we use it

-
    -
  • To run your account and sign you in.
  • -
  • To show your lists, compute your scores, and suggest films you might like.
  • -
  • To show your activity to the people who can see your profile, and theirs to you.
  • -
  • To send emails you ask for, such as a password reset.
  • -
- -

Who can see what

-

Your username, display name, bio, avatar, rankings, posts and follower counts are visible to other Movi members and on your public profile. If you make your account private in Settings, only people you approve as followers see your rankings and activity. Your email address is never shown to other members.

- -

Services we use

-

We don't sell or rent your information. Movi relies on a few services to work, and they handle data only to provide that service:

-
    -
  • Supabase stores accounts and app data and handles sign-in.
  • -
  • Google handles "Continue with Google" if you use it. Google Fonts serves the app's fonts.
  • -
  • Anthropic (Claude) receives the movie titles you type into To rank, with no name or email attached, to match them to real films.
  • -
  • GitHub Pages (and Cloudflare, for ascoding11.com) hosts the website, and jsDelivr serves a code library. Like any web host, they may log basic request data such as IP addresses.
  • -
  • TMDB serves the movie posters. Your browser loads them directly from TMDB.
  • -
-

We may share information if the law requires it.

- -

How long we keep it

-

We keep your data while you have an account. When you delete your account, your profile, rankings, lists, posts, comments, likes and follows are deleted.

- -

Your choices

-
    -
  • See and download your data: Settings → Your data → Export my data.
  • -
  • Change your details: edit your profile or make it private in Settings.
  • -
  • Delete your account: Settings → Account → Delete account. This can't be undone.
  • -
- -

Security

-

Data is sent over encrypted connections (HTTPS), and the database only lets each member change their own data. No system is perfectly secure, so use a password you don't use anywhere else.

- -

Children

-

Movi is not meant for children under 13, and we don't knowingly collect information from them. If you believe a child under 13 has made an account, contact us and we'll delete it.

- -

Changes

-

If we change this policy, we'll update the date at the top of this page. For big changes, we'll also say so in the app.

- -

Contact

-

Questions or requests about your data? Open an issue at github.com/ngcoding10/claude/issues.

- -
- - diff --git a/movi/styles.css b/movi/styles.css deleted file mode 100644 index a4c22579..00000000 --- a/movi/styles.css +++ /dev/null @@ -1,712 +0,0 @@ -/* Movi — one stylesheet, built from the tokens below. Components use tokens, not raw values. */ - -:root { - /* Color, by role */ - --bg: #161616; /* page */ - --bg-2: #1c1c1c; /* sheets, dialogs */ - --card: #222222; /* raised surfaces */ - --card-2: #2b2b2b; /* controls, nested surfaces */ - --card-3: #353535; /* hover, selected */ - --line: rgba(255, 255, 255, .07); - --line-2: rgba(255, 255, 255, .14); - --text: #f2f0ee; - --text-2: #d8d5d2; /* long-form text: plots, notes, bios */ - --muted: #a8a5a2; - --dim: #99958f; - --accent: #d63a3f; /* fills: primary buttons, active marks */ - --accent-hover: #e2474c; - --accent-lt: #ff8589; /* red used as text on dark */ - --accent-tint: rgba(229, 72, 77, .16); - --accent-ring: rgba(229, 72, 77, .45); - --on-accent: #ffffff; - --on-score: #1b1b1b; - --loved: #6fdcb0; - --fine: #f5cf6b; - --disliked: #f4a6a6; - - /* Type */ - --font: Poppins, system-ui, -apple-system, sans-serif; - --font-brand: Righteous, Poppins, sans-serif; - --fs-xs: 12px; - --fs-sm: 13px; - --fs-md: 14px; - --fs-base: 16px; - --fs-lg: 18px; - --fs-xl: 22px; - --fs-2xl: 34px; - --measure: 62ch; - - /* Space */ - --space-1: 4px; - --space-2: 8px; - --space-3: 12px; - --space-4: 16px; - --space-5: 24px; - --space-6: 32px; - --space-7: 48px; - - /* Shape and depth */ - --radius-s: 8px; - --radius-m: 14px; - --radius-l: 18px; - --radius: 22px; - --pill: 999px; - --shadow: 0 24px 60px rgba(0, 0, 0, .45); - --soft: 0 8px 28px rgba(0, 0, 0, .25); - /* Motion: quiet by default — short, small, eased; one bigger moment for the score reveal */ - --ease: cubic-bezier(.25, .8, .25, 1); - --ease-out: cubic-bezier(.2, .8, .2, 1); - --ease-in: cubic-bezier(.4, 0, 1, 1); - --dur-fast: 180ms; - --dur-med: 280ms; - --dur-slow: 420ms; - --tabbar: 68px; - color-scheme: dark; -} - -/* ---------- Base ---------- */ -* { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; } -body { margin: 0; min-height: 100vh; background: var(--bg); color: var(--text); font: var(--fs-base)/1.5 var(--font); } -body::before { - content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 100; opacity: .025; - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E"); -} -body.locked { overflow: hidden; } -a { color: inherit; text-decoration: none; } -button { font: inherit; color: inherit; cursor: pointer; border: 0; background: none; padding: 0; } -button:disabled { cursor: default; opacity: .6; } -input, select, textarea { font: inherit; color: inherit; } -h1, h2, h3 { font-family: var(--font); font-weight: 600; letter-spacing: -.015em; margin: 0; text-wrap: balance; } -p { text-wrap: pretty; } -img { display: block; } -code { background: var(--card-2); padding: 1px 6px; border-radius: 6px; font-size: .9em; } -::selection { background: var(--accent-tint); } -:focus-visible { outline: 2px solid var(--accent-lt); outline-offset: 3px; border-radius: 12px; } -svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex: none; } - -/* ---------- Text helpers and spacing utilities ---------- */ -.muted { color: var(--muted); } -.small { font-size: var(--fs-xs); } -.sub-line { margin: var(--space-1) 0 0; color: var(--muted); max-width: var(--measure); } -.center-t { text-align: center; display: block; margin: var(--space-3) auto 0; } -.link, .linkish { color: var(--accent-lt); } -.link { font-weight: 600; font-size: var(--fs-md); white-space: nowrap; } -.linkish { font-weight: 500; font-size: var(--fs-md); } -.linkish:hover, .uname:hover, .ftitle:hover { text-decoration: underline; } -.uname { font-weight: 600; } -.row-c { display: flex; gap: var(--space-3); justify-content: center; flex-wrap: wrap; margin-top: var(--space-4); } -.h2m { font-size: var(--fs-xl); margin: var(--space-6) 0 var(--space-3); } -.mt-0 { margin-top: 0 !important; } -.mt-3 { margin-top: var(--space-3); } -.mt-4 { margin-top: var(--space-4); } -.mt-5 { margin-top: var(--space-5); } -.flush { margin: 0; } -.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } -.skip { position: absolute; left: var(--space-3); top: -60px; z-index: 200; padding: 10px var(--space-4); border-radius: 12px; background: var(--accent); color: var(--on-accent); font-weight: 600; } -.skip:focus { top: var(--space-3); } -#view:focus { outline: none; } - -/* ---------- Top bar and tab bar ---------- */ -.topbar { - position: sticky; top: 0; z-index: 20; - display: flex; align-items: center; gap: 22px; - padding: 10px max(var(--space-4), calc((100vw - 1160px) / 2)); - padding-top: max(10px, env(safe-area-inset-top)); - background: rgba(22, 22, 22, .82); - backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); - box-shadow: 0 1px 0 rgba(255, 255, 255, .04); -} -.logo { - font-family: var(--font-brand); font-size: 28px; line-height: 1; - background: linear-gradient(120deg, var(--accent-lt), var(--accent)); - -webkit-background-clip: text; background-clip: text; color: transparent; -} -.logo.big { font-size: 44px; } -.topnav { display: flex; gap: 2px; } -.topnav a { - display: flex; align-items: center; gap: var(--space-2); - padding: 9px var(--space-4); border-radius: var(--pill); - color: var(--muted); font-weight: 500; font-size: var(--fs-md); - transition: color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease); -} -.topnav a:hover { color: var(--text); background: var(--card); } -.topnav a.active { background: var(--accent-tint); color: var(--accent-lt); } -.topright { margin-left: auto; display: flex; align-items: center; gap: 6px; } -.iconbtn { position: relative; width: 40px; height: 40px; border-radius: 50%; display: grid; place-items: center; color: var(--muted); } -.iconbtn:hover, .iconbtn.active { color: var(--text); background: var(--card-2); } -.bell b { position: absolute; top: 4px; right: 3px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: var(--pill); background: var(--disliked); color: #fff; font-size: 11px; line-height: 18px; text-align: center; } -.me-link { margin-left: 6px; border-radius: 50%; } -.me-link.active .avatar { box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); } -.mobile-only, .tabbar { display: none; } -.backbtn { display: none; margin-right: -10px; color: var(--text); } - -@media (max-width: 860px) { - .topbar { gap: var(--space-3); padding-left: var(--space-4); padding-right: var(--space-4); backdrop-filter: none; -webkit-backdrop-filter: none; background: rgba(22, 22, 22, .97); } - .topnav { display: none; } - .desktop-only { display: none !important; } - .mobile-only { display: grid; } - .backbtn:not([hidden]) { display: grid; } - .tabbar { - position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; - display: flex; justify-content: space-around; align-items: center; - height: calc(var(--tabbar) + env(safe-area-inset-bottom)); - padding-bottom: env(safe-area-inset-bottom); - background: rgba(28, 28, 28, .97); - box-shadow: 0 -1px 0 rgba(255, 255, 255, .04); - } - .guest .tabbar { display: none; } - .tabbar a { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 2px; padding: var(--space-2) 2px; font-size: 11px; color: var(--muted); font-weight: 500; } - .tabbar a.active { color: var(--accent-lt); } - .tab-add { width: 52px; height: 52px; margin-top: -18px; border-radius: 50%; display: grid; place-items: center; color: var(--on-accent); background: var(--accent); box-shadow: 0 8px 22px rgba(229, 72, 77, .3); } - .tab-add svg { width: 26px; height: 26px; stroke-width: 2.6; } - body:not(.guest) .view { padding-bottom: calc(var(--tabbar) + 40px + env(safe-area-inset-bottom)); } -} - -/* ---------- Page layout ---------- */ -.view { max-width: 1160px; margin: 0 auto; padding: var(--space-5) var(--space-4) 72px; } -.section { margin-top: var(--space-7); } -.section-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); margin-bottom: var(--space-3); } -.section-head h2 { font-size: var(--fs-xl); } -.section-head p { margin: 2px 0 0; color: var(--muted); font-size: var(--fs-sm); max-width: var(--measure); } -.list-head { display: flex; justify-content: space-between; align-items: flex-end; gap: var(--space-4); flex-wrap: wrap; margin-bottom: var(--space-4); } -.list-head h1, .feed-head h1 { font-size: var(--fs-2xl); } -.empty { text-align: center; padding: var(--space-7) 20px; border: 1.5px dashed rgba(255, 255, 255, .09); border-radius: var(--radius); color: var(--muted); margin-top: 20px; } -.empty h3 { color: var(--text); font-size: var(--fs-xl); margin-bottom: 6px; } -.empty p { max-width: 440px; margin: 0 auto; } -.empty .btn, .empty .row-c { margin-top: var(--space-4); } -.loading { display: grid; place-items: center; gap: var(--space-4); padding: 100px 0; color: var(--muted); } -.reel { width: 44px; height: 44px; border-radius: 50%; border: 4px solid var(--line); border-top-color: var(--accent); animation: spin .9s linear infinite; } -@keyframes spin { to { transform: rotate(360deg); } } -.banner { display: flex; align-items: center; gap: 10px; padding: var(--space-3) var(--space-4); margin: var(--space-4) 0; border-radius: var(--radius-l); background: var(--card); font-weight: 500; } -.banner.accent { background: var(--accent-tint); color: var(--accent-lt); } -.panel-card { background: var(--card); border-radius: var(--radius); box-shadow: var(--soft); padding: 18px; margin-bottom: var(--space-4); } -.panel-card h3 { font-size: var(--fs-lg); margin-bottom: var(--space-3); } -.two { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; } -@media (max-width: 800px) { .two { grid-template-columns: 1fr; } } - -/* ---------- Buttons, chips, segmented controls ---------- */ -.btn { - display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); - min-height: 44px; padding: 11px 22px; border-radius: var(--pill); - font-weight: 600; font-size: var(--fs-md); white-space: nowrap; - background: var(--card-2); border: 0; - transition: transform var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease), box-shadow var(--dur-fast) var(--ease); -} -.btn:hover { background: var(--card-3); } -.btn:active { transform: scale(.98); } -.btn.primary { background: var(--accent); color: var(--on-accent); box-shadow: 0 6px 20px rgba(229, 72, 77, .22); } -.btn.primary:hover { background: var(--accent-hover); } -.btn.ghost { background: transparent; } -.btn.ghost:hover { background: var(--card-2); } -.btn.danger { color: var(--disliked); } -.btn.danger-fill { background: var(--disliked); color: #2a0d0d; } -.btn.sm { min-height: 36px; padding: var(--space-2) var(--space-4); font-size: var(--fs-sm); } -.btn.block { width: 100%; } -.btn svg { width: 16px; height: 16px; stroke-width: 2.2; } -.btn.google { background: #fff; color: #1f1f1f; min-height: 48px; } -.btn.google:hover { background: #f2f2f2; } -.g-logo { width: 18px !important; height: 18px !important; stroke: none !important; } - -.chips { display: flex; gap: var(--space-2); overflow-x: auto; scrollbar-width: none; padding-bottom: 2px; } -.chips::-webkit-scrollbar { display: none; } -.chips.wrap { flex-wrap: wrap; overflow: visible; } -.chip { flex: none; padding: var(--space-2) var(--space-4); border-radius: var(--pill); font-size: var(--fs-sm); font-weight: 500; background: var(--card); color: var(--muted); transition: background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease); } -.chip:hover { background: var(--card-2); color: var(--text); } -.chip.on { background: var(--accent-tint); color: var(--accent-lt); } -.tag { display: inline-block; padding: 3px 10px; border-radius: var(--pill); font-size: var(--fs-xs); background: var(--card-2); color: var(--muted); vertical-align: middle; } -.tag.demo { padding: 1px 7px; font-size: 10.5px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; background: rgba(155, 152, 168, .14); margin-left: var(--space-1); } -.tag.ai { background: var(--accent-tint); color: var(--accent-lt); display: inline-flex; align-items: center; gap: var(--space-1); } -.tag.ai svg { width: 13px; height: 13px; } -.seg { display: inline-flex; gap: var(--space-1); padding: 5px; border-radius: var(--pill); background: var(--card); max-width: 100%; overflow-x: auto; scrollbar-width: none; } -.seg button, .seg a { padding: var(--space-2) 18px; border-radius: var(--pill); font-size: var(--fs-md); font-weight: 500; color: var(--muted); white-space: nowrap; transition: background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease); } -.seg .on { background: var(--card-3); color: var(--text); box-shadow: 0 2px 10px rgba(0, 0, 0, .25); } -.seg.big { display: flex; width: fit-content; margin: var(--space-2) 0 var(--space-1); } - -/* ---------- Posters, cards, rails ---------- */ -.poster { position: relative; aspect-ratio: 2 / 3; border-radius: var(--radius-m); overflow: hidden; background: var(--card-2); box-shadow: 0 8px 22px rgba(0, 0, 0, .28); } -.poster img { position: relative; width: 100%; height: 100%; object-fit: cover; } -.poster .fallback { position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: flex-end; padding: var(--space-3); font-weight: 600; font-size: 15px; letter-spacing: -.01em; line-height: 1.15; overflow: hidden; } -.poster .fallback small { font-size: 11px; font-weight: 400; opacity: .75; margin-top: var(--space-1); } -/* Small thumbnails: no title text on the fallback, smaller corners */ -.rowi .poster, .mposter .poster { border-radius: var(--radius-s); box-shadow: none; } -.nposter .poster, .crow .poster, .qa-row .poster { border-radius: 6px; } -.rowi .fallback, .mposter .fallback, .nposter .fallback, .crow .fallback, .qa-row .fallback { font-size: 0 !important; } -.rowi .fallback small, .mposter .fallback small, .nposter .fallback small, .crow .fallback small, .qa-row .fallback small { display: none; } - -.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 20px 14px; } -.card { position: relative; text-align: left; display: block; width: 100%; min-width: 0; } -.card .hit { display: block; width: 100%; text-align: left; } -.card .meta { padding: var(--space-2) 2px 0; } -.card .t { font-weight: 600; font-size: var(--fs-md); line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } -.card .y { color: var(--dim); font-size: var(--fs-xs); } -.card .poster { transition: transform var(--dur-med) var(--ease); } -@media (hover: hover) { .card .hit:hover .poster { transform: translateY(-2px); } } -.badge { position: absolute; top: var(--space-2); right: var(--space-2); z-index: 2; min-width: 38px; padding: 3px var(--space-2); border-radius: var(--pill); text-align: center; font-weight: 700; font-size: var(--fs-sm); color: var(--on-score); pointer-events: none; } -.badge.loved, .score.loved, .big-score.loved { background: var(--loved); } -.badge.fine, .score.fine, .big-score.fine { background: var(--fine); } -.badge.disliked, .score.disliked, .big-score.disliked { background: var(--disliked); } -.ribbon { position: absolute; top: var(--space-2); left: var(--space-2); z-index: 2; width: 26px; height: 26px; border-radius: 50%; display: grid; place-items: center; background: rgba(22, 22, 22, .75); pointer-events: none; } -.ribbon svg { width: 14px; height: 14px; fill: var(--accent-lt); stroke: var(--accent-lt); } -.quick .card { display: flex; flex-direction: column; } -.quick .card .acts { display: flex; gap: 6px; margin-top: auto; padding-top: var(--space-2); } -.quick .card .acts button { flex: 1; min-height: 34px; padding: 6px 0; border-radius: 12px; font-size: var(--fs-xs); font-weight: 600; background: var(--card-2); transition: background var(--dur-fast) var(--ease); } -.quick .card .acts button:hover { background: var(--card-3); } -.quick .card .acts button:first-child { background: var(--accent-tint); color: var(--accent-lt); } -.quick .card .acts button:first-child:hover { background: rgba(229, 72, 77, .24); } - -.rail { display: grid; grid-auto-flow: column; grid-auto-columns: 140px; gap: 14px; overflow-x: auto; scroll-snap-type: x mandatory; padding-bottom: var(--space-2); scrollbar-width: thin; scrollbar-color: var(--line) transparent; } -.rail > * { scroll-snap-align: start; } -@media (max-width: 480px) { - .grid { grid-template-columns: repeat(3, 1fr); gap: var(--space-4) 10px; } - .poster .fallback { font-size: var(--fs-xs); padding: var(--space-2); } - .rail { grid-auto-columns: 116px; } -} - -.score { display: inline-grid; place-items: center; flex: none; width: 44px; height: 44px; border-radius: 50%; font-weight: 700; color: var(--on-score); font-size: var(--fs-md); } -.score.lg { width: 56px; height: 56px; font-size: var(--fs-lg); } -.avatar { --s: 40px; flex: none !important; width: var(--s) !important; min-width: var(--s); height: var(--s); border-radius: 50%; display: inline-grid; place-items: center; font-weight: 600; font-size: calc(var(--s) * .42); color: var(--on-score); background: var(--card-2); } -.lock svg { width: 15px; height: 15px; vertical-align: -2px; color: var(--muted); } - -/* ---------- Discover, search ---------- */ -.hero { position: relative; overflow: hidden; border-radius: var(--radius); box-shadow: var(--soft); padding: 36px 28px; background: radial-gradient(120% 140% at 100% 0%, rgba(229, 72, 77, .16), transparent 55%), linear-gradient(160deg, #272727, #1c1c1c); } -.hero h1 { font-size: clamp(30px, 5vw, 46px); line-height: 1.05; max-width: 680px; } -.hero h1 em { font-style: normal; color: var(--accent-lt); } -.hero p { color: var(--muted); max-width: 560px; margin: var(--space-3) 0 22px; } -.hero .row { display: flex; gap: 10px; flex-wrap: wrap; } -.hero.compact { display: flex; justify-content: space-between; align-items: center; gap: var(--space-4); flex-wrap: wrap; padding: var(--space-5) 26px; } -.hero.compact h1 { font-size: 32px; } -.hero.compact p { margin: var(--space-1) 0 0; } -.searchbar { position: relative; display: block; } -.searchbar > svg { position: absolute; left: var(--space-4); top: 50%; translate: 0 -50%; color: var(--muted); } -.searchbar input { width: 100%; padding: 14px 18px 14px 48px; border-radius: var(--pill); font-size: var(--fs-base); background: var(--card); border: 0; box-shadow: var(--soft); outline: none; } -.searchbar input:focus { box-shadow: 0 0 0 2px var(--accent-ring); } -.searchbar.fake { margin-top: 20px; padding: 14px 18px 14px 48px; border-radius: var(--pill); background: var(--card); box-shadow: var(--soft); color: var(--dim); } -.searchbar.fake:hover { background: var(--card-2); } -.filters { display: flex; gap: 10px; margin: 14px 0 10px; flex-wrap: wrap; align-items: center; } -.filters select, .filters input { background: var(--card); border: 0; border-radius: var(--pill); padding: 9px var(--space-4); font-size: var(--fs-sm); outline: none; max-width: 100%; } -.filters input { min-width: 180px; flex: 1 1 180px; } -.filters input:focus, .filters select:focus { box-shadow: 0 0 0 2px var(--accent-ring); } -@media (max-width: 560px) { - .list-controls .filters { flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; margin-left: calc(-1 * var(--space-4)); margin-right: calc(-1 * var(--space-4)); padding: 0 var(--space-4); } - .list-controls .filters > * { flex: none; } - .list-controls .filters input { min-width: 150px; } -} -.count { color: var(--muted); font-size: var(--fs-sm); margin: 14px 0; } -.more { display: flex; justify-content: center; margin-top: 28px; } - -/* ---------- Lists ---------- */ -.list-controls { margin-top: 18px; } -.rows { display: flex; flex-direction: column; gap: var(--space-2); margin-top: 10px; } -.rowi { display: grid; grid-template-columns: 34px 50px 1fr auto; align-items: center; gap: 14px; padding: var(--space-3) var(--space-4) var(--space-3) var(--space-3); border-radius: var(--radius-l); background: var(--card); text-align: left; width: 100%; transition: background var(--dur-fast) var(--ease); } -.rowi:hover { background: var(--card-2); } -.rowi .n { color: var(--dim); text-align: center; font-size: 17px; font-weight: 600; } -.rinfo { display: flex; flex-direction: column; min-width: 0; } -.rinfo .t { font-weight: 600; } -.rinfo .sub { color: var(--dim); font-size: var(--fs-sm); } -.rnote { color: var(--muted); font-size: var(--fs-sm); font-style: italic; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.recs { display: flex; flex-direction: column; gap: var(--space-3); margin-top: 18px; } -.rec { display: grid; grid-template-columns: 84px 1fr; gap: var(--space-4); padding: 14px; border-radius: var(--radius); background: var(--card); box-shadow: var(--soft); } -.rec-from { display: flex; align-items: center; gap: var(--space-2); font-size: var(--fs-md); flex-wrap: wrap; } -.ftitle { font-weight: 600; text-align: left; } -.ftitle.big { display: block; font-size: 20px; margin: 6px 0 2px; } -.ftitle.big .muted { font-size: var(--fs-sm); font-weight: 400; } -.rec-msg { margin: var(--space-1) 0; color: var(--text-2); font-style: italic; } -.rec-acts { display: flex; gap: var(--space-2); flex-wrap: wrap; margin-top: 10px; align-items: center; } -.pmine { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--muted); font-size: var(--fs-sm); } -.pmine .score { width: 34px; height: 34px; font-size: var(--fs-xs); } - -/* ---------- To rank: bulk add ---------- */ -.bulk p { margin: 0 0 var(--space-3); max-width: var(--measure); } -.bulk-text { min-height: 120px; font-size: 15px; } -.bulk-acts { display: flex; align-items: center; gap: var(--space-3); flex-wrap: wrap; margin-top: var(--space-3); } -.review-head { display: flex; align-items: center; gap: 10px; margin: 22px 0 10px; flex-wrap: wrap; } -.match-list { display: flex; flex-direction: column; gap: var(--space-2); } -.match-row { display: grid; grid-template-columns: 48px 1fr auto; gap: 14px; align-items: start; padding: 10px var(--space-3); border-radius: var(--radius-l); background: var(--card-2); transition: opacity var(--dur-fast) var(--ease); } -.match-row.off { opacity: .55; } -.mposter { width: 48px; display: block; } -.mposter.none { aspect-ratio: 2 / 3; border-radius: var(--radius-s); background: var(--card-3); display: grid; place-items: center; color: var(--dim); font-weight: 600; } -.minfo { min-width: 0; display: flex; flex-direction: column; gap: var(--space-1); } -.minfo small { color: var(--dim); } -.minfo .linkish { font-size: var(--fs-xs); } -.mtitle .tag { margin-left: var(--space-1); } -.mfix { display: flex; flex-direction: column; gap: 6px; margin-top: var(--space-1); } -.malt, .msearch .msq { background: var(--card); border: 0; border-radius: 10px; padding: 7px 10px; font-size: var(--fs-sm); color: var(--text); outline: none; } -.malt { max-width: 100%; } -.msearch .msq { width: 100%; max-width: 360px; } -.malt:focus, .msearch .msq:focus { box-shadow: 0 0 0 2px var(--accent-ring); } -.msr { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } -.msr:empty { display: none; } -.mseries { display: flex; align-items: flex-start; gap: var(--space-2); font-size: var(--fs-sm); cursor: pointer; margin-top: 2px; } -.mseries input, .mtoggle input { flex: none; width: 20px; height: 20px; accent-color: var(--accent); } -.mseries input { margin-top: 1px; } -.mtoggle { padding-top: var(--space-1); cursor: pointer; } - -/* ---------- Feed ---------- */ -.feed-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 28px; align-items: start; } -.feed-side { position: sticky; top: 84px; } -.feed-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); margin-bottom: var(--space-4); flex-wrap: wrap; } -.week { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } -.week .btn { grid-column: 1 / -1; } -.wk { display: flex; align-items: center; gap: 10px; } -.wk b { display: block; font-size: 15px; } -.wk small { display: block; color: var(--muted); font-size: var(--fs-xs); line-height: 1.3; } -.flame { width: 44px; height: 44px; border-radius: 50%; display: grid; place-items: center; background: var(--card-2); color: var(--dim); flex: none; } -.flame.on { color: #fdba74; background: rgba(253, 186, 116, .12); } -.goal { position: relative; width: 44px; height: 44px; flex: none; display: grid; place-items: center; } -.goal em { position: absolute; font-style: normal; font-size: 11px; font-weight: 700; } -.ring { position: absolute; inset: 0; width: 100%; height: 100%; transform: rotate(-90deg); } -.ring circle { fill: none; stroke: var(--card-2); stroke-width: 3.5; } -.ring circle + circle { stroke: var(--accent); stroke-linecap: round; stroke-dasharray: 0 100; } -@media (max-width: 960px) { - .feed-layout { grid-template-columns: 1fr; } - .feed-side { position: static; order: -1; } - .feed-side #suggest { display: none; } - .week { grid-template-columns: 1fr 1fr auto; align-items: center; } - .week .btn { grid-column: auto; } -} -@media (max-width: 560px) { .week { grid-template-columns: 1fr 1fr; } .week .btn { grid-column: 1 / -1; } } - -.posts, #posts { display: flex; flex-direction: column; gap: 14px; } -.post { background: var(--card); border-radius: var(--radius); box-shadow: var(--soft); padding: 20px; } -.post header { display: flex; gap: var(--space-3); align-items: flex-start; } -.pwho { flex: 1; min-width: 0; line-height: 1.4; } -.pverb { color: var(--muted); } -.pverb .ftitle { color: var(--text); } -.pwho small { display: block; color: var(--dim); font-size: var(--fs-sm); } -.ptime { color: var(--dim); font-size: var(--fs-sm); white-space: nowrap; } -.pbody { display: grid; grid-template-columns: 92px 1fr; gap: var(--space-4); margin: 14px 0 6px 54px; align-items: start; } -.pposter { display: block; width: 100%; } -.pposter .poster .fallback { font-size: var(--fs-xs); padding: var(--space-2); } -.ptext p { margin: 10px 0 0; color: var(--text-2); font-size: 15px; max-width: var(--measure); } -.post footer { display: flex; gap: 6px; margin-left: 46px; } -.pbtn { display: inline-flex; align-items: center; gap: 6px; padding: var(--space-2) var(--space-3); border-radius: var(--pill); color: var(--muted); font-size: var(--fs-sm); font-weight: 500; transition: background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease); } -.pbtn:hover { background: var(--card-2); color: var(--text); } -.pbtn svg { width: 18px; height: 18px; } -.pbtn.like.on { color: #f9a8b8; } -.pbtn.like.on svg { fill: #f9a8b8; } -.pbtn.on:not(.like) { color: var(--accent-lt); } -.pbtn.on:not(.like) svg { fill: var(--accent); } -.pbtn.end { margin-left: auto; } -.cmts { margin: 10px 0 0 54px; padding-top: var(--space-3); border-top: 1px solid var(--line); display: flex; flex-direction: column; gap: 10px; } -.cmts[hidden] { display: none; } -.cmt { display: flex; gap: 10px; font-size: var(--fs-md); } -.cmt small { display: block; color: var(--dim); font-size: var(--fs-xs); } -.cmt-form { display: flex; gap: var(--space-2); } -.cmt-form input { flex: 1; min-width: 0; padding: 9px 14px; border-radius: var(--pill); background: var(--card-2); border: 0; outline: none; } -.cmt-form input:focus { box-shadow: 0 0 0 2px var(--accent-ring); } -@media (max-width: 560px) { - .pbody { grid-template-columns: 76px 1fr; margin-left: 0; } - .post footer, .cmts { margin-left: 0; } -} - -/* ---------- People ---------- */ -.urow { display: flex; align-items: center; gap: 10px; padding: var(--space-2) 0; } -.urow + .urow { border-top: 1px solid var(--line); } -.urow-main { flex: 1; display: flex; align-items: center; gap: var(--space-3); min-width: 0; } -.urow-main > span { min-width: 0; } -.urow-main b { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.urow-main small { display: block; color: var(--dim); font-size: var(--fs-sm); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.un { display: flex; align-items: center; gap: var(--space-1); min-width: 0; } -.un .tag.demo { margin-left: 2px; flex: none; } -.ulist { background: var(--card); border-radius: var(--radius); box-shadow: var(--soft); padding: 6px var(--space-4); } -.dialog .ulist { background: none; box-shadow: none; padding: 0; } -.invite { display: flex; align-items: center; justify-content: space-between; gap: 14px; margin-top: var(--space-4); flex-wrap: wrap; } -.invite small { display: block; color: var(--muted); } -.pick-people { display: flex; flex-direction: column; gap: var(--space-1); max-height: 320px; overflow-y: auto; margin: 14px 0; } -.pick-people.inline { max-height: none; display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 10px; } -.pp { display: flex; align-items: center; gap: var(--space-3); padding: 10px var(--space-3); border-radius: var(--radius-l); background: var(--card-2); border: 2px solid transparent; cursor: pointer; } -.pp span { flex: 1; min-width: 0; font-weight: 500; } -.pp small { display: block; color: var(--dim); font-weight: 400; font-size: var(--fs-xs); } -.pp input { width: 20px; height: 20px; accent-color: var(--accent); } -.pp.on, .pp:has(input:checked) { border-color: var(--accent); } - -/* ---------- Leaderboard, notifications ---------- */ -.board { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-2); } -.board li { display: flex; align-items: center; gap: 14px; padding: 10px var(--space-4); border-radius: var(--radius-l); background: var(--card); } -.board li.me { box-shadow: inset 0 0 0 1.5px rgba(229, 72, 77, .55); } -.place { width: 32px; text-align: center; font-size: var(--fs-lg); font-weight: 600; color: var(--dim); } -.place.p1 { color: #fcd34d; } .place.p2 { color: #d1d5db; } .place.p3 { color: #d97706; } -.count-big { font-size: var(--fs-xl); font-weight: 600; text-align: right; line-height: 1; } -.count-big small { display: block; font-size: 11px; font-weight: 400; color: var(--muted); } -.notes { display: flex; flex-direction: column; } -.note-row { display: flex; gap: var(--space-3); align-items: center; padding: var(--space-3); border-radius: var(--radius-m); } -.note-row > div { flex: 1; min-width: 0; color: var(--text-2); } -.note-row small { display: block; color: var(--dim); font-size: var(--fs-xs); } -.note-row.unread { background: rgba(229, 72, 77, .07); } -.nposter { width: 40px; flex: none; } - -/* ---------- Profile ---------- */ -.phead { display: flex; gap: 22px; align-items: flex-start; flex-wrap: wrap; margin-bottom: 10px; } -.pinfo { flex: 1; min-width: 240px; } -.pinfo h1 { font-size: 32px; line-height: 1.1; } -.archetype { color: var(--accent-lt); font-weight: 600; } -.bio { margin: var(--space-2) 0 0; color: var(--text-2); max-width: var(--measure); } -.pstats { display: flex; gap: 18px; flex-wrap: wrap; margin-top: var(--space-3); font-size: var(--fs-md); color: var(--muted); } -.pstats b { color: var(--text); } -.pstats a:hover, .pstats button:hover { color: var(--text); } -.match { display: inline-block; margin-top: var(--space-3); padding: 6px 14px; border-radius: var(--pill); background: rgba(52, 211, 153, .12); color: #a7f3d0; font-size: var(--fs-md); } -.match.muted { background: var(--card); color: var(--muted); } -.pacts { display: flex; gap: var(--space-2); flex-wrap: wrap; } -.tiles { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-3); margin-top: 20px; } -.tile { background: var(--card); border-radius: var(--radius); box-shadow: var(--soft); padding: var(--space-4); } -.tile b { display: block; font-size: 26px; font-weight: 600; } -.tile b small { font-size: var(--fs-md); margin-left: 2px; color: var(--muted); } -.tile span { color: var(--muted); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .08em; } -.goal-tile { display: flex; align-items: center; gap: var(--space-3); } -.goal-tile .goal { width: 54px; height: 54px; } -.goal-tile b { font-size: var(--fs-xl); } -@media (max-width: 640px) { .tiles { grid-template-columns: repeat(2, 1fr); } } -.top4 { display: grid; grid-template-columns: repeat(4, minmax(0, 170px)); gap: 14px; } -.bars { display: flex; flex-direction: column; gap: 10px; background: var(--card); border-radius: var(--radius); box-shadow: var(--soft); padding: 18px; } -.bar { display: grid; grid-template-columns: 120px 1fr 70px; align-items: center; gap: var(--space-3); font-size: var(--fs-md); } -.track { height: 10px; border-radius: var(--pill); background: var(--card-2); overflow: hidden; } -.fill { height: 100%; border-radius: var(--pill); background: linear-gradient(90deg, #c93a3f, var(--accent-lt)); } -.bar .v { color: var(--muted); text-align: right; font-size: var(--fs-sm); } -@media (max-width: 480px) { .bar { grid-template-columns: 92px 1fr 58px; } } -.badges { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: var(--space-3); } -.bdg { padding: 14px; border-radius: var(--radius-m); background: var(--card); display: flex; flex-direction: column; gap: var(--space-1); opacity: .75; } -.bdg.on { opacity: 1; background: linear-gradient(160deg, rgba(229, 72, 77, .1), var(--card)); box-shadow: inset 0 0 0 1px rgba(229, 72, 77, .3); } -.bdg i { width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; background: var(--card-2); color: var(--dim); margin-bottom: var(--space-1); } -.bdg.on i { background: var(--accent-tint); color: var(--accent-lt); } -.bdg small { color: var(--muted); font-size: var(--fs-xs); } -.bdg .track { height: 6px; margin-top: 6px; } -.compare-hero { display: flex; justify-content: center; align-items: center; gap: 28px; margin-top: var(--space-5); } -.compare-hero > div:not(.big-match) { display: flex; flex-direction: column; align-items: center; gap: 6px; } -.big-match { font-family: var(--font-brand); font-size: 44px; color: var(--loved); text-align: center; line-height: 1; } -.big-match small { display: block; font-family: var(--font); font-size: var(--fs-xs); color: var(--muted); margin-top: var(--space-1); } -.crows { display: flex; flex-direction: column; gap: var(--space-2); } -.crow { display: grid; grid-template-columns: 40px 1fr auto auto 64px; gap: 14px; align-items: center; padding: var(--space-2) 14px var(--space-2) var(--space-2); background: var(--card); border-radius: var(--radius-l); text-align: left; } -.crow .t { font-weight: 600; min-width: 0; } -.crow .t small { display: block; color: var(--dim); font-weight: 400; } -.cs { display: flex; flex-direction: column; align-items: center; font-size: 11px; color: var(--muted); max-width: 70px; overflow: hidden; } -.cs .score { width: 38px; height: 38px; font-size: var(--fs-sm); } -.cd { text-align: right; font-size: var(--fs-sm); color: var(--muted); } -.cd.agree { color: var(--loved); } -.cd.clash { color: var(--disliked); } -@media (max-width: 520px) { .crow { grid-template-columns: 34px 1fr auto auto; } .cd { display: none; } } - -/* ---------- Film page (sheet) and dialogs ---------- */ -.sheet, .modal { position: fixed; inset: 0; z-index: 40; display: grid; place-items: end center; } -.modal { z-index: 45; } -.sheet[hidden], .modal[hidden], .flow[hidden] { display: none; } -.scrim { position: absolute; inset: 0; background: rgba(10, 10, 10, .6); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); animation: fade var(--dur-med) var(--ease); } -.panel, .dialog { position: relative; max-height: 92vh; overflow-y: auto; overscroll-behavior: contain; background: var(--bg-2); border-radius: 24px 24px 0 0; box-shadow: var(--shadow); animation: up var(--dur-slow) var(--ease-out); } -.panel { width: min(860px, 100%); } -.dialog { width: min(520px, 100%); max-height: 88vh; padding: var(--space-5); } -.dialog.wide { width: min(640px, 100%); } -@media (min-width: 761px) { .sheet, .modal { place-items: center; } .panel, .dialog { border-radius: 24px; } } -@keyframes up { from { transform: translateY(40px); opacity: 0; } } -@keyframes fade { from { opacity: 0; } } -.backdrop { position: absolute; inset: 0 0 auto; height: 280px; overflow: hidden; pointer-events: none; } -.backdrop img { width: 100%; height: 100%; object-fit: cover; filter: blur(30px) saturate(1.2); opacity: .45; transform: scale(1.3); } -.backdrop::after { content: ""; position: absolute; inset: 0; background: linear-gradient(transparent, var(--bg-2)); } -.close { position: absolute; top: 14px; right: 14px; z-index: 3; width: 36px; height: 36px; border-radius: 50%; background: rgba(255, 255, 255, .08); display: grid; place-items: center; } -.close:hover { background: rgba(255, 255, 255, .14); } -.close svg { width: 18px; height: 18px; stroke-width: 2.4; } -.film { position: relative; display: grid; grid-template-columns: 200px 1fr; gap: 26px; padding: 28px; } -.film h2 { font-size: clamp(26px, 4vw, 36px); line-height: 1.1; padding-right: 36px; } -.film .facts { display: flex; gap: var(--space-2); flex-wrap: wrap; margin: 10px 0 var(--space-4); } -.film .plot { color: var(--text-2); font-size: 15px; max-width: var(--measure); } -.film .cast { color: var(--muted); font-size: var(--fs-md); } -.film .cast b { color: var(--text); font-weight: 500; } -.film .acts { display: flex; gap: var(--space-2); flex-wrap: wrap; margin: var(--space-4) 0; } -.yourscore { display: flex; align-items: center; gap: 14px; padding: 14px; border-radius: var(--radius-m); background: var(--card); margin: 6px 0 var(--space-1); } -.yourscore small { display: block; color: var(--muted); } -.yourscore.rec { border: 1px dashed var(--line-2); } -.statline { display: flex; align-items: center; gap: var(--space-2); font-size: var(--fs-md); color: var(--muted); margin-bottom: var(--space-3); } -.statline b { color: var(--text); } -.statline svg { width: 16px; height: 16px; } -.film-more { padding: 0 28px 28px; position: relative; } -.whos { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--space-2); } -.who { display: flex; align-items: center; gap: var(--space-3); padding: 10px var(--space-3); border-radius: var(--radius-l); background: var(--card); } -.who > span:not(.avatar):not(.score) { flex: 1; min-width: 0; } -.who b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.who small { display: block; color: var(--muted); font-size: var(--fs-sm); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.who .score { width: 38px; height: 38px; font-size: var(--fs-sm); } -.wiki { color: var(--muted); font-size: var(--fs-sm); text-decoration: underline; } -@media (max-width: 600px) { - .film { grid-template-columns: 110px 1fr; gap: var(--space-4); padding: 22px var(--space-4); } - .film .body { grid-column: 1 / -1; } - .film-more { padding: 0 var(--space-4) var(--space-5); } -} -.dlg-title { font-size: var(--fs-xl); margin-bottom: var(--space-2); padding-right: 40px; } -.dlg-acts { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; } -.qa-results { margin-top: 14px; display: flex; flex-direction: column; gap: var(--space-1); min-height: 200px; } -.qa-row { display: grid; grid-template-columns: 40px 1fr auto; gap: var(--space-3); align-items: center; padding: var(--space-2); border-radius: 12px; text-align: left; } -.qa-row:hover, .qa-row:focus-visible { background: var(--card); } -.qa-row small { display: block; color: var(--dim); } -.qa-row .score { width: 36px; height: 36px; font-size: var(--fs-xs); } -.qa-go { color: var(--accent-lt); padding-right: 6px; } -.qa-hint { margin: var(--space-1) var(--space-2) var(--space-2); font-size: var(--fs-sm); } -.qa-bulk { display: flex; align-items: center; gap: var(--space-3); margin-top: var(--space-3); padding: var(--space-3) 14px; border-radius: var(--radius-l); background: var(--card); } -.qa-bulk:hover { background: var(--card-2); } -.qa-bulk > span { flex: 1; } -.qa-bulk small { display: block; color: var(--muted); } -.qa-bulk > svg:first-child { color: var(--accent-lt); } - -/* ---------- Watch details form (film page and ranking reveal) ---------- */ -.details { display: flex; flex-direction: column; gap: 10px; margin-top: var(--space-3); } -.details label { margin: 0; } -.drow { display: flex; gap: var(--space-3); align-items: center; flex-wrap: wrap; } -.drow label { display: flex; flex-direction: row; align-items: center; gap: var(--space-2); font-size: var(--fs-sm); color: var(--muted); } -.details input[type=date], .details input[type=text] { background: var(--card-2); border: 0; border-radius: var(--radius-m); padding: 9px var(--space-3); outline: none; color-scheme: dark; } -.details input[type=text] { width: 100%; } -.check { cursor: pointer; } -.check input { width: 18px; height: 18px; accent-color: var(--accent); } -.check svg { width: 16px; height: 16px; } -.note { width: 100%; min-height: 76px; resize: vertical; padding: var(--space-3); border-radius: var(--radius-m); background: var(--card-2); border: 0; outline: none; } -.details input:focus, .note:focus { box-shadow: 0 0 0 2px var(--accent-ring); } - -/* ---------- Ranking flow ---------- */ -.flow { position: fixed; inset: 0; z-index: 50; background: radial-gradient(90% 70% at 50% 0%, #2a1718, var(--bg) 70%); overflow-y: auto; animation: fade var(--dur-fast) var(--ease-out); } -.flow-in { min-height: 100%; max-width: 760px; margin: 0 auto; padding: max(22px, env(safe-area-inset-top)) var(--space-4) 40px; display: flex; flex-direction: column; } -.flow-top { display: flex; justify-content: space-between; align-items: center; } -.flow-top .step { color: var(--muted); font-size: var(--fs-sm); font-weight: 500; } -.flow h2 { text-align: center; font-size: clamp(26px, 5vw, 38px); margin: 22px 0 6px; } -.flow .sub { text-align: center; color: var(--muted); margin: 0 0 var(--space-5); } -.flow .center { display: flex; flex-direction: column; align-items: center; flex: 1; justify-content: center; } -.feel-poster { width: 150px; margin: 6px auto 0; } -.feels { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-3); width: 100%; max-width: 560px; } -.feel { position: relative; padding: 20px 10px; border-radius: var(--radius); background: var(--card); box-shadow: var(--soft); display: flex; flex-direction: column; align-items: center; gap: var(--space-2); font-weight: 600; text-align: center; transition: transform var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease), box-shadow var(--dur-fast) var(--ease); } -.feel:hover { background: var(--card-2); } -@media (hover: hover) { .feel:hover { transform: translateY(-3px); } } -.feel i { width: 46px; height: 46px; border-radius: 50%; display: grid; place-items: center; } -.feel i svg { width: 24px; height: 24px; stroke: var(--on-score); stroke-width: 2.4; } -.feel small { color: var(--muted); font-weight: 400; font-size: var(--fs-xs); } -.feel kbd { position: absolute; top: var(--space-2); right: 10px; font: 600 11px var(--font); color: var(--dim); } -@media (hover: none) { .feel kbd { display: none; } } -.feel.loved i { background: var(--loved); } -.feel.fine i { background: var(--fine); } -.feel.disliked i { background: var(--disliked); } -.feel.loved:hover { box-shadow: 0 0 0 2px rgba(111, 220, 176, .6), var(--soft); } -.feel.fine:hover { box-shadow: 0 0 0 2px rgba(245, 207, 107, .6), var(--soft); } -.feel.disliked:hover { box-shadow: 0 0 0 2px rgba(243, 154, 154, .6), var(--soft); } -.duel { display: grid; grid-template-columns: 1fr auto 1fr; gap: 14px; align-items: center; width: 100%; max-width: 600px; } -.pick { border-radius: 24px; padding: var(--space-3); background: var(--card); box-shadow: var(--soft); text-align: center; transition: transform var(--dur-med) var(--ease), box-shadow var(--dur-med) var(--ease), opacity var(--dur-med) var(--ease); } -.pick .poster { width: min(100%, 210px); margin: 0 auto; } -@media (hover: hover) { .pick:hover { transform: translateY(-3px); box-shadow: 0 0 0 2px rgba(229, 72, 77, .55), 0 18px 40px rgba(0, 0, 0, .3); } } -.pick.chosen { box-shadow: 0 0 0 2.5px var(--accent), 0 18px 40px rgba(229, 72, 77, .18); transform: scale(1.02); } -.pick.lost { opacity: .4; transform: scale(.97); } -.pick .t { font-weight: 600; margin-top: 10px; line-height: 1.3; } -.pick .y { color: var(--dim); font-size: var(--fs-sm); } -.pick .new { display: inline-block; margin-top: 6px; font-size: 11px; font-weight: 700; color: var(--accent-lt); letter-spacing: .1em; text-transform: uppercase; } -.vs { width: 52px; height: 52px; border-radius: 50%; display: grid; place-items: center; font-weight: 700; font-size: 15px; color: var(--accent-lt); background: var(--card-3); box-shadow: 0 0 0 6px rgba(255, 255, 255, .03); } -@media (max-width: 520px) { - .duel { gap: var(--space-2); } - .vs { width: 38px; height: 38px; font-size: var(--fs-md); } - .pick { padding: var(--space-2); } - .feels { gap: var(--space-2); } - .feel { padding: var(--space-4) 6px; font-size: var(--fs-md); } -} -.flow-foot { display: flex; justify-content: center; gap: 10px; margin-top: var(--space-5); flex-wrap: wrap; } -.dots { display: flex; gap: 6px; justify-content: center; margin-top: 18px; } -.dots i { width: 8px; height: 8px; border-radius: 50%; background: var(--line); } -.dots i.on { background: var(--accent-lt); } -.reveal { text-align: center; } -.big-score { width: 140px; height: 140px; margin: 14px auto; border-radius: 50%; display: grid; place-items: center; font-family: var(--font-brand); font-size: 52px; color: var(--on-score); box-shadow: 0 0 80px rgba(229, 72, 77, .14); animation: pop .7s cubic-bezier(.3, 1.4, .5, 1); } -@keyframes pop { from { transform: scale(.3); opacity: 0; } } -.reveal .rank { color: var(--muted); margin: 6px 0 0; } -.reveal .rank b { color: var(--text); } -.beat { color: var(--dim); font-size: var(--fs-sm); margin: var(--space-1) 0 0; } -.reveal-details { max-width: 480px; margin: 14px auto 0; text-align: left; } -.spark { position: fixed; top: 22%; left: 50%; width: 8px; height: 8px; border-radius: 2px; pointer-events: none; animation: burst 1s ease-out forwards; } -@keyframes burst { to { transform: translate(var(--dx), var(--dy)) rotate(540deg); opacity: 0; } } - -/* ---------- Welcome, sign in, onboarding, settings ---------- */ -.welcome { display: grid; grid-template-columns: 1.1fr 1fr; gap: var(--space-7); align-items: center; min-height: calc(100vh - 160px); } -@media (max-width: 860px) { .welcome { grid-template-columns: 1fr; gap: 28px; } } -.w-copy h1 { font-size: clamp(34px, 5.5vw, 56px); line-height: 1.04; margin: 18px 0 14px; } -.lead { color: var(--text-2); font-size: 17px; max-width: 540px; margin: 0; } -.w-feats { list-style: none; padding: 0; margin: 26px 0; display: flex; flex-direction: column; gap: var(--space-3); } -.w-feats li { display: flex; gap: var(--space-3); align-items: center; color: var(--muted); } -.w-feats li > svg { width: 38px; height: 38px; padding: 9px; border-radius: 12px; background: var(--card); color: var(--accent-lt); } -.w-feats b { color: var(--text); font-weight: 600; } -.auth { background: var(--card); border-radius: 24px; padding: var(--space-5); box-shadow: var(--shadow); } -.auth .seg { display: flex; margin-bottom: 18px; background: var(--card-2); } -.auth .seg button { flex: 1; } -.auth .seg .on { background: var(--card-3); } -.auth h2 { font-size: 26px; margin-bottom: var(--space-2); } -.or { display: flex; align-items: center; gap: var(--space-3); margin: var(--space-4) 0; color: var(--dim); font-size: var(--fs-sm); } -.or::before, .or::after { content: ""; flex: 1; height: 1px; background: var(--line); } -#auth-form label, .form label { display: flex; flex-direction: column; gap: 6px; font-size: var(--fs-sm); font-weight: 500; color: var(--muted); margin-bottom: var(--space-3); } -#auth-form input, .form input:not([type=checkbox]):not([type=range]), .form textarea, .field { - width: 100%; padding: var(--space-3) 14px; border-radius: var(--radius-m); background: var(--card-2); border: 0; outline: none; font-size: 15px; color: var(--text); -} -#auth-form input:focus, .form input:focus, .form textarea:focus, .field:focus-within { box-shadow: 0 0 0 2px var(--accent-ring); } -.field { display: flex; align-items: center; padding: 0; } -.field .at { padding: 0 var(--space-1) 0 14px; color: var(--dim); font-size: 15px; } -.field .at:last-child { padding: 0 14px 0 var(--space-1); } -.field input { box-shadow: none !important; background: none !important; padding-left: 2px !important; } -.hint { font-weight: 400; color: var(--dim); } -.hint.good { color: var(--loved); } -.hint.bad { color: var(--disliked); } -.form-err { color: var(--disliked); font-size: var(--fs-md); margin: 0 0 10px; } -.form-err:empty { display: none; } -.demo-note { display: flex; gap: 10px; margin-top: 18px; padding: var(--space-3); border-radius: 12px; background: var(--bg-2); color: var(--muted); font-size: var(--fs-sm); line-height: 1.45; } -.demo-note svg { width: 16px; height: 16px; margin-top: 2px; color: var(--accent-lt); } -.ob { max-width: 920px; margin: 0 auto; text-align: center; } -.ob h1 { font-size: 36px; margin: 18px 0 6px; } -.ob .ulist { text-align: left; margin-top: 20px; } -.ob .grid { text-align: left; } -.ob-steps { display: flex; gap: 6px; justify-content: center; } -.ob-steps i { width: 36px; height: 5px; border-radius: var(--pill); background: var(--line); } -.ob-steps i.on { background: var(--accent); } -.form { max-width: 640px; display: flex; flex-direction: column; } -.form h3 { margin-bottom: 14px; } -.form .btn { align-self: flex-start; } -.form p { margin: 0 0 var(--space-3); } -.av-edit { display: flex; align-items: center; gap: 18px; margin-bottom: 14px; } -.av-edit label { flex: 1; margin: 0; } -.av-edit input[type=range] { accent-color: var(--accent); } -.switch { flex-direction: row !important; align-items: flex-start; gap: var(--space-3) !important; cursor: pointer; } -.switch input { width: 20px; height: 20px; margin-top: 2px; accent-color: var(--accent); } -.switch b { color: var(--text); display: block; } -.switch small { font-weight: 400; } -.settings { display: flex; gap: 10px; flex-wrap: wrap; } - -/* ---------- Toast ---------- */ -.toast { position: fixed; left: 50%; bottom: 28px; z-index: 60; translate: -50% 20px; opacity: 0; pointer-events: none; padding: 11px 18px; border-radius: var(--radius-l); background: var(--card-3); color: var(--text); box-shadow: var(--shadow); font-weight: 500; font-size: var(--fs-md); transition: opacity .25s, translate .25s; max-width: calc(100vw - 32px); text-align: center; } -.toast.show { opacity: 1; translate: -50% 0; } -@media (max-width: 860px) { body:not(.guest) .toast { bottom: calc(var(--tabbar) + 18px + env(safe-area-inset-bottom)); } } - -/* ---------- Motion ---------- */ -@keyframes rise { from { opacity: 0; transform: translateY(8px); } } -@keyframes fade-out { to { opacity: 0; } } -@keyframes sink { to { opacity: 0; transform: translateY(24px); } } -.view.enter > * { animation: rise var(--dur-med) var(--ease-out) both; } -.flow-in { animation: rise var(--dur-med) var(--ease-out) both; } -.closing { pointer-events: none; } -.closing .scrim, .flow.closing { animation: fade-out var(--dur-fast) var(--ease-in) forwards; } -.closing .panel, .closing .dialog { animation: sink var(--dur-fast) var(--ease-in) forwards; } -/* Touch screens: a quick press-in instead of hover lifts */ -@media (hover: none) { - .card .hit:active .poster, .pick:active, .feel:active, .rowi:active, .qa-row:active { transform: scale(.97); transition: transform 90ms var(--ease-out); } -} - -@media (prefers-reduced-motion: reduce) { - *, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; } -} -.qa-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); } -.qa-head .qa-hint { margin: 0 var(--space-2); } - -/* ---------- View transitions (tab switches, removed items) ---------- */ -.topbar { view-transition-name: topbar; } -.tabbar { view-transition-name: tabbar; } -.seg .on { view-transition-name: seg-on; } -::view-transition-old(root), ::view-transition-new(root) { animation-duration: var(--dur-fast); } -::view-transition-group(seg-on) { animation-duration: var(--dur-med); animation-timing-function: var(--ease-out); } -.vt-cards .grid .card, .vt-cards .rec, .vt-cards .post, .vt-cards .urow { view-transition-name: match-element; view-transition-class: item; } -::view-transition-group(.item) { animation-duration: var(--dur-med); animation-timing-function: var(--ease-out); } -::view-transition-old(.item):only-child { animation: vt-out var(--dur-fast) var(--ease-in) forwards; } -::view-transition-new(.item):only-child { animation: vt-in var(--dur-med) var(--ease-out); } -@keyframes vt-in { from { opacity: 0; transform: scale(.92); } } -@keyframes vt-out { to { opacity: 0; transform: scale(.92); } } -@media (prefers-reduced-motion: reduce) { - ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; } -} - -.legal { margin: var(--space-4) 0 0; font-size: var(--fs-sm); color: var(--dim); text-align: center; line-height: 1.5; } -.legal.left { text-align: left; margin-top: var(--space-3); } -.legal a { color: var(--muted); text-decoration: underline; text-underline-offset: 2px; } -.legal a:hover { color: var(--text); } diff --git a/movi/terms.html b/movi/terms.html deleted file mode 100644 index 76788860..00000000 --- a/movi/terms.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - Terms of service · Movi - - - - - - - - - - -
- -

Terms of service

-

Last updated November 22, 2026

-

Movi is a free app for ranking movies and sharing them with friends. By making an account or using Movi, you agree to these terms. If you don't agree, please don't use it.

- -

Who can use Movi

-

You must be at least 13 years old. If you're under the age of adulthood where you live, a parent or guardian should agree to these terms with you. Movi is available at ngcoding10.github.io/claude and at ascoding11.github.io/movi, with the same accounts at both.

- -

Your account

-
    -
  • Give accurate sign-up details, and keep your password to yourself. You're responsible for what happens on your account.
  • -
  • One person per account. Don't pretend to be someone else, and don't pick a username that's offensive or misleading.
  • -
  • You can delete your account at any time in Settings.
  • -
- -

What you post

-

You own what you write in Movi: your rankings, notes, posts and comments. You give us permission to store it and to show it to other members, as your privacy settings allow, so the app can work. This permission ends when you delete the content or your account.

- -

Rules

-

Don't use Movi to:

-
    -
  • harass, bully, threaten or impersonate anyone, or post hateful, sexual or violent content;
  • -
  • post spam, scams, or other people's private information;
  • -
  • post things you don't have the right to share;
  • -
  • break the law;
  • -
  • interfere with the app, get around its limits, read other members' data, or overload it with automated requests or scraping.
  • -
-

We may remove content or suspend or delete accounts that break these rules.

- -

Movie information

-

Film details come from Wikipedia, and posters from TMDB. This product uses the TMDB API but is not endorsed or certified by TMDB. Movie titles, posters and artwork belong to their owners. Scores and recommendations in Movi are opinions and estimates, not facts.

- -

AI title matching

-

When you type a list of movies into To rank, Movi may use an AI model to guess which films you mean. Its guesses can be wrong, so check the matches before you add them.

- -

The service

-

Movi is free and provided "as is". We work to keep it running, but we can't promise it will always be available or free of errors, and we may change features or stop the service. Export your data from Settings if you want your own copy. To the extent the law allows, we aren't liable for any indirect or incidental losses from using Movi, including lost data.

- -

Privacy

-

Our privacy policy explains what we collect and how we use it.

- -

Changes

-

We may update these terms. If we do, we'll change the date at the top of this page. For big changes, we'll also say so in the app. Using Movi after a change means you accept the new terms.

- -

Contact

-

Questions? Open an issue at github.com/ngcoding10/claude/issues.

- -
- - diff --git a/offline.js b/offline.js index dd0a2c4b..8c598df2 100644 --- a/offline.js +++ b/offline.js @@ -1,7 +1,7 @@ /* * Offline mode: turns on the site's service worker (/sw.js) and shows what works without internet. * - * on the home, projects/, productivity/, engineering/ and movi/ pages, + * on the home, projects/, productivity/ and engineering/ pages, * the Back Room page and the phone page (any one of them turns it on * for the whole site, installed app included) * diff --git a/projects/index.html b/projects/index.html index df66609f..fdaecbe6 100644 --- a/projects/index.html +++ b/projects/index.html @@ -29,8 +29,7 @@ "isPartOf": { "@type": "WebSite", "name": "Arjun's Projects", "url": "https://ascoding11.github.io/" }, "hasPart": [ { "@type": "VideoGame", "name": "Hype Cycle Exchange", "url": "https://ascoding11.github.io/hype-cycle-exchange/" }, - { "@type": "VideoGame", "name": "Boxed", "url": "https://ascoding11.github.io/boxed/" }, - { "@type": "WebApplication", "name": "Movi", "url": "https://ascoding11.github.io/movi/" } + { "@type": "VideoGame", "name": "Boxed", "url": "https://ascoding11.github.io/boxed/" } ] } @@ -124,32 +123,6 @@

Boxed

-
- - Movi's Discover page: a row of movie posters, each with Seen it, Save and Skip buttons, under a Rank a film button. - -
-

Movi

-

Rank every movie you've seen by picking which one you liked more. A few quick head-to-heads place each film on your list and give it a score from 0 to 10, and you can follow friends to see what they're watching.

-
    -
  • JavaScript
  • Supabase
  • PostgreSQL
  • Claude API
  • -
-
    -
  • Head-to-head ranking: Loved it, Fine or Didn't like it, then two or three "which was better?" picks
  • -
  • Over 36,000 films with posters and descriptions
  • -
  • To rank: type every movie you remember ("star wars 1, lotr 2, karate kid") and AI matches them to the real films
  • -
  • A feed of what friends ranked, likes and comments, and recommendations picked from your taste and theirs
  • -
  • Watch together: films that everyone in a group is likely to enjoy
  • -
  • Sign in with Google or email; your account works here and on Movi's own site
  • -
- -

Ranking and following need a free account. Film data and posters from Wikipedia and TMDB.

-
-
-