diff --git a/.agents/skills/frontend-design/LICENSE.txt b/.agents/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/.agents/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..5be498e --- /dev/null +++ b/.agents/skills/frontend-design/SKILL.md @@ -0,0 +1,42 @@ +--- +name: frontend-design +description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics. +license: Complete terms in LICENSE.txt +--- + +This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices. + +The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints. + +## Design Thinking + +Before coding, understand the context and commit to a BOLD aesthetic direction: +- **Purpose**: What problem does this interface solve? Who uses it? +- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction. +- **Constraints**: Technical requirements (framework, performance, accessibility). +- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember? + +**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. + +Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is: +- Production-grade and functional +- Visually striking and memorable +- Cohesive with a clear aesthetic point-of-view +- Meticulously refined in every detail + +## Frontend Aesthetics Guidelines + +Focus on: +- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font. +- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. +- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise. +- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density. +- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays. + +NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character. + +Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations. + +**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well. + +Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision. diff --git a/.agents/skills/next-best-practices/SKILL.md b/.agents/skills/next-best-practices/SKILL.md new file mode 100644 index 0000000..437896b --- /dev/null +++ b/.agents/skills/next-best-practices/SKILL.md @@ -0,0 +1,153 @@ +--- +name: next-best-practices +description: Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling +user-invocable: false +--- + +# Next.js Best Practices + +Apply these rules when writing or reviewing Next.js code. + +## File Conventions + +See [file-conventions.md](./file-conventions.md) for: +- Project structure and special files +- Route segments (dynamic, catch-all, groups) +- Parallel and intercepting routes +- Middleware rename in v16 (middleware → proxy) + +## RSC Boundaries + +Detect invalid React Server Component patterns. + +See [rsc-boundaries.md](./rsc-boundaries.md) for: +- Async client component detection (invalid) +- Non-serializable props detection +- Server Action exceptions + +## Async Patterns + +Next.js 15+ async API changes. + +See [async-patterns.md](./async-patterns.md) for: +- Async `params` and `searchParams` +- Async `cookies()` and `headers()` +- Migration codemod + +## Runtime Selection + +See [runtime-selection.md](./runtime-selection.md) for: +- Default to Node.js runtime +- When Edge runtime is appropriate + +## Directives + +See [directives.md](./directives.md) for: +- `'use client'`, `'use server'` (React) +- `'use cache'` (Next.js) + +## Functions + +See [functions.md](./functions.md) for: +- Navigation hooks: `useRouter`, `usePathname`, `useSearchParams`, `useParams` +- Server functions: `cookies`, `headers`, `draftMode`, `after` +- Generate functions: `generateStaticParams`, `generateMetadata` + +## Error Handling + +See [error-handling.md](./error-handling.md) for: +- `error.tsx`, `global-error.tsx`, `not-found.tsx` +- `redirect`, `permanentRedirect`, `notFound` +- `forbidden`, `unauthorized` (auth errors) +- `unstable_rethrow` for catch blocks + +## Data Patterns + +See [data-patterns.md](./data-patterns.md) for: +- Server Components vs Server Actions vs Route Handlers +- Avoiding data waterfalls (`Promise.all`, Suspense, preload) +- Client component data fetching + +## Route Handlers + +See [route-handlers.md](./route-handlers.md) for: +- `route.ts` basics +- GET handler conflicts with `page.tsx` +- Environment behavior (no React DOM) +- When to use vs Server Actions + +## Metadata & OG Images + +See [metadata.md](./metadata.md) for: +- Static and dynamic metadata +- `generateMetadata` function +- OG image generation with `next/og` +- File-based metadata conventions + +## Image Optimization + +See [image.md](./image.md) for: +- Always use `next/image` over `` +- Remote images configuration +- Responsive `sizes` attribute +- Blur placeholders +- Priority loading for LCP + +## Font Optimization + +See [font.md](./font.md) for: +- `next/font` setup +- Google Fonts, local fonts +- Tailwind CSS integration +- Preloading subsets + +## Bundling + +See [bundling.md](./bundling.md) for: +- Server-incompatible packages +- CSS imports (not link tags) +- Polyfills (already included) +- ESM/CommonJS issues +- Bundle analysis + +## Scripts + +See [scripts.md](./scripts.md) for: +- `next/script` vs native script tags +- Inline scripts need `id` +- Loading strategies +- Google Analytics with `@next/third-parties` + +## Hydration Errors + +See [hydration-error.md](./hydration-error.md) for: +- Common causes (browser APIs, dates, invalid HTML) +- Debugging with error overlay +- Fixes for each cause + +## Suspense Boundaries + +See [suspense-boundaries.md](./suspense-boundaries.md) for: +- CSR bailout with `useSearchParams` and `usePathname` +- Which hooks require Suspense boundaries + +## Parallel & Intercepting Routes + +See [parallel-routes.md](./parallel-routes.md) for: +- Modal patterns with `@slot` and `(.)` interceptors +- `default.tsx` for fallbacks +- Closing modals correctly with `router.back()` + +## Self-Hosting + +See [self-hosting.md](./self-hosting.md) for: +- `output: 'standalone'` for Docker +- Cache handlers for multi-instance ISR +- What works vs needs extra setup + +## Debug Tricks + +See [debug-tricks.md](./debug-tricks.md) for: +- MCP endpoint for AI-assisted debugging +- Rebuild specific routes with `--debug-build-paths` + diff --git a/.agents/skills/next-best-practices/async-patterns.md b/.agents/skills/next-best-practices/async-patterns.md new file mode 100644 index 0000000..dce8d8c --- /dev/null +++ b/.agents/skills/next-best-practices/async-patterns.md @@ -0,0 +1,87 @@ +# Async Patterns + +In Next.js 15+, `params`, `searchParams`, `cookies()`, and `headers()` are asynchronous. + +## Async Params and SearchParams + +Always type them as `Promise<...>` and await them. + +### Pages and Layouts + +```tsx +type Props = { params: Promise<{ slug: string }> } + +export default async function Page({ params }: Props) { + const { slug } = await params +} +``` + +### Route Handlers + +```tsx +export async function GET( + request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params +} +``` + +### SearchParams + +```tsx +type Props = { + params: Promise<{ slug: string }> + searchParams: Promise<{ query?: string }> +} + +export default async function Page({ params, searchParams }: Props) { + const { slug } = await params + const { query } = await searchParams +} +``` + +### Synchronous Components + +Use `React.use()` for non-async components: + +```tsx +import { use } from 'react' + +type Props = { params: Promise<{ slug: string }> } + +export default function Page({ params }: Props) { + const { slug } = use(params) +} +``` + +### generateMetadata + +```tsx +type Props = { params: Promise<{ slug: string }> } + +export async function generateMetadata({ params }: Props): Promise { + const { slug } = await params + return { title: slug } +} +``` + +## Async Cookies and Headers + +```tsx +import { cookies, headers } from 'next/headers' + +export default async function Page() { + const cookieStore = await cookies() + const headersList = await headers() + + const theme = cookieStore.get('theme') + const userAgent = headersList.get('user-agent') +} +``` + +## Migration Codemod + +```bash +npx @next/codemod@latest next-async-request-api . +``` diff --git a/.agents/skills/next-best-practices/bundling.md b/.agents/skills/next-best-practices/bundling.md new file mode 100644 index 0000000..ac5e814 --- /dev/null +++ b/.agents/skills/next-best-practices/bundling.md @@ -0,0 +1,180 @@ +# Bundling + +Fix common bundling issues with third-party packages. + +## Server-Incompatible Packages + +Some packages use browser APIs (`window`, `document`, `localStorage`) and fail in Server Components. + +### Error Signs + +``` +ReferenceError: window is not defined +ReferenceError: document is not defined +ReferenceError: localStorage is not defined +Module not found: Can't resolve 'fs' +``` + +### Solution 1: Mark as Client-Only + +If the package is only needed on client: + +```tsx +// Bad: Fails - package uses window +import SomeChart from 'some-chart-library' + +export default function Page() { + return +} + +// Good: Use dynamic import with ssr: false +import dynamic from 'next/dynamic' + +const SomeChart = dynamic(() => import('some-chart-library'), { + ssr: false, +}) + +export default function Page() { + return +} +``` + +### Solution 2: Externalize from Server Bundle + +For packages that should run on server but have bundling issues: + +```js +// next.config.js +module.exports = { + serverExternalPackages: ['problematic-package'], +} +``` + +Use this for: +- Packages with native bindings (sharp, bcrypt) +- Packages that don't bundle well (some ORMs) +- Packages with circular dependencies + +### Solution 3: Client Component Wrapper + +Wrap the entire usage in a client component: + +```tsx +// components/ChartWrapper.tsx +'use client' + +import { Chart } from 'chart-library' + +export function ChartWrapper(props) { + return +} + +// app/page.tsx (server component) +import { ChartWrapper } from '@/components/ChartWrapper' + +export default function Page() { + return +} +``` + +## CSS Imports + +Import CSS files instead of using `` tags. Next.js handles bundling and optimization. + +```tsx +// Bad: Manual link tag + + +// Good: Import CSS +import './styles.css' + +// Good: CSS Modules +import styles from './Button.module.css' +``` + +## Polyfills + +Next.js includes common polyfills automatically. Don't load redundant ones from polyfill.io or similar CDNs. + +Already included: `Array.from`, `Object.assign`, `Promise`, `fetch`, `Map`, `Set`, `Symbol`, `URLSearchParams`, and 50+ others. + +```tsx +// Bad: Redundant polyfills + + +// Good: Next.js Script component +import Script from 'next/script' + + +``` + +## Don't Put Script in Head + +`next/script` should not be placed inside `next/head`. It handles its own positioning. + +```tsx +// Bad: Script inside Head +import Head from 'next/head' +import Script from 'next/script' + + + + +// Good: Next.js component +import { GoogleAnalytics } from '@next/third-parties/google' + +export default function Layout({ children }) { + return ( + + {children} + + + ) +} +``` + +## Google Tag Manager + +```tsx +import { GoogleTagManager } from '@next/third-parties/google' + +export default function Layout({ children }) { + return ( + + + {children} + + ) +} +``` + +## Other Third-Party Scripts + +```tsx +// YouTube embed +import { YouTubeEmbed } from '@next/third-parties/google' + + + +// Google Maps +import { GoogleMapsEmbed } from '@next/third-parties/google' + + +``` + +## Quick Reference + +| Pattern | Issue | Fix | +|---------|-------|-----| +| ` + - + +
@@ -17,7 +19,7 @@ W Fancy Wordle - Non-stop five-letter play + One word every hour @@ -36,9 +38,9 @@
-

Daily pace optional

+

Hourly challenge

Guess the word in six tries.

-

Play as many rounds as you want. Valid words reveal with smooth flips, warm feedback, confetti, sound, and a definition at the end.

+

Play one five-letter word per hour. Valid words reveal with smooth flips, warm feedback, confetti, sound, and a definition at the end.

diff --git a/index.html b/index.html index f55f92f..a3b8069 100644 --- a/index.html +++ b/index.html @@ -7,8 +7,10 @@ Fancy Wordle + - + +
@@ -17,7 +19,7 @@ W Fancy Wordle - Non-stop five-letter play + One word every hour @@ -36,9 +38,9 @@
-

Daily pace optional

+

Hourly challenge

Guess the word in six tries.

-

Play as many rounds as you want. Valid words reveal with smooth flips, warm feedback, confetti, sound, and a definition at the end.

+

Play one five-letter word per hour. Valid words reveal with smooth flips, warm feedback, confetti, sound, and a definition at the end.

diff --git a/script.js b/script.js index 568f965..63279cf 100644 --- a/script.js +++ b/script.js @@ -9,12 +9,17 @@ let lastResult = null let hasInitialized = false let wordListMode = "loading" let isAnimating = false +let hourlyRound = null +let lockCountdownTimer = null +let supabaseClient = null const WORD_LENGTH = 5 const MAX_GUESSES = 6 const FLIP_ANIMATION_DURATION = 500 const DANCE_ANIMATION_DURATION = 500 const STATS_KEY = "fancy-wordle-stats-v2" +const LOCAL_ROUND_KEY = "fancy-wordle-hourly-round-v1" +const PLAY_INTERVAL_MS = 60 * 60 * 1000 const KEY_ROWS = ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"] const FALLBACK_TARGET_WORDS = [ "about", @@ -92,10 +97,7 @@ async function initializeGame() { showAlert("Using a compact offline word set", 3000) } - targetWord = targetWords[Math.floor(Math.random() * targetWords.length)] - dictionarySet.add(targetWord) - updateTriesStatus() - startInteraction() + await startHourlyRound() } async function loadWordLists() { @@ -165,6 +167,145 @@ function normalizeWords(words) { .filter(word => word.length === WORD_LENGTH) } +async function startHourlyRound() { + const selectedWord = getCurrentHourlyWord() + const remoteRound = await startRemoteHourlyRound() + const round = remoteRound || startLocalHourlyRound(selectedWord) + + applyHourlyRound(round) +} + +async function startRemoteHourlyRound() { + const client = getSupabaseClient() + if (!client) return null + + try { + await ensureSupabaseSession(client) + const { data, error } = await client.rpc("start_hourly_round") + if (error) throw error + + const row = Array.isArray(data) ? data[0] : data + if (!row) throw new Error("Supabase did not return a round") + + return normalizeRemoteRound(row) + } catch (error) { + console.warn("Supabase hourly lock unavailable; using local lock.", error) + showAlert("Using local hourly lock", 3000) + return null + } +} + +function getSupabaseClient() { + const config = window.FANCY_WORDLE_SUPABASE || {} + if (!config.url || !config.anonKey || !window.supabase) return null + + if (!supabaseClient) { + supabaseClient = window.supabase.createClient(config.url, config.anonKey) + } + + return supabaseClient +} + +async function ensureSupabaseSession(client) { + const { data: { session } } = await client.auth.getSession() + if (session) return + + const { error } = await client.auth.signInAnonymously() + if (error) throw error +} + +function normalizeRemoteRound(row) { + return { + id: row.round_id, + backend: "supabase", + word: row.word, + hourStart: Date.parse(row.hour_start), + startedAt: Date.parse(row.started_at), + nextPlayableAt: Date.parse(row.next_playable_at), + completedAt: row.completed_at ? Date.parse(row.completed_at) : null, + won: row.won, + guessCount: row.guess_count, + isExisting: row.is_existing + } +} + +function startLocalHourlyRound(selectedWord) { + const savedRound = getLocalHourlyRound() + if (savedRound && savedRound.nextPlayableAt > Date.now()) return savedRound + + const now = Date.now() + const hourStart = getCurrentHourStart(now) + const round = { + id: `local-${now}`, + backend: "local", + word: selectedWord, + hourStart, + startedAt: now, + nextPlayableAt: hourStart + PLAY_INTERVAL_MS, + completedAt: null, + won: null, + guessCount: null, + isExisting: false + } + + saveLocalHourlyRound(round) + return round +} + +function getLocalHourlyRound() { + try { + const round = JSON.parse(localStorage.getItem(LOCAL_ROUND_KEY)) + if (!round?.word || !round?.nextPlayableAt) return null + + return { + ...round, + backend: "local", + hourStart: Number(round.hourStart) || getCurrentHourStart(Number(round.startedAt) || Date.now()), + startedAt: Number(round.startedAt), + nextPlayableAt: Number(round.nextPlayableAt), + completedAt: round.completedAt ? Number(round.completedAt) : null, + isExisting: true + } + } catch { + return null + } +} + +function saveLocalHourlyRound(round) { + localStorage.setItem(LOCAL_ROUND_KEY, JSON.stringify(round)) +} + +function getCurrentHourlyWord() { + const hourStart = getCurrentHourStart(Date.now()) + const hourIndex = Math.floor(hourStart / PLAY_INTERVAL_MS) + return targetWords[hourIndex % targetWords.length] +} + +function getCurrentHourStart(timestamp) { + return Math.floor(timestamp / PLAY_INTERVAL_MS) * PLAY_INTERVAL_MS +} + +function applyHourlyRound(round) { + hourlyRound = round + targetWord = round.word + dictionarySet.add(targetWord) + currentGuessIndex = round.completedAt ? round.guessCount || 0 : 0 + updateTriesStatus() + + if (round.completedAt) { + lastResult = { + won: Boolean(round.won), + guesses: round.guessCount || MAX_GUESSES, + word: round.word + } + lockUntilNextWord() + return + } + + roundStatus.textContent = round.isExisting ? "Hourly word resumed" : "Hourly word ready" + startInteraction() +} + function createBoard() { guessGrid.innerHTML = "" @@ -453,6 +594,7 @@ function checkWinLose(guess, tiles) { celebrateWithConfetti() roundStatus.textContent = `Solved in ${currentGuessIndex}` setTimeout(() => showWordDefinition(targetWord, true), 1800) + startLockCountdown(2400) stopInteraction() return } @@ -465,6 +607,7 @@ function checkWinLose(guess, tiles) { showAlert(targetWord.toUpperCase(), null) roundStatus.textContent = "Round complete" showWordDefinition(targetWord, false) + startLockCountdown(2400) stopInteraction() return } @@ -477,6 +620,62 @@ function updateTriesStatus() { triesStatus.textContent = `${currentGuessIndex} / ${MAX_GUESSES}` } +function lockUntilNextWord() { + gameFinished = true + stopInteraction() + startLockCountdown() +} + +function startLockCountdown(delay = 0) { + clearLockCountdown() + + const beginCountdown = () => { + updateLockCountdown() + lockCountdownTimer = setInterval(updateLockCountdown, 1000) + } + + if (delay > 0) { + lockCountdownTimer = setTimeout(beginCountdown, delay) + return + } + + beginCountdown() +} + +function clearLockCountdown() { + if (!lockCountdownTimer) return + + clearTimeout(lockCountdownTimer) + clearInterval(lockCountdownTimer) + lockCountdownTimer = null +} + +function updateLockCountdown() { + if (!hourlyRound?.nextPlayableAt) return + + const remaining = hourlyRound.nextPlayableAt - Date.now() + if (remaining <= 0) { + clearLockCountdown() + if (hourlyRound.backend === "local") localStorage.removeItem(LOCAL_ROUND_KEY) + roundStatus.textContent = "New word available" + triesStatus.textContent = "Ready" + showAlert("New word available. Refresh to play.", null) + return + } + + roundStatus.textContent = `Next word in ${formatRemainingTime(remaining)}` + triesStatus.textContent = "Locked" +} + +function formatRemainingTime(milliseconds) { + const totalSeconds = Math.max(1, Math.ceil(milliseconds / 1000)) + const minutes = Math.floor(totalSeconds / 60) + const seconds = totalSeconds % 60 + + if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, "0")}s` + return `${seconds}s` +} + function playCelebrationSound() { const audio = new Audio("Celebration.mp3") audio.volume = 0.45 @@ -613,6 +812,40 @@ function saveGameResult(result) { } saveStats(stats) + completeHourlyRound(result) +} + +function completeHourlyRound(result) { + if (!hourlyRound || hourlyRound.completedAt) return + + hourlyRound = { + ...hourlyRound, + completedAt: Date.now(), + won: result.won, + guessCount: result.guesses + } + + if (hourlyRound.backend === "local") { + saveLocalHourlyRound(hourlyRound) + return + } + + completeRemoteHourlyRound(result).catch(error => { + console.warn("Failed to complete Supabase hourly round:", error) + }) +} + +async function completeRemoteHourlyRound(result) { + const client = getSupabaseClient() + if (!client || !hourlyRound?.id) return + + const { error } = await client.rpc("complete_hourly_round", { + round_id: hourlyRound.id, + did_win: result.won, + guess_total: result.guesses + }) + + if (error) throw error } function renderStats() { @@ -670,8 +903,15 @@ function buildShareText() { const status = lastResult ? `${lastResult.won ? lastResult.guesses : "X"}/${MAX_GUESSES}` : `${currentGuessIndex}/${MAX_GUESSES}` + const roundLabel = getShareRoundLabel() - return `Fancy Wordle ${status}\n${getResultGrid()}` + return `Fancy Wordle ${roundLabel} ${status}\n${getResultGrid()}` +} + +function getShareRoundLabel() { + if (!Number.isFinite(hourlyRound?.hourStart)) return "Hourly" + + return new Date(hourlyRound.hourStart).toISOString().slice(0, 13).replace("T", " ") + ":00 UTC" } function getResultGrid() { diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..cdd644a --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,17 @@ +{ + "version": 1, + "skills": { + "frontend-design": { + "source": "anthropics/skills", + "sourceType": "github", + "skillPath": "skills/frontend-design/SKILL.md", + "computedHash": "063a0e6448123cd359ad0044cc46b0e490cc7964d45ef4bb9fd842bd2ffbca67" + }, + "next-best-practices": { + "source": "vercel-labs/next-skills", + "sourceType": "github", + "skillPath": "skills/next-best-practices/SKILL.md", + "computedHash": "f4678aef4ffc10a5ea64a91e57abe5a5081af813b06d58d565caf3e8ef56e26c" + } + } +} diff --git a/supabase-config.js b/supabase-config.js new file mode 100644 index 0000000..e4bcb9c --- /dev/null +++ b/supabase-config.js @@ -0,0 +1,4 @@ +window.FANCY_WORDLE_SUPABASE = { + url: "", + anonKey: "" +} diff --git a/supabase/schema.sql b/supabase/schema.sql new file mode 100644 index 0000000..1e3744a --- /dev/null +++ b/supabase/schema.sql @@ -0,0 +1,287 @@ +create extension if not exists pgcrypto; + +create table if not exists public.wordle_words ( + position integer primary key, + word text not null unique check (word ~ '^[a-z]{5}$') +); + +insert into public.wordle_words (position, word) values + (1, 'cigar'), + (2, 'rebut'), + (3, 'sissy'), + (4, 'humph'), + (5, 'awake'), + (6, 'blush'), + (7, 'focal'), + (8, 'evade'), + (9, 'naval'), + (10, 'serve'), + (11, 'heath'), + (12, 'dwarf'), + (13, 'model'), + (14, 'karma'), + (15, 'stink'), + (16, 'grade'), + (17, 'quiet'), + (18, 'bench'), + (19, 'abate'), + (20, 'feign'), + (21, 'major'), + (22, 'death'), + (23, 'fresh'), + (24, 'crust'), + (25, 'stool'), + (26, 'colon'), + (27, 'abase'), + (28, 'marry'), + (29, 'react'), + (30, 'batty'), + (31, 'pride'), + (32, 'floss'), + (33, 'helix'), + (34, 'croak'), + (35, 'staff'), + (36, 'paper'), + (37, 'unfed'), + (38, 'whelp'), + (39, 'trawl'), + (40, 'outdo'), + (41, 'adobe'), + (42, 'crazy'), + (43, 'sower'), + (44, 'repay'), + (45, 'digit'), + (46, 'crate'), + (47, 'cluck'), + (48, 'spike'), + (49, 'mimic'), + (50, 'pound'), + (51, 'maxim'), + (52, 'linen'), + (53, 'unmet'), + (54, 'flesh'), + (55, 'booby'), + (56, 'forth'), + (57, 'first'), + (58, 'stand'), + (59, 'belly'), + (60, 'ivory'), + (61, 'seedy'), + (62, 'print'), + (63, 'yearn'), + (64, 'drain'), + (65, 'bribe'), + (66, 'stout'), + (67, 'panel'), + (68, 'crass'), + (69, 'flume'), + (70, 'offal'), + (71, 'agree'), + (72, 'error'), + (73, 'swirl'), + (74, 'argue'), + (75, 'bleed'), + (76, 'delta'), + (77, 'flick'), + (78, 'totem'), + (79, 'wooer'), + (80, 'front'), + (81, 'shrub'), + (82, 'parry'), + (83, 'biome'), + (84, 'lapel'), + (85, 'start'), + (86, 'greet'), + (87, 'goner'), + (88, 'golem'), + (89, 'lusty'), + (90, 'loopy'), + (91, 'round'), + (92, 'audit'), + (93, 'lying'), + (94, 'gamma'), + (95, 'labor'), + (96, 'islet'), + (97, 'civic'), + (98, 'forge'), + (99, 'corny'), + (100, 'moult'), + (101, 'basic'), + (102, 'salad'), + (103, 'agate'), + (104, 'spicy'), + (105, 'spray'), + (106, 'essay'), + (107, 'fjord'), + (108, 'spend'), + (109, 'kebab'), + (110, 'guild'), + (111, 'aback'), + (112, 'motor'), + (113, 'alone'), + (114, 'hatch'), + (115, 'hyper'), + (116, 'thumb'), + (117, 'dowry'), + (118, 'ought'), + (119, 'belch'), + (120, 'dutch') +on conflict (position) do nothing; + +alter table public.wordle_words enable row level security; + +create table if not exists public.wordle_rounds ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references auth.users(id) on delete cascade, + word text not null check (word ~ '^[a-z]{5}$'), + hour_start timestamptz, + started_at timestamptz not null default now(), + next_playable_at timestamptz not null default (now() + interval '1 hour'), + completed_at timestamptz, + won boolean, + guess_count integer check (guess_count between 1 and 6), + created_at timestamptz not null default now() +); + +alter table public.wordle_rounds + add column if not exists hour_start timestamptz; + +update public.wordle_rounds +set hour_start = date_trunc('hour', started_at) +where hour_start is null; + +alter table public.wordle_rounds + alter column hour_start set not null; + +create index if not exists wordle_rounds_user_started_idx + on public.wordle_rounds (user_id, started_at desc); + +create unique index if not exists wordle_rounds_user_hour_idx + on public.wordle_rounds (user_id, hour_start); + +alter table public.wordle_rounds enable row level security; + +drop policy if exists "Users can read their own rounds" on public.wordle_rounds; +create policy "Users can read their own rounds" + on public.wordle_rounds + for select + using (auth.uid() = user_id); + +drop function if exists public.start_hourly_round(text); + +create or replace function public.start_hourly_round() +returns table ( + round_id uuid, + word text, + hour_start timestamptz, + started_at timestamptz, + next_playable_at timestamptz, + completed_at timestamptz, + won boolean, + guess_count integer, + server_now timestamptz, + is_existing boolean +) +language plpgsql +security definer +set search_path = public +as $$ +declare + existing_round public.wordle_rounds%rowtype; + new_round public.wordle_rounds%rowtype; + current_hour timestamptz := date_trunc('hour', now()); + word_count integer; + word_offset integer; + hourly_word text; +begin + if auth.uid() is null then + raise exception 'Authentication required'; + end if; + + select count(*) into word_count from public.wordle_words; + if word_count = 0 then + raise exception 'No hourly words are configured'; + end if; + + word_offset := (floor(extract(epoch from current_hour) / 3600)::bigint % word_count)::integer; + + select public.wordle_words.word + into hourly_word + from public.wordle_words + order by position + limit 1 offset word_offset; + + select * + into existing_round + from public.wordle_rounds + where user_id = auth.uid() + and public.wordle_rounds.hour_start = current_hour + order by started_at desc + limit 1; + + if found then + return query select + existing_round.id, + existing_round.word, + existing_round.hour_start, + existing_round.started_at, + existing_round.next_playable_at, + existing_round.completed_at, + existing_round.won, + existing_round.guess_count, + now(), + true; + return; + end if; + + insert into public.wordle_rounds (user_id, word, hour_start, next_playable_at) + values (auth.uid(), hourly_word, current_hour, current_hour + interval '1 hour') + returning * into new_round; + + return query select + new_round.id, + new_round.word, + new_round.hour_start, + new_round.started_at, + new_round.next_playable_at, + new_round.completed_at, + new_round.won, + new_round.guess_count, + now(), + false; +end; +$$; + +create or replace function public.complete_hourly_round( + round_id uuid, + did_win boolean, + guess_total integer +) +returns void +language plpgsql +security definer +set search_path = public +as $$ +begin + if auth.uid() is null then + raise exception 'Authentication required'; + end if; + + if guess_total < 1 or guess_total > 6 then + raise exception 'Guess total must be between 1 and 6'; + end if; + + update public.wordle_rounds + set completed_at = coalesce(completed_at, now()), + won = did_win, + guess_count = guess_total + where id = round_id + and user_id = auth.uid(); +end; +$$; + +revoke all on public.wordle_rounds from anon, authenticated; +revoke all on public.wordle_words from anon, authenticated; +grant select on public.wordle_rounds to authenticated; +grant execute on function public.start_hourly_round() to authenticated; +grant execute on function public.complete_hourly_round(uuid, boolean, integer) to authenticated;