diff --git a/app/Actions/CreateWrappedNotifications.php b/app/Actions/CreateWrappedNotifications.php new file mode 100644 index 0000000000..94c785193d --- /dev/null +++ b/app/Actions/CreateWrappedNotifications.php @@ -0,0 +1,62 @@ +whereNotIn('github_id', User::BOT_GITHUB_IDS) + ->whereHas( + 'commits', + fn (Builder $commits): Builder => $commits + ->where('status', CommitStatus::Approved) + ->whereYear('created_at', $year), + ) + ->pluck('users.id'); + + $now = now(); + + $notifications = []; + + foreach ($recipientIds as $recipientId) { + $notifications[] = [ + 'id' => Str::uuid7()->toString(), + 'recipient_id' => $recipientId, + 'actor_id' => $recipientId, + 'type' => NotificationType::WrappedReady->value, + 'commit_id' => null, + 'key' => 'wrapped:'.$year, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + foreach (array_chunk($notifications, 500) as $chunk) { + Notification::query()->insertOrIgnore($chunk); + } + + if ($recipientIds->isNotEmpty()) { + event(new UsersUpdated($recipientIds->all(), UserUpdate::Notifications)); + } + + return count($notifications); + } +} diff --git a/app/Console/Commands/NotifyWrappedCommand.php b/app/Console/Commands/NotifyWrappedCommand.php new file mode 100644 index 0000000000..ef065c6046 --- /dev/null +++ b/app/Console/Commands/NotifyWrappedCommand.php @@ -0,0 +1,32 @@ +option('year') ?? date('Y')); + + if ($year !== (int) date('Y')) { + $this->components->error('Wrapped notifications can only be queued for the current year.'); + + return self::FAILURE; + } + + $count = $createWrappedNotifications->handle($year); + + $this->components->info("Wrapped notifications queued for {$count} handles for {$year}."); + + return self::SUCCESS; + } +} diff --git a/app/Enums/NotificationType.php b/app/Enums/NotificationType.php index 4f091a3409..69eac0843a 100644 --- a/app/Enums/NotificationType.php +++ b/app/Enums/NotificationType.php @@ -16,4 +16,5 @@ enum NotificationType: string case LeveledUp = 'leveled_up'; case FirstCommit = 'first_commit'; case TimedOut = 'timed_out'; + case WrappedReady = 'wrapped_ready'; } diff --git a/app/Http/Controllers/YearInReviewController.php b/app/Http/Controllers/YearInReviewController.php new file mode 100644 index 0000000000..835fd6f4ec --- /dev/null +++ b/app/Http/Controllers/YearInReviewController.php @@ -0,0 +1,83 @@ +user; + $currentYear = (int) now()->year; + $requestedYear = $request->integer('year'); + $year = $requestedYear > 0 && $requestedYear <= $currentYear ? $requestedYear : $currentYear; + + abort_unless($user instanceof User, 404); + + $parameters = ['profile' => $profile->handle]; + + if ($year !== $currentYear) { + $parameters['year'] = $year; + } + + $shareUrl = route('wrapped.show', $parameters); + + // Wrapped drops with the notification, every December 3rd at 09:00. + $unlocksAt = now()->setDate($year, 12, 3)->setTime(9, 0); + + $hasPreviousYear = $user->commits() + ->whereBetween('commits.created_at', [ + now()->setDate($year - 1, 1, 1)->startOfDay(), + now()->setDate($year - 1, 12, 31)->endOfDay(), + ]) + ->exists(); + + if (now()->lt($unlocksAt)) { + return Inertia::render('wrapped/show', [ + 'handle' => $profile->handle, + 'name' => $user->name, + 'avatarUrl' => $user->avatar_url, + 'stats' => null, + 'shareUrl' => $shareUrl, + 'locked' => true, + 'unlocksAt' => $unlocksAt->toIso8601String(), + 'year' => $year, + 'currentYear' => $currentYear, + 'hasPreviousYear' => $hasPreviousYear, + ])->withViewData(['preview' => $metadata->page( + "{$profile->handle}'s {$year} Wrapped - /dev/null", + "The {$year} Wrapped for @{$profile->handle} unwraps December 3rd.", + $shareUrl, + )]); + } + + $stats = $review->get($user, $currentUser, $year); + + return Inertia::render('wrapped/show', [ + 'handle' => $profile->handle, + 'name' => $user->name, + 'avatarUrl' => $user->avatar_url, + 'stats' => $stats, + 'shareUrl' => $shareUrl, + 'locked' => false, + 'unlocksAt' => null, + 'year' => $year, + 'currentYear' => $currentYear, + 'hasPreviousYear' => $hasPreviousYear, + ])->withViewData(['preview' => $metadata->page( + "{$profile->handle}'s {$year} in review - /dev/null", + "What @{$profile->handle} shipped in {$year}: {$stats['commits']} commits, {$stats['starsEarned']} stars and a {$stats['longestStreak']}-day streak.", + $shareUrl, + )]); + } +} diff --git a/app/Queries/NotificationBuilder.php b/app/Queries/NotificationBuilder.php index 52404c1171..55368d99c1 100644 --- a/app/Queries/NotificationBuilder.php +++ b/app/Queries/NotificationBuilder.php @@ -48,7 +48,7 @@ public function relevant(): self ->whereColumn('organization_members.organization_id', 'notifications.organization_id') ->whereColumn('organization_members.user_id', 'notifications.recipient_id'))) ->offset(0))) - ->orWhereIn('type', [NotificationType::LeveledUp, NotificationType::TimedOut])) + ->orWhereIn('type', [NotificationType::LeveledUp, NotificationType::TimedOut, NotificationType::WrappedReady])) ->withoutSilencedActors(); } diff --git a/app/Queries/YearInReviewQuery.php b/app/Queries/YearInReviewQuery.php new file mode 100644 index 0000000000..4246ee1aca --- /dev/null +++ b/app/Queries/YearInReviewQuery.php @@ -0,0 +1,219 @@ +, weekdays: list, hourCounts: list, comeback: bool, languages: array, dayCounts: array, topCommit: array{id: string, body: string, stars: int}|null} + */ +final readonly class YearInReviewQuery +{ + /** + * Fence tags authors already wrote, so no API calls and no new tables. + */ + private const FENCE_EXCLUDED = ['ansi', 'diff', 'fix', 'log', 'output', 'plaintext', 'terminal', 'text', 'txt']; + + /** @var array */ + private const LANGUAGE_CANONICAL = [ + 'js' => 'javascript', + 'sh' => 'bash', + 'shell' => 'bash', + 'ts' => 'typescript', + 'yml' => 'yaml', + ]; + + /** @var array */ + private const LANGUAGE_DISPLAY = [ + 'bash' => 'Shell', + 'blade' => 'Blade', + 'c#' => 'C#', + 'c++' => 'C++', + 'css' => 'CSS', + 'go' => 'Go', + 'html' => 'HTML', + 'java' => 'Java', + 'javascript' => 'JavaScript', + 'js' => 'JavaScript', + 'json' => 'JSON', + 'jsx' => 'JSX', + 'kotlin' => 'Kotlin', + 'php' => 'PHP', + 'python' => 'Python', + 'ruby' => 'Ruby', + 'rust' => 'Rust', + 'sh' => 'Shell', + 'shell' => 'Shell', + 'sql' => 'SQL', + 'swift' => 'Swift', + 'ts' => 'TypeScript', + 'tsx' => 'TSX', + 'typescript' => 'TypeScript', + 'vue' => 'Vue', + 'xml' => 'XML', + 'yaml' => 'YAML', + 'yml' => 'YAML', + ]; + + /** + * @return YearInReview + */ + public function get(User $user, ?User $viewer, int $year): array + { + $start = CarbonImmutable::create($year, 1, 1)->startOfDay(); + $end = $start->endOfYear(); + + $commits = $user->commits()->visibleTo($viewer)->whereBetween('commits.created_at', [$start, $end]); + + $starsEarned = (int) DB::table('stars') + ->join('commits', 'commits.id', '=', 'stars.commit_id') + ->where('commits.author_id', $user->id) + ->whereBetween('stars.created_at', [$start, $end]) + ->count(); + + $top = (clone $commits)->withCount('stars')->orderByDesc('stars_count')->orderBy('commits.created_at')->first(); + + /** @var array $dayCounts */ + $dayCounts = (clone $commits)->whereNull('commits.parent_id') + ->selectRaw('date(commits.created_at) as day, count(*) as total') + ->groupBy('day') + ->orderBy('day') + ->pluck('total', 'day') + ->map(fn ($total) => (int) $total) + ->all(); + + $days = array_keys($dayCounts); + + $months = array_fill(0, 12, 0); + + foreach ((clone $commits)->whereNull('commits.parent_id')->selectRaw('extract(month from commits.created_at) as month, count(*) as total')->groupBy('month')->pluck('total', 'month') as $month => $total) { + $months[(int) $month - 1] = (int) $total; + } + + $weekdays = array_fill(0, 7, 0); + + foreach ((clone $commits)->whereNull('commits.parent_id')->selectRaw('extract(dow from commits.created_at) as dow, count(*) as total')->groupBy('dow')->pluck('total', 'dow') as $dow => $total) { + $weekdays[(int) $dow] = (int) $total; + } + + $hourCounts = array_fill(0, 24, 0); + + foreach ((clone $commits)->whereNull('commits.parent_id')->selectRaw('extract(hour from commits.created_at) as hour, count(*) as total')->groupBy('hour')->pluck('total', 'hour') as $hour => $total) { + $hourCounts[(int) $hour] = (int) $total; + } + + return [ + 'year' => $year, + 'commits' => (clone $commits)->whereNull('commits.parent_id')->count(), + 'replies' => (clone $commits)->whereNotNull('commits.parent_id')->count(), + 'starsEarned' => $starsEarned, + 'followersGained' => $user->followers()->wherePivot('follows.created_at', '>=', $start)->wherePivot('follows.created_at', '<=', $end)->count(), + 'activeDays' => count($days), + 'longestStreak' => $this->longestRun($days), + 'months' => $months, + 'weekdays' => $weekdays, + 'hourCounts' => $hourCounts, + 'comeback' => $this->hasComeback($days), + 'languages' => $this->topLanguages((clone $commits)->whereNull('commits.parent_id')->pluck('commits.body')), + 'dayCounts' => $dayCounts, + 'topCommit' => $top === null ? null : [ + 'id' => $top->id, + 'body' => mb_strimwidth($top->body, 0, 140, '…'), + 'stars' => (int) $top->stars_count, + ], + ]; + } + + /** + * A 7-plus day streak that starts after a 30-plus day silence. + * + * @param list $days Ordered Y-m-d dates with at least one commit. + */ + private function hasComeback(array $days): bool + { + $run = 0; + $gap = 0; + $previous = null; + + foreach ($days as $day) { + $current = CarbonImmutable::parse($day); + + if ($previous !== null && $current->toDateString() === $previous->addDay()->toDateString()) { + $run++; + } else { + $gap = $previous === null ? 0 : (int) $previous->diffInDays($current); + $run = 1; + } + + if ($run >= 7 && $gap >= 30) { + return true; + } + + $previous = $current; + } + + return false; + } + + /** + * Top 3 fence-tagged languages across the year's posts. Each post counts + * once per language, no matter how many blocks it holds. + * + * @return array + */ + private function topLanguages(iterable $bodies): array + { + $counts = []; + + foreach ($bodies as $body) { + preg_match_all('/```([a-zA-Z0-9_+#-]+)/', (string) $body, $matches); + + $tags = array_map(strtolower(...), $matches[1]); + $tags = array_map(fn ($tag) => self::LANGUAGE_CANONICAL[$tag] ?? $tag, $tags); + + foreach (array_unique($tags) as $tag) { + if (in_array($tag, self::FENCE_EXCLUDED, true)) { + continue; + } + + $counts[$tag] = ($counts[$tag] ?? 0) + 1; + } + } + + arsort($counts); + + $top = []; + + foreach (array_slice($counts, 0, 3, true) as $tag => $commits) { + $tag = (string) $tag; + $top[] = ['language' => self::LANGUAGE_DISPLAY[$tag] ?? ucfirst($tag), 'commits' => $commits]; + } + + return $top; + } + + /** + * @param list $days Ordered Y-m-d dates with at least one commit. + */ + private function longestRun(array $days): int + { + $longest = 0; + $run = 0; + $previous = null; + + foreach ($days as $day) { + $current = CarbonImmutable::parse($day); + $run = $previous !== null && $current->toDateString() === $previous->addDay()->toDateString() ? $run + 1 : 1; + $longest = max($longest, $run); + $previous = $current; + } + + return $longest; + } +} diff --git a/resources/js/lib/confetti.ts b/resources/js/lib/confetti.ts index 55fd049b94..dfa669bcd6 100644 --- a/resources/js/lib/confetti.ts +++ b/resources/js/lib/confetti.ts @@ -135,3 +135,125 @@ export function dropConfetti(): void { frame = window.requestAnimationFrame(tick); } } + +type Spark = { + x: number; + y: number; + vx: number; + vy: number; + color: string; + life: number; + maxLife: number; +}; + +export function dropFireworks(): void { + if (typeof document === 'undefined') return; + if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; + + const show = document.createElement('canvas'); + show.setAttribute('aria-hidden', 'true'); + show.style.position = 'fixed'; + show.style.inset = '0'; + show.style.width = '100%'; + show.style.height = '100%'; + show.style.pointerEvents = 'none'; + show.style.zIndex = '60'; + document.body.appendChild(show); + + const ctx = show.getContext('2d'); + if (!ctx) { + show.remove(); + return; + } + + const ratio = Math.min(window.devicePixelRatio || 1, 2); + show.width = Math.floor(window.innerWidth * ratio); + show.height = Math.floor(window.innerHeight * ratio); + ctx.setTransform(ratio, 0, 0, ratio, 0, 0); + + const width = window.innerWidth; + const height = window.innerHeight; + const rockets: Spark[] = []; + const sparks: Spark[] = []; + let frames = 0; + + const launch = (): void => { + rockets.push({ + x: width * (0.08 + Math.random() * 0.84), + y: height + 8, + vx: (Math.random() - 0.5) * 1.5, + vy: -(height / 90 + Math.random() * 2), + color: '#ffd166', + life: 0, + maxLife: 1000, + }); + }; + + launch(); + window.setTimeout(launch, 300); + window.setTimeout(launch, 600); + window.setTimeout(launch, 900); + + const explode = (rocket: Spark): void => { + const count = 46 + Math.floor(Math.random() * 20); + for (let index = 0; index < count; index++) { + const angle = (index / count) * Math.PI * 2 + Math.random() * 0.3; + const speed = 1.4 + Math.random() * 3.6; + sparks.push({ + x: rocket.x, + y: rocket.y, + vx: Math.cos(angle) * speed, + vy: Math.sin(angle) * speed, + color: colors[Math.floor(Math.random() * colors.length)], + life: 0, + maxLife: 55 + Math.floor(Math.random() * 30), + }); + } + }; + + const step = (): void => { + frames += 1; + ctx.clearRect(0, 0, width, height); + + for (let index = rockets.length - 1; index >= 0; index--) { + const rocket = rockets[index]; + rocket.vy += 0.12; + rocket.x += rocket.vx; + rocket.y += rocket.vy; + ctx.fillStyle = rocket.color; + ctx.beginPath(); + ctx.arc(rocket.x, rocket.y, 2, 0, Math.PI * 2); + ctx.fill(); + if (rocket.vy >= -2.2) { + explode(rocket); + rockets.splice(index, 1); + } + } + + for (let index = sparks.length - 1; index >= 0; index--) { + const spark = sparks[index]; + spark.life += 1; + spark.vx *= 0.985; + spark.vy = spark.vy * 0.985 + 0.05; + spark.x += spark.vx; + spark.y += spark.vy; + ctx.globalAlpha = Math.max(0, 1 - spark.life / spark.maxLife); + ctx.fillStyle = spark.color; + ctx.beginPath(); + ctx.arc(spark.x, spark.y, 1.6, 0, Math.PI * 2); + ctx.fill(); + ctx.globalAlpha = 1; + if (spark.life >= spark.maxLife) { + sparks.splice(index, 1); + } + } + + if (rockets.length > 0 || sparks.length > 0 || frames < 280) { + window.requestAnimationFrame(step); + } else { + show.remove(); + } + }; + + window.requestAnimationFrame(step); +} diff --git a/resources/js/pages/notification/index.tsx b/resources/js/pages/notification/index.tsx index 1428874df4..8278bcd0fc 100644 --- a/resources/js/pages/notification/index.tsx +++ b/resources/js/pages/notification/index.tsx @@ -17,6 +17,7 @@ import { GitCommitVertical, Hourglass, MessageSquareReply, + PartyPopper, Quote, Star, UserPlus, @@ -1184,6 +1185,10 @@ export function NotificationContent({ notification.type === 'mentioned' || notification.type === 'first_commit'; const level = notification.type === 'leveled_up' ? notification : null; + const wrappedYear = + notification.type === 'wrapped_ready' + ? new Date(notification.created_at).getFullYear() + : null; const Icon = { followed: UserPlus, leveled_up: ChevronsUp, @@ -1195,6 +1200,7 @@ export function NotificationContent({ approved: Check, rejected: X, timed_out: Hourglass, + wrapped_ready: PartyPopper, }[notification.type]; const icon = ( {notification.rank_description} @@ -1640,6 +1650,14 @@ export function NotificationContent({ ) )} + ) : notification.type === + 'wrapped_ready' ? ( + + {`@${user.handle}`} + ) : ( <> ; + dayCounts: Record; + topCommit: { id: string; body: string; stars: number } | null; +}; + +type WrappedProps = { + handle: string; + name: string; + avatarUrl: string | null; + stats: WrappedStats | null; + shareUrl: string; + locked: boolean; + unlocksAt: string | null; + year: number; + currentYear: number; + hasPreviousYear: boolean; +}; + +function Countdown({ to }: { to: string }) { + const target = useMemo(() => new Date(to).getTime(), [to]); + const [now, setNow] = useState(() => Date.now()); + const reloaded = useRef(false); + const reloadTimeout = useRef(null); + + useEffect(() => { + const id = window.setInterval(() => { + const left = target - Date.now(); + setNow(Date.now()); + + if (left <= 0 && !reloaded.current) { + reloaded.current = true; + reloadTimeout.current = window.setTimeout( + () => window.location.reload(), + 1500, + ); + } + }, 1000); + + return () => { + window.clearInterval(id); + + if (reloadTimeout.current !== null) { + window.clearTimeout(reloadTimeout.current); + } + }; + }, [target]); + + const remaining = Math.max(0, target - now); + const units: Array<{ value: number; label: string }> = [ + { value: Math.floor(remaining / 86_400_000), label: 'days' }, + { + value: Math.floor(remaining / 3_600_000) % 24, + label: 'hours', + }, + { value: Math.floor(remaining / 60_000) % 60, label: 'mins' }, + { value: Math.floor(remaining / 1000) % 60, label: 'secs' }, + ]; + + return ( +
+ {units.map((unit) => ( +
+

+ {String(unit.value).padStart(2, '0')} +

+

+ {unit.label} +

+
+ ))} +
+ ); +} + +function BigNumber({ value, label }: { value: number; label: string }) { + return ( +
+

+ {value.toLocaleString()} +

+

{label}

+
+ ); +} + +function MonthBars({ months }: { months: number[] }) { + const peak = Math.max(1, ...months); + const level = (total: number): number => + total === 0 ? 0 : 1 + Math.min(3, Math.floor((total / peak) * 4)); + + return ( +
+ {months.map((total, index) => ( +
+ ))} +
+ ); +} + +function Eyebrow({ children }: { children: ReactNode }) { + return ( +

+ {children} +

+ ); +} + +const MONTHS = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +function archetype(stats: WrappedStats): { name: string; quip: string } { + if (stats.commits === 0) { + return { + name: 'The Ghost', + quip: 'You were here. Git remembers.', + }; + } + + const total = stats.commits > 0 ? stats.commits : 1; + const night = + (stats.hourCounts[22] ?? 0) + + (stats.hourCounts[23] ?? 0) + + stats.hourCounts.slice(0, 6).reduce((sum, count) => sum + count, 0); + + if (night / total >= 0.4) { + return { + name: 'Night Owl', + quip: 'Your best ideas apparently do not believe in business hours.', + }; + } + + const weekend = (stats.weekdays[0] ?? 0) + (stats.weekdays[6] ?? 0); + + if (weekend / total >= 0.45) { + return { + name: 'Weekend Warrior', + quip: 'While everyone else logged off, you logged commits.', + }; + } + + if (stats.comeback) { + return { + name: 'The Comeback Kid', + quip: 'Quiet periods are just intermissions.', + }; + } + + if (stats.starsEarned >= 100 || stats.followersGained >= 25) { + return { + name: 'Main Character Energy', + quip: 'Somehow, your repositories are the plot.', + }; + } + + if (stats.replies > stats.commits && stats.replies >= 5) { + return { + name: 'Merge Overlord', + quip: 'Nothing gets merged without your blessing.', + }; + } + + if (stats.activeDays >= 200) { + return { + name: 'The Green Square Addict', + quip: 'Those contribution squares are not going to fill themselves.', + }; + } + + if (stats.longestStreak >= 14) { + return { + name: 'One More Commit', + quip: 'You said that three hours ago.', + }; + } + + if (stats.activeDays >= 100) { + return { + name: 'The Infinite Loop', + quip: 'Start coding. Forget time. Repeat.', + }; + } + + if (stats.commits >= 100) { + return { + name: '404: Free Time Not Found', + quip: 'Your calendar has been replaced by commits.', + }; + } + + if (stats.replies <= 2) { + return { + name: 'The Silent Shipper', + quip: 'No noise. Just output.', + }; + } + + return { + name: 'Steady Builder', + quip: 'Brick by brick. That is how codebases get built.', + }; +} + +function buildInsights(stats: WrappedStats): string[] { + const total = stats.commits > 0 ? stats.commits : 1; + + if (stats.commits === 0) { + return ['No commits this year. The graph is a blank canvas.']; + } + + const best = stats.months.indexOf(Math.max(...stats.months)); + const weekend = (stats.weekdays[0] ?? 0) + (stats.weekdays[6] ?? 0); + const night = + (stats.hourCounts[22] ?? 0) + + (stats.hourCounts[23] ?? 0) + + stats.hourCounts.slice(0, 6).reduce((sum, count) => sum + count, 0); + + const insights = [ + `Most productive month: ${MONTHS[best]} with ${stats.months[best]} commits.`, + weekend / total >= 0.4 + ? 'Weekend warrior: nearly half your commits land on Sat/Sun.' + : 'Weekday grinder: evenings and weekends stay yours.', + ]; + + if (night / total >= 0.25) { + insights.push( + `Night shift: ${Math.round((night / total) * 100)} percent of commits landed between 10pm and 6am.`, + ); + } + + if (stats.comeback) { + insights.push( + 'Comeback season: a 7-plus day streak after a month away.', + ); + } + + const [stackTop] = stats.languages; + + if (stackTop) { + insights.push( + `${stackTop.language} tops your stack with ${stackTop.commits} code posts.`, + ); + } + + insights.push( + stats.replies > stats.commits + ? 'You reply more than you post. Threads love you.' + : 'You post more than you reply. A builder first.', + ); + + return insights; +} + +function YearHeatmap({ + year, + dayCounts, +}: { + year: number; + dayCounts: Record; +}) { + const peak = Math.max(1, ...Object.values(dayCounts)); + + return ( +
+
+ {MONTHS.map((label, month) => { + const total = new Date(year, month + 1, 0).getDate(); + return ( +
+ + {label} + +
+ {Array.from({ length: total }, (_, day) => { + const key = `${year}-${String(month + 1).padStart(2, '0')}-${String(day + 1).padStart(2, '0')}`; + const count = dayCounts[key] ?? 0; + return ( + + ); + })} +
+
+ ); + })} +
+
+ ); +} + +export default function Show({ + handle, + name, + avatarUrl, + stats, + shareUrl, + locked, + unlocksAt, + year, + currentYear, + hasPreviousYear, +}: WrappedProps) { + const [slide, setSlide] = useState(0); + const [copiedLink, copyLink] = useClipboard(); + const [copiedSummary, copySummary] = useClipboard(); + const celebrated = useRef(false); + const touchStart = useRef<{ x: number; y: number } | null>(null); + + if (locked) { + const year = unlocksAt + ? new Date(unlocksAt).getFullYear() + : new Date().getFullYear(); + + return ( + <> + +
+
+ Wrapped · {year} +
+ +
+

+ Your {year} Wrapped is still being prepared. +

+

+ It unwraps on December 3rd, and we’ll notify you + when it’s ready. +

+ {unlocksAt && } +
+
+ + ); + } + + if (!stats) { + return null; + } + + const last = 7; + const hasCommits = stats.commits > 0; + const bestMonth = stats.months.indexOf(Math.max(...stats.months)); + const craft = archetype(stats); + const insightList = buildInsights(stats); + const summary = `My ${stats.year} on /dev/null - @${handle}: ${stats.commits} commits, ${stats.starsEarned} stars, best streak ${stats.longestStreak} days. ${shareUrl}`; + const go = useCallback( + (next: number) => setSlide(Math.min(last, Math.max(0, next))), + [last], + ); + + useEffect(() => { + if (slide === last && !celebrated.current) { + celebrated.current = true; + dropFireworks(); + } + }, [slide, last]); + + useEffect(() => { + const onKey = (event: KeyboardEvent): void => { + if (event.key === 'ArrowRight') { + go(slide + 1); + } else if (event.key === 'ArrowLeft') { + go(slide - 1); + } + }; + + window.addEventListener('keydown', onKey); + + return () => window.removeEventListener('keydown', onKey); + }, [slide, go]); + + useEffect(() => { + setSlide(0); + }, [year]); + + return ( + <> + +
+
+
+
+ +
{ + const touch = event.touches[0]; + touchStart.current = + event.touches.length === 1 && touch + ? { x: touch.clientX, y: touch.clientY } + : null; + }} + onTouchEnd={(event) => { + const touch = event.changedTouches[0]; + const from = touchStart.current; + touchStart.current = null; + + if (!touch || !from) { + return; + } + + const dx = touch.clientX - from.x; + const dy = touch.clientY - from.y; + + if (Math.abs(dx) < 48 || Math.abs(dx) < Math.abs(dy)) { + return; + } + + go(slide + (dx < 0 ? 1 : -1)); + }} + > + {slide === 0 && ( +
+ + {stats.commits.toLocaleString()} contributions + in {stats.year} + + + + + {handle.slice(0, 2).toUpperCase()} + + +

+ @{handle} +

+ { + + } +

+ {stats.year} in review +

+

+ {stats.commits === 0 + ? 'A quiet year. Next one ships more.' + : `${stats.commits.toLocaleString()} commits shipped. Here is how they landed.`} +

+
+ )} + {slide === 1 && ( +
+ 01 · Output +
+ +
+ {stats.replies > 0 && ( +

+ plus {stats.replies.toLocaleString()}{' '} + replies in threads +

+ )} + + {hasCommits && ( + <> +

+ Best month: {MONTHS[bestMonth]} with{' '} + {stats.months[bestMonth]} commits +

+
+ {stats.months.map((total, index) => ( +
+

+ {MONTHS[index]} +

+

+ {total} +

+
+ ))} +
+ + )} +
+ )} + {slide === 2 && ( +
+ 02 · Impact +
+ +
+ {stats.starsEarned === 0 && ( +

+ No stars yet. The work still counted. +

+ )} + {stats.topCommit !== null && ( + +
+ {stats.topCommit.body} +
+

+ Your top commit ·{' '} + {stats.topCommit.stars.toLocaleString()}{' '} + stars +

+
+ )} +
+ )} + {slide === 3 && ( +
+ 03 · Consistency +
+ +
+

+ active on {stats.activeDays.toLocaleString()}{' '} + days this year +

+ +
+ )} + {slide === 4 && ( +
+ 04 · Community +
+ +
+

+ {stats.followersGained === 0 + ? 'Quiet on the follower front. The work comes first.' + : 'people who want to read what you ship next'} +

+
+ )} + {slide === 5 && ( +
+ 05 · Your stack +

+ Your tech stack +

+ {stats.languages.length > 0 ? ( + <> +

+ Top 3 languages from your tagged code + blocks. +

+
+ {stats.languages.map((entry, index) => ( +
+
+

+ {index + 1}.{' '} + {entry.language} +

+

+ {entry.commits.toLocaleString()}{' '} + code posts +

+
+
+
+
+
+ ))} +
+ + ) : ( +

+ No tagged code blocks this year. Tag a fence + and it lands here. +

+ )} +
+ )} + {slide === 6 && ( +
+ 06 · Archetype +

+ {craft.name} +

+

+ {craft.quip} +

+
    + {insightList.map((insight) => ( +
  • + {insight} +
  • + ))} +
+
+ )} + {slide === 7 && ( +
+ 07 · Happy New Year +
+ +
+

+ {year < currentYear + ? `That was ${year}, nuller` + : 'See you next year, nuller'} +

+

+ Thank you, nullers, for every commit, reply, and + star this year. From the team, happy New Year. +

+

+ {shareUrl} +

+

+ {summary} +

+
+ + + {year < currentYear && ( + + )} +
+
+ )} +
+ +
+
+ {slide > 0 && ( + + )} +
+ +
+ {slide < last ? ( + + ) : ( + + )} +
+
+

+ + ← + {' '} + + → + {' '} + to move through your year +

+
+ + ); +} + +Show.layout = AppLayout; diff --git a/resources/js/types/notification.ts b/resources/js/types/notification.ts index 8a7a253337..ea442da277 100644 --- a/resources/js/types/notification.ts +++ b/resources/js/types/notification.ts @@ -79,4 +79,10 @@ export type Notification = commit_id: string; subject_id: null; commit: Omit; + }) + | (BaseNotification & { + type: 'wrapped_ready'; + commit_id: null; + subject_id: null; + commit: null; }); diff --git a/routes/console.php b/routes/console.php index 28f126fa5d..8e71bcd391 100644 --- a/routes/console.php +++ b/routes/console.php @@ -14,6 +14,7 @@ Schedule::job(new EndLiveStreams())->everyFiveMinutes(); Schedule::job(new GenerateHotHeadlineSummaries())->everyFifteenMinutes(); Schedule::command('model:prune', ['--model' => [Headline::class]])->hourly()->withoutOverlapping(); +Schedule::command('wrapped:notify')->yearlyOn(12, 3, '9:00')->withoutOverlapping(); Schedule::call(function (): void { DB::table('pending_file_deletions')->orderBy('id')->chunkById(100, function (Collection $pending): void { diff --git a/routes/web.php b/routes/web.php index 15be6e4484..c1edb093c7 100644 --- a/routes/web.php +++ b/routes/web.php @@ -162,6 +162,7 @@ use App\Http\Controllers\UserTimeoutController; use App\Http\Controllers\UserTimezoneController; use App\Http\Controllers\UserTranslationLanguageController; +use App\Http\Controllers\YearInReviewController; use App\Http\Middleware\PreventPostingInTimeout; use App\Http\Middleware\RedirectToHandleCase; use App\Http\Middleware\RememberIntendedUrl; @@ -312,6 +313,8 @@ ->name('user-preview.show'); Route::get('@{profile:handle}/og.png', [ProfileOpenGraphImageController::class, 'show']) ->name('user-open-graph-image.show'); +Route::get('@{profile:handle}/wrapped', [YearInReviewController::class, 'show']) + ->name('wrapped.show'); Route::get('@{user:handle}/feed.atom', [UserFeedController::class, 'show']) ->middleware('cache.headers:public;max_age=300;etag') ->name('user-feed.show'); diff --git a/tests/Feature/Commands/NotifyWrappedTest.php b/tests/Feature/Commands/NotifyWrappedTest.php new file mode 100644 index 0000000000..263efa2c62 --- /dev/null +++ b/tests/Feature/Commands/NotifyWrappedTest.php @@ -0,0 +1,40 @@ +create(); + Commit::factory()->create(['author_id' => $withCommit->id, 'created_at' => now()]); + $withoutCommit = User::factory()->create(); + + $this->artisan('wrapped:notify', ['--year' => (string) $year])->assertSuccessful(); + + $this->assertDatabaseHas('notifications', [ + 'recipient_id' => $withCommit->id, + 'actor_id' => $withCommit->id, + 'type' => 'wrapped_ready', + 'key' => 'wrapped:'.$year, + ]); + $this->assertDatabaseMissing('notifications', [ + 'recipient_id' => $withoutCommit->id, + 'type' => 'wrapped_ready', + ]); + + $this->artisan('wrapped:notify', ['--year' => (string) $year])->assertSuccessful(); + + $this->assertDatabaseCount('notifications', 1); +}); + +it('rejects years other than the current year', function (): void { + $user = User::factory()->create(); + Commit::factory()->create(['author_id' => $user->id, 'created_at' => now()->subYear()]); + + $this->artisan('wrapped:notify', ['--year' => (string) ((int) date('Y') - 1)])->assertFailed(); + + $this->assertDatabaseCount('notifications', 0); +}); diff --git a/tests/Feature/Controllers/YearInReviewControllerTest.php b/tests/Feature/Controllers/YearInReviewControllerTest.php new file mode 100644 index 0000000000..4aaa275045 --- /dev/null +++ b/tests/Feature/Controllers/YearInReviewControllerTest.php @@ -0,0 +1,176 @@ +create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + $top = Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 3, 10)]); + $top->stars()->attach(User::factory()->count(2)->create(), ['created_at' => now()->setDate($year, 4, 1)]); + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 5, 20)]); + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year - 1, 6, 15)]); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('wrapped/show') + ->where('handle', $user->profile->handle) + ->where('stats.year', $year) + ->where('stats.commits', 2) + ->where('shareUrl', route('wrapped.show', ['profile' => $user->profile->handle])) + ->where('stats.starsEarned', 2) + ->where('stats.topCommit.stars', 2) + ->where('stats.months.2', 1) + ->where('stats.months.4', 1) + ->where('stats.languages', []) + ->where('stats.comeback', false) + ->where('stats.year', $year) + ->where('year', $year) + ->where('currentYear', $year) + ->where('hasPreviousYear', true) + ->has('stats.hourCounts', 24)); +}); + +it('describes the review to search engines and link previews', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertSee("{$user->profile->handle}'s {$year} in review - /dev/null", false); +}); + +it('locks wrapped behind a countdown until December 3rd at 09:00', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 2, 23, 59)); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('wrapped/show') + ->where('handle', $user->profile->handle) + ->where('locked', true) + ->where('stats', null) + ->where('unlocksAt', Carbon::create($year, 12, 3, 9)->toIso8601String())); +}); + +it('opens wrapped once the unlock moment passes', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 3, 9)); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('wrapped/show') + ->where('locked', false) + ->where('unlocksAt', null) + ->where('stats.year', $year)); +}); + +it('counts consecutive calendar days as a streak', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 1, 5)]); + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 1, 6)]); + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 1, 7)]); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->where('stats.longestStreak', 3) + ->where('stats.comeback', false)); +}); + +it('flags a 7-day run after a month of silence as a comeback', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 1, 1)]); + + foreach (range(1, 7) as $day) { + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year, 3, $day)]); + } + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->where('stats.longestStreak', 7) + ->where('stats.comeback', true)); +}); + +it('merges language aliases into one entry per post', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + Commit::factory()->for($user)->create(['body' => "Note\n```js\nconst a = 1;\n```", 'created_at' => now()->setDate($year, 2, 1)]); + Commit::factory()->for($user)->create(['body' => "Note\n```javascript\nconst b = 2;\n```\n```php\necho 1;\n```", 'created_at' => now()->setDate($year, 2, 2)]); + Commit::factory()->for($user)->create(['body' => "Note\n```js\nconst c = 3;\n```\n```javascript\nconst d = 4;\n```", 'created_at' => now()->setDate($year, 2, 3)]); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->where('stats.languages', [ + ['language' => 'JavaScript', 'commits' => 3], + ['language' => 'PHP', 'commits' => 1], + ])); +}); + +it('renders numeric fence tags without failing', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + Commit::factory()->for($user)->create(['body' => "Note\n```123\n456\n```", 'created_at' => now()->setDate($year, 2, 1)]); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->where('stats.languages', [ + ['language' => '123', 'commits' => 1], + ])); +}); + +it('opens a past year from a notification link', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + Commit::factory()->for($user)->create(['created_at' => now()->setDate($year - 1, 6, 15)]); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle, 'year' => $year - 1])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->component('wrapped/show') + ->where('locked', false) + ->where('stats.year', $year - 1) + ->where('stats.commits', 1) + ->where('year', $year - 1) + ->where('currentYear', $year) + ->where('hasPreviousYear', false) + ->where('shareUrl', route('wrapped.show', ['profile' => $user->profile->handle, 'year' => $year - 1]))); +}); + +it('falls back to the current year for a future year', function (): void { + $user = User::factory()->create(); + $year = (int) now()->year; + $this->travelTo(Carbon::create($year, 12, 4, 9, 1)); + + $this->get(route('wrapped.show', ['profile' => $user->profile->handle, 'year' => $year + 5])) + ->assertOk() + ->assertInertia(fn ($page) => $page + ->where('locked', false) + ->where('stats.year', $year)); +}); diff --git a/tests/Unit/Enums/NotificationTypeTest.php b/tests/Unit/Enums/NotificationTypeTest.php index 5f87c51bba..491525adf0 100644 --- a/tests/Unit/Enums/NotificationTypeTest.php +++ b/tests/Unit/Enums/NotificationTypeTest.php @@ -16,5 +16,6 @@ 'LeveledUp' => 'leveled_up', 'FirstCommit' => 'first_commit', 'TimedOut' => 'timed_out', + 'WrappedReady' => 'wrapped_ready', ]); });