-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: added shareable results #140
Conversation
WalkthroughThis update adds new API endpoints in Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant A as API Route (route.ts)
participant V as Auth Service (JWT)
participant D as Database
U->>A: POST request with scores & cookie
A->>V: Verify token
V-->>A: Return user info / error
A->>D: Retrieve user and celebrities data
D-->>A: Return data
A->>D: Update PublicFigurePerUser with match
D-->>A: Acknowledge update
A->>U: Respond with matched celebrity
U->>A: GET request for latest match
A->>V: Verify token
V-->>A: Return user info
A->>D: Query PublicFigurePerUser for match
D-->>A: Return match info
A->>U: Respond with celebrity name
sequenceDiagram
participant U as User
participant I as Insights Page
participant A as API Endpoint
participant C as Canvas Component
U->>I: Load page / trigger fetchInsights()
I->>A: GET request for celebrity match
A-->>I: Return public figure data
I->>I: Update state with publicFigure
U->>I: Click share button
I->>I: Open share modal (isShareModalOpen = true)
U->>I: Choose Instagram share option
I->>C: Convert canvas to Blob
I->>U: Initiate native share functionality
Poem
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for lucent-florentine-971919 ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (7)
frontend/src/app/api/public-figures/route.ts (3)
167-172
: Potential concurrency concern with manually incremented ID.
Constructing nextCelebrityId by sorting "celebrity_user_id" descending and then adding 1 can lead to collisions in concurrent requests. Consider using an auto-increment field or a robust unique ID generator to avoid race conditions.
82-85
: Mentioned “similarity” field is never returned.
The Swagger doc for the POST operation references a "similarity" property, but the implemented code only returns the matched celebrity (public_figure). If you intend to share the similarity score, consider returning it or removing its reference from the documentation.Also applies to: 181-182
173-179
: Double-check the “create” vs “update or create” logic.
The comment says “Update or create PublicFigurePerUser record,” but the code only calls create(). If you need to handle existing records, an upsert pattern may be necessary to avoid possible duplicates or conflicting entries.frontend/src/components/Canvas.tsx (2)
62-73
: Optimize parallel loading of images.
Currently, images are loaded sequentially with multiple await calls inside drawCanvas(). Loading them in parallel (e.g., Promise.all) can shorten total load time, especially on low-bandwidth connections.Here is a possible snippet:
- const logo = await loadImage('/MindVaultLogoTransparentHD.svg'); - const icons = { - equality: await loadImage('/equality-icon.svg'), - market: await loadImage('/market-icon.svg'), - ... - }; + const [logo, equality, market, nation, globe, authority, liberty, tradition, progress] = await Promise.all([ + loadImage('/MindVaultLogoTransparentHD.svg'), + loadImage('/equality-icon.svg'), + loadImage('/market-icon.svg'), + loadImage('/nation-icon.svg'), + loadImage('/globe-icon.svg'), + loadImage('/authority-icon.svg'), + loadImage('/liberty-icon.svg'), + loadImage('/tradition-icon.svg'), + loadImage('/progress-icon.svg'), + ]); + const icons = { equality, market, nation, globe, authority, liberty, tradition, progress };
117-119
: Provide a more universal font fallback.
Using “Inter” inside ctx.font may not be available on all user devices if the custom font does not load. Consider providing a fallback font family (e.g., “Inter, sans-serif”) for a consistent rendering experience.frontend/src/app/insights/page.tsx (2)
147-200
: Clarify the share button label versus actual behavior.
The button label “Share Link” might be misleading since the flow attempts to share an image on Instagram or downloads it. Renaming it to “Share Image” or “Share on Instagram” can improve clarity for users.
308-407
: Enhance modal accessibility.
The share modal doesn’t appear to have ARIA roles or focus management. Improving accessibility (e.g., setting focus on close button upon opening, providing aria-modal attributes) can help keyboard or screen-reader users.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (9)
frontend/public/MindVaultLogoTransparentHD.svg
is excluded by!**/*.svg
frontend/public/authority-icon.svg
is excluded by!**/*.svg
frontend/public/equality-icon.svg
is excluded by!**/*.svg
frontend/public/globe-icon.svg
is excluded by!**/*.svg
frontend/public/liberty-icon.svg
is excluded by!**/*.svg
frontend/public/market-icon.svg
is excluded by!**/*.svg
frontend/public/nation-icon.svg
is excluded by!**/*.svg
frontend/public/progress-icon.svg
is excluded by!**/*.svg
frontend/public/tradition-icon.svg
is excluded by!**/*.svg
📒 Files selected for processing (3)
frontend/src/app/api/public-figures/route.ts
(1 hunks)frontend/src/app/insights/page.tsx
(11 hunks)frontend/src/components/Canvas.tsx
(1 hunks)
🔇 Additional comments (4)
frontend/src/app/api/public-figures/route.ts (1)
155-165
: Verify null checks when accessing celebrity scores.
The code casts celebrity.scores to UserScores, but there's no guard if celebrity.scores is null or undefined. If the underlying database record lacks scores, this will throw. Consider validating or providing fallback values.frontend/src/components/Canvas.tsx (1)
16-18
: Validate rendering context before drawing images.
Although you already check if ctx is null, consider providing an early return or fallback if the image loading or drawing fails. This avoids potential runtime errors in edge cases (e.g., the user’s device or environment lacking canvas support).Also applies to: 29-31
frontend/src/app/insights/page.tsx (2)
79-82
: Ensure consistent handling of the public figure field.
The GET endpoint returns the celebrity property, and code here expects “figureData.celebrity.” In case of mismatch or error, you use "Unknown Match" as fallback. That’s fine, but consider logging or notifying the user if no valid data is returned to help with debugging.
449-454
: Limit the “Share Analysis” button if no advanced analysis is displayed.
If the user is not Pro, the entire advanced analysis is locked. Ensure the “Share Analysis” button is not shown, or is disabled. Currently, it appears only inside an if (isProUser) block, so you might be fine. Double-check the logic to avoid confusion.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (3)
frontend/src/app/insights/page.tsx (3)
37-39
: Consider using TypeScript interfaces for state variables.Define interfaces for the scores and public figure state to improve type safety and code maintainability.
+interface Scores { + econ: number; + dipl: number; + govt: number; + scty: number; +} -const [scores, setScores] = useState({ econ: 0, dipl: 0, govt: 0, scty: 0 }); +const [scores, setScores] = useState<Scores>({ econ: 0, dipl: 0, govt: 0, scty: 0 });
147-199
: Improve Instagram sharing implementation.The Instagram sharing implementation has several areas for improvement:
- The fallback mechanism using URL scheme might not work on all devices
- The timeout for the alert is arbitrary and might not be necessary
- Consider using a more robust sharing solution
const handleInstagramShare = async () => { if (!canvasRef.current) return; try { // Convert canvas to Blob const blob = await new Promise<Blob>((resolve, reject) => { canvasRef.current?.toBlob((b) => { b ? resolve(b) : reject(new Error('Canvas conversion failed')); }, 'image/png'); }); const file = new File([blob], 'results.png', { type: 'image/png' }); // Use native share if available if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) { try { await navigator.share({ files: [file], title: 'My Political Compass Results', text: 'Check out my political compass results!', }); return; } catch (error) { console.error('Error with native sharing:', error); } } - // Fallback: share via Instagram Stories URL scheme - const dataUrl = canvasRef.current.toDataURL('image/png'); - const encodedImage = encodeURIComponent(dataUrl); - const instagramUrl = `instagram-stories://share?backgroundImage=${encodedImage}&backgroundTopColor=%23000000&backgroundBottomColor=%23000000`; - window.location.href = instagramUrl; + // Fallback: download image with instructions + const dataUrl = canvasRef.current.toDataURL('image/png'); + const link = document.createElement('a'); + link.download = 'results.png'; + link.href = dataUrl; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); - // Alert if Instagram doesn't open automatically - setTimeout(() => { - alert( - 'If Instagram did not open automatically, please open Instagram and use the image from your camera roll to share to your story.' - ); - }, 2500); + alert( + 'The image has been downloaded. Open Instagram and select this image from your camera roll to share to your story.' + ); - // Final fallback: download the image - const link = document.createElement('a'); - link.download = 'results.png'; - link.href = dataUrl; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); } catch (error) { console.error('Error sharing to Instagram:', error); alert( 'Unable to share directly to Instagram. The image has been downloaded to your device – you can manually share it to your Instagram story.' ); } };
346-356
: Consider adding loading state for canvas rendering.The canvas rendering might take time, especially with complex visualizations. Consider adding a loading state to improve user experience.
+const [isCanvasLoading, setIsCanvasLoading] = useState(true); <div className="p-6 text-center max-h-[70vh] overflow-y-auto scrollbar-custom"> <div className="w-full max-w-md mx-auto"> + {isCanvasLoading && ( + <div className="flex justify-center items-center h-[300px]"> + <LoadingSpinner /> + </div> + )} <ResultsCanvas ref={canvasRef} + onLoad={() => setIsCanvasLoading(false)} econ={scores.econ} dipl={scores.dipl} govt={scores.govt} scty={scores.scty} closestMatch={publicFigure} /> </div> </div>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (3)
frontend/src/app/api/public-figures/route.ts (1)
24-34
: Simplify the similarity calculation using array methods.The average calculation can be simplified using array methods for better readability and maintainability.
function calculateSimilarity(userScores: UserScores, celebrityScores: UserScores): number { - const diff = { - dipl: Math.abs(userScores.dipl - celebrityScores.dipl), - econ: Math.abs(userScores.econ - celebrityScores.econ), - govt: Math.abs(userScores.govt - celebrityScores.govt), - scty: Math.abs(userScores.scty - celebrityScores.scty) - }; - - // Return average difference (lower is better) - return (diff.dipl + diff.econ + diff.govt + diff.scty) / 4; + const dimensions = ['dipl', 'econ', 'govt', 'scty'] as const; + const differences = dimensions.map(dim => + Math.abs(userScores[dim] - celebrityScores[dim]) + ); + return differences.reduce((sum, diff) => sum + diff, 0) / differences.length; }frontend/src/app/insights/page.tsx (2)
156-208
: Improve code organization by extracting Instagram share fallback logic.The Instagram share implementation could be more maintainable by extracting the fallback logic into separate functions.
+ const shareNatively = async (file: File) => { + try { + await navigator.share({ + files: [file], + title: 'My Political Compass Results', + text: 'Check out my political compass results!', + }); + return true; + } catch (error) { + console.error('Error with native sharing:', error); + return false; + } + }; + + const shareToInstagramStories = (dataUrl: string) => { + const encodedImage = encodeURIComponent(dataUrl); + const instagramUrl = `instagram-stories://share?backgroundImage=${encodedImage}&backgroundBottomColor=%23000000&backgroundTopColor=%23000000`; + window.location.href = instagramUrl; + }; + const handleInstagramShare = async () => { if (!canvasRef.current) return; try { const blob = await new Promise<Blob>((resolve, reject) => { canvasRef.current?.toBlob((b) => { b ? resolve(b) : reject(new Error('Canvas conversion failed')); }, 'image/png'); }); const file = new File([blob], 'results.png', { type: 'image/png' }); if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) { - try { - await navigator.share({ - files: [file], - title: 'My Political Compass Results', - text: 'Check out my political compass results!', - }); - return; - } catch (error) { - console.error('Error with native sharing:', error); - } + const shared = await shareNatively(file); + if (shared) return; } const dataUrl = canvasRef.current.toDataURL('image/png'); - const encodedImage = encodeURIComponent(dataUrl); - const instagramUrl = `instagram-stories://share?backgroundImage=${encodedImage}&backgroundBottomColor=%23000000&backgroundTopColor=%23000000`; - window.location.href = instagramUrl; + shareToInstagramStories(dataUrl); setTimeout(() => { alert( 'If Instagram did not open automatically, please open Instagram and use the image from your camera roll to share to your story.' ); }, 2500); const link = document.createElement('a'); link.download = 'results.png'; link.href = dataUrl; document.body.appendChild(link); link.click(); document.body.removeChild(link); } catch (error) { console.error('Error sharing to Instagram:', error); alert( 'Unable to share directly to Instagram. The image has been downloaded to your device – you can manually share it to your Instagram story.' ); } };
317-420
: Extract common modal code into a reusable component.Both modals share similar structure and styling. Consider creating a reusable modal component to reduce code duplication.
Create a new file
components/ui/Modal.tsx
:interface ModalProps { isOpen: boolean; onClose: () => void; title: string; children: React.ReactNode; footer?: React.ReactNode; } export function Modal({ isOpen, onClose, title, children, footer }: ModalProps) { if (!isOpen) return null; return ( <motion.div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={onClose} > <motion.div className="relative w-full max-w-2xl bg-gradient-to-b from-brand-tertiary/20 to-brand-tertiary/5 border border-white/10 rounded-3xl shadow-2xl overflow-hidden backdrop-blur-xl" initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.95, opacity: 0 }} transition={{ duration: 0.3 }} onClick={(e) => e.stopPropagation()} > <div className="absolute inset-0 bg-gradient-to-br from-brand-tertiary/20 via-transparent to-transparent pointer-events-none" /> <div className="relative p-6 pb-4 text-center border-b border-white/10 bg-white/5"> <button onClick={onClose} className="absolute top-4 right-4 text-white/70 hover:text-white transition-colors hover:bg-white/10 p-2 rounded-full" > <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /> </svg> </button> <h2 className="text-2xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-slate-100 to-slate-300"> {title} </h2> </div> <div className="p-6 text-center max-h-[70vh] overflow-y-auto scrollbar-custom"> {children} </div> {footer && ( <div className="flex justify-between gap-3 p-4 border-t border-white/10 bg-[#162026]/80"> {footer} </div> )} </motion.div> </motion.div> ); }Then use it in your component:
- {isShareModalOpen && ( - <motion.div - className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" - initial={{ opacity: 0 }} - animate={{ opacity: 1 }} - exit={{ opacity: 0 }} - onClick={() => setIsShareModalOpen(false)} - > + <Modal + isOpen={isShareModalOpen} + onClose={() => setIsShareModalOpen(false)} + title="Share Your Results" + footer={ + <div className="flex justify-between gap-3 w-full"> + <FilledButton /* ... */ /> + <FilledButton /* ... */ /> + </div> + } + > + <div className="w-full max-w-md mx-auto"> + <ResultsCanvas /* ... */ /> + </div> + </Modal>Also applies to: 422-515
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
frontend/src/app/api/public-figures/route.ts
(1 hunks)frontend/src/app/insights/page.tsx
(7 hunks)
🧰 Additional context used
🪛 GitHub Actions: PR Check
frontend/src/app/api/public-figures/route.ts
[error] 143-143: Property 'PublicFigures' does not exist on type 'SchemaPluginResult'.
🔇 Additional comments (3)
frontend/src/app/api/public-figures/route.ts (1)
218-281
: LGTM!The GET endpoint is well-implemented with proper error handling, token verification, and response structure.
frontend/src/app/insights/page.tsx (2)
32-39
: LGTM!The state management and data fetching implementation is robust with proper error handling.
Also applies to: 69-84
305-314
: LGTM!The share functionality is well-implemented with proper error handling and accessibility features.
Also applies to: 317-420
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm! Fixed the missing table with #142
This PR enhances the insights experience by adding share functionality:
These changes aim to boost user engagement and make sharing insights more interactive and visually appealing.
Summary by CodeRabbit