Repository navigation
Add analytics seed data and fix chart display issues on mobile - #807
Conversation
|
@kulterryan is attempting to deploy a commit to the Better T Stack Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughThis PR updates chart container sizing behavior across three analytics chart component files by adding Changes
Possibly related PRs
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
packages/backend/convex/seed.ts (5)
6-39: Use standard function declarations instead of arrow functions.Per coding guidelines, functions should use standard function declaration syntax. These helper functions are defined as arrow functions assigned to
const.🔎 Proposed refactor to function declarations
-function incrementKey( - dist: Record<string, number>, - key: string | undefined, -): Record<string, number> { +function incrementKey( + dist: Record<string, number>, + key: string | undefined, +) { if (!key) return dist; return { ...dist, [key]: (dist[key] || 0) + 1 }; } -function incrementKeys( - dist: Record<string, number>, - keys: string[] | undefined, -): Record<string, number> { +function incrementKeys( + dist: Record<string, number>, + keys: string[] | undefined, +) { if (!keys) return dist; const result = { ...dist }; for (const key of keys) { result[key] = (result[key] || 0) + 1; } return result; } -function incrementBool( - dist: Record<string, number>, - val: boolean | undefined, -): Record<string, number> { +function incrementBool( + dist: Record<string, number>, + val: boolean | undefined, +) { if (val === undefined) return dist; const key = val ? "Yes" : "No"; return { ...dist, [key]: (dist[key] || 0) + 1 }; } -function getMajorVersion(version: string | undefined): string | undefined { +function getMajorVersion(version: string | undefined) { if (!version) return undefined; const clean = version.startsWith("v") ? version.slice(1) : version; return `v${clean.split(".")[0]}`; }As per coding guidelines, explicit return types should also be removed.
97-101: Non-uniform shuffle algorithm.The
sort(() => Math.random() - 0.5)shuffle is not uniformly distributed. For seed data this is acceptable, but if truly random distribution matters, consider Fisher-Yates shuffle.🔎 Fisher-Yates shuffle alternative
function randomSubset<T>(arr: readonly T[], maxCount: number): T[] { const count = Math.floor(Math.random() * (maxCount + 1)); - const shuffled = [...arr].sort(() => Math.random() - 0.5); + const shuffled = [...arr]; + for (let i = shuffled.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; + } return shuffled.slice(0, count); }
174-177: Consider validating input bounds.Negative values for
countordayscould cause unexpected behavior: a negativecountwould skip the loop entirely, while a negativedayswould generate future-dated events (positivedaysAgovalues).🔎 Add input validation
handler: async (ctx, args) => { - const count = args.count ?? 100; - const days = args.days ?? 60; + const count = Math.max(0, args.count ?? 100); + const days = Math.max(1, args.days ?? 60);
280-348: Significant code duplication between create and update paths.The stats field initialization (Lines 323-348) largely mirrors the patch logic (Lines 288-313). Consider extracting a helper to build the stats delta, reducing duplication.
🔎 Sketch of refactor approach
function buildStatsDelta(event: EventType, hourKey: string) { const emptyDist: Record<string, number> = {}; const fe = event.frontend[0] || "none"; const be = event.backend || "none"; const stackKey = `${be} + ${fe}`; const db = event.database || "none"; const o = event.orm || "none"; const dbOrmKey = `${db} + ${o}`; return { backend: incrementKey(emptyDist, event.backend), frontend: incrementKeys(emptyDist, event.frontend), // ... remaining fields stackCombinations: incrementKey(emptyDist, stackKey), dbOrmCombinations: incrementKey(emptyDist, dbOrmKey), }; }Then merge the delta with existing stats or use as initial values.
408-454: Consider reusing helper functions for consistency.This section manually implements the same increment pattern used in
incrementKey,incrementKeys, andincrementBool. Using the existing helpers would reduce duplication and ensure consistent behavior.🔎 Example refactor using helpers
- if (ev.backend) stats.backend[ev.backend] = (stats.backend[ev.backend] || 0) + 1; - if (ev.frontend) { - for (const f of ev.frontend) { - stats.frontend[f] = (stats.frontend[f] || 0) + 1; - } - } + stats.backend = incrementKey(stats.backend, ev.backend); + stats.frontend = incrementKeys(stats.frontend, ev.frontend); // ... apply similar changes to remaining fields
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
bun.lockis excluded by!**/*.lockpackages/backend/convex/_generated/api.d.tsis excluded by!**/_generated/**
📒 Files selected for processing (4)
apps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsxapps/web/src/app/(home)/analytics/_components/timeline-charts.tsxpackages/backend/convex/seed.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/better-t-stack-repo.mdc)
Define functions using the standard function declaration syntax, not arrow functions
Files:
apps/web/src/app/(home)/analytics/_components/timeline-charts.tsxpackages/backend/convex/seed.tsapps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/better-t-stack-repo.mdc)
**/*.{ts,tsx}: Use TypeScript type aliases instead of interface declarations
Do not use explicit return types
Files:
apps/web/src/app/(home)/analytics/_components/timeline-charts.tsxpackages/backend/convex/seed.tsapps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)
**/*.{ts,tsx,js,jsx}: Usebun <file>instead ofnode <file>orts-node <file>for running TypeScript/JavaScript files
Bun automatically loads .env files, so don't use the dotenv package
UseBun.serve()which supports WebSockets, HTTPS, and routes instead ofexpress
Usebun:sqlitemodule for SQLite instead ofbetter-sqlite3
UseBun.redisfor Redis instead ofioredis
UseBun.sqlfor Postgres instead ofpgorpostgres.js
Use built-inWebSocketinstead of thewspackage
PreferBun.fileovernode:fsreadFile/writeFile methods
UseBun.$template literal syntax instead ofexecafor shell command execution
Import .css files directly in TypeScript/JavaScript files; Bun's CSS bundler will handle bundling
Run server withbun --hot <file>to enable hot reloading during development
Files:
apps/web/src/app/(home)/analytics/_components/timeline-charts.tsxpackages/backend/convex/seed.tsapps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx
**/*.{ts,tsx,js,jsx,css}
📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)
Use
bun build <file>instead ofwebpackoresbuildfor bundling TypeScript, JavaScript, and CSS files
Files:
apps/web/src/app/(home)/analytics/_components/timeline-charts.tsxpackages/backend/convex/seed.tsapps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx
**/*.{html,tsx,ts,jsx,js}
📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)
Use HTML imports with
Bun.serve()for frontend instead of Vite
Files:
apps/web/src/app/(home)/analytics/_components/timeline-charts.tsxpackages/backend/convex/seed.tsapps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx
🧬 Code graph analysis (2)
apps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsx (2)
apps/web/src/components/ui/chart.tsx (1)
ChartContainer(319-319)apps/web/src/app/(home)/analytics/_components/types.ts (1)
chartConfig(49-52)
apps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx (2)
apps/web/src/components/ui/chart.tsx (1)
ChartContainer(319-319)apps/web/src/app/(home)/analytics/_components/types.ts (1)
chartConfig(49-52)
🔇 Additional comments (4)
packages/backend/convex/seed.ts (1)
355-363: rebuildStats does not rebuild analyticsDailyStats.The mutation deletes and rebuilds
analyticsStatsbut doesn't touchanalyticsDailyStats. If daily stats get out of sync, this rebuild won't fix them. Consider whether this is intentional or if daily stats should also be rebuilt for consistency.apps/web/src/app/(home)/analytics/_components/timeline-charts.tsx (1)
74-77: LGTM! Consistent mobile optimization applied across timeline charts.All chart containers properly use
aspect-autoto override default aspect ratios, and YAxis components include the reducedwidth={16}for better spacing. The changes align perfectly with the mobile responsiveness improvements in other analytics components.Also applies to: 88-88, 113-116, 126-126, 134-137, 160-163, 174-174
apps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx (1)
41-45: LGTM! Chart components updated consistently.The
aspect-autoaddition and YAxis width adjustment follow the same mobile optimization pattern applied throughout the analytics components. Thestyle={{ height }}prop correctly preserves dynamic height behavior.Also applies to: 55-55
apps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsx (1)
47-51: Unable to proceed: No review comment was provided for rewriting. Please provide the review comment within<review_comment>tags so I can verify and rewrite it according to the specified format.
There was a problem hiding this comment.
Pull request overview
This PR adds analytics seed data functionality for development/testing and fixes chart display issues on mobile devices by correcting aspect ratios and reducing Y-axis padding.
- Added comprehensive seed data generation with randomized analytics events and configurable parameters
- Fixed chart overflow on mobile by adding
aspect-autoto override baseaspect-videostyling - Reduced excessive left padding in charts by setting Y-axis width to 16px
Reviewed changes
Copilot reviewed 5 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
packages/backend/convex/seed.ts |
New seed file that generates mock analytics data with randomized stack configurations, supports historical event distribution, and includes stats rebuilding capability |
packages/backend/convex/_generated/api.d.ts |
Auto-generated API file updated to include the new seed module |
bun.lock |
Lock file updates for fumadocs package version bumps |
apps/web/src/app/(home)/analytics/_components/timeline-charts.tsx |
Added aspect-auto to all ChartContainer instances and set YAxis width to 16px for timeline, monthly, platform, and hourly charts |
apps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsx |
Added aspect-auto to ChartContainer instances and set YAxis width to 16px for bar and pie charts |
apps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsx |
Added aspect-auto to ChartContainer instances and set YAxis width to 16px for vertical bar, version bar, and pie charts |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| await ctx.db.insert("analyticsEvents", { | ||
| database: event.database, | ||
| orm: event.orm, | ||
| backend: event.backend, | ||
| runtime: event.runtime, | ||
| frontend: event.frontend, | ||
| addons: event.addons, | ||
| examples: event.examples, | ||
| auth: event.auth, | ||
| payments: event.payments, | ||
| git: event.git, | ||
| packageManager: event.packageManager, | ||
| install: event.install, | ||
| dbSetup: event.dbSetup, | ||
| api: event.api, | ||
| webDeploy: event.webDeploy, | ||
| serverDeploy: event.serverDeploy, | ||
| cli_version: event.cli_version, | ||
| node_version: event.node_version, | ||
| platform: event.platform, | ||
| }); | ||
|
|
||
| const now = Date.now(); | ||
| const eventTime = now - daysAgo * 24 * 60 * 60 * 1000; | ||
| const date = new Date(eventTime).toISOString().slice(0, 10); |
There was a problem hiding this comment.
The inserted analyticsEvent will have its _creationTime set to the current time, not the historical time calculated by eventTime (lines 262-264). This means all seed events will appear to have been created at the same time (when seeding runs), rather than being distributed across the daysAgo range.
Additionally, the hourOfDay parameter is only used for the hourlyDistribution stat (line 277), but the actual event's creation time will not reflect this hour. This creates an inconsistency where the event's _creationTime doesn't match the hourly distribution being tracked.
To fix this, you'll need to either:
- Store a custom timestamp field in the event and use that throughout instead of
_creationTime, or - Find an alternative approach to insert events with backdated timestamps if the database supports it
The rebuildStats function (line 400) relies on ev._creationTime to extract the hour, which will be incorrect for seed data.
| const daysAgo = Math.floor(Math.random() * days); | ||
| const hourOfDay = Math.floor(Math.random() * 24); | ||
|
|
||
| await ctx.scheduler.runAfter(i * 10, internal.seed.ingestSeedEvent, { |
There was a problem hiding this comment.
The seeding process schedules all events with a fixed 10ms delay between each mutation (i * 10). For the default 100 events, this results in a 1-second total delay, which is reasonable. However, if a user calls this with a large count (e.g., 10,000 events), the last event would be scheduled to run after 100 seconds (1.67 minutes).
Consider either:
- Adding validation to limit the maximum count to a reasonable number
- Using a smaller delay multiplier (e.g.,
i * 5or eveni * 1) - Batching the events instead of scheduling them individually
This will prevent potential timeout issues or excessive delays when seeding large datasets.
| const existingEvents = await ctx.db.query("analyticsEvents").collect(); | ||
| for (const event of existingEvents) { | ||
| await ctx.db.delete(event._id); | ||
| } | ||
|
|
||
| const existingStats = await ctx.db.query("analyticsStats").first(); | ||
| if (existingStats) { | ||
| await ctx.db.delete(existingStats._id); | ||
| } | ||
|
|
||
| const existingDaily = await ctx.db.query("analyticsDailyStats").collect(); | ||
| for (const daily of existingDaily) { | ||
| await ctx.db.delete(daily._id); | ||
| } |
There was a problem hiding this comment.
The deletion loops use .collect() which loads all matching documents into memory before deleting them one by one. For large datasets, this could be memory-intensive and slow.
Consider using pagination or batching for deletions if the number of events could be large:
let batch = await ctx.db.query("analyticsEvents").take(100);
while (batch.length > 0) {
for (const event of batch) {
await ctx.db.delete(event._id);
}
batch = await ctx.db.query("analyticsEvents").take(100);
}This approach processes documents in chunks rather than loading everything into memory at once.
|
|
||
| function randomSubset<T>(arr: readonly T[], maxCount: number): T[] { | ||
| const count = Math.floor(Math.random() * (maxCount + 1)); | ||
| const shuffled = [...arr].sort(() => Math.random() - 0.5); |
There was a problem hiding this comment.
The shuffle implementation [...arr].sort(() => Math.random() - 0.5) is not a proper shuffle algorithm and has bias. This approach doesn't produce a uniform distribution of permutations.
Consider using the Fisher-Yates shuffle algorithm for proper randomization:
function randomSubset<T>(arr: readonly T[], maxCount: number): T[] {
const count = Math.floor(Math.random() * (maxCount + 1));
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled.slice(0, count);
}While this is seed data and the bias may not be critical, using a proper shuffle algorithm is a best practice.
| const shuffled = [...arr].sort(() => Math.random() - 0.5); | |
| const shuffled = [...arr]; | |
| for (let i = shuffled.length - 1; i > 0; i--) { | |
| const j = Math.floor(Math.random() * (i + 1)); | |
| [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; | |
| } |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Will check tomorrow 🫡 . Thanks @kulterryan ! |
…tribution timeline
…ructions" This reverts commit 585a7c7.
There was a problem hiding this comment.
This PR is being reviewed by Cursor Bugbot
Details
You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.
To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.
| if (!preserveTimeline) { | ||
| const hourKey = String(new Date(ev._creationTime).getUTCHours()).padStart(2, "0"); | ||
| stats.hourlyDistribution[hourKey] = (stats.hourlyDistribution[hourKey] || 0) + 1; | ||
| } |
There was a problem hiding this comment.
Empty hourly distribution when no stats exist to preserve
Medium Severity
When rebuildStats() is called with the default preserveTimeline: true but no analyticsStats record exists in the database, the hourlyDistribution will be empty even if events exist. This happens because existingHourlyDistribution falls back to {} when no stats exist (line 364), and the loop that populates hourly data from events only runs when preserveTimeline is false (lines 457-460). The result is rebuilt stats with an empty hourlyDistribution, causing the hourly activity chart to display no data despite events being present. The condition on line 457 should also check whether there was actually existing data to preserve.
Additional Locations (1)
|
Thanks for this I removed the seed file for now as it was hurting my brain 😅 Also removed the width in the y-axis, the number were overflowing because of it. |
| config={chartConfig} | ||
| className="aspect-auto w-full min-h-[200px]" | ||
| style={{ height }} | ||
| > |
There was a problem hiding this comment.
Missing YAxis width fix claimed in PR description
Medium Severity
The PR description states that width={16} was set on all YAxis components to fix excessive left padding in charts, but this change was never implemented. All YAxis components in the modified files still lack the width prop, meaning the "excessive left padding" issue described in the PR remains unfixed. This affects chart visibility on all viewports.
Add analytics seed data and fix chart display issues on mobile
Changes
1. Add seed file for analytics data (
packages/backend/convex/seed.ts)Added a seed file to generate mock analytics data for development and testing purposes. The seed file:
seedAnalyticsmutation for populating test data2. Fix chart overflow on mobile devices
Problem: Chart cards were overflowing vertically on smaller screens.
Cause: The
ChartContainercomponent hasaspect-video(16:9) in its base className, which conflicted with explicith-[280px]heights on constrained mobile widths.Solution: Added
aspect-autoto allChartContainerinstances to override the base aspect ratio.3. Fix excessive left padding in charts
Problem: Large empty space on the left side of charts.
Cause: Recharts'
YAxiscomponent defaults to 60px width.Solution: Set
width={16}on allYAxiscomponents.Files Changed
packages/backend/convex/seed.ts(new)apps/web/src/app/(home)/analytics/_components/timeline-charts.tsxapps/web/src/app/(home)/analytics/_components/stack-configuration-charts.tsxapps/web/src/app/(home)/analytics/_components/dev-environment-charts.tsxTesting
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.
Note
Addresses chart overflow on small screens by overriding the base aspect ratio on analytics charts.
aspect-autoto allChartContainerinstances intimeline-charts.tsx,stack-configuration-charts.tsx, anddev-environment-charts.tsxso charts respect explicit heights and don’t vertically overflow on mobileWritten by Cursor Bugbot for commit 0385e93. This will update automatically on new commits. Configure here.