From 0a71e973cf2a7206396b095617d45bc6e0ee7c8c Mon Sep 17 00:00:00 2001 From: Rohita Date: Sat, 14 Nov 2026 12:53:06 +0530 Subject: [PATCH 1/2] feat(community): rank trending paths, link to experiences, and fix desktop language menu --- .../src/controllers/community.controller.ts | 5 +- .../community/getGraph.processor.ts | 4 +- backend/src/services/community.service.ts | 135 +++++++++++------- backend/src/services/trendingPaths.ts | 95 ++++++++++++ backend/tests/trendingPaths.test.ts | 54 +++++++ frontend/api/community.api.ts | 9 ++ frontend/app/(tabs)/community.tsx | 100 +++++++------ frontend/app/(tabs)/profile.tsx | 8 +- frontend/app/u/[username].tsx | 41 +++++- frontend/components/community/VisualGraph.tsx | 20 ++- .../components/desktop/DesktopCommunity.tsx | 27 ++-- .../components/desktop/DesktopProfile.tsx | 58 ++++++-- frontend/components/desktop/DesktopUI.tsx | 5 +- .../components/journey/ExpandableCards.tsx | 7 +- 14 files changed, 436 insertions(+), 132 deletions(-) create mode 100644 backend/src/services/trendingPaths.ts create mode 100644 backend/tests/trendingPaths.test.ts diff --git a/backend/src/controllers/community.controller.ts b/backend/src/controllers/community.controller.ts index f199533..afead8a 100644 --- a/backend/src/controllers/community.controller.ts +++ b/backend/src/controllers/community.controller.ts @@ -145,7 +145,8 @@ export async function getGraphController( res: Response ): Promise { try { - const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 20; + const requestedLimit = typeof req.query.limit === "string" ? Number(req.query.limit) : 20; + const limit = Number.isInteger(requestedLimit) ? Math.max(1, Math.min(20, requestedLimit)) : 20; const { getGraph } = await import("../processors/community/getGraph.processor.js"); const graph = await getGraph(limit); @@ -155,4 +156,4 @@ export async function getGraphController( const message = error instanceof Error ? error.message : String(error); res.status(500).json({ error: message }); } -} \ No newline at end of file +} diff --git a/backend/src/processors/community/getGraph.processor.ts b/backend/src/processors/community/getGraph.processor.ts index 04ad8ca..5b8bb40 100644 --- a/backend/src/processors/community/getGraph.processor.ts +++ b/backend/src/processors/community/getGraph.processor.ts @@ -1,5 +1,5 @@ -import { getTrendingGraph, type GraphNode, type GraphEdge } from "../../services/community.service.js"; +import { getTrendingGraph } from "../../services/community.service.js"; -export async function getGraph(limit = 20): Promise<{ nodes: GraphNode[]; edges: GraphEdge[] }> { +export function getGraph(limit = 20) { return getTrendingGraph(limit); } diff --git a/backend/src/services/community.service.ts b/backend/src/services/community.service.ts index f518820..6571b80 100644 --- a/backend/src/services/community.service.ts +++ b/backend/src/services/community.service.ts @@ -1,3 +1,4 @@ +import { rankTrendingPaths, type PathVote, type RankedCommunityPath } from "./trendingPaths.js"; import { getSession, closeSession } from "./neo4j.service.js"; import { attachExperienceGoals, mapJourneyExperience, mapJourneyGoal, mapJourneyTransition } from "./journeyMapping.js"; @@ -147,7 +148,7 @@ export async function searchCommunityUsers( hasVerifiedExperience, journeyHighlights, journeyScore - WHERE size(matchingGoals) > 0 + WHERE size(matchingGoals) > 0 OR ($topic IS NULL AND $subtopic IS NULL AND size(journeyHighlights) > 0 AND journeyHighlights[0] IS NOT NULL) WITH u, @@ -434,7 +435,8 @@ export async function toggleUpvote( WITH u, e, author, rel WITH u, e, author, rel WHERE rel IS NULL - MERGE (u)-[:UPVOTED]->(e) + MERGE (u)-[vote:UPVOTED]->(e) + ON CREATE SET vote.createdAt = datetime() SET author.reputationScore = coalesce(author.reputationScore, 0) + 2 RETURN true AS toggledState } @@ -471,64 +473,97 @@ export interface GraphEdge { label: string | null; } -export async function getTrendingGraph(limit = 20): Promise<{ nodes: GraphNode[]; edges: GraphEdge[] }> { +export async function getTrendingGraph(limit = 20): Promise<{ + nodes: GraphNode[]; + edges: GraphEdge[]; + paths: RankedCommunityPath[]; +}> { const session = getSession(); + const now = Date.now(); + const since = new Date(now - 30 * 86_400_000).toISOString(); + const candidateLimit = Math.max(80, limit * 8); try { - const result = await session.run( + const seedResult = await session.run( ` - MATCH (u1:User)-[:HAS_EXPERIENCE]->(e1:Experience)-[t:TRANSITION]->(e2:Experience)<-[:HAS_EXPERIENCE]-(u2:User) - - WITH e1, e2, t, u1, u2, count { (e1)<-[:UPVOTED]-() } AS e1Upvotes, count { (e2)<-[:UPVOTED]-() } AS e2Upvotes - - ORDER BY (e1Upvotes + e2Upvotes) DESC, e1.startDate DESC - LIMIT toInteger($limit) - - RETURN - e1.id AS e1Id, e1.title AS e1Title, u1.username AS e1Author, e1Upvotes, - e2.id AS e2Id, e2.title AS e2Title, u2.username AS e2Author, e2Upvotes, - t.decisionLabel AS decisionLabel + MATCH (author:User)-[:HAS_EXPERIENCE]->(seed:Experience) + WHERE author.username IS NOT NULL AND NOT coalesce(author.isFlagged, false) + AND EXISTS { + MATCH (seed)-[:TRANSITION]-(neighbor:Experience)<-[:HAS_EXPERIENCE]-(other:User) + WHERE other.username IS NOT NULL AND NOT coalesce(other.isFlagged, false) + } + WITH DISTINCT seed + OPTIONAL MATCH (seed)<-[vote:UPVOTED]-(voter:User) + WHERE NOT EXISTS { MATCH (voter)-[:HAS_EXPERIENCE]->(seed) } + WITH seed, count(DISTINCT voter) AS lifetime, + count(DISTINCT CASE WHEN vote.createdAt >= datetime($since) AND vote.createdAt <= datetime($now) THEN voter END) AS recent + WITH seed, lifetime, recent + ORDER BY recent DESC, lifetime DESC, seed.startDate DESC, seed.id + LIMIT toInteger($candidateLimit) + RETURN seed.id AS id `, - { limit } + { since, now: new Date(now).toISOString(), candidateLimit }, ); + const seedIds = seedResult.records.map(record => record.get("id") as string); + if (!seedIds.length) return { nodes: [], edges: [], paths: [] }; - const nodesMap = new Map(); - const edges: GraphEdge[] = []; - - for (const record of result.records) { - const e1Id = record.get("e1Id"); - const e2Id = record.get("e2Id"); - - if (!nodesMap.has(e1Id)) { - nodesMap.set(e1Id, { - id: e1Id, - title: record.get("e1Title"), - authorUsername: record.get("e1Author"), - upvoteCount: Number(record.get("e1Upvotes")) - }); - } - - if (!nodesMap.has(e2Id)) { - nodesMap.set(e2Id, { - id: e2Id, - title: record.get("e2Title"), - authorUsername: record.get("e2Author"), - upvoteCount: Number(record.get("e2Upvotes")) - }); + const edgeResult = await session.run( + ` + UNWIND $seedIds AS seedId + MATCH (seed:Experience {id: seedId}) + CALL { + WITH seed + MATCH (seed)-[transition:TRANSITION]-(neighbor:Experience) + WITH DISTINCT transition + WITH startNode(transition) AS source, endNode(transition) AS target, transition + MATCH (a:User)-[:HAS_EXPERIENCE]->(source), (b:User)-[:HAS_EXPERIENCE]->(target) + WHERE a.username IS NOT NULL AND b.username IS NOT NULL + AND NOT coalesce(a.isFlagged, false) AND NOT coalesce(b.isFlagged, false) + WITH source, target, transition, min(a.username) AS sourceAuthor, min(b.username) AS targetAuthor + ORDER BY + (CASE WHEN source.id IN $seedIds THEN 1 ELSE 0 END) + + (CASE WHEN target.id IN $seedIds THEN 1 ELSE 0 END) DESC, + source.id, target.id + LIMIT 12 + RETURN source, target, sourceAuthor, targetAuthor, transition } - - edges.push({ - fromId: e1Id, - toId: e2Id, - label: record.get("decisionLabel") || null - }); + RETURN DISTINCT source.id AS fromId, source.title AS fromTitle, sourceAuthor, + target.id AS toId, target.title AS toTitle, targetAuthor, transition.decisionLabel AS label + ORDER BY fromId, toId, label + `, + { seedIds }, + ); + const nodes = new Map(); + const edges = new Map(); + for (const record of edgeResult.records) { + const fromId = record.get("fromId") as string; + const toId = record.get("toId") as string; + nodes.set(fromId, { id: fromId, title: record.get("fromTitle"), authorUsername: record.get("sourceAuthor"), upvoteCount: 0 }); + nodes.set(toId, { id: toId, title: record.get("toTitle"), authorUsername: record.get("targetAuthor"), upvoteCount: 0 }); + const key = JSON.stringify([fromId, toId]); + if (!edges.has(key)) edges.set(key, { fromId, toId, label: record.get("label") ?? null }); } + if (!nodes.size) return { nodes: [], edges: [], paths: [] }; - return { - nodes: Array.from(nodesMap.values()), - edges - }; + const voteResult = await session.run( + ` + UNWIND $ids AS id + MATCH (e:Experience {id: id})<-[vote:UPVOTED]-(voter:User) + WHERE NOT EXISTS { MATCH (voter)-[:HAS_EXPERIENCE]->(e) } + WITH e, voter, max(vote.createdAt) AS latestVote + RETURN e.id AS experienceId, elementId(voter) AS voterId, latestVote.epochMillis AS castAt + `, + { ids: [...nodes.keys()] }, + ); + const votes: PathVote[] = voteResult.records.map(record => { + const experienceId = record.get("experienceId") as string; + const castAt = record.get("castAt"); + nodes.get(experienceId)!.upvoteCount++; + return { experienceId, voterId: record.get("voterId"), castAt: castAt == null ? null : Number(castAt) }; + }); + const paths = rankTrendingPaths(seedIds, [...nodes.values()], [...edges.values()], votes, now, limit); + return { paths, nodes: paths.flatMap(path => path.nodes), edges: paths.flatMap(path => path.edges) }; } finally { await closeSession(session); } -} \ No newline at end of file +} diff --git a/backend/src/services/trendingPaths.ts b/backend/src/services/trendingPaths.ts new file mode 100644 index 0000000..689740c --- /dev/null +++ b/backend/src/services/trendingPaths.ts @@ -0,0 +1,95 @@ +import type { GraphEdge, GraphNode } from "./community.service.js"; + +const DAY = 86_400_000; +const MAX_PATH_EDGES = 12; + +export interface PathVote { + experienceId: string; + voterId: string; + castAt: number | null; +} + +export interface RankedCommunityPath { + id: string; + nodes: GraphNode[]; + edges: GraphEdge[]; + recentVoters: number; + lifetimeVoters: number; +} + +export function rankTrendingPaths( + seedIds: string[], + nodes: GraphNode[], + edges: GraphEdge[], + votes: PathVote[], + now: number, + limit: number, +): RankedCommunityPath[] { + const nodeById = new Map(nodes.map(node => [node.id, node])); + const votesByNode = new Map(); + for (const vote of votes) { + const entries = votesByNode.get(vote.experienceId) ?? []; + entries.push(vote); + votesByNode.set(vote.experienceId, entries); + } + + const adjacent = new Map(); + for (const edge of edges) { + for (const id of new Set([edge.fromId, edge.toId])) { + const incident = adjacent.get(id) ?? []; + incident.push(edge); + adjacent.set(id, incident); + } + } + + const candidates = new Map(); + for (const seed of seedIds) { + const ids = new Set([seed]); + const pathEdges = new Set(); + for (const id of ids) { + if (pathEdges.size >= MAX_PATH_EDGES) break; + for (const edge of adjacent.get(id) ?? []) { + pathEdges.add(edge); + ids.add(edge.fromId); + ids.add(edge.toId); + if (pathEdges.size >= MAX_PATH_EDGES) break; + } + } + if (!pathEdges.size) continue; + const pathNodes = [...ids].map(id => nodeById.get(id)).filter((node): node is GraphNode => !!node); + const id = JSON.stringify([...pathEdges].map(edge => [edge.fromId, edge.toId]).sort()); + if (candidates.has(id)) continue; + + const lifetime = new Set(); + const recent = new Map(); + for (const nodeId of ids) { + for (const vote of votesByNode.get(nodeId) ?? []) { + lifetime.add(vote.voterId); + if (vote.castAt !== null && vote.castAt >= now - 30 * DAY && vote.castAt <= now) { + recent.set(vote.voterId, Math.max(vote.castAt, recent.get(vote.voterId) ?? -Infinity)); + } + } + } + const dates = [...recent.values()]; + candidates.set(id, { + path: { id, nodes: pathNodes, edges: [...pathEdges], recentVoters: recent.size, lifetimeVoters: lifetime.size }, + score: dates.reduce((sum, time) => sum + 2 ** (-(now - time) / (14 * DAY)), 0), + latest: dates.reduce((latest, time) => Math.max(latest, time), 0), + }); + } + + const ranked = [...candidates.values()].sort((a, b) => + b.score - a.score || b.latest - a.latest || + (a.score === 0 && b.score === 0 ? b.path.lifetimeVoters - a.path.lifetimeVoters : 0) || + a.path.id.localeCompare(b.path.id), + ); + const used = new Set(); + const paths: RankedCommunityPath[] = []; + for (const { path } of ranked) { + if (path.nodes.some(node => used.has(node.id))) continue; + paths.push(path); + for (const node of path.nodes) used.add(node.id); + if (paths.length === limit) break; + } + return paths; +} diff --git a/backend/tests/trendingPaths.test.ts b/backend/tests/trendingPaths.test.ts new file mode 100644 index 0000000..6749c91 --- /dev/null +++ b/backend/tests/trendingPaths.test.ts @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { rankTrendingPaths, type PathVote } from "../src/services/trendingPaths.js"; + +const now = Date.UTC(2026, 10, 14); +const day = 86_400_000; +const node = (id: string) => ({ id, title: id, authorUsername: "author", upvoteCount: 0 }); +const edge = (fromId: string, toId: string) => ({ fromId, toId, label: fromId + " to " + toId }); +const vote = (experienceId: string, voterId: string, daysAgo: number | null): PathVote => ({ + experienceId, voterId, castAt: daysAgo === null ? null : now - daysAgo * day, +}); + +test("connected paths still display before their first vote", () => { + const edges = [edge("a", "b"), edge("b", "c")]; + const paths = rankTrendingPaths(["a", "b", "c"], ["a", "b", "c"].map(node), edges, [], now, 5); + assert.equal(paths.length, 1); + assert.deepEqual(paths[0]?.edges, edges); + assert.equal(paths[0]?.recentVoters, 0); + assert.equal(paths[0]?.lifetimeVoters, 0); +}); + +test("recent distinct voters outrank lifetime popularity and duplicated votes count once", () => { + const edges = [edge("a", "b"), edge("b", "c"), edge("x", "y")]; + const votes = [ + vote("a", "recent", 12), vote("b", "recent", 1), vote("c", "second", 4), + vote("x", "old1", null), vote("x", "old2", 40), vote("y", "old3", null), + ]; + const paths = rankTrendingPaths(["x", "a", "b"], ["a", "b", "c", "x", "y"].map(node), edges, votes, now, 5); + assert.equal(paths.length, 2); + assert.deepEqual(paths[0]?.edges, edges.slice(0, 2)); + assert.equal(paths[0]?.recentVoters, 2); + assert.equal(paths[0]?.lifetimeVoters, 2); + assert.equal(paths[1]?.recentVoters, 0); + assert.equal(paths[1]?.lifetimeVoters, 3); +}); + +test("recent weighting uses the latest vote per voter and ties are stable", () => { + const edges = [edge("a", "b"), edge("x", "y"), edge("j", "k")]; + const nodes = ["a", "b", "x", "y", "j", "k"].map(node); + const votes = [vote("a", "u1", 1), vote("b", "u1", 1), vote("x", "u2", 1), vote("j", "u3", 0)]; + const paths = rankTrendingPaths(["x", "a", "j"], nodes, edges, votes, now, 3); + assert.deepEqual(paths.map(path => path.edges[0]?.fromId), ["j", "a", "x"]); +}); + +test("a large hub has a bounded path and cannot take multiple slots", () => { + const edges = Array.from({ length: 16 }, (_, index) => edge("hub", String(index))); + edges.push(edge("x", "y")); + const nodes = [...new Set(edges.flatMap(({ fromId, toId }) => [fromId, toId]))].map(node); + const votes = [vote("hub", "voter", 0), vote("15", "other", 0), vote("x", "popular", null)]; + const paths = rankTrendingPaths(["hub", "15", "x"], nodes, edges, votes, now, 3); + assert.equal(paths.length, 2); + assert.equal(paths[0]?.edges.length, 12); + assert.equal(paths[1]?.edges[0]?.fromId, "x"); +}); diff --git a/frontend/api/community.api.ts b/frontend/api/community.api.ts index 35dbc5b..77c0fb0 100644 --- a/frontend/api/community.api.ts +++ b/frontend/api/community.api.ts @@ -36,6 +36,15 @@ export interface GraphEdge { export interface CommunityGraph { nodes: GraphNode[]; edges: GraphEdge[]; + paths?: RankedCommunityPath[]; +} + +export interface RankedCommunityPath { + id: string; + nodes: GraphNode[]; + edges: GraphEdge[]; + recentVoters: number; + lifetimeVoters: number; } export async function getCommunityGraph(limit = 20): Promise { diff --git a/frontend/app/(tabs)/community.tsx b/frontend/app/(tabs)/community.tsx index 6560f86..7ac3981 100644 --- a/frontend/app/(tabs)/community.tsx +++ b/frontend/app/(tabs)/community.tsx @@ -14,7 +14,6 @@ import { getTopics, getSubtopics, searchCommunity, SearchCommunityUser, getCommunityGraph, CommunityGraph } from '../../api/community.api'; -import { useAuth } from '@clerk/clerk-expo'; import { VisualGraph } from '../../components/community/VisualGraph'; import { SectionLabel } from '../../components/ui/SectionLabel'; import { useDesktopLayout } from '../../utils/useDesktopLayout'; @@ -327,7 +326,6 @@ function SkeletonCard() { export default function CommunityPage() { const desktop = useDesktopLayout(); const router = useRouter(); - const { getToken } = useAuth(); const [graph, setGraph] = useState(null); const [topics, setTopics] = useState([]); @@ -338,33 +336,43 @@ export default function CommunityPage() { const [users, setUsers] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isRefreshing, setIsRefreshing] = useState(false); + const [journeyLoadFailed, setJourneyLoadFailed] = useState(false); + const [graphLoadFailed, setGraphLoadFailed] = useState(false); + const requestId = useRef(0); const [topicPickerVisible, setTopicPickerVisible] = useState(false); const [subtopicPickerVisible, setSubtopicPickerVisible] = useState(false); const [graphExpanded, setGraphExpanded] = useState(true); const fetchData = async () => { + const id = ++requestId.current; setIsLoading(true); - try { - const [usersData, graphData] = await Promise.all([ - searchCommunity({ - topic: selectedTopic || undefined, - subtopic: selectedSubtopic || undefined, - limit: 50, - }), - !selectedTopic ? getCommunityGraph() : Promise.resolve(null) - ]); - setUsers(usersData); - if (!selectedTopic && graphData) { - setGraph(graphData); - } - } catch (e: any) { - console.warn('Failed to fetch data:', e); - setUsers([]); - } finally { + setJourneyLoadFailed(false); + setGraphLoadFailed(false); + const journeysRequest = searchCommunity({ + topic: selectedTopic || undefined, + subtopic: selectedSubtopic || undefined, + limit: 50, + }).then(settledUsers => { + if (id === requestId.current) setUsers(settledUsers); + }).catch(error => { + if (id !== requestId.current) return; + console.warn('Failed to load community journeys:', error); + setJourneyLoadFailed(true); + }).finally(() => { + if (id !== requestId.current) return; setIsLoading(false); setIsRefreshing(false); - } + }); + + const graphRequest = (selectedTopic ? Promise.resolve(null) : getCommunityGraph()).then(result => { + if (id === requestId.current) setGraph(result); + }).catch(error => { + if (id !== requestId.current) return; + console.warn('Failed to load trending paths:', error); + setGraphLoadFailed(true); + }); + await Promise.all([journeysRequest, graphRequest]); }; useEffect(() => { @@ -420,7 +428,7 @@ export default function CommunityPage() { } else { fetchTopics(); } - }, [selectedTopic, selectedSubtopic, getToken]); + }, [selectedTopic, selectedSubtopic]); const handleTopicSelect = (topic: string) => { if (selectedTopic === topic) { @@ -437,14 +445,18 @@ export default function CommunityPage() { setSubtopicPickerVisible(false); }; + const openCommunityJourney = useCallback((username: string) => { + router.push({ pathname: '/u/[username]', params: { username, fromCommunity: 'true' } }); + }, [router]); + const renderUserCard = useCallback(({ item, index }: { item: SearchCommunityUser; index: number }) => ( router.push(`/u/${item.username || 'user'}`)} + onViewJourney={() => openCommunityJourney(item.username || 'user')} /> - ), [router]); + ), [openCommunityJourney]); const isSearchEnabled = selectedTopic != null; @@ -459,10 +471,12 @@ export default function CommunityPage() { graphExpanded={graphExpanded} isLoading={isLoading} isRefreshing={isRefreshing} + journeyLoadFailed={journeyLoadFailed} + graphLoadFailed={graphLoadFailed} onTopicPress={() => setTopicPickerVisible(true)} onSubtopicPress={() => setSubtopicPickerVisible(true)} onToggleGraph={() => setGraphExpanded(prev => !prev)} - onViewJourney={username => router.push(`/u/${username}`)} + onViewJourney={openCommunityJourney} onRefresh={onRefresh} /> ) : <> @@ -512,22 +526,11 @@ export default function CommunityPage() { ) : ( - users.length === 0 ? ( - - 🌱 - - {isSearchEnabled ? "No journeys match yet" : "It's quiet here"} - - - {isSearchEnabled ? "Try exploring a different topic or subtopic." : "No journeys have been shared yet. Be the first!"} - - - ) : ( item.username || `user-${index}`} ListHeaderComponent={ - graph && graph.nodes.length > 0 ? ( + !selectedTopic && graph && graph.nodes.length > 0 ? ( {graphExpanded && graph && graph.nodes.length > 0 && ( - + )} - Recommended Journeys - + } ) : null } + ListEmptyComponent={!journeyLoadFailed ? ( + + + {isSearchEnabled ? 'No journeys match yet' : 'No recommended journeys yet'} + + {isSearchEnabled && Try exploring a different topic or subtopic.} + + ) : null} + ListFooterComponent={journeyLoadFailed || (!selectedTopic && graphLoadFailed) ? ( + + + {journeyLoadFailed ? 'Could not load journeys.' : 'Could not load Trending Paths.'} Tap to retry. + + + ) : null} renderItem={renderUserCard} contentContainerStyle={{ paddingHorizontal: 24, paddingBottom: 24 }} showsVerticalScrollIndicator={false} @@ -581,7 +596,6 @@ export default function CommunityPage() { } /> - ) )} } diff --git a/frontend/app/(tabs)/profile.tsx b/frontend/app/(tabs)/profile.tsx index 61b9ab1..98d6bed 100644 --- a/frontend/app/(tabs)/profile.tsx +++ b/frontend/app/(tabs)/profile.tsx @@ -170,7 +170,9 @@ export default function ProfilePage() { onSaveUsername={handleSaveUsername} onUsernameButtonPress={() => { Keyboard.dismiss(); handleSaveUsername(); }} languageLabel={LANGUAGES.find(l => l.code === languageCode)?.label || languageCode} - onLanguagePress={() => bottomSheetRef.current?.expand()} + languageCode={languageCode} + languages={LANGUAGES} + onSelectLanguage={handleSaveLanguage} onAddExperience={() => router.push('/share-journey')} onSignOut={handleSignOut} showSuccessTick={showSuccessTick} @@ -316,7 +318,7 @@ export default function ProfilePage() { } {/* Bottom Sheet Picker (Language) */} - - + } ); } diff --git a/frontend/app/u/[username].tsx b/frontend/app/u/[username].tsx index 8ff2759..62a6c05 100644 --- a/frontend/app/u/[username].tsx +++ b/frontend/app/u/[username].tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useMemo } from 'react'; +import { useState, useEffect, useMemo, useRef, useCallback } from 'react'; import { View, Text, ScrollView, TouchableOpacity, Modal, ActivityIndicator, Platform, Image, Share, Alert @@ -15,13 +15,32 @@ import { WebView } from 'react-native-webview'; export default function PublicProfilePage() { const router = useRouter(); - const { username, fromQuery, imageUrl, expandedDetails } = useLocalSearchParams<{ username: string; fromQuery?: string; imageUrl?: string; expandedDetails?: string; }>(); + const { username, fromCommunity, fromQuery, imageUrl, expandedDetails, experienceId } = useLocalSearchParams<{ + username: string; fromCommunity?: string; fromQuery?: string; imageUrl?: string; expandedDetails?: string; experienceId?: string; + }>(); + const goBack = () => { + if (fromCommunity === 'true') router.dismissTo('/(tabs)/community'); + else if (router.canGoBack()) router.back(); + else router.replace('/'); + }; const [journey, setJourney] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [showGraph, setShowGraph] = useState(false); const [selectedNodeId, setSelectedNodeId] = useState(null); + const scrollRef = useRef(null); + const contentRef = useRef(null); + const targetRef = useRef(null); + const scrolledTo = useRef(undefined); + const scrollToExperience = useCallback(() => { + if (!experienceId || scrolledTo.current === experienceId || !contentRef.current) return; + targetRef.current?.measureLayout(contentRef.current, (_x, y) => { + if (!scrollRef.current || scrolledTo.current === experienceId) return; + scrolledTo.current = experienceId; + scrollRef.current.scrollTo({ y: Math.max(0, y - 12), animated: false }); + }); + }, [experienceId]); const graphHtml = useMemo( () => createJourneyGraphHtml(buildJourneyGraphElements(journey, { filterMissingTransitions: true })), [journey], @@ -181,6 +200,9 @@ export default function PublicProfilePage() { Retry + {fromCommunity === 'true' && + Back to Community + } ); } @@ -190,7 +212,9 @@ export default function PublicProfilePage() { {/* Header */} { if (router.canGoBack()) { router.back(); } else { router.replace('/'); } }} + accessibilityRole="button" + accessibilityLabel={fromCommunity === 'true' ? 'Back to Community' : 'Go back'} + onPress={goBack} activeOpacity={0.7} style={{ width: 40, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center', backgroundColor: L.surface }} > @@ -204,7 +228,9 @@ export default function PublicProfilePage() { - + + {/* Summary Stat Block */} @@ -286,8 +312,12 @@ export default function PublicProfilePage() { .filter((title): title is string => !!title) : []; return ( - + )} + {/* Graph Modal */} diff --git a/frontend/components/community/VisualGraph.tsx b/frontend/components/community/VisualGraph.tsx index 3daad56..21cfc1c 100644 --- a/frontend/components/community/VisualGraph.tsx +++ b/frontend/components/community/VisualGraph.tsx @@ -4,7 +4,7 @@ import { PinchGestureHandler, State, ScrollView as GHScrollView } from 'react-na import { Feather } from '@expo/vector-icons'; import Svg, { Defs, Marker, Path } from 'react-native-svg'; import { useRouter } from 'expo-router'; -import type { GraphNode, GraphEdge } from '../../api/community.api'; +import type { CommunityGraph, RankedCommunityPath } from '../../api/community.api'; import { L } from '../../constants/colors'; import { groupCommunityPaths, layoutCommunityPath, PATH_CARD_WIDTH, PATH_CARD_HEIGHT, @@ -16,7 +16,7 @@ const MAX_SCALE = 2.5; const INITIAL_SCALE = 0.85; const clampScale = (value: number) => Math.min(MAX_SCALE, Math.max(MIN_SCALE, value)); -function PathCanvas({ path }: { path: CommunityPath }) { +function PathCanvas({ path }: { path: CommunityPath | RankedCommunityPath }) { const router = useRouter(); const layout = useMemo(() => layoutCommunityPath(path), [path]); const [scale, setScale] = useState(INITIAL_SCALE); @@ -44,6 +44,13 @@ function PathCanvas({ path }: { path: CommunityPath }) { {path.nodes.length} {path.nodes.length === 1 ? 'experience' : 'experiences'} {' · '}{path.edges.length} {path.edges.length === 1 ? 'connection' : 'connections'} + {'recentVoters' in path && + {path.recentVoters > 0 + ? `${path.recentVoters} ${path.recentVoters === 1 ? 'person' : 'people'} upvoted this path in the last 30 days` + : path.lifetimeVoters > 0 + ? `Popular · ${path.lifetimeVoters} ${path.lifetimeVoters === 1 ? 'person' : 'people'} upvoted this path` + : 'No upvotes yet'} + } @@ -81,7 +88,10 @@ function PathCanvas({ path }: { path: CommunityPath }) { accessibilityRole="button" accessibilityLabel={`${node.title}. Open ${node.authorUsername || 'this user'}'s journey`} disabled={!node.authorUsername} - onPress={() => router.push({ pathname: '/u/[username]', params: { username: node.authorUsername } })} + onPress={() => router.push({ + pathname: '/u/[username]', + params: { username: node.authorUsername, fromCommunity: 'true', experienceId: node.id }, + })} style={({ pressed }) => [styles.node, { left: node.x, top: node.y, opacity: pressed ? 0.7 : 1 }]} > @@ -117,8 +127,8 @@ function PathCanvas({ path }: { path: CommunityPath }) { ); } -export function VisualGraph({ nodes, edges }: { nodes: GraphNode[]; edges: GraphEdge[] }) { - const paths = useMemo(() => groupCommunityPaths(nodes, edges), [nodes, edges]); +export function VisualGraph({ nodes, edges, paths: rankedPaths }: CommunityGraph) { + const paths = useMemo(() => rankedPaths ?? groupCommunityPaths(nodes, edges), [rankedPaths, nodes, edges]); const [selectedPathId, setSelectedPathId] = useState(null); const currentIndex = Math.max(0, paths.findIndex(path => path.id === selectedPathId)); const path = paths[currentIndex]; diff --git a/frontend/components/desktop/DesktopCommunity.tsx b/frontend/components/desktop/DesktopCommunity.tsx index 034841b..b96815c 100644 --- a/frontend/components/desktop/DesktopCommunity.tsx +++ b/frontend/components/desktop/DesktopCommunity.tsx @@ -13,6 +13,8 @@ type Props = { graphExpanded: boolean; isLoading: boolean; isRefreshing: boolean; + journeyLoadFailed: boolean; + graphLoadFailed: boolean; onTopicPress: () => void; onSubtopicPress: () => void; onToggleGraph: () => void; @@ -84,24 +86,33 @@ export function DesktopCommunity(props: Props) { - {!loading && {props.users.length} {props.users.length === 1 ? 'journey' : 'journeys'} found} + {!loading && !props.journeyLoadFailed && {props.users.length} {props.users.length === 1 ? 'journey' : 'journeys'} found} {loading ? {[0, 1, 2].map(index => )} - : props.users.length === 0 ? - 🌱 - {props.selectedTopic ? 'No journeys match yet' : "It's quiet here"} - {props.selectedTopic ? 'Try exploring a different topic or subtopic.' : 'No journeys have been shared yet. Be the first!'} : <> - {props.graph && props.graph.nodes.length > 0 && + {!props.selectedTopic && props.graph && props.graph.nodes.length > 0 && Trending Paths - {props.graphExpanded && } + {props.graphExpanded && } } - + {!props.selectedTopic && props.graphLoadFailed && + Could not load Trending Paths. + + } + {props.journeyLoadFailed && + Could not load journeys. + + } + {!props.journeyLoadFailed && props.users.length === 0 && + 🌱 + {props.selectedTopic ? 'No journeys match yet' : 'No recommended journeys yet'} + {props.selectedTopic ? 'Try exploring a different topic or subtopic.' : 'Check back as more journeys are shared.'} + } + {props.users.length > 0 && } {/* This component is rendered only on desktop web. Equal grid tracks grow to fit all card content. */}
{props.users.map((user, index) => props.onViewJourney(user.username || 'user')} />)} diff --git a/frontend/components/desktop/DesktopProfile.tsx b/frontend/components/desktop/DesktopProfile.tsx index c5cc3a9..8cf0d01 100644 --- a/frontend/components/desktop/DesktopProfile.tsx +++ b/frontend/components/desktop/DesktopProfile.tsx @@ -1,5 +1,5 @@ -import type { ComponentProps, RefObject } from 'react'; -import { StyleSheet, Text, TextInput, TouchableOpacity, View, useWindowDimensions } from 'react-native'; +import { useState, type ComponentProps, type RefObject } from 'react'; +import { ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View, useWindowDimensions } from 'react-native'; import { Feather } from '@expo/vector-icons'; import Animated from 'react-native-reanimated'; import { L } from '../../constants/colors'; @@ -15,7 +15,9 @@ type Props = { onSaveUsername: () => void; onUsernameButtonPress: () => void; languageLabel: string; - onLanguagePress: () => void; + languageCode: string; + languages: readonly { code: string; label: string }[]; + onSelectLanguage: (code: string) => void; onAddExperience: () => void; onSignOut: () => void; showSuccessTick: 'username' | 'language' | null; @@ -26,7 +28,17 @@ type Props = { export function DesktopProfile(props: Props) { const { width } = useWindowDimensions(); const compact = width < 1100; - return + const [languageOpen, setLanguageOpen] = useState(false); + const [languageMenuHeight, setLanguageMenuHeight] = useState(0); + const [languageSearch, setLanguageSearch] = useState(''); + const visibleLanguages = props.languages.filter(language => + language.label.toLowerCase().includes(languageSearch.trim().toLowerCase()), + ); + const closeLanguages = () => { + setLanguageOpen(false); + setLanguageSearch(''); + }; + return @@ -46,7 +58,7 @@ export function DesktopProfile(props: Props) { - + Account detailsManage how you appear on PathFinder. @@ -76,14 +88,37 @@ export function DesktopProfile(props: Props) { - + Preferred languageChoose your language. - - {props.languageLabel} - - + + languageOpen ? closeLanguages() : setLanguageOpen(true)} + style={[styles.control, { justifyContent: 'space-between' }]}> + {props.languageLabel} + + + {languageOpen && setLanguageMenuHeight(event.nativeEvent.layout.height)}> + { if (event.nativeEvent.key === 'Escape') closeLanguages(); }} + style={styles.languageSearch} /> + + {visibleLanguages.map(language => { + const selected = language.code === props.languageCode; + return { closeLanguages(); props.onSelectLanguage(language.code); }}> + {language.label} + {selected && } + ; + })} + {!visibleLanguages.length && No languages found} + + } + @@ -110,6 +145,9 @@ const styles = StyleSheet.create({ fieldLabel: { fontFamily: 'Manrope_700Bold', color: L.navy, fontSize: 13, lineHeight: 20 }, hint: { fontFamily: 'Manrope_400Regular', color: '#5D6A6F', fontSize: 11, lineHeight: 18, marginTop: 5 }, control: { flexDirection: 'row', alignItems: 'center', borderWidth: 1, borderColor: '#C7D2CC', borderRadius: 9, paddingVertical: 11, paddingHorizontal: 12, minHeight: 44, backgroundColor: L.surface }, + languageMenu: { position: 'absolute', top: '100%', marginTop: 6, left: 0, right: 0, zIndex: 1, borderWidth: 1, borderColor: '#C7D2CC', borderRadius: 9, backgroundColor: L.surface, padding: 6, gap: 4 }, + languageSearch: { padding: 8, color: L.navy, fontSize: 13, borderBottomWidth: 1, borderColor: L.border }, + languageOption: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 8, minHeight: 34, borderRadius: 6 }, invite: { flex: 1, minWidth: 285, backgroundColor: '#E9F0E9', borderWidth: 1, borderColor: '#D3E0D6', borderRadius: 16, paddingHorizontal: 29, paddingVertical: 26 }, journeyIcon: { width: 43, height: 43, alignItems: 'center', justifyContent: 'center', backgroundColor: '#F7FAF5', borderWidth: 1, borderColor: '#C3D5C6', borderRadius: 12, marginBottom: 20 }, footer: { alignItems: 'flex-end', paddingVertical: 19, borderTopWidth: 1, borderColor: '#E2E5DE', marginTop: 26 }, diff --git a/frontend/components/desktop/DesktopUI.tsx b/frontend/components/desktop/DesktopUI.tsx index 4a095f9..6778247 100644 --- a/frontend/components/desktop/DesktopUI.tsx +++ b/frontend/components/desktop/DesktopUI.tsx @@ -15,15 +15,16 @@ export const desktopStyles = StyleSheet.create({ card: { backgroundColor: L.surface, borderWidth: 1, borderColor: '#E2E5DE', borderRadius: 16 }, }); -export function DesktopPage({ children, maxWidth = 1200, refreshControl }: { +export function DesktopPage({ children, maxWidth = 1200, refreshControl, extraBottomSpace = 0 }: { children: ReactNode; maxWidth?: number; refreshControl?: ComponentProps['refreshControl']; + extraBottomSpace?: number; }) { const { width } = useWindowDimensions(); return diff --git a/frontend/components/journey/ExpandableCards.tsx b/frontend/components/journey/ExpandableCards.tsx index ce27346..87eb23c 100644 --- a/frontend/components/journey/ExpandableCards.tsx +++ b/frontend/components/journey/ExpandableCards.tsx @@ -189,6 +189,7 @@ export interface ExpandableExperienceCardProps { transitionLabel?: string; transitionDecision?: string; onSetEndDate?: (endDate: string) => Promise; + initiallyExpanded?: boolean; } export function ExpandableExperienceCard({ @@ -206,8 +207,9 @@ export function ExpandableExperienceCard({ transitionLabel, transitionDecision, onSetEndDate, + initiallyExpanded = false, }: ExpandableExperienceCardProps) { - const [expanded, setExpanded] = useState(false); + const [expanded, setExpanded] = useState(initiallyExpanded); const toggle = () => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); @@ -244,7 +246,8 @@ export function ExpandableExperienceCard({ /> {/* Tap Target Area Header */} - + From a1da2ecd00c4b366742cb30f454f8fd01b08f4e9 Mon Sep 17 00:00:00 2001 From: Rohita Date: Sat, 14 Nov 2026 13:12:30 +0530 Subject: [PATCH 2/2] feat(ask): update sample questions using indexed journeys --- frontend/app/(tabs)/ask.tsx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/frontend/app/(tabs)/ask.tsx b/frontend/app/(tabs)/ask.tsx index 5c21c4b..16a969e 100644 --- a/frontend/app/(tabs)/ask.tsx +++ b/frontend/app/(tabs)/ask.tsx @@ -17,28 +17,28 @@ import { Feather } from '@expo/vector-icons'; const SUGGESTED_QUESTIONS = [ { - label: "Which open-source tools helped early-career engineers prove their coding skills off campus?", - prompt: "Instead of building standard clone apps or simple layout designs, what unique open-source developer utilities and tracking dashboards have early-career engineers built to prove their low-level coding skills off-campus?", + label: "How did bootstrapped SaaS founders find their first paying customers?", + prompt: "How did bootstrapped B2B SaaS founders find their first paying customers? Compare customer interviews, manual onboarding, and audience-led launches.", }, { - label: "Which build and queue setups helped teams speed up data delivery?", - prompt: "When scaling data delivery tiers, what specific automated build configurations, non-blocking queue setups, and multi-platform compilation rules were implemented to ensure fast execution speeds?", + label: "What did SaaS founders learn before building their MVP?", + prompt: "How did bootstrapped B2B SaaS founders use customer discovery to decide what to build into their first MVP, and what did they learn from launching it?", }, { - label: "How did self-taught developers turn technical outreach into interviews?", - prompt: "How have self-taught developers transformed their professional applications from generic, blind messaging into data-driven technical consultation notes that win direct technical interviews?", + label: "How did students turn open-source projects into internships?", + prompt: "How did college students build experience for open-source internships such as Linux Foundation LFX? Look at open-source contributions, student projects, and hackathons.", }, { - label: "How did engineers process dense data without running out of memory?", - prompt: "What core algorithmic strategies, bit manipulations, and custom array allocation frameworks do developers rely on when they need to process dense, multi-layered data rows without creating system memory drops?", + label: "How did founders test demand before launching their SaaS?", + prompt: "How did SaaS founders test demand before launching their first product? Look at examples of building in public, using presale waitlists, and launching an MVP.", }, { - label: "How did bootstrapped SaaS and edtech founders grow past ₹50 lakh a year without heavy ad spend?", - prompt: "How did self-funded or bootstrapped founders scale their SaaS or edtech platforms past the 50 LPA milestone without spending heavy capital on traditional ad agencies?", + label: "How did Zoho train people for software careers without degree requirements?", + prompt: "How did Zoho University train people for software careers without requiring a degree, and how did Zoho expand that training beyond its original program?", }, { - label: "What do engineers work on after learning to scale infrastructure?", - prompt: "Once a software engineer moves past basic application frameworks and masters low-level infrastructure scaling, what complex systems-level goals do they typically target next?", + label: "How did Zerodha grow by changing brokerage pricing?", + prompt: "How did Zerodha use flat-fee brokerage and zero-brokerage equity delivery to attract retail investors and grow its fintech business?", }, ];