diff --git a/.agents/skills/convex-create-component/SKILL.md b/.agents/skills/convex-create-component/SKILL.md index a79c18e0..64bd42f9 100644 --- a/.agents/skills/convex-create-component/SKILL.md +++ b/.agents/skills/convex-create-component/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-create-component -description: Designs and builds Convex components with isolated tables, clear boundaries, and app-facing wrappers. Use this skill when creating a new Convex component, extracting reusable backend logic into a component, building a third-party integration that owns its own tables, packaging Convex functionality for reuse, or when the user mentions defineComponent, app.use, ComponentApi, ctx.runQuery/runMutation across component boundaries, or wants to separate concerns into isolated Convex modules. +description: Builds reusable Convex components with isolated tables and app-facing APIs. Use for new components, reusable backend modules, integrations, or component boundary work. --- # Convex Create Component @@ -42,12 +42,12 @@ Create reusable Convex components with clear boundaries and a small app-facing A Ask the user, then pick one path: -| Goal | Shape | Reference | -|------|-------|-----------| -| Component for this app only | Local | `references/local-components.md` | -| Publish or share across apps | Packaged | `references/packaged-components.md` | -| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | -| Not sure | Default to local | `references/local-components.md` | +| Goal | Shape | Reference | +| ------------------------------------------------- | ---------------- | ----------------------------------- | +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | Read exactly one reference file before proceeding. @@ -111,7 +111,7 @@ export const listUnread = query({ userId: v.string(), message: v.string(), read: v.boolean(), - }) + }), ), handler: async (ctx, args) => { return await ctx.db @@ -234,12 +234,16 @@ export const sendNotification = mutation({ ```ts // Bad: parent app table IDs are not valid component validators -args: { userId: v.id("users") } +args: { + userId: v.id("users"); +} ``` ```ts // Good: treat parent-owned IDs as strings at the boundary -args: { userId: v.string() } +args: { + userId: v.string(); +} ``` ### Advanced Patterns diff --git a/.agents/skills/convex-migration-helper/SKILL.md b/.agents/skills/convex-migration-helper/SKILL.md index 97f64c1a..4a4ed167 100644 --- a/.agents/skills/convex-migration-helper/SKILL.md +++ b/.agents/skills/convex-migration-helper/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-migration-helper -description: Plans and executes safe Convex schema and data migrations using the widen-migrate-narrow workflow and the @convex-dev/migrations component. Use this skill when a deployment fails schema validation, existing documents need backfilling, fields need adding or removing or changing type, tables need splitting or merging, or a zero-downtime migration strategy is needed. Also use when the user mentions breaking schema changes, multi-deploy rollouts, or data transformations on existing Convex tables. +description: Plans Convex schema and data migrations with widen-migrate-narrow and @convex-dev/migrations. Use for breaking schema changes, backfills, table reshaping, or zero-downtime rollouts. --- # Convex Migration Helper @@ -55,13 +55,13 @@ Unless you are certain, prefer deprecating fields over deleting them. Mark the f // Before users: defineTable({ name: v.string(), -}) +}); // After - safe, new field is optional users: defineTable({ name: v.string(), bio: v.optional(v.string()), -}) +}); ``` ### Adding New Table @@ -70,7 +70,7 @@ users: defineTable({ posts: defineTable({ userId: v.id("users"), title: v.string(), -}).index("by_user", ["userId"]) +}).index("by_user", ["userId"]); ``` ### Adding Index @@ -79,8 +79,7 @@ posts: defineTable({ users: defineTable({ name: v.string(), email: v.string(), -}) - .index("by_email", ["email"]) +}).index("by_email", ["email"]); ``` ## Breaking Changes: The Deployment Workflow diff --git a/.agents/skills/convex-migration-helper/references/migration-patterns.md b/.agents/skills/convex-migration-helper/references/migration-patterns.md index 219583e0..53b4946f 100644 --- a/.agents/skills/convex-migration-helper/references/migration-patterns.md +++ b/.agents/skills/convex-migration-helper/references/migration-patterns.md @@ -9,7 +9,7 @@ Common migration patterns, zero-downtime strategies, and verification techniques users: defineTable({ name: v.string(), role: v.optional(v.union(v.literal("user"), v.literal("admin"))), -}) +}); // Migration: backfill the field export const addDefaultRole = migrations.define({ @@ -25,7 +25,7 @@ export const addDefaultRole = migrations.define({ users: defineTable({ name: v.string(), role: v.union(v.literal("user"), v.literal("admin")), -}) +}); ``` ## Deleting a Field diff --git a/.agents/skills/convex-migration-helper/references/migrations-component.md b/.agents/skills/convex-migration-helper/references/migrations-component.md index c80522f2..95ec2921 100644 --- a/.agents/skills/convex-migration-helper/references/migrations-component.md +++ b/.agents/skills/convex-migration-helper/references/migrations-component.md @@ -151,8 +151,7 @@ Process only matching documents instead of the full table: ```typescript export const fixEmptyNames = migrations.define({ table: "users", - customRange: (query) => - query.withIndex("by_name", (q) => q.eq("name", "")), + customRange: (query) => query.withIndex("by_name", (q) => q.eq("name", "")), migrateOne: () => ({ name: "" }), }); ``` diff --git a/.agents/skills/convex-performance-audit/SKILL.md b/.agents/skills/convex-performance-audit/SKILL.md index 9d92b33c..f2554dca 100644 --- a/.agents/skills/convex-performance-audit/SKILL.md +++ b/.agents/skills/convex-performance-audit/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-performance-audit -description: Audits and optimizes Convex application performance across hot-path reads, write contention, subscription cost, and function limits. Use this skill when a Convex feature is slow or expensive, npx convex insights shows high bytes or documents read, OCC conflict errors or mutation retries appear, subscriptions or UI updates are costly, functions hit execution or transaction limits, or the user mentions performance, latency, read amplification, or invalidation problems in a Convex app. +description: Audits Convex performance for reads, subscriptions, write contention, and function limits. Use for slow features, insights findings, OCC conflicts, or read amplification. --- # Convex Performance Audit @@ -43,13 +43,13 @@ Start with the strongest signal available: After gathering signals, identify the problem class and read the matching reference file. -| Signal | Reference | -|---|---| -| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | -| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | -| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | -| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | -| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | +| Signal | Reference | +| -------------------------------------------------------------- | ----------------------------------------- | +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. @@ -107,7 +107,7 @@ After finding one problem, inspect both sibling readers and sibling writers for Examples: - If one list query switches from full docs to a digest table, inspect the other list queries for that table -- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one mutation isolates a frequently-updated field or splits a hot document, inspect the other writers to the same table - If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. @@ -119,7 +119,7 @@ Confirm all of these: 1. Results are the same as before, no dropped records 2. Eliminated reads or writes are no longer in the path where expected 3. Fallback behavior works when denormalized or indexed fields are missing -4. New writes avoid unnecessary invalidation when data is unchanged +4. Frequently-updated fields are isolated from widely-read documents where needed 5. Every relevant sibling reader and writer was inspected, not just the original function ## Reference Files diff --git a/.agents/skills/convex-performance-audit/references/function-budget.md b/.agents/skills/convex-performance-audit/references/function-budget.md index c71d14cb..d4d4aa5a 100644 --- a/.agents/skills/convex-performance-audit/references/function-budget.md +++ b/.agents/skills/convex-performance-audit/references/function-budget.md @@ -10,17 +10,17 @@ Convex functions run inside transactions with budgets for time, reads, and write These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. -| Resource | Limit | -|---|---| -| Query/mutation execution time | 1 second (user code only, excludes DB operations) | -| Action execution time | 10 minutes | -| Data read per transaction | 16 MiB | -| Data written per transaction | 16 MiB | +| Resource | Limit | +| --------------------------------- | ----------------------------------------------------- | +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | | Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | -| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | -| Documents written per transaction | 16,000 | -| Individual document size | 1 MiB | -| Function return value size | 16 MiB | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | ## Symptoms diff --git a/.agents/skills/convex-performance-audit/references/hot-path-rules.md b/.agents/skills/convex-performance-audit/references/hot-path-rules.md index e3e44b15..e003e052 100644 --- a/.agents/skills/convex-performance-audit/references/hot-path-rules.md +++ b/.agents/skills/convex-performance-audit/references/hot-path-rules.md @@ -121,13 +121,15 @@ Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need // Bad: two indexes where one would do defineTable({ team: v.id("teams"), user: v.id("users") }) .index("by_team", ["team"]) - .index("by_team_and_user", ["team", "user"]) + .index("by_team_and_user", ["team", "user"]); ``` ```ts // Good: single compound index serves both query patterns -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team_and_user", ["team", "user"]) +defineTable({ team: v.id("teams"), user: v.id("users") }).index( + "by_team_and_user", + ["team", "user"], +); ``` Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. @@ -170,9 +172,7 @@ const ownerName = project.ownerName ?? "Unknown owner"; ```ts // Good: denormalized data is an optimization, not the only source of truth const ownerName = - project.ownerName ?? - (await ctx.db.get(project.ownerId))?.name ?? - null; + project.ownerName ?? (await ctx.db.get(project.ownerId))?.name ?? null; ``` Bad lookup map pattern: @@ -241,35 +241,33 @@ const projects = await ctx.db .take(20); ``` -## 4. Skip No-Op Writes - -No-op writes still cost work in Convex: +## 4. Isolate Frequently-Updated Fields -- invalidation -- replication -- trigger execution -- downstream sync +Convex already no-ops unchanged writes. The invalidation problem here is real writes hitting documents that many queries subscribe to. -Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. +Move high-churn fields like `lastSeen`, counters, presence, or ephemeral status off widely-read documents when most readers do not need them. -Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. +Apply this across sibling writers too. Splitting one write path does not help much if three other mutations still update the same widely-read document. ```ts -// Bad: patching unchanged values still triggers invalidation and downstream work -await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, +// Bad: every presence heartbeat invalidates subscribers to the whole profile +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, + lastSeen: Date.now(), }); ``` ```ts -// Good: only write when something actually changed -if (settings.theme !== args.theme || settings.locale !== args.locale) { - await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, - }); -} +// Good: keep profile reads stable, move heartbeat updates to a separate document +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, +}); + +await ctx.db.patch(presence._id, { + lastSeen: Date.now(), +}); ``` ## 5. Match Consistency To Read Patterns diff --git a/.agents/skills/convex-performance-audit/references/occ-conflicts.md b/.agents/skills/convex-performance-audit/references/occ-conflicts.md index a96d0466..1da43801 100644 --- a/.agents/skills/convex-performance-audit/references/occ-conflicts.md +++ b/.agents/skills/convex-performance-audit/references/occ-conflicts.md @@ -73,42 +73,30 @@ await ctx.db.patch(shardId, { count: shard!.count + 1 }); Aggregate the shards in a query or scheduled job when you need the total. -### 3. Skip no-op writes +### 3. Move non-critical work to scheduled functions -Writes that do not change data still participate in conflict detection and trigger invalidation. +If a mutation does primary work plus secondary bookkeeping (analytics, non-critical notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. ```ts -// Bad: patches even when nothing changed -await ctx.db.patch(doc._id, { status: args.status }); -``` - -```ts -// Good: only write when the value actually differs -if (doc.status !== args.status) { - await ctx.db.patch(doc._id, { status: args.status }); -} -``` - -### 4. Move non-critical work to scheduled functions - -If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. - -```ts -// Bad: analytics update in the same transaction as the user action -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +// Bad: canonical write and derived work happen in the same transaction +await ctx.db.patch(userId, { name: args.name }); +await ctx.db.insert("userUpdateAnalytics", { + userId, + kind: "name_changed", + name: args.name, +}); ``` ```ts -// Good: schedule the bookkeeping so the primary transaction is smaller -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { - event: "action", +// Good: keep the primary write small, defer the analytics work +await ctx.db.patch(userId, { name: args.name }); +await ctx.scheduler.runAfter(0, internal.users.recordNameChangeAnalytics, { userId, + name: args.name, }); ``` -### 5. Combine competing writes +### 4. Combine competing writes If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. diff --git a/.agents/skills/convex-quickstart/SKILL.md b/.agents/skills/convex-quickstart/SKILL.md index 792bba3d..f506b3e4 100644 --- a/.agents/skills/convex-quickstart/SKILL.md +++ b/.agents/skills/convex-quickstart/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-quickstart -description: Initializes a new Convex project from scratch or adds Convex to an existing app. Use this skill when starting a new project with Convex, scaffolding with npm create convex@latest, adding Convex to an existing React, Next.js, Vue, Svelte, or other frontend, wiring up ConvexProvider, configuring environment variables for the deployment URL, or running npx convex dev for the first time, even if the user just says "set up Convex" or "add a backend." +description: Creates or adds Convex to an app. Use for new Convex projects, npm create convex@latest, frontend setup, env vars, or the first npx convex dev run. --- # Convex Quickstart @@ -32,15 +32,15 @@ Use the official scaffolding tool. It creates a complete project with the fronte ### Pick a template -| Template | Stack | -|----------|-------| -| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | -| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | -| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | -| `nextjs-clerk` | Next.js + Clerk auth | -| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | -| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | -| `bare` | Convex backend only, no frontend | +| Template | Stack | +| -------------------------- | ----------------------------------------- | +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. @@ -77,6 +77,7 @@ npm install **Ask the user to run this themselves:** Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: + - Create a Convex project and dev deployment - Write the deployment URL to `.env.local` - Create the `convex/` directory with generated types @@ -111,6 +112,7 @@ my-app/ ``` The template already has: + - `ConvexProvider` wired into the app root - Correct env var names for the framework - Tailwind and shadcn/ui ready (for shadcn templates) @@ -141,7 +143,9 @@ Create the `ConvexReactClient` at module scope, not inside a component: ```tsx // Bad: re-creates the client on every render function App() { - const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + const convex = new ConvexReactClient( + import.meta.env.VITE_CONVEX_URL as string, + ); return ...; } @@ -192,7 +196,11 @@ export function ConvexClientProvider({ children }: { children: ReactNode }) { // app/layout.tsx import { ConvexClientProvider } from "./ConvexClientProvider"; -export default function RootLayout({ children }: { children: React.ReactNode }) { +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { return ( @@ -218,11 +226,11 @@ For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the mat The env var name depends on the framework: -| Framework | Variable | -|-----------|----------| -| Vite | `VITE_CONVEX_URL` | -| Next.js | `NEXT_PUBLIC_CONVEX_URL` | -| Remix | `CONVEX_URL` | +| Framework | Variable | +| ------------ | ------------------------ | +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | | React Native | `EXPO_PUBLIC_CONVEX_URL` | `npx convex dev` writes the correct variable to `.env.local` automatically. @@ -299,7 +307,9 @@ function Tasks() { return (
- {tasks?.map((t) =>
{t.text}
)} + {tasks?.map((t) => ( +
{t.text}
+ ))}
); } diff --git a/.agents/skills/convex-setup-auth/SKILL.md b/.agents/skills/convex-setup-auth/SKILL.md index 0fa00e2f..59a92285 100644 --- a/.agents/skills/convex-setup-auth/SKILL.md +++ b/.agents/skills/convex-setup-auth/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-setup-auth -description: Sets up Convex authentication with user management, identity mapping, and access control. Use this skill when adding login or signup to a Convex app, configuring Convex Auth, Clerk, WorkOS AuthKit, Auth0, or custom JWT providers, wiring auth.config.ts, protecting queries and mutations with ctx.auth.getUserIdentity(), creating a users table with identity mapping, or setting up role-based access control, even if the user just says "add auth" or "make it require login." +description: Sets up Convex auth, identity mapping, and access control. Use for login, auth providers, users tables, protected functions, or roles in a Convex app. --- # Convex Authentication Setup @@ -102,7 +102,7 @@ export const getMyProfile = query({ return await ctx.db .query("users") .withIndex("by_tokenIdentifier", (q) => - q.eq("tokenIdentifier", identity.tokenIdentifier) + q.eq("tokenIdentifier", identity.tokenIdentifier), ) .unique(); }, diff --git a/.agents/skills/convex/SKILL.md b/.agents/skills/convex/SKILL.md new file mode 100644 index 00000000..9e8ebbd8 --- /dev/null +++ b/.agents/skills/convex/SKILL.md @@ -0,0 +1,47 @@ +--- +name: convex +description: Routes general Convex requests to the right project skill. Use when the user asks which Convex skill to use or gives an underspecified Convex app task. +--- + +# Convex + +Use this as the routing skill for Convex work in this repo. + +If a more specific Convex skill clearly matches the request, use that instead. + +## Start Here + +If the project does not already have Convex AI guidance installed, or the existing guidance looks stale, strongly recommend installing it first. + +Preferred: + +```bash +npx convex ai-files install +``` + +This installs or refreshes the managed Convex AI files. It is the recommended starting point for getting the official Convex guidelines in place and following the current Convex AI setup described in the docs: + +- [Convex AI docs](https://docs.convex.dev/ai) + +Simple fallback: + +- [convex_rules.txt](https://convex.link/convex_rules.txt) + +Prefer `npx convex ai-files install` over copying rules by hand when possible. + +## Route to the Right Skill + +After that, use the most specific Convex skill for the task: + +- New project or adding Convex to an app: `convex-quickstart` +- Authentication setup: `convex-setup-auth` +- Building a reusable Convex component: `convex-create-component` +- Planning or running a migration: `convex-migration-helper` +- Investigating performance issues: `convex-performance-audit` + +If one of those clearly matches the user's goal, switch to it instead of staying in this skill. + +## When Not to Use + +- The user has already named a more specific Convex workflow +- Another Convex skill obviously fits the request better diff --git a/.claude/skills/convex-create-component/SKILL.md b/.claude/skills/convex-create-component/SKILL.md index a79c18e0..64bd42f9 100644 --- a/.claude/skills/convex-create-component/SKILL.md +++ b/.claude/skills/convex-create-component/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-create-component -description: Designs and builds Convex components with isolated tables, clear boundaries, and app-facing wrappers. Use this skill when creating a new Convex component, extracting reusable backend logic into a component, building a third-party integration that owns its own tables, packaging Convex functionality for reuse, or when the user mentions defineComponent, app.use, ComponentApi, ctx.runQuery/runMutation across component boundaries, or wants to separate concerns into isolated Convex modules. +description: Builds reusable Convex components with isolated tables and app-facing APIs. Use for new components, reusable backend modules, integrations, or component boundary work. --- # Convex Create Component @@ -42,12 +42,12 @@ Create reusable Convex components with clear boundaries and a small app-facing A Ask the user, then pick one path: -| Goal | Shape | Reference | -|------|-------|-----------| -| Component for this app only | Local | `references/local-components.md` | -| Publish or share across apps | Packaged | `references/packaged-components.md` | -| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | -| Not sure | Default to local | `references/local-components.md` | +| Goal | Shape | Reference | +| ------------------------------------------------- | ---------------- | ----------------------------------- | +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | Read exactly one reference file before proceeding. @@ -111,7 +111,7 @@ export const listUnread = query({ userId: v.string(), message: v.string(), read: v.boolean(), - }) + }), ), handler: async (ctx, args) => { return await ctx.db @@ -234,12 +234,16 @@ export const sendNotification = mutation({ ```ts // Bad: parent app table IDs are not valid component validators -args: { userId: v.id("users") } +args: { + userId: v.id("users"); +} ``` ```ts // Good: treat parent-owned IDs as strings at the boundary -args: { userId: v.string() } +args: { + userId: v.string(); +} ``` ### Advanced Patterns diff --git a/.claude/skills/convex-migration-helper/SKILL.md b/.claude/skills/convex-migration-helper/SKILL.md index 97f64c1a..4a4ed167 100644 --- a/.claude/skills/convex-migration-helper/SKILL.md +++ b/.claude/skills/convex-migration-helper/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-migration-helper -description: Plans and executes safe Convex schema and data migrations using the widen-migrate-narrow workflow and the @convex-dev/migrations component. Use this skill when a deployment fails schema validation, existing documents need backfilling, fields need adding or removing or changing type, tables need splitting or merging, or a zero-downtime migration strategy is needed. Also use when the user mentions breaking schema changes, multi-deploy rollouts, or data transformations on existing Convex tables. +description: Plans Convex schema and data migrations with widen-migrate-narrow and @convex-dev/migrations. Use for breaking schema changes, backfills, table reshaping, or zero-downtime rollouts. --- # Convex Migration Helper @@ -55,13 +55,13 @@ Unless you are certain, prefer deprecating fields over deleting them. Mark the f // Before users: defineTable({ name: v.string(), -}) +}); // After - safe, new field is optional users: defineTable({ name: v.string(), bio: v.optional(v.string()), -}) +}); ``` ### Adding New Table @@ -70,7 +70,7 @@ users: defineTable({ posts: defineTable({ userId: v.id("users"), title: v.string(), -}).index("by_user", ["userId"]) +}).index("by_user", ["userId"]); ``` ### Adding Index @@ -79,8 +79,7 @@ posts: defineTable({ users: defineTable({ name: v.string(), email: v.string(), -}) - .index("by_email", ["email"]) +}).index("by_email", ["email"]); ``` ## Breaking Changes: The Deployment Workflow diff --git a/.claude/skills/convex-migration-helper/references/migration-patterns.md b/.claude/skills/convex-migration-helper/references/migration-patterns.md index 219583e0..53b4946f 100644 --- a/.claude/skills/convex-migration-helper/references/migration-patterns.md +++ b/.claude/skills/convex-migration-helper/references/migration-patterns.md @@ -9,7 +9,7 @@ Common migration patterns, zero-downtime strategies, and verification techniques users: defineTable({ name: v.string(), role: v.optional(v.union(v.literal("user"), v.literal("admin"))), -}) +}); // Migration: backfill the field export const addDefaultRole = migrations.define({ @@ -25,7 +25,7 @@ export const addDefaultRole = migrations.define({ users: defineTable({ name: v.string(), role: v.union(v.literal("user"), v.literal("admin")), -}) +}); ``` ## Deleting a Field diff --git a/.claude/skills/convex-migration-helper/references/migrations-component.md b/.claude/skills/convex-migration-helper/references/migrations-component.md index c80522f2..95ec2921 100644 --- a/.claude/skills/convex-migration-helper/references/migrations-component.md +++ b/.claude/skills/convex-migration-helper/references/migrations-component.md @@ -151,8 +151,7 @@ Process only matching documents instead of the full table: ```typescript export const fixEmptyNames = migrations.define({ table: "users", - customRange: (query) => - query.withIndex("by_name", (q) => q.eq("name", "")), + customRange: (query) => query.withIndex("by_name", (q) => q.eq("name", "")), migrateOne: () => ({ name: "" }), }); ``` diff --git a/.claude/skills/convex-performance-audit/SKILL.md b/.claude/skills/convex-performance-audit/SKILL.md index 9d92b33c..f2554dca 100644 --- a/.claude/skills/convex-performance-audit/SKILL.md +++ b/.claude/skills/convex-performance-audit/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-performance-audit -description: Audits and optimizes Convex application performance across hot-path reads, write contention, subscription cost, and function limits. Use this skill when a Convex feature is slow or expensive, npx convex insights shows high bytes or documents read, OCC conflict errors or mutation retries appear, subscriptions or UI updates are costly, functions hit execution or transaction limits, or the user mentions performance, latency, read amplification, or invalidation problems in a Convex app. +description: Audits Convex performance for reads, subscriptions, write contention, and function limits. Use for slow features, insights findings, OCC conflicts, or read amplification. --- # Convex Performance Audit @@ -43,13 +43,13 @@ Start with the strongest signal available: After gathering signals, identify the problem class and read the matching reference file. -| Signal | Reference | -|---|---| -| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | -| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | -| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | -| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | -| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | +| Signal | Reference | +| -------------------------------------------------------------- | ----------------------------------------- | +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. @@ -107,7 +107,7 @@ After finding one problem, inspect both sibling readers and sibling writers for Examples: - If one list query switches from full docs to a digest table, inspect the other list queries for that table -- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one mutation isolates a frequently-updated field or splits a hot document, inspect the other writers to the same table - If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. @@ -119,7 +119,7 @@ Confirm all of these: 1. Results are the same as before, no dropped records 2. Eliminated reads or writes are no longer in the path where expected 3. Fallback behavior works when denormalized or indexed fields are missing -4. New writes avoid unnecessary invalidation when data is unchanged +4. Frequently-updated fields are isolated from widely-read documents where needed 5. Every relevant sibling reader and writer was inspected, not just the original function ## Reference Files diff --git a/.claude/skills/convex-performance-audit/references/function-budget.md b/.claude/skills/convex-performance-audit/references/function-budget.md index c71d14cb..d4d4aa5a 100644 --- a/.claude/skills/convex-performance-audit/references/function-budget.md +++ b/.claude/skills/convex-performance-audit/references/function-budget.md @@ -10,17 +10,17 @@ Convex functions run inside transactions with budgets for time, reads, and write These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. -| Resource | Limit | -|---|---| -| Query/mutation execution time | 1 second (user code only, excludes DB operations) | -| Action execution time | 10 minutes | -| Data read per transaction | 16 MiB | -| Data written per transaction | 16 MiB | +| Resource | Limit | +| --------------------------------- | ----------------------------------------------------- | +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | | Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | -| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | -| Documents written per transaction | 16,000 | -| Individual document size | 1 MiB | -| Function return value size | 16 MiB | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | ## Symptoms diff --git a/.claude/skills/convex-performance-audit/references/hot-path-rules.md b/.claude/skills/convex-performance-audit/references/hot-path-rules.md index e3e44b15..e003e052 100644 --- a/.claude/skills/convex-performance-audit/references/hot-path-rules.md +++ b/.claude/skills/convex-performance-audit/references/hot-path-rules.md @@ -121,13 +121,15 @@ Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need // Bad: two indexes where one would do defineTable({ team: v.id("teams"), user: v.id("users") }) .index("by_team", ["team"]) - .index("by_team_and_user", ["team", "user"]) + .index("by_team_and_user", ["team", "user"]); ``` ```ts // Good: single compound index serves both query patterns -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team_and_user", ["team", "user"]) +defineTable({ team: v.id("teams"), user: v.id("users") }).index( + "by_team_and_user", + ["team", "user"], +); ``` Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. @@ -170,9 +172,7 @@ const ownerName = project.ownerName ?? "Unknown owner"; ```ts // Good: denormalized data is an optimization, not the only source of truth const ownerName = - project.ownerName ?? - (await ctx.db.get(project.ownerId))?.name ?? - null; + project.ownerName ?? (await ctx.db.get(project.ownerId))?.name ?? null; ``` Bad lookup map pattern: @@ -241,35 +241,33 @@ const projects = await ctx.db .take(20); ``` -## 4. Skip No-Op Writes - -No-op writes still cost work in Convex: +## 4. Isolate Frequently-Updated Fields -- invalidation -- replication -- trigger execution -- downstream sync +Convex already no-ops unchanged writes. The invalidation problem here is real writes hitting documents that many queries subscribe to. -Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. +Move high-churn fields like `lastSeen`, counters, presence, or ephemeral status off widely-read documents when most readers do not need them. -Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. +Apply this across sibling writers too. Splitting one write path does not help much if three other mutations still update the same widely-read document. ```ts -// Bad: patching unchanged values still triggers invalidation and downstream work -await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, +// Bad: every presence heartbeat invalidates subscribers to the whole profile +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, + lastSeen: Date.now(), }); ``` ```ts -// Good: only write when something actually changed -if (settings.theme !== args.theme || settings.locale !== args.locale) { - await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, - }); -} +// Good: keep profile reads stable, move heartbeat updates to a separate document +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, +}); + +await ctx.db.patch(presence._id, { + lastSeen: Date.now(), +}); ``` ## 5. Match Consistency To Read Patterns diff --git a/.claude/skills/convex-performance-audit/references/occ-conflicts.md b/.claude/skills/convex-performance-audit/references/occ-conflicts.md index a96d0466..1da43801 100644 --- a/.claude/skills/convex-performance-audit/references/occ-conflicts.md +++ b/.claude/skills/convex-performance-audit/references/occ-conflicts.md @@ -73,42 +73,30 @@ await ctx.db.patch(shardId, { count: shard!.count + 1 }); Aggregate the shards in a query or scheduled job when you need the total. -### 3. Skip no-op writes +### 3. Move non-critical work to scheduled functions -Writes that do not change data still participate in conflict detection and trigger invalidation. +If a mutation does primary work plus secondary bookkeeping (analytics, non-critical notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. ```ts -// Bad: patches even when nothing changed -await ctx.db.patch(doc._id, { status: args.status }); -``` - -```ts -// Good: only write when the value actually differs -if (doc.status !== args.status) { - await ctx.db.patch(doc._id, { status: args.status }); -} -``` - -### 4. Move non-critical work to scheduled functions - -If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. - -```ts -// Bad: analytics update in the same transaction as the user action -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +// Bad: canonical write and derived work happen in the same transaction +await ctx.db.patch(userId, { name: args.name }); +await ctx.db.insert("userUpdateAnalytics", { + userId, + kind: "name_changed", + name: args.name, +}); ``` ```ts -// Good: schedule the bookkeeping so the primary transaction is smaller -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { - event: "action", +// Good: keep the primary write small, defer the analytics work +await ctx.db.patch(userId, { name: args.name }); +await ctx.scheduler.runAfter(0, internal.users.recordNameChangeAnalytics, { userId, + name: args.name, }); ``` -### 5. Combine competing writes +### 4. Combine competing writes If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. diff --git a/.claude/skills/convex-quickstart/SKILL.md b/.claude/skills/convex-quickstart/SKILL.md index 792bba3d..f506b3e4 100644 --- a/.claude/skills/convex-quickstart/SKILL.md +++ b/.claude/skills/convex-quickstart/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-quickstart -description: Initializes a new Convex project from scratch or adds Convex to an existing app. Use this skill when starting a new project with Convex, scaffolding with npm create convex@latest, adding Convex to an existing React, Next.js, Vue, Svelte, or other frontend, wiring up ConvexProvider, configuring environment variables for the deployment URL, or running npx convex dev for the first time, even if the user just says "set up Convex" or "add a backend." +description: Creates or adds Convex to an app. Use for new Convex projects, npm create convex@latest, frontend setup, env vars, or the first npx convex dev run. --- # Convex Quickstart @@ -32,15 +32,15 @@ Use the official scaffolding tool. It creates a complete project with the fronte ### Pick a template -| Template | Stack | -|----------|-------| -| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | -| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | -| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | -| `nextjs-clerk` | Next.js + Clerk auth | -| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | -| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | -| `bare` | Convex backend only, no frontend | +| Template | Stack | +| -------------------------- | ----------------------------------------- | +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. @@ -77,6 +77,7 @@ npm install **Ask the user to run this themselves:** Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: + - Create a Convex project and dev deployment - Write the deployment URL to `.env.local` - Create the `convex/` directory with generated types @@ -111,6 +112,7 @@ my-app/ ``` The template already has: + - `ConvexProvider` wired into the app root - Correct env var names for the framework - Tailwind and shadcn/ui ready (for shadcn templates) @@ -141,7 +143,9 @@ Create the `ConvexReactClient` at module scope, not inside a component: ```tsx // Bad: re-creates the client on every render function App() { - const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + const convex = new ConvexReactClient( + import.meta.env.VITE_CONVEX_URL as string, + ); return ...; } @@ -192,7 +196,11 @@ export function ConvexClientProvider({ children }: { children: ReactNode }) { // app/layout.tsx import { ConvexClientProvider } from "./ConvexClientProvider"; -export default function RootLayout({ children }: { children: React.ReactNode }) { +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { return ( @@ -218,11 +226,11 @@ For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the mat The env var name depends on the framework: -| Framework | Variable | -|-----------|----------| -| Vite | `VITE_CONVEX_URL` | -| Next.js | `NEXT_PUBLIC_CONVEX_URL` | -| Remix | `CONVEX_URL` | +| Framework | Variable | +| ------------ | ------------------------ | +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | | React Native | `EXPO_PUBLIC_CONVEX_URL` | `npx convex dev` writes the correct variable to `.env.local` automatically. @@ -299,7 +307,9 @@ function Tasks() { return (
- {tasks?.map((t) =>
{t.text}
)} + {tasks?.map((t) => ( +
{t.text}
+ ))}
); } diff --git a/.claude/skills/convex-setup-auth/SKILL.md b/.claude/skills/convex-setup-auth/SKILL.md index 0fa00e2f..59a92285 100644 --- a/.claude/skills/convex-setup-auth/SKILL.md +++ b/.claude/skills/convex-setup-auth/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-setup-auth -description: Sets up Convex authentication with user management, identity mapping, and access control. Use this skill when adding login or signup to a Convex app, configuring Convex Auth, Clerk, WorkOS AuthKit, Auth0, or custom JWT providers, wiring auth.config.ts, protecting queries and mutations with ctx.auth.getUserIdentity(), creating a users table with identity mapping, or setting up role-based access control, even if the user just says "add auth" or "make it require login." +description: Sets up Convex auth, identity mapping, and access control. Use for login, auth providers, users tables, protected functions, or roles in a Convex app. --- # Convex Authentication Setup @@ -102,7 +102,7 @@ export const getMyProfile = query({ return await ctx.db .query("users") .withIndex("by_tokenIdentifier", (q) => - q.eq("tokenIdentifier", identity.tokenIdentifier) + q.eq("tokenIdentifier", identity.tokenIdentifier), ) .unique(); }, diff --git a/.claude/skills/convex/SKILL.md b/.claude/skills/convex/SKILL.md new file mode 100644 index 00000000..9e8ebbd8 --- /dev/null +++ b/.claude/skills/convex/SKILL.md @@ -0,0 +1,47 @@ +--- +name: convex +description: Routes general Convex requests to the right project skill. Use when the user asks which Convex skill to use or gives an underspecified Convex app task. +--- + +# Convex + +Use this as the routing skill for Convex work in this repo. + +If a more specific Convex skill clearly matches the request, use that instead. + +## Start Here + +If the project does not already have Convex AI guidance installed, or the existing guidance looks stale, strongly recommend installing it first. + +Preferred: + +```bash +npx convex ai-files install +``` + +This installs or refreshes the managed Convex AI files. It is the recommended starting point for getting the official Convex guidelines in place and following the current Convex AI setup described in the docs: + +- [Convex AI docs](https://docs.convex.dev/ai) + +Simple fallback: + +- [convex_rules.txt](https://convex.link/convex_rules.txt) + +Prefer `npx convex ai-files install` over copying rules by hand when possible. + +## Route to the Right Skill + +After that, use the most specific Convex skill for the task: + +- New project or adding Convex to an app: `convex-quickstart` +- Authentication setup: `convex-setup-auth` +- Building a reusable Convex component: `convex-create-component` +- Planning or running a migration: `convex-migration-helper` +- Investigating performance issues: `convex-performance-audit` + +If one of those clearly matches the user's goal, switch to it instead of staying in this skill. + +## When Not to Use + +- The user has already named a more specific Convex workflow +- Another Convex skill obviously fits the request better diff --git a/.windsurf/skills/convex-create-component/SKILL.md b/.windsurf/skills/convex-create-component/SKILL.md index a79c18e0..64bd42f9 100644 --- a/.windsurf/skills/convex-create-component/SKILL.md +++ b/.windsurf/skills/convex-create-component/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-create-component -description: Designs and builds Convex components with isolated tables, clear boundaries, and app-facing wrappers. Use this skill when creating a new Convex component, extracting reusable backend logic into a component, building a third-party integration that owns its own tables, packaging Convex functionality for reuse, or when the user mentions defineComponent, app.use, ComponentApi, ctx.runQuery/runMutation across component boundaries, or wants to separate concerns into isolated Convex modules. +description: Builds reusable Convex components with isolated tables and app-facing APIs. Use for new components, reusable backend modules, integrations, or component boundary work. --- # Convex Create Component @@ -42,12 +42,12 @@ Create reusable Convex components with clear boundaries and a small app-facing A Ask the user, then pick one path: -| Goal | Shape | Reference | -|------|-------|-----------| -| Component for this app only | Local | `references/local-components.md` | -| Publish or share across apps | Packaged | `references/packaged-components.md` | -| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | -| Not sure | Default to local | `references/local-components.md` | +| Goal | Shape | Reference | +| ------------------------------------------------- | ---------------- | ----------------------------------- | +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | Read exactly one reference file before proceeding. @@ -111,7 +111,7 @@ export const listUnread = query({ userId: v.string(), message: v.string(), read: v.boolean(), - }) + }), ), handler: async (ctx, args) => { return await ctx.db @@ -234,12 +234,16 @@ export const sendNotification = mutation({ ```ts // Bad: parent app table IDs are not valid component validators -args: { userId: v.id("users") } +args: { + userId: v.id("users"); +} ``` ```ts // Good: treat parent-owned IDs as strings at the boundary -args: { userId: v.string() } +args: { + userId: v.string(); +} ``` ### Advanced Patterns diff --git a/.windsurf/skills/convex-migration-helper/SKILL.md b/.windsurf/skills/convex-migration-helper/SKILL.md index 97f64c1a..4a4ed167 100644 --- a/.windsurf/skills/convex-migration-helper/SKILL.md +++ b/.windsurf/skills/convex-migration-helper/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-migration-helper -description: Plans and executes safe Convex schema and data migrations using the widen-migrate-narrow workflow and the @convex-dev/migrations component. Use this skill when a deployment fails schema validation, existing documents need backfilling, fields need adding or removing or changing type, tables need splitting or merging, or a zero-downtime migration strategy is needed. Also use when the user mentions breaking schema changes, multi-deploy rollouts, or data transformations on existing Convex tables. +description: Plans Convex schema and data migrations with widen-migrate-narrow and @convex-dev/migrations. Use for breaking schema changes, backfills, table reshaping, or zero-downtime rollouts. --- # Convex Migration Helper @@ -55,13 +55,13 @@ Unless you are certain, prefer deprecating fields over deleting them. Mark the f // Before users: defineTable({ name: v.string(), -}) +}); // After - safe, new field is optional users: defineTable({ name: v.string(), bio: v.optional(v.string()), -}) +}); ``` ### Adding New Table @@ -70,7 +70,7 @@ users: defineTable({ posts: defineTable({ userId: v.id("users"), title: v.string(), -}).index("by_user", ["userId"]) +}).index("by_user", ["userId"]); ``` ### Adding Index @@ -79,8 +79,7 @@ posts: defineTable({ users: defineTable({ name: v.string(), email: v.string(), -}) - .index("by_email", ["email"]) +}).index("by_email", ["email"]); ``` ## Breaking Changes: The Deployment Workflow diff --git a/.windsurf/skills/convex-migration-helper/references/migration-patterns.md b/.windsurf/skills/convex-migration-helper/references/migration-patterns.md index 219583e0..53b4946f 100644 --- a/.windsurf/skills/convex-migration-helper/references/migration-patterns.md +++ b/.windsurf/skills/convex-migration-helper/references/migration-patterns.md @@ -9,7 +9,7 @@ Common migration patterns, zero-downtime strategies, and verification techniques users: defineTable({ name: v.string(), role: v.optional(v.union(v.literal("user"), v.literal("admin"))), -}) +}); // Migration: backfill the field export const addDefaultRole = migrations.define({ @@ -25,7 +25,7 @@ export const addDefaultRole = migrations.define({ users: defineTable({ name: v.string(), role: v.union(v.literal("user"), v.literal("admin")), -}) +}); ``` ## Deleting a Field diff --git a/.windsurf/skills/convex-migration-helper/references/migrations-component.md b/.windsurf/skills/convex-migration-helper/references/migrations-component.md index c80522f2..95ec2921 100644 --- a/.windsurf/skills/convex-migration-helper/references/migrations-component.md +++ b/.windsurf/skills/convex-migration-helper/references/migrations-component.md @@ -151,8 +151,7 @@ Process only matching documents instead of the full table: ```typescript export const fixEmptyNames = migrations.define({ table: "users", - customRange: (query) => - query.withIndex("by_name", (q) => q.eq("name", "")), + customRange: (query) => query.withIndex("by_name", (q) => q.eq("name", "")), migrateOne: () => ({ name: "" }), }); ``` diff --git a/.windsurf/skills/convex-performance-audit/SKILL.md b/.windsurf/skills/convex-performance-audit/SKILL.md index 9d92b33c..f2554dca 100644 --- a/.windsurf/skills/convex-performance-audit/SKILL.md +++ b/.windsurf/skills/convex-performance-audit/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-performance-audit -description: Audits and optimizes Convex application performance across hot-path reads, write contention, subscription cost, and function limits. Use this skill when a Convex feature is slow or expensive, npx convex insights shows high bytes or documents read, OCC conflict errors or mutation retries appear, subscriptions or UI updates are costly, functions hit execution or transaction limits, or the user mentions performance, latency, read amplification, or invalidation problems in a Convex app. +description: Audits Convex performance for reads, subscriptions, write contention, and function limits. Use for slow features, insights findings, OCC conflicts, or read amplification. --- # Convex Performance Audit @@ -43,13 +43,13 @@ Start with the strongest signal available: After gathering signals, identify the problem class and read the matching reference file. -| Signal | Reference | -|---|---| -| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | -| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | -| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | -| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | -| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | +| Signal | Reference | +| -------------------------------------------------------------- | ----------------------------------------- | +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. @@ -107,7 +107,7 @@ After finding one problem, inspect both sibling readers and sibling writers for Examples: - If one list query switches from full docs to a digest table, inspect the other list queries for that table -- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one mutation isolates a frequently-updated field or splits a hot document, inspect the other writers to the same table - If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. @@ -119,7 +119,7 @@ Confirm all of these: 1. Results are the same as before, no dropped records 2. Eliminated reads or writes are no longer in the path where expected 3. Fallback behavior works when denormalized or indexed fields are missing -4. New writes avoid unnecessary invalidation when data is unchanged +4. Frequently-updated fields are isolated from widely-read documents where needed 5. Every relevant sibling reader and writer was inspected, not just the original function ## Reference Files diff --git a/.windsurf/skills/convex-performance-audit/references/function-budget.md b/.windsurf/skills/convex-performance-audit/references/function-budget.md index c71d14cb..d4d4aa5a 100644 --- a/.windsurf/skills/convex-performance-audit/references/function-budget.md +++ b/.windsurf/skills/convex-performance-audit/references/function-budget.md @@ -10,17 +10,17 @@ Convex functions run inside transactions with budgets for time, reads, and write These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. -| Resource | Limit | -|---|---| -| Query/mutation execution time | 1 second (user code only, excludes DB operations) | -| Action execution time | 10 minutes | -| Data read per transaction | 16 MiB | -| Data written per transaction | 16 MiB | +| Resource | Limit | +| --------------------------------- | ----------------------------------------------------- | +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | | Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | -| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | -| Documents written per transaction | 16,000 | -| Individual document size | 1 MiB | -| Function return value size | 16 MiB | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | ## Symptoms diff --git a/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md b/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md index e3e44b15..e003e052 100644 --- a/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md +++ b/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md @@ -121,13 +121,15 @@ Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need // Bad: two indexes where one would do defineTable({ team: v.id("teams"), user: v.id("users") }) .index("by_team", ["team"]) - .index("by_team_and_user", ["team", "user"]) + .index("by_team_and_user", ["team", "user"]); ``` ```ts // Good: single compound index serves both query patterns -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team_and_user", ["team", "user"]) +defineTable({ team: v.id("teams"), user: v.id("users") }).index( + "by_team_and_user", + ["team", "user"], +); ``` Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. @@ -170,9 +172,7 @@ const ownerName = project.ownerName ?? "Unknown owner"; ```ts // Good: denormalized data is an optimization, not the only source of truth const ownerName = - project.ownerName ?? - (await ctx.db.get(project.ownerId))?.name ?? - null; + project.ownerName ?? (await ctx.db.get(project.ownerId))?.name ?? null; ``` Bad lookup map pattern: @@ -241,35 +241,33 @@ const projects = await ctx.db .take(20); ``` -## 4. Skip No-Op Writes - -No-op writes still cost work in Convex: +## 4. Isolate Frequently-Updated Fields -- invalidation -- replication -- trigger execution -- downstream sync +Convex already no-ops unchanged writes. The invalidation problem here is real writes hitting documents that many queries subscribe to. -Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. +Move high-churn fields like `lastSeen`, counters, presence, or ephemeral status off widely-read documents when most readers do not need them. -Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. +Apply this across sibling writers too. Splitting one write path does not help much if three other mutations still update the same widely-read document. ```ts -// Bad: patching unchanged values still triggers invalidation and downstream work -await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, +// Bad: every presence heartbeat invalidates subscribers to the whole profile +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, + lastSeen: Date.now(), }); ``` ```ts -// Good: only write when something actually changed -if (settings.theme !== args.theme || settings.locale !== args.locale) { - await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, - }); -} +// Good: keep profile reads stable, move heartbeat updates to a separate document +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, +}); + +await ctx.db.patch(presence._id, { + lastSeen: Date.now(), +}); ``` ## 5. Match Consistency To Read Patterns diff --git a/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md b/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md index a96d0466..1da43801 100644 --- a/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md +++ b/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md @@ -73,42 +73,30 @@ await ctx.db.patch(shardId, { count: shard!.count + 1 }); Aggregate the shards in a query or scheduled job when you need the total. -### 3. Skip no-op writes +### 3. Move non-critical work to scheduled functions -Writes that do not change data still participate in conflict detection and trigger invalidation. +If a mutation does primary work plus secondary bookkeeping (analytics, non-critical notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. ```ts -// Bad: patches even when nothing changed -await ctx.db.patch(doc._id, { status: args.status }); -``` - -```ts -// Good: only write when the value actually differs -if (doc.status !== args.status) { - await ctx.db.patch(doc._id, { status: args.status }); -} -``` - -### 4. Move non-critical work to scheduled functions - -If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. - -```ts -// Bad: analytics update in the same transaction as the user action -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +// Bad: canonical write and derived work happen in the same transaction +await ctx.db.patch(userId, { name: args.name }); +await ctx.db.insert("userUpdateAnalytics", { + userId, + kind: "name_changed", + name: args.name, +}); ``` ```ts -// Good: schedule the bookkeeping so the primary transaction is smaller -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { - event: "action", +// Good: keep the primary write small, defer the analytics work +await ctx.db.patch(userId, { name: args.name }); +await ctx.scheduler.runAfter(0, internal.users.recordNameChangeAnalytics, { userId, + name: args.name, }); ``` -### 5. Combine competing writes +### 4. Combine competing writes If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. diff --git a/.windsurf/skills/convex-quickstart/SKILL.md b/.windsurf/skills/convex-quickstart/SKILL.md index 792bba3d..f506b3e4 100644 --- a/.windsurf/skills/convex-quickstart/SKILL.md +++ b/.windsurf/skills/convex-quickstart/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-quickstart -description: Initializes a new Convex project from scratch or adds Convex to an existing app. Use this skill when starting a new project with Convex, scaffolding with npm create convex@latest, adding Convex to an existing React, Next.js, Vue, Svelte, or other frontend, wiring up ConvexProvider, configuring environment variables for the deployment URL, or running npx convex dev for the first time, even if the user just says "set up Convex" or "add a backend." +description: Creates or adds Convex to an app. Use for new Convex projects, npm create convex@latest, frontend setup, env vars, or the first npx convex dev run. --- # Convex Quickstart @@ -32,15 +32,15 @@ Use the official scaffolding tool. It creates a complete project with the fronte ### Pick a template -| Template | Stack | -|----------|-------| -| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | -| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | -| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | -| `nextjs-clerk` | Next.js + Clerk auth | -| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | -| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | -| `bare` | Convex backend only, no frontend | +| Template | Stack | +| -------------------------- | ----------------------------------------- | +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. @@ -77,6 +77,7 @@ npm install **Ask the user to run this themselves:** Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: + - Create a Convex project and dev deployment - Write the deployment URL to `.env.local` - Create the `convex/` directory with generated types @@ -111,6 +112,7 @@ my-app/ ``` The template already has: + - `ConvexProvider` wired into the app root - Correct env var names for the framework - Tailwind and shadcn/ui ready (for shadcn templates) @@ -141,7 +143,9 @@ Create the `ConvexReactClient` at module scope, not inside a component: ```tsx // Bad: re-creates the client on every render function App() { - const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + const convex = new ConvexReactClient( + import.meta.env.VITE_CONVEX_URL as string, + ); return ...; } @@ -192,7 +196,11 @@ export function ConvexClientProvider({ children }: { children: ReactNode }) { // app/layout.tsx import { ConvexClientProvider } from "./ConvexClientProvider"; -export default function RootLayout({ children }: { children: React.ReactNode }) { +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { return ( @@ -218,11 +226,11 @@ For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the mat The env var name depends on the framework: -| Framework | Variable | -|-----------|----------| -| Vite | `VITE_CONVEX_URL` | -| Next.js | `NEXT_PUBLIC_CONVEX_URL` | -| Remix | `CONVEX_URL` | +| Framework | Variable | +| ------------ | ------------------------ | +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | | React Native | `EXPO_PUBLIC_CONVEX_URL` | `npx convex dev` writes the correct variable to `.env.local` automatically. @@ -299,7 +307,9 @@ function Tasks() { return (
- {tasks?.map((t) =>
{t.text}
)} + {tasks?.map((t) => ( +
{t.text}
+ ))}
); } diff --git a/.windsurf/skills/convex-setup-auth/SKILL.md b/.windsurf/skills/convex-setup-auth/SKILL.md index 0fa00e2f..59a92285 100644 --- a/.windsurf/skills/convex-setup-auth/SKILL.md +++ b/.windsurf/skills/convex-setup-auth/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-setup-auth -description: Sets up Convex authentication with user management, identity mapping, and access control. Use this skill when adding login or signup to a Convex app, configuring Convex Auth, Clerk, WorkOS AuthKit, Auth0, or custom JWT providers, wiring auth.config.ts, protecting queries and mutations with ctx.auth.getUserIdentity(), creating a users table with identity mapping, or setting up role-based access control, even if the user just says "add auth" or "make it require login." +description: Sets up Convex auth, identity mapping, and access control. Use for login, auth providers, users tables, protected functions, or roles in a Convex app. --- # Convex Authentication Setup @@ -102,7 +102,7 @@ export const getMyProfile = query({ return await ctx.db .query("users") .withIndex("by_tokenIdentifier", (q) => - q.eq("tokenIdentifier", identity.tokenIdentifier) + q.eq("tokenIdentifier", identity.tokenIdentifier), ) .unique(); }, diff --git a/.windsurf/skills/convex/SKILL.md b/.windsurf/skills/convex/SKILL.md new file mode 100644 index 00000000..9e8ebbd8 --- /dev/null +++ b/.windsurf/skills/convex/SKILL.md @@ -0,0 +1,47 @@ +--- +name: convex +description: Routes general Convex requests to the right project skill. Use when the user asks which Convex skill to use or gives an underspecified Convex app task. +--- + +# Convex + +Use this as the routing skill for Convex work in this repo. + +If a more specific Convex skill clearly matches the request, use that instead. + +## Start Here + +If the project does not already have Convex AI guidance installed, or the existing guidance looks stale, strongly recommend installing it first. + +Preferred: + +```bash +npx convex ai-files install +``` + +This installs or refreshes the managed Convex AI files. It is the recommended starting point for getting the official Convex guidelines in place and following the current Convex AI setup described in the docs: + +- [Convex AI docs](https://docs.convex.dev/ai) + +Simple fallback: + +- [convex_rules.txt](https://convex.link/convex_rules.txt) + +Prefer `npx convex ai-files install` over copying rules by hand when possible. + +## Route to the Right Skill + +After that, use the most specific Convex skill for the task: + +- New project or adding Convex to an app: `convex-quickstart` +- Authentication setup: `convex-setup-auth` +- Building a reusable Convex component: `convex-create-component` +- Planning or running a migration: `convex-migration-helper` +- Investigating performance issues: `convex-performance-audit` + +If one of those clearly matches the user's goal, switch to it instead of staying in this skill. + +## When Not to Use + +- The user has already named a more specific Convex workflow +- Another Convex skill obviously fits the request better diff --git a/AGENTS.md b/AGENTS.md index 3cb60907..e942f4ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,7 @@ A Flutter desktop app for creating interactive Valorant game strategies. See `RE ### Key caveats - **FVM is required.** Flutter is pinned to `3.38.4` via `.fvmrc`. Always prefix Flutter/Dart commands with `fvm` (e.g. `fvm flutter run`, `fvm dart run`). +- **Cloud is still dev-build only.** The cloud backend has not shipped publicly yet, so backwards compatibility with existing dev cloud data is not automatically required. If a change breaks cloud data/API compatibility, explicitly tell the user first and let them decide whether to wipe/migrate the dev database or take another action. - **`xdg-user-dirs` must be initialized.** The `path_provider` plugin needs XDG user directories. Run `sudo apt-get install -y xdg-user-dirs && xdg-user-dirs-update` if the app crashes with `MissingPlatformDirectoryException`. - **Linux build deps.** `clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-14-dev` must be installed for Linux desktop builds. - **Code generation.** After changing Hive models, Riverpod providers, or JSON-serializable classes, regenerate with: `fvm flutter pub run build_runner build --delete-conflicting-outputs`. diff --git a/README.md b/README.md index 21e68a62..4d4f9d7c 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,22 @@ flutter pub get flutter run ``` +### Windows dev OAuth callbacks +Discord OAuth redirects back into the desktop app through the `icarus://auth/callback` +protocol. On Windows, the installed app normally owns that protocol handler, so a +dev build may not receive the browser callback. + +For a temporary dev session, run the Windows build with the force protocol +registration flag: + +```powershell +fvm flutter run -d windows --dart-define=ICARUS_FORCE_PROTOCOL_REGISTER=true +``` + +This rewrites the current user's `icarus://` handler to the debug executable. +After testing OAuth, launch the installed Icarus app once to restore the handler +back to the installed build. + ## Build ```bash flutter build diff --git a/assets/icarus-icon.webp b/assets/icarus-icon.webp new file mode 100644 index 00000000..e77acefc Binary files /dev/null and b/assets/icarus-icon.webp differ diff --git a/convex/_generated/ai/ai-files.state.json b/convex/_generated/ai/ai-files.state.json index a8f6e5f4..41c8ea62 100644 --- a/convex/_generated/ai/ai-files.state.json +++ b/convex/_generated/ai/ai-files.state.json @@ -1,9 +1,10 @@ { - "guidelinesHash": "294b619f8246c26bd6bfb6a57122503f0e2149872fc6b26609b7a95bfefaf2b8", + "guidelinesHash": "62d72acb9afcc18f658d88dd772f34b5b1da5fa60ef0402e57a784d97c458e57", "agentsMdSectionHash": "bbf30bd25ceea0aefd279d62e1cb2b4c207fcb712b69adf26f3d02b296ffc7b2", "claudeMdHash": "bbf30bd25ceea0aefd279d62e1cb2b4c207fcb712b69adf26f3d02b296ffc7b2", - "agentSkillsSha": "dc8ff761cfe4da450af2ea8a9ec708f737064bed", + "agentSkillsSha": "d0fa8085af313029add5740f67198aa42ca60c8d", "installedSkillNames": [ + "convex", "convex-create-component", "convex-migration-helper", "convex-performance-audit", diff --git a/convex/_generated/ai/guidelines.md b/convex/_generated/ai/guidelines.md index 151cdf71..e41beddc 100644 --- a/convex/_generated/ai/guidelines.md +++ b/convex/_generated/ai/guidelines.md @@ -1,78 +1,90 @@ # Convex guidelines + ## Function guidelines + ### Http endpoint syntax + - HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example: + ```typescript import { httpRouter } from "convex/server"; import { httpAction } from "./_generated/server"; const http = httpRouter(); http.route({ - path: "/echo", - method: "POST", - handler: httpAction(async (ctx, req) => { + path: "/echo", + method: "POST", + handler: httpAction(async (ctx, req) => { const body = await req.bytes(); return new Response(body, { status: 200 }); - }), + }), }); ``` + - HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`. ### Validators + - Below is an example of an array validator: + ```typescript import { mutation } from "./_generated/server"; import { v } from "convex/values"; export default mutation({ -args: { + args: { simpleArray: v.array(v.union(v.string(), v.number())), -}, -handler: async (ctx, args) => { + }, + handler: async (ctx, args) => { //... -}, + }, }); ``` + - Below is an example of a schema with validators that codify a discriminated union type: + ```typescript import { defineSchema, defineTable } from "convex/server"; import { v } from "convex/values"; export default defineSchema({ - results: defineTable( - v.union( - v.object({ - kind: v.literal("error"), - errorMessage: v.string(), - }), - v.object({ - kind: v.literal("success"), - value: v.number(), - }), - ), - ) + results: defineTable( + v.union( + v.object({ + kind: v.literal("error"), + errorMessage: v.string(), + }), + v.object({ + kind: v.literal("success"), + value: v.number(), + }), + ), + ), }); ``` + - Here are the valid Convex types along with their respective validators: -Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes | -| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| Id | string | `doc._id` | `v.id(tableName)` | | -| Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. | -| Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. | -| Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. | -| Boolean | boolean | `true` | `v.boolean()` | -| String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. | -| Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. | -| Array | Array | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. | -| Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". | -| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "_". | + Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes | + | ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + | Id | string | `doc._id` | `v.id(tableName)` | | + | Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. | + | Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. | + | Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. | + | Boolean | boolean | `true` | `v.boolean()` | + | String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. | + | Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. | + | Array | Array | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. | + | Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". | +| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "\_". | ### Function registration + - Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`. - Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private. - You CANNOT register a function through the `api` or `internal` objects. - ALWAYS include argument validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. ### Function calling + - Use `ctx.runQuery` to call a query from a query, mutation, or action. - Use `ctx.runMutation` to call a mutation from a mutation or action. - Use `ctx.runAction` to call an action from an action. @@ -80,6 +92,7 @@ Convex Type | TS/JS type | Example Usage | Validator for argument val - Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions. - All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls. - When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example, + ``` export const f = query({ args: { name: v.string() }, @@ -98,6 +111,7 @@ export const g = query({ ``` ### Function references + - Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`. - Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`. - Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`. @@ -105,6 +119,7 @@ export const g = query({ - Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`. ### Pagination + - Define pagination using the following syntax: ```ts @@ -112,17 +127,19 @@ import { v } from "convex/values"; import { query, mutation } from "./_generated/server"; import { paginationOptsValidator } from "convex/server"; export const listWithExtraArg = query({ - args: { paginationOpts: paginationOptsValidator, author: v.string() }, - handler: async (ctx, args) => { - return await ctx.db - .query("messages") - .withIndex("by_author", (q) => q.eq("author", args.author)) - .order("desc") - .paginate(args.paginationOpts); - }, + args: { paginationOpts: paginationOptsValidator, author: v.string() }, + handler: async (ctx, args) => { + return await ctx.db + .query("messages") + .withIndex("by_author", (q) => q.eq("author", args.author)) + .order("desc") + .paginate(args.paginationOpts); + }, }); ``` + Note: `paginationOpts` is an object with the following properties: + - `numItems`: the maximum number of documents to return (the validator is `v.number()`) - `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`) - A query that ends in `.paginate()` returns an object that has the following properties: @@ -130,8 +147,8 @@ Note: `paginationOpts` is an object with the following properties: - isDone (a boolean that represents whether or not this is the last page of documents) - continueCursor (a string that represents the cursor to use to fetch the next page of documents) - ## Schema guidelines + - Always define your schema in `convex/schema.ts`. - Always import the schema definition functions from `convex/server`. - System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`. @@ -141,8 +158,10 @@ Note: `paginationOpts` is an object with the following properties: - Separate high-churn operational data (e.g. heartbeats, online status, typing indicators) from stable profile data. Storing frequently updated fields on a shared document forces every write to contend with reads of the entire document. Instead, create a dedicated table for the high-churn data with a foreign key back to the parent record. ## Authentication guidelines + - Convex supports JWT-based authentication through `convex/auth.config.ts`. ALWAYS create this file when using authentication. Without it, `ctx.auth.getUserIdentity()` will always return `null`. - Example `convex/auth.config.ts`: + ```typescript export default { providers: [ @@ -153,11 +172,14 @@ export default { ], }; ``` + The `domain` must be the issuer URL of the JWT provider. Convex fetches `{domain}/.well-known/openid-configuration` to discover the JWKS endpoint. The `applicationID` is checked against the JWT `aud` (audience) claim. + - Use `ctx.auth.getUserIdentity()` to get the authenticated user's identity in any query, mutation, or action. This returns `null` if the user is not authenticated, or a `UserIdentity` object with fields like `subject`, `issuer`, `name`, `email`, etc. The `subject` field is the unique user identifier. - In Convex `UserIdentity`, `tokenIdentifier` is guaranteed and is the canonical stable identifier for the authenticated identity. For any auth-linked database lookup or ownership check, prefer `identity.tokenIdentifier` over `identity.subject`. Do NOT use `identity.subject` alone as a global identity key. - NEVER accept a `userId` or any user identifier as a function argument for authorization purposes. Always derive the user identity server-side via `ctx.auth.getUserIdentity()`. - When using an external auth provider with Convex on the client, use `ConvexProviderWithAuth` instead of `ConvexProvider`: + ```tsx import { ConvexProviderWithAuth, ConvexReactClient } from "convex/react"; @@ -171,45 +193,51 @@ function App({ children }: { children: React.ReactNode }) { ); } ``` + The `useAuth` prop must return `{ isLoading, isAuthenticated, fetchAccessToken }`. Do NOT use plain `ConvexProvider` when authentication is needed — it will not send tokens with requests. ## Typescript guidelines -- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table. + +- You can use the helper typescript type `Id` imported from './\_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table. - Use `Doc<"tableName">` from `./_generated/dataModel` to get the full document type for a table. - Use `QueryCtx`, `MutationCtx`, `ActionCtx` from `./_generated/server` for typing function contexts. NEVER use `any` for ctx parameters — always use the proper context type. - If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record, string>`. Below is an example of using `Record` with an `Id` type in a query: + ```ts import { query } from "./_generated/server"; import { Doc, Id } from "./_generated/dataModel"; export const exampleQuery = query({ - args: { userIds: v.array(v.id("users")) }, - handler: async (ctx, args) => { - const idToUsername: Record, string> = {}; - for (const userId of args.userIds) { - const user = await ctx.db.get("users", userId); - if (user) { - idToUsername[user._id] = user.username; - } - } - - return idToUsername; - }, + args: { userIds: v.array(v.id("users")) }, + handler: async (ctx, args) => { + const idToUsername: Record, string> = {}; + for (const userId of args.userIds) { + const user = await ctx.db.get("users", userId); + if (user) { + idToUsername[user._id] = user.username; + } + } + + return idToUsername; + }, }); ``` + - Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`. ## Full text search guidelines + - A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like: const messages = await ctx.db - .query("messages") - .withSearchIndex("search_body", (q) => - q.search("body", "hello hi").eq("channel", "#general"), - ) - .take(10); +.query("messages") +.withSearchIndex("search_body", (q) => +q.search("body", "hello hi").eq("channel", "#general"), +) +.take(10); ## Query guidelines + - Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead. - If the user does not explicitly tell you to return all results from a query you should ALWAYS return a bounded collection instead. So that is instead of using `.collect()` you should use `.take()` or paginate on database queries. This prevents future performance issues when tables grow in an unbounded way. - Never use `.collect().length` to count rows. Convex has no built-in count operator, so if you need a count that stays efficient at scale, maintain a denormalized counter in a separate document and update it in your mutations. @@ -217,39 +245,46 @@ const messages = await ctx.db - Convex mutations are transactions with limits on the number of documents read and written. If a mutation needs to process more documents than fit in a single transaction (e.g. bulk deletion on a large table), process a batch with `.take(n)` and then call `ctx.scheduler.runAfter(0, api.myModule.myMutation, args)` to schedule itself to continue. This way each invocation stays within transaction limits. - Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query. - When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax. + ### Ordering + - By default Convex always returns documents in ascending `_creationTime` order. - You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending. - Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans. - ## Mutation guidelines + - Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })` - Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })` ## Action guidelines + - Always add `"use node";` to the top of files containing actions that use Node.js built-in modules. - Never add `"use node";` to a file that also exports queries or mutations. Only actions can run in the Node.js runtime; queries and mutations must stay in the default Convex runtime. If you need Node.js built-ins alongside queries or mutations, put the action in a separate file. - `fetch()` is available in the default Convex runtime. You do NOT need `"use node";` just to use `fetch()`. - Never use `ctx.db` inside of an action. Actions don't have access to the database. - Below is an example of the syntax for an action: + ```ts import { action } from "./_generated/server"; export const exampleAction = action({ - args: {}, - handler: async (ctx, args) => { - console.log("This action does not return anything"); - return null; - }, + args: {}, + handler: async (ctx, args) => { + console.log("This action does not return anything"); + return null; + }, }); ``` ## Scheduling guidelines + ### Cron guidelines + - Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers. - Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods. - Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example, + ```ts import { cronJobs } from "convex/server"; import { internal } from "./_generated/api"; @@ -269,14 +304,16 @@ crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {}); export default crons; ``` -- You can register Convex functions within `crons.ts` just like any other file. -- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file. +- You can register Convex functions within `crons.ts` just like any other file. +- If a cron calls an internal function, always import the `internal` object from '\_generated/api', even if the internal function is registered in the same file. ## Testing guidelines + - Use `convex-test` with `vitest` and `@edge-runtime/vm` to test Convex functions. Always install the latest versions of these packages. Configure vitest with `environment: "edge-runtime"` in `vitest.config.ts`. Test files go inside the `convex/` directory. You must pass a module map from `import.meta.glob` to `convexTest`: + ```typescript /// import { convexTest } from "convex-test"; @@ -293,13 +330,16 @@ test("some behavior", async () => { expect(messages).toMatchObject([{ body: "Hi!", author: "Sarah" }]); }); ``` + The `modules` argument is required so convex-test can discover and load function files. The `/// ` directive is needed for TypeScript to recognize `import.meta.glob`. ## File storage guidelines + - The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist. - Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata. Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`. + ``` import { query } from "./_generated/server"; import { Id } from "./_generated/dataModel"; @@ -321,6 +361,5 @@ export const exampleQuery = query({ }, }); ``` -- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage. - +- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage. diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index 97f292b1..8f77e1aa 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -20,6 +20,7 @@ import type * as lib_opTypes from "../lib/opTypes.js"; import type * as lineups from "../lineups.js"; import type * as ops from "../ops.js"; import type * as pages from "../pages.js"; +import type * as shares from "../shares.js"; import type * as strategies from "../strategies.js"; import type * as users from "../users.js"; @@ -42,6 +43,7 @@ declare const fullApi: ApiFromModules<{ lineups: typeof lineups; ops: typeof ops; pages: typeof pages; + shares: typeof shares; strategies: typeof strategies; users: typeof users; }>; diff --git a/convex/elements.ts b/convex/elements.ts index f41ae5fa..4653aa8d 100644 --- a/convex/elements.ts +++ b/convex/elements.ts @@ -38,3 +38,41 @@ export const listForPage = query({ })); }, }); + +export const listForStrategy = query({ + args: { + strategyPublicId: v.string(), + }, + handler: async (ctx, args) => { + const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); + await assertStrategyRole(ctx, strategy, "viewer"); + + const pages = await ctx.db + .query("pages") + .withIndex("by_strategyId", (q) => q.eq("strategyId", strategy._id)) + .collect(); + const pagePublicIds = new Map( + pages.map((page) => [page._id, page.publicId]), + ); + + const elements = await ctx.db + .query("elements") + .withIndex("by_strategyId", (q) => q.eq("strategyId", strategy._id)) + .collect(); + + return elements + .sort((a, b) => a.sortIndex - b.sortIndex) + .map((element) => ({ + publicId: element.publicId, + strategyPublicId: strategy.publicId, + pagePublicId: pagePublicIds.get(element.pageId) ?? "", + elementType: element.elementType, + payload: element.payload, + sortIndex: element.sortIndex, + revision: element.revision, + deleted: element.deleted, + createdAt: element.createdAt, + updatedAt: element.updatedAt, + })); + }, +}); diff --git a/convex/folders.ts b/convex/folders.ts index 31bd20ca..b435df97 100644 --- a/convex/folders.ts +++ b/convex/folders.ts @@ -1,46 +1,144 @@ +import type { Doc, Id } from "./_generated/dataModel"; +import type { QueryCtx, MutationCtx } from "./_generated/server"; import { mutation, query } from "./_generated/server"; import { v } from "convex/values"; -import { requireCurrentUser } from "./lib/auth"; +import { + assertFolderRole, + getEffectiveFolderRoleForUser, + requireCurrentUser, +} from "./lib/auth"; import { getFolderByPublicId } from "./lib/entities"; +type FolderScope = "owned" | "shared" | "all"; +type AnyCtx = QueryCtx | MutationCtx; + +function matchesScope( + ownerId: string, + userId: string, + scope: FolderScope, +): boolean { + if (scope === "all") { + return true; + } + if (scope === "owned") { + return ownerId === userId; + } + return ownerId !== userId; +} + +async function listAccessibleFoldersForScope( + ctx: AnyCtx, + userId: Id<"users">, + scope: FolderScope, +): Promise< + Array<{ folder: Doc<"folders">; role: "owner" | "editor" | "viewer" }> +> { + const candidates = new Map, Doc<"folders">>(); + + if (scope === "owned" || scope === "all") { + const owned = await ctx.db + .query("folders") + .withIndex("by_ownerId", (q) => q.eq("ownerId", userId)) + .collect(); + for (const folder of owned) { + candidates.set(folder._id, folder); + } + } + + if (scope === "shared" || scope === "all") { + const directShares = await ctx.db + .query("folderCollaborators") + .withIndex("by_userId", (q) => q.eq("userId", userId)) + .collect(); + const queue = ( + await Promise.all(directShares.map((share) => ctx.db.get(share.folderId))) + ).filter( + (folder): folder is Doc<"folders"> => + folder !== null && folder.ownerId !== userId, + ); + + while (queue.length > 0) { + const folder = queue.shift()!; + if (candidates.has(folder._id)) { + continue; + } + candidates.set(folder._id, folder); + const children = await ctx.db + .query("folders") + .withIndex("by_parentFolderId", (q) => + q.eq("parentFolderId", folder._id), + ) + .collect(); + queue.push(...children.filter((child) => child.ownerId !== userId)); + } + } + + const results: Array<{ + folder: Doc<"folders">; + role: "owner" | "editor" | "viewer"; + }> = []; + + for (const folder of candidates.values()) { + const role = await getEffectiveFolderRoleForUser(ctx, folder, userId); + if (role === null) { + continue; + } + if (!matchesScope(folder.ownerId, userId, scope)) { + continue; + } + results.push({ folder, role }); + } + + return results; +} + +const folderScopeValidator = v.optional( + v.union(v.literal("owned"), v.literal("shared"), v.literal("all")), +); + export const listForParent = query({ args: { parentFolderPublicId: v.optional(v.string()), + scope: folderScopeValidator, }, handler: async (ctx, args) => { const user = await requireCurrentUser(ctx); + const scope = args.scope ?? "owned"; - let parentFolderId; + let parentFolderId: Id<"folders"> | undefined; if (args.parentFolderPublicId !== undefined) { const parent = await getFolderByPublicId(ctx, args.parentFolderPublicId); - if (parent.ownerId !== user._id) { - throw new Error("Forbidden"); - } + await assertFolderRole(ctx, parent, "viewer"); parentFolderId = parent._id; } - const folders = await ctx.db - .query("folders") - .withIndex("by_ownerId", (q) => q.eq("ownerId", user._id)) - .collect(); + const accessible = await listAccessibleFoldersForScope( + ctx, + user._id, + scope, + ); + const folderLookup = new Map( + accessible.map(({ folder }) => [folder._id, folder]), + ); - return folders - .filter((f) => f.parentFolderId === parentFolderId) - .sort((a, b) => a.createdAt - b.createdAt) - .map((f) => ({ - publicId: f.publicId, - name: f.name, - iconCodePoint: f.iconCodePoint ?? null, - iconFontFamily: f.iconFontFamily ?? null, - iconFontPackage: f.iconFontPackage ?? null, - color: f.color ?? null, - customColorValue: f.customColorValue ?? null, + return accessible + .filter(({ folder }) => folder.parentFolderId === parentFolderId) + .sort((a, b) => a.folder.createdAt - b.folder.createdAt) + .map(({ folder, role }) => ({ + publicId: folder.publicId, + name: folder.name, + iconCodePoint: folder.iconCodePoint ?? null, + iconFontFamily: folder.iconFontFamily ?? null, + iconFontPackage: folder.iconFontPackage ?? null, + color: folder.color ?? null, + customColorValue: folder.customColorValue ?? null, parentFolderPublicId: - f.parentFolderId === undefined + folder.parentFolderId === undefined ? null - : folders.find((p) => p._id === f.parentFolderId)?.publicId ?? null, - createdAt: f.createdAt, - updatedAt: f.updatedAt, + : (folderLookup.get(folder.parentFolderId)?.publicId ?? null), + createdAt: folder.createdAt, + updatedAt: folder.updatedAt, + role, })); }, }); @@ -60,10 +158,11 @@ export const create = mutation({ const user = await requireCurrentUser(ctx); const now = Date.now(); - let parentFolderId; + let parentFolderId: Id<"folders"> | undefined; if (args.parentFolderPublicId !== undefined) { const parent = await getFolderByPublicId(ctx, args.parentFolderPublicId); - if (parent.ownerId !== user._id) { + const { role } = await assertFolderRole(ctx, parent, "owner"); + if (role !== "owner") { throw new Error("Forbidden"); } parentFolderId = parent._id; @@ -113,10 +212,10 @@ export const update = mutation({ clearCustomColorValue: v.optional(v.boolean()), }, handler: async (ctx, args) => { - const user = await requireCurrentUser(ctx); const folder = await getFolderByPublicId(ctx, args.folderPublicId); + const { role } = await assertFolderRole(ctx, folder, "owner"); - if (folder.ownerId !== user._id) { + if (role !== "owner") { throw new Error("Forbidden"); } @@ -163,30 +262,38 @@ export const update = mutation({ }); export const listAll = query({ - args: {}, - handler: async (ctx) => { + args: { + scope: folderScopeValidator, + }, + handler: async (ctx, args) => { const user = await requireCurrentUser(ctx); - const folders = await ctx.db - .query("folders") - .withIndex("by_ownerId", (q) => q.eq("ownerId", user._id)) - .collect(); + const scope = args.scope ?? "all"; + const accessible = await listAccessibleFoldersForScope( + ctx, + user._id, + scope, + ); + const folderLookup = new Map( + accessible.map(({ folder }) => [folder._id, folder]), + ); - return folders - .sort((a, b) => a.createdAt - b.createdAt) - .map((f) => ({ - publicId: f.publicId, - name: f.name, - iconCodePoint: f.iconCodePoint ?? null, - iconFontFamily: f.iconFontFamily ?? null, - iconFontPackage: f.iconFontPackage ?? null, - color: f.color ?? null, - customColorValue: f.customColorValue ?? null, + return accessible + .sort((a, b) => a.folder.createdAt - b.folder.createdAt) + .map(({ folder, role }) => ({ + publicId: folder.publicId, + name: folder.name, + iconCodePoint: folder.iconCodePoint ?? null, + iconFontFamily: folder.iconFontFamily ?? null, + iconFontPackage: folder.iconFontPackage ?? null, + color: folder.color ?? null, + customColorValue: folder.customColorValue ?? null, parentFolderPublicId: - f.parentFolderId === undefined + folder.parentFolderId === undefined ? null - : folders.find((p) => p._id === f.parentFolderId)?.publicId ?? null, - createdAt: f.createdAt, - updatedAt: f.updatedAt, + : (folderLookup.get(folder.parentFolderId)?.publicId ?? null), + createdAt: folder.createdAt, + updatedAt: folder.updatedAt, + role, })); }, }); @@ -197,17 +304,18 @@ export const move = mutation({ parentFolderPublicId: v.optional(v.string()), }, handler: async (ctx, args) => { - const user = await requireCurrentUser(ctx); const folder = await getFolderByPublicId(ctx, args.folderPublicId); + const { role } = await assertFolderRole(ctx, folder, "owner"); - if (folder.ownerId !== user._id) { + if (role !== "owner") { throw new Error("Forbidden"); } - let parentFolderId; + let parentFolderId: Id<"folders"> | undefined; if (args.parentFolderPublicId !== undefined) { const parent = await getFolderByPublicId(ctx, args.parentFolderPublicId); - if (parent.ownerId !== user._id) { + const parentAccess = await assertFolderRole(ctx, parent, "owner"); + if (parentAccess.role !== "owner" || parent.ownerId !== folder.ownerId) { throw new Error("Forbidden"); } parentFolderId = parent._id; @@ -227,10 +335,10 @@ export const deleteFolder = mutation({ folderPublicId: v.string(), }, handler: async (ctx, args) => { - const user = await requireCurrentUser(ctx); const folder = await getFolderByPublicId(ctx, args.folderPublicId); + const { role } = await assertFolderRole(ctx, folder, "owner"); - if (folder.ownerId !== user._id) { + if (role !== "owner") { throw new Error("Forbidden"); } @@ -250,6 +358,22 @@ export const deleteFolder = mutation({ throw new Error("Folder has strategies"); } + const collaborators = await ctx.db + .query("folderCollaborators") + .withIndex("by_folderId", (q) => q.eq("folderId", folder._id)) + .collect(); + for (const collaborator of collaborators) { + await ctx.db.delete(collaborator._id); + } + + const links = await ctx.db + .query("shareLinks") + .withIndex("by_folderId", (q) => q.eq("folderId", folder._id)) + .collect(); + for (const link of links) { + await ctx.db.delete(link._id); + } + await ctx.db.delete(folder._id); return { ok: true }; }, diff --git a/convex/images.ts b/convex/images.ts index 88b5be31..db72a8d4 100644 --- a/convex/images.ts +++ b/convex/images.ts @@ -1,70 +1,204 @@ -import { mutation, query } from "./_generated/server"; +import type { Doc } from "./_generated/dataModel"; +import { mutation, query, type MutationCtx, type QueryCtx } from "./_generated/server"; import { v } from "convex/values"; -import { assertStrategyRole, requireCurrentUser } from "./lib/auth"; -import { - getElementByPublicId, - getPageByPublicId, - getStrategyByPublicId, -} from "./lib/entities"; - -export const registerAssetRef = mutation({ +import { assertStrategyRole } from "./lib/auth"; +import { getStrategyByPublicId } from "./lib/entities"; + +type AnyCtx = MutationCtx | QueryCtx; + +async function getImageAssetByPublicId( + ctx: AnyCtx, + assetPublicId: string, +): Promise | null> { + return await ctx.db + .query("imageAssets") + .withIndex("by_publicId", (q) => q.eq("publicId", assetPublicId)) + .unique(); +} + +function inferFileExtension( + asset: Pick, "fileExtension" | "storagePath">, +): string { + if (asset.fileExtension !== undefined && asset.fileExtension.length > 0) { + return asset.fileExtension; + } + + const legacyPath = asset.storagePath ?? ""; + const match = legacyPath.match(/(\.[A-Za-z0-9]+)(?:$|[?#])/); + return match?.[1]?.toLowerCase() ?? ""; +} + +function decodeObject(payload: string): Record | null { + try { + const decoded = JSON.parse(payload); + if (typeof decoded === "object" && decoded !== null) { + return decoded as Record; + } + } catch (_) { + // Ignore malformed payloads while gathering asset references. + } + return null; +} + +function collectAssetIdFromElementPayload(payload: string): string | null { + const decoded = decodeObject(payload); + if (decoded === null) { + return null; + } + return typeof decoded.id === "string" ? decoded.id : null; +} + +function collectAssetIdsFromLineupPayload(payload: string): Set { + const assetIds = new Set(); + const decoded = decodeObject(payload); + if (decoded === null) { + return assetIds; + } + + const rawImages = decoded.images; + if (!Array.isArray(rawImages)) { + return assetIds; + } + + for (const image of rawImages) { + if (typeof image === "object" && image !== null && typeof image.id === "string") { + assetIds.add(image.id); + } + } + return assetIds; +} + +async function collectReferencedAssetIdsForStrategy( + ctx: AnyCtx, + strategyId: Doc<"strategies">["_id"], +): Promise> { + const assetIds = new Set(); + + const elements = await ctx.db + .query("elements") + .withIndex("by_strategyId", (q) => q.eq("strategyId", strategyId)) + .collect(); + for (const element of elements) { + if (element.deleted || element.elementType !== "image") { + continue; + } + + const assetId = collectAssetIdFromElementPayload(element.payload); + if (assetId !== null) { + assetIds.add(assetId); + } + } + + const lineups = await ctx.db + .query("lineups") + .withIndex("by_strategyId", (q) => q.eq("strategyId", strategyId)) + .collect(); + for (const lineup of lineups) { + if (lineup.deleted) { + continue; + } + + for (const assetId of collectAssetIdsFromLineupPayload(lineup.payload)) { + assetIds.add(assetId); + } + } + + return assetIds; +} + +async function strategyReferencesAsset( + ctx: AnyCtx, + strategyId: Doc<"strategies">["_id"], + assetPublicId: string, +): Promise { + const referencedAssetIds = await collectReferencedAssetIdsForStrategy(ctx, strategyId); + return referencedAssetIds.has(assetPublicId); +} + +async function serializeAssetForViewer( + ctx: QueryCtx, + asset: Doc<"imageAssets">, +): Promise<{ + publicId: string; + fileExtension: string; + mimeType: string | null; + width: number | null; + height: number | null; + url: string | null; + legacyStoragePath: string | null; +}> { + return { + publicId: asset.publicId, + fileExtension: inferFileExtension(asset), + mimeType: asset.mimeType ?? null, + width: asset.width ?? null, + height: asset.height ?? null, + url: + asset.storageId === undefined ? null : await ctx.storage.getUrl(asset.storageId), + legacyStoragePath: asset.storagePath ?? null, + }; +} + +export async function deleteImageAsset( + ctx: MutationCtx, + asset: Doc<"imageAssets">, +): Promise { + if (asset.storageId !== undefined) { + await ctx.storage.delete(asset.storageId); + } + await ctx.db.delete(asset._id); +} + +export const generateUploadUrl = mutation({ + args: { + strategyPublicId: v.string(), + }, + handler: async (ctx, args) => { + const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); + await assertStrategyRole(ctx, strategy, "editor"); + + return { + uploadUrl: await ctx.storage.generateUploadUrl(), + }; + }, +}); + +export const completeUpload = mutation({ args: { strategyPublicId: v.string(), - pagePublicId: v.string(), assetPublicId: v.string(), - elementPublicId: v.optional(v.string()), - storagePath: v.string(), - mimeType: v.string(), + storageId: v.id("_storage"), + mimeType: v.optional(v.string()), + fileExtension: v.optional(v.string()), width: v.optional(v.number()), height: v.optional(v.number()), }, handler: async (ctx, args) => { const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); - const { user } = await assertStrategyRole(ctx, strategy, "editor"); - const page = await getPageByPublicId(ctx, args.pagePublicId); - - if (page.strategyId !== strategy._id) { - throw new Error("Page strategy mismatch"); - } - - let elementId; - if (args.elementPublicId !== undefined) { - const element = await getElementByPublicId(ctx, args.elementPublicId); - if (element.strategyId !== strategy._id || element.pageId !== page._id) { - throw new Error("Element context mismatch"); - } - elementId = element._id; - } + await assertStrategyRole(ctx, strategy, "editor"); - const existing = await ctx.db - .query("imageAssets") - .withIndex("by_publicId", (q) => q.eq("publicId", args.assetPublicId)) - .first(); + const existing = await getImageAssetByPublicId(ctx, args.assetPublicId); + const now = Date.now(); if (existing === null) { await ctx.db.insert("imageAssets", { publicId: args.assetPublicId, - strategyId: strategy._id, - pageId: page._id, - elementId, - storagePath: args.storagePath, + storageId: args.storageId, + fileExtension: args.fileExtension, mimeType: args.mimeType, width: args.width, height: args.height, - createdByUserId: user._id, - createdAt: Date.now(), - updatedAt: Date.now(), + createdAt: now, + updatedAt: now, }); } else { await ctx.db.patch(existing._id, { - strategyId: strategy._id, - pageId: page._id, - elementId, - storagePath: args.storagePath, + storageId: args.storageId, + fileExtension: args.fileExtension, mimeType: args.mimeType, width: args.width, height: args.height, - updatedAt: Date.now(), + updatedAt: now, }); } @@ -80,22 +214,44 @@ export const listForStrategy = query({ const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); await assertStrategyRole(ctx, strategy, "viewer"); - const assets = await ctx.db - .query("imageAssets") - .withIndex("by_strategyId", (q) => q.eq("strategyId", strategy._id)) - .collect(); - - return assets.map((asset) => ({ - publicId: asset.publicId, - storagePath: asset.storagePath, - mimeType: asset.mimeType, - width: asset.width ?? null, - height: asset.height ?? null, - pageId: asset.pageId, - elementId: asset.elementId ?? null, - createdAt: asset.createdAt, - updatedAt: asset.updatedAt, - })); + const referencedAssetIds = await collectReferencedAssetIdsForStrategy(ctx, strategy._id); + const assets = await Promise.all( + [...referencedAssetIds].map((assetPublicId) => + getImageAssetByPublicId(ctx, assetPublicId), + ), + ); + + const serialized = await Promise.all( + assets + .filter((asset): asset is Doc<"imageAssets"> => asset !== null) + .map((asset) => serializeAssetForViewer(ctx, asset)), + ); + + return serialized; + }, +}); + +export const getAssetUrl = query({ + args: { + strategyPublicId: v.string(), + assetPublicId: v.string(), + }, + handler: async (ctx, args) => { + const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); + await assertStrategyRole(ctx, strategy, "viewer"); + + const asset = await getImageAssetByPublicId(ctx, args.assetPublicId); + if ( + asset === null || + !(await strategyReferencesAsset(ctx, strategy._id, args.assetPublicId)) + ) { + throw new Error("Asset not found"); + } + + return { + url: + asset.storageId === undefined ? null : await ctx.storage.getUrl(asset.storageId), + }; }, }); @@ -108,16 +264,15 @@ export const deleteAssetRef = mutation({ const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); await assertStrategyRole(ctx, strategy, "editor"); - const asset = await ctx.db - .query("imageAssets") - .withIndex("by_publicId", (q) => q.eq("publicId", args.assetPublicId)) - .first(); - - if (asset === null || asset.strategyId !== strategy._id) { + const asset = await getImageAssetByPublicId(ctx, args.assetPublicId); + if ( + asset === null || + !(await strategyReferencesAsset(ctx, strategy._id, args.assetPublicId)) + ) { throw new Error("Asset not found"); } - await ctx.db.delete(asset._id); + await deleteImageAsset(ctx, asset); return { ok: true }; }, }); @@ -127,15 +282,8 @@ export const listPotentiallyStale = query({ strategyPublicId: v.string(), }, handler: async (ctx, args) => { - const user = await requireCurrentUser(ctx); const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); await assertStrategyRole(ctx, strategy, "editor"); - - const assets = await ctx.db - .query("imageAssets") - .withIndex("by_strategyId", (q) => q.eq("strategyId", strategy._id)) - .collect(); - - return assets.filter((asset) => asset.createdByUserId === user._id); + return []; }, }); diff --git a/convex/lib/auth.ts b/convex/lib/auth.ts index 37b601a2..4e01eefc 100644 --- a/convex/lib/auth.ts +++ b/convex/lib/auth.ts @@ -91,6 +91,77 @@ export async function getStrategyRoleForUser( return collaborator?.role ?? null; } +export async function getFolderRoleForUser( + ctx: AnyCtx, + folder: Doc<"folders">, + userId: Id<"users">, +): Promise { + if (folder.ownerId === userId) { + return "owner"; + } + + const collaborator = await ctx.db + .query("folderCollaborators") + .withIndex("by_folderId_userId", (q) => + q.eq("folderId", folder._id).eq("userId", userId), + ) + .first(); + + return collaborator?.role ?? null; +} + +function higherRole( + left: StrategyRole | null, + right: StrategyRole | null, +): StrategyRole | null { + if (left === null) return right; + if (right === null) return left; + return roleRank[left] >= roleRank[right] ? left : right; +} + +export async function getEffectiveFolderRoleForUser( + ctx: AnyCtx, + folder: Doc<"folders">, + userId: Id<"users">, +): Promise { + let current: Doc<"folders"> | null = folder; + let bestRole: StrategyRole | null = null; + + while (current !== null) { + bestRole = higherRole( + bestRole, + await getFolderRoleForUser(ctx, current, userId), + ); + const parentFolderId: Id<"folders"> | undefined = current.parentFolderId; + if (parentFolderId === undefined) { + break; + } + current = (await ctx.db.get(parentFolderId)) as Doc<"folders"> | null; + } + + return bestRole; +} + +export async function getEffectiveStrategyRoleForUser( + ctx: AnyCtx, + strategy: Doc<"strategies">, + userId: Id<"users">, +): Promise { + let bestRole = await getStrategyRoleForUser(ctx, strategy, userId); + + if (strategy.folderId !== undefined) { + const folder = await ctx.db.get(strategy.folderId); + if (folder !== null) { + bestRole = higherRole( + bestRole, + await getEffectiveFolderRoleForUser(ctx, folder, userId), + ); + } + } + + return bestRole; +} + export function hasRole( actual: StrategyRole | null, required: StrategyRole, @@ -105,7 +176,22 @@ export async function assertStrategyRole( required: StrategyRole, ): Promise<{ user: Doc<"users">; role: StrategyRole }> { const user = await requireCurrentUser(ctx); - const role = await getStrategyRoleForUser(ctx, strategy, user._id); + const role = await getEffectiveStrategyRoleForUser(ctx, strategy, user._id); + + if (!hasRole(role, required)) { + throw new Error("Forbidden"); + } + + return { user, role: role as StrategyRole }; +} + +export async function assertFolderRole( + ctx: AnyCtx, + folder: Doc<"folders">, + required: StrategyRole, +): Promise<{ user: Doc<"users">; role: StrategyRole }> { + const user = await requireCurrentUser(ctx); + const role = await getEffectiveFolderRoleForUser(ctx, folder, user._id); if (!hasRole(role, required)) { throw new Error("Forbidden"); diff --git a/convex/lineups.ts b/convex/lineups.ts index c3bcb902..88dba540 100644 --- a/convex/lineups.ts +++ b/convex/lineups.ts @@ -37,3 +37,40 @@ export const listForPage = query({ })); }, }); + +export const listForStrategy = query({ + args: { + strategyPublicId: v.string(), + }, + handler: async (ctx, args) => { + const strategy = await getStrategyByPublicId(ctx, args.strategyPublicId); + await assertStrategyRole(ctx, strategy, "viewer"); + + const pages = await ctx.db + .query("pages") + .withIndex("by_strategyId", (q) => q.eq("strategyId", strategy._id)) + .collect(); + const pagePublicIds = new Map( + pages.map((page) => [page._id, page.publicId]), + ); + + const lineups = await ctx.db + .query("lineups") + .withIndex("by_strategyId", (q) => q.eq("strategyId", strategy._id)) + .collect(); + + return lineups + .sort((a, b) => a.sortIndex - b.sortIndex) + .map((lineup) => ({ + publicId: lineup.publicId, + strategyPublicId: strategy.publicId, + pagePublicId: pagePublicIds.get(lineup.pageId) ?? "", + payload: lineup.payload, + sortIndex: lineup.sortIndex, + revision: lineup.revision, + deleted: lineup.deleted, + createdAt: lineup.createdAt, + updatedAt: lineup.updatedAt, + })); + }, +}); diff --git a/convex/ops.ts b/convex/ops.ts index 27216d23..a9e21280 100644 --- a/convex/ops.ts +++ b/convex/ops.ts @@ -1,5 +1,6 @@ import { mutation } from "./_generated/server"; import { v } from "convex/values"; +import type { Id } from "./_generated/dataModel"; import { assertStrategyRole } from "./lib/auth"; import { getElementByPublicId, @@ -81,6 +82,7 @@ export const applyBatch = mutation({ let appliedRevision: number | undefined; let latestRevision: number | undefined; let latestPayload: string | undefined; + let eventPageId: Id<"pages"> | undefined; try { if ( @@ -136,6 +138,7 @@ export const applyBatch = mutation({ if (existingPage.strategyId !== strategy._id) { throw new Error("Page strategy mismatch"); } + eventPageId = existingPage._id; await ctx.db.patch(existingPage._id, { name: @@ -156,7 +159,7 @@ export const applyBatch = mutation({ }); appliedRevision = existingPage.revision + 1; } else { - await ctx.db.insert("pages", { + const insertedPageId = await ctx.db.insert("pages", { publicId: pagePublicId, strategyId: strategy._id, name: typeof payload.name === "string" ? payload.name : "Page", @@ -170,6 +173,7 @@ export const applyBatch = mutation({ createdAt: now, updatedAt: now, }); + eventPageId = insertedPageId; appliedRevision = 1; } @@ -183,6 +187,7 @@ export const applyBatch = mutation({ if (page.strategyId !== strategy._id) { throw new Error("Page strategy mismatch"); } + eventPageId = page._id; latestRevision = page.revision; @@ -251,6 +256,7 @@ export const applyBatch = mutation({ if (page.strategyId !== strategy._id) { throw new Error("Page strategy mismatch"); } + eventPageId = page._id; const payload = parsePayload(op.payload); const elementType = typeof payload.elementType === "string" @@ -300,6 +306,7 @@ export const applyBatch = mutation({ if (element.strategyId !== strategy._id) { throw new Error("Element strategy mismatch"); } + eventPageId = element.pageId; latestRevision = element.revision; latestPayload = element.payload; @@ -335,6 +342,7 @@ export const applyBatch = mutation({ throw new Error("Page strategy mismatch"); } patch.pageId = page._id; + eventPageId = page._id; } await ctx.db.patch(element._id, patch); @@ -363,6 +371,7 @@ export const applyBatch = mutation({ if (page.strategyId !== strategy._id) { throw new Error("Page strategy mismatch"); } + eventPageId = page._id; const now = Date.now(); const existingLineup = await ctx.db .query("lineups") @@ -405,6 +414,7 @@ export const applyBatch = mutation({ if (lineup.strategyId !== strategy._id) { throw new Error("Lineup strategy mismatch"); } + eventPageId = lineup.pageId; latestRevision = lineup.revision; latestPayload = lineup.payload; @@ -440,6 +450,7 @@ export const applyBatch = mutation({ throw new Error("Page strategy mismatch"); } patch.pageId = page._id; + eventPageId = page._id; } await ctx.db.patch(lineup._id, patch); appliedRevision = lineup.revision + 1; @@ -466,7 +477,7 @@ export const applyBatch = mutation({ await ctx.db.insert("operationEvents", { strategyId: strategy._id, - pageId: undefined, + pageId: eventPageId, clientId: args.clientId, opId: op.opId, opType: `${op.entityType}.${op.kind}`, @@ -500,5 +511,3 @@ export const applyBatch = mutation({ }; }, }); - - diff --git a/convex/pages.ts b/convex/pages.ts index daa465e6..347a56d0 100644 --- a/convex/pages.ts +++ b/convex/pages.ts @@ -175,14 +175,6 @@ export const deletePage = mutation({ await ctx.db.delete(lineup._id); } - const assets = await ctx.db - .query("imageAssets") - .withIndex("by_pageId", (q) => q.eq("pageId", page._id)) - .collect(); - for (const asset of assets) { - await ctx.db.delete(asset._id); - } - await ctx.db.delete(page._id); const ordered = sortByNumberField( @@ -190,7 +182,7 @@ export const deletePage = mutation({ "sortIndex", ); for (let i = 0; i < ordered.length; i += 1) { - const current = ordered[i]; + const current = ordered[i]!; if (current.sortIndex !== i) { await ctx.db.patch(current._id, { sortIndex: i, @@ -231,7 +223,7 @@ export const reorder = mutation({ const now = Date.now(); for (let i = 0; i < args.orderedPagePublicIds.length; i += 1) { - const publicId = args.orderedPagePublicIds[i]; + const publicId = args.orderedPagePublicIds[i]!; const page = pageByPublicId.get(publicId); if (!page) { throw new Error(`Unknown page id: ${publicId}`); diff --git a/convex/schema.ts b/convex/schema.ts index 4ee76e00..ad4f37c9 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -94,6 +94,31 @@ export default defineSchema({ .index("by_strategyId", ["strategyId"]) .index("by_userId", ["userId"]) .index("by_strategyId_userId", ["strategyId", "userId"]), + folderCollaborators: defineTable({ + folderId: v.id("folders"), + userId: v.id("users"), + role: v.union(v.literal("editor"), v.literal("viewer")), + invitedByUserId: v.optional(v.id("users")), + createdAt: v.number(), + updatedAt: v.number(), + }) + .index("by_folderId", ["folderId"]) + .index("by_userId", ["userId"]) + .index("by_folderId_userId", ["folderId", "userId"]), + shareLinks: defineTable({ + token: v.string(), + targetType: v.union(v.literal("strategy"), v.literal("folder")), + strategyId: v.optional(v.id("strategies")), + folderId: v.optional(v.id("folders")), + role: v.union(v.literal("editor"), v.literal("viewer")), + createdByUserId: v.id("users"), + revokedAt: v.optional(v.number()), + createdAt: v.number(), + updatedAt: v.number(), + }) + .index("by_token", ["token"]) + .index("by_strategyId", ["strategyId"]) + .index("by_folderId", ["folderId"]), inviteTokens: defineTable({ token: v.string(), strategyId: v.id("strategies"), @@ -109,20 +134,17 @@ export default defineSchema({ .index("by_strategyId", ["strategyId"]), imageAssets: defineTable({ publicId: v.string(), - strategyId: v.id("strategies"), - pageId: v.id("pages"), - elementId: v.optional(v.id("elements")), - storagePath: v.string(), - mimeType: v.string(), + storageId: v.optional(v.id("_storage")), + fileExtension: v.optional(v.string()), + mimeType: v.optional(v.string()), width: v.optional(v.number()), height: v.optional(v.number()), - createdByUserId: v.id("users"), - createdAt: v.number(), - updatedAt: v.number(), + createdAt: v.optional(v.number()), + updatedAt: v.optional(v.number()), + // Legacy rows may still have a storagePath that can help infer the extension. + storagePath: v.optional(v.string()), }) - .index("by_publicId", ["publicId"]) - .index("by_strategyId", ["strategyId"]) - .index("by_pageId", ["pageId"]), + .index("by_publicId", ["publicId"]), operationEvents: defineTable({ strategyId: v.id("strategies"), pageId: v.optional(v.id("pages")), @@ -141,4 +163,3 @@ export default defineSchema({ .index("by_strategyId_clientId_opId", ["strategyId", "clientId", "opId"]), }); - diff --git a/convex/shares.ts b/convex/shares.ts new file mode 100644 index 00000000..faed291f --- /dev/null +++ b/convex/shares.ts @@ -0,0 +1,254 @@ +import type { QueryCtx, MutationCtx } from "./_generated/server"; +import { mutation, query } from "./_generated/server"; +import { v } from "convex/values"; +import { + assertFolderRole, + assertStrategyRole, + requireCurrentUser, +} from "./lib/auth"; +import { getFolderByPublicId, getStrategyByPublicId } from "./lib/entities"; + +const targetTypeValidator = v.union(v.literal("strategy"), v.literal("folder")); +const collaboratorRoleValidator = v.union(v.literal("viewer"), v.literal("editor")); +type AnyCtx = QueryCtx | MutationCtx; + +async function resolveTarget( + ctx: AnyCtx, + targetType: "strategy" | "folder", + targetPublicId: string, +) { + if (targetType === "strategy") { + const strategy = await getStrategyByPublicId(ctx, targetPublicId); + return { targetType, strategy, folder: null }; + } + + const folder = await getFolderByPublicId(ctx, targetPublicId); + return { targetType, strategy: null, folder }; +} + +export const list = query({ + args: { + targetType: targetTypeValidator, + targetPublicId: v.string(), + }, + handler: async (ctx, args) => { + const resolved = await resolveTarget(ctx, args.targetType, args.targetPublicId); + + if (resolved.strategy !== null) { + const { role } = await assertStrategyRole(ctx, resolved.strategy, "owner"); + if (role !== "owner") { + throw new Error("Forbidden"); + } + } else if (resolved.folder !== null) { + const { role } = await assertFolderRole(ctx, resolved.folder, "owner"); + if (role !== "owner") { + throw new Error("Forbidden"); + } + } + + const links = + resolved.strategy !== null + ? await ctx.db + .query("shareLinks") + .withIndex("by_strategyId", (q) => q.eq("strategyId", resolved.strategy!._id)) + .collect() + : await ctx.db + .query("shareLinks") + .withIndex("by_folderId", (q) => q.eq("folderId", resolved.folder!._id)) + .collect(); + + return links + .sort((a, b) => b.createdAt - a.createdAt) + .map((link) => ({ + token: link.token, + role: link.role, + createdAt: link.createdAt, + revokedAt: link.revokedAt ?? null, + })); + }, +}); + +export const create = mutation({ + args: { + targetType: targetTypeValidator, + targetPublicId: v.string(), + token: v.string(), + role: collaboratorRoleValidator, + }, + handler: async (ctx, args) => { + const user = await requireCurrentUser(ctx); + const resolved = await resolveTarget(ctx, args.targetType, args.targetPublicId); + + if (resolved.strategy !== null) { + const { role } = await assertStrategyRole(ctx, resolved.strategy, "owner"); + if (role !== "owner") { + throw new Error("Forbidden"); + } + } else if (resolved.folder !== null) { + const { role } = await assertFolderRole(ctx, resolved.folder, "owner"); + if (role !== "owner") { + throw new Error("Forbidden"); + } + } + + await ctx.db.insert("shareLinks", { + token: args.token, + targetType: args.targetType, + strategyId: resolved.strategy?._id, + folderId: resolved.folder?._id, + role: args.role, + createdByUserId: user._id, + createdAt: Date.now(), + updatedAt: Date.now(), + }); + + return { ok: true }; + }, +}); + +export const revoke = mutation({ + args: { + targetType: targetTypeValidator, + targetPublicId: v.string(), + token: v.string(), + }, + handler: async (ctx, args) => { + const resolved = await resolveTarget(ctx, args.targetType, args.targetPublicId); + + if (resolved.strategy !== null) { + const { role } = await assertStrategyRole(ctx, resolved.strategy, "owner"); + if (role !== "owner") { + throw new Error("Forbidden"); + } + } else if (resolved.folder !== null) { + const { role } = await assertFolderRole(ctx, resolved.folder, "owner"); + if (role !== "owner") { + throw new Error("Forbidden"); + } + } + + const link = await ctx.db + .query("shareLinks") + .withIndex("by_token", (q) => q.eq("token", args.token)) + .first(); + + if (link === null) { + throw new Error("Share link not found"); + } + + if ( + (resolved.strategy !== null && link.strategyId !== resolved.strategy._id) || + (resolved.folder !== null && link.folderId !== resolved.folder._id) + ) { + throw new Error("Share link not found"); + } + + await ctx.db.patch(link._id, { + revokedAt: Date.now(), + updatedAt: Date.now(), + }); + + return { ok: true }; + }, +}); + +export const redeem = mutation({ + args: { + token: v.string(), + }, + handler: async (ctx, args) => { + const user = await requireCurrentUser(ctx); + const link = await ctx.db + .query("shareLinks") + .withIndex("by_token", (q) => q.eq("token", args.token)) + .first(); + + if (link === null) { + throw new Error("Share link not found"); + } + + if (link.revokedAt !== undefined) { + throw new Error("Share link revoked"); + } + + if (link.targetType === "strategy") { + const strategy = link.strategyId === undefined ? null : await ctx.db.get(link.strategyId); + if (strategy === null) { + throw new Error("Strategy not found"); + } + + if (strategy.ownerId !== user._id) { + const existingMembership = await ctx.db + .query("strategyCollaborators") + .withIndex("by_strategyId_userId", (q) => + q.eq("strategyId", strategy._id).eq("userId", user._id), + ) + .first(); + + if (existingMembership === null) { + await ctx.db.insert("strategyCollaborators", { + strategyId: strategy._id, + userId: user._id, + role: link.role, + invitedByUserId: link.createdByUserId, + createdAt: Date.now(), + updatedAt: Date.now(), + }); + } else { + await ctx.db.patch(existingMembership._id, { + role: link.role, + updatedAt: Date.now(), + }); + } + } + + const folder = + strategy.folderId === undefined ? null : await ctx.db.get(strategy.folderId); + + return { + ok: true, + targetType: "strategy", + strategyPublicId: strategy.publicId, + folderPublicId: folder?.publicId ?? null, + role: strategy.ownerId === user._id ? "owner" : link.role, + }; + } + + const folder = link.folderId === undefined ? null : await ctx.db.get(link.folderId); + if (folder === null) { + throw new Error("Folder not found"); + } + + if (folder.ownerId !== user._id) { + const existingMembership = await ctx.db + .query("folderCollaborators") + .withIndex("by_folderId_userId", (q) => + q.eq("folderId", folder._id).eq("userId", user._id), + ) + .first(); + + if (existingMembership === null) { + await ctx.db.insert("folderCollaborators", { + folderId: folder._id, + userId: user._id, + role: link.role, + invitedByUserId: link.createdByUserId, + createdAt: Date.now(), + updatedAt: Date.now(), + }); + } else { + await ctx.db.patch(existingMembership._id, { + role: link.role, + updatedAt: Date.now(), + }); + } + } + + return { + ok: true, + targetType: "folder", + folderPublicId: folder.publicId, + role: folder.ownerId === user._id ? "owner" : link.role, + }; + }, +}); diff --git a/convex/strategies.ts b/convex/strategies.ts index 5444e57e..ed8e9cdb 100644 --- a/convex/strategies.ts +++ b/convex/strategies.ts @@ -1,85 +1,102 @@ import { mutation, query } from "./_generated/server"; import { v } from "convex/values"; -import { assertStrategyRole, requireCurrentUser } from "./lib/auth"; +import type { Doc, Id } from "./_generated/dataModel"; +import type { MutationCtx, QueryCtx } from "./_generated/server"; +import { + assertFolderRole, + assertStrategyRole, + getEffectiveStrategyRoleForUser, + requireCurrentUser, +} from "./lib/auth"; import { getFolderByPublicId, getStrategyByPublicId } from "./lib/entities"; -async function listAccessibleStrategies(ctx: any, userId: any) { - const owned = await ctx.db - .query("strategies") - .withIndex("by_ownerId", (q: any) => q.eq("ownerId", userId)) - .collect(); - - const memberships = await ctx.db - .query("strategyCollaborators") - .withIndex("by_userId", (q: any) => q.eq("userId", userId)) - .collect(); - - const fromMembership = await Promise.all( - memberships.map((m: any) => ctx.db.get(m.strategyId)), - ); +type StrategyScope = "owned" | "shared" | "all"; + +type StrategyCreateInput = { + publicId: string; + name: string; + mapData: string; + folderPublicId?: string; + themeProfileId?: string; + themeOverridePalette?: string; +}; + +type InitialPageInput = { + publicId: string; + name: string; + isAttack: boolean; + settings?: string; +}; + +function createPublicId(): string { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => { + const random = Math.floor(Math.random() * 16); + const value = char === "x" ? random : (random & 0x3) | 0x8; + return value.toString(16); + }); +} - const dedup = new Map(); - for (const strategy of [...owned, ...fromMembership]) { - if (strategy !== null) { - dedup.set(strategy._id, strategy); - } +const strategyScopeValidator = v.optional( + v.union(v.literal("owned"), v.literal("shared"), v.literal("all")), +); + +function matchesScope( + ownerId: Id<"users">, + userId: Id<"users">, + scope: StrategyScope, +): boolean { + if (scope === "all") { + return true; } - - return Array.from(dedup.values()); + if (scope === "owned") { + return ownerId === userId; + } + return ownerId !== userId; } -export const listForFolder = query({ - args: { - folderPublicId: v.optional(v.string()), - }, - handler: async (ctx, args) => { - const user = await requireCurrentUser(ctx); - const all = await listAccessibleStrategies(ctx as any, user._id); - const memberships = await ctx.db - .query("strategyCollaborators") - .withIndex("by_userId", (q) => q.eq("userId", user._id)) - .collect(); - - let folderId; - if (args.folderPublicId !== undefined) { - const folder = await getFolderByPublicId(ctx, args.folderPublicId); - if (folder.ownerId !== user._id) { - throw new Error("Forbidden"); - } - folderId = folder._id; - } +async function summarizeStrategies( + ctx: QueryCtx, + strategies: Doc<"strategies">[], + userId: Id<"users">, +) { + const memberships = await ctx.db + .query("strategyCollaborators") + .withIndex("by_userId", (q) => q.eq("userId", userId)) + .collect(); - const folderIdToPublicId = new Map(); - for (const strategy of all) { - if ( - strategy.folderId !== undefined && - !folderIdToPublicId.has(strategy.folderId) - ) { - const strategyFolder = await ctx.db.get(strategy.folderId); - if (strategyFolder !== null) { - folderIdToPublicId.set(strategy.folderId, strategyFolder.publicId); - } + const folderIdToPublicId = new Map, string>(); + for (const strategy of strategies) { + if ( + strategy.folderId !== undefined && + !folderIdToPublicId.has(strategy.folderId) + ) { + const folder = await ctx.db.get(strategy.folderId); + if (folder !== null) { + folderIdToPublicId.set(strategy.folderId, folder.publicId); } } + } - return await Promise.all( - all - .filter((s) => s.folderId === folderId) - .sort((a, b) => b.updatedAt - a.updatedAt) - .map(async (s) => { + return await Promise.all( + strategies + .sort((a, b) => b.updatedAt - a.updatedAt) + .map(async (s) => { const pages = await ctx.db .query("pages") .withIndex("by_strategyId", (q) => q.eq("strategyId", s._id)) .collect(); let attackLabel = "Unknown"; if (pages.length > 0) { - const first = pages[0].isAttack; + const first = pages[0]!.isAttack; const mixed = pages.some((page) => page.isAttack !== first); attackLabel = mixed ? "Mixed" : first ? "Attack" : "Defend"; } - const role = s.ownerId === user._id - ? "owner" - : memberships.find((m: any) => m.strategyId === s._id)?.role ?? "viewer"; + const role = + s.ownerId === userId + ? "owner" + : ((await getEffectiveStrategyRoleForUser(ctx, s, userId)) ?? + memberships.find((m: any) => m.strategyId === s._id)?.role ?? + "viewer"); return { publicId: s.publicId, @@ -91,12 +108,241 @@ export const listForFolder = query({ role, attackLabel, folderPublicId: - s.folderId === undefined ? null : folderIdToPublicId.get(s.folderId) ?? null, + s.folderId === undefined + ? null + : (folderIdToPublicId.get(s.folderId) ?? null), themeProfileId: s.themeProfileId ?? null, themeOverridePalette: s.themeOverridePalette ?? null, }; - }), + }), + ); +} + +async function listStrategiesInFolder( + ctx: QueryCtx, + folderId: Id<"folders"> | undefined, + userId: Id<"users">, + scope: StrategyScope, +) { + let candidates: Doc<"strategies">[]; + if (folderId !== undefined) { + candidates = await ctx.db + .query("strategies") + .withIndex("by_folderId", (q) => q.eq("folderId", folderId)) + .collect(); + } else if (scope === "shared") { + const memberships = await ctx.db + .query("strategyCollaborators") + .withIndex("by_userId", (q) => q.eq("userId", userId)) + .collect(); + const shared = await Promise.all( + memberships.map((membership) => ctx.db.get(membership.strategyId)), ); + candidates = shared.filter( + (strategy): strategy is Doc<"strategies"> => + strategy !== null && + strategy.ownerId !== userId && + strategy.folderId === undefined, + ); + } else { + candidates = await ctx.db + .query("strategies") + .withIndex("by_ownerId", (q) => q.eq("ownerId", userId)) + .collect(); + candidates = candidates.filter( + (strategy) => strategy.folderId === undefined, + ); + + if (scope === "all") { + const memberships = await ctx.db + .query("strategyCollaborators") + .withIndex("by_userId", (q) => q.eq("userId", userId)) + .collect(); + const shared = await Promise.all( + memberships.map((membership) => ctx.db.get(membership.strategyId)), + ); + candidates.push( + ...shared.filter( + (strategy): strategy is Doc<"strategies"> => + strategy !== null && + strategy.ownerId !== userId && + strategy.folderId === undefined, + ), + ); + } + } + + const dedup = new Map, Doc<"strategies">>(); + for (const strategy of candidates) { + if ( + matchesScope(strategy.ownerId, userId, scope) && + (await getEffectiveStrategyRoleForUser(ctx, strategy, userId)) !== null + ) { + dedup.set(strategy._id, strategy); + } + } + return Array.from(dedup.values()); +} + +async function resolveOwnedFolderId( + ctx: MutationCtx, + folderPublicId: string | undefined, + userId: Id<"users">, +) { + if (folderPublicId === undefined) { + return undefined; + } + const folder = await getFolderByPublicId(ctx, folderPublicId); + if (folder.ownerId !== userId) { + throw new Error("Forbidden"); + } + return folder._id; +} + +async function assertInitialPagePublicIdAvailable( + ctx: MutationCtx, + pagePublicId: string, + allowedStrategyId?: Id<"strategies">, +) { + const existingPage = await ctx.db + .query("pages") + .withIndex("by_publicId", (q) => q.eq("publicId", pagePublicId)) + .first(); + if ( + existingPage !== null && + (allowedStrategyId === undefined || + existingPage.strategyId !== allowedStrategyId) + ) { + throw new Error(`Page publicId already exists: ${pagePublicId}`); + } +} + +async function insertInitialPage( + ctx: MutationCtx, + args: { + strategyId: Id<"strategies">; + initialPage: InitialPageInput; + now: number; + }, +) { + await ctx.db.insert("pages", { + publicId: args.initialPage.publicId, + strategyId: args.strategyId, + name: args.initialPage.name, + sortIndex: 0, + isAttack: args.initialPage.isAttack, + settings: args.initialPage.settings, + revision: 1, + createdAt: args.now, + updatedAt: args.now, + }); +} + +async function createStrategyWithInitialPageRecord( + ctx: MutationCtx, + args: StrategyCreateInput, + userId: Id<"users">, + initialPage: InitialPageInput, +) { + const now = Date.now(); + const folderId = await resolveOwnedFolderId(ctx, args.folderPublicId, userId); + + const existing = await ctx.db + .query("strategies") + .withIndex("by_publicId", (q) => q.eq("publicId", args.publicId)) + .collect(); + const existingOwned = existing.find((item) => item.ownerId === userId); + if (existingOwned !== undefined) { + const pages = await ctx.db + .query("pages") + .withIndex("by_strategyId", (q) => q.eq("strategyId", existingOwned._id)) + .collect(); + if (pages.length === 0) { + await assertInitialPagePublicIdAvailable( + ctx, + initialPage.publicId, + existingOwned._id, + ); + await insertInitialPage(ctx, { + strategyId: existingOwned._id, + initialPage, + now, + }); + } + return { ok: true, reused: true }; + } + if (existing.length > 0) { + throw new Error(`Strategy publicId already exists: ${args.publicId}`); + } + + await assertInitialPagePublicIdAvailable(ctx, initialPage.publicId); + + const strategyId = await ctx.db.insert("strategies", { + publicId: args.publicId, + ownerId: userId, + folderId, + name: args.name, + mapData: args.mapData, + sequence: 0, + themeProfileId: args.themeProfileId, + themeOverridePalette: args.themeOverridePalette, + createdAt: now, + updatedAt: now, + }); + + await insertInitialPage(ctx, { + strategyId, + initialPage, + now, + }); + + return { ok: true }; +} + +export const listForFolder = query({ + args: { + folderPublicId: v.optional(v.string()), + scope: strategyScopeValidator, + }, + handler: async (ctx, args) => { + const user = await requireCurrentUser(ctx); + const scope = args.scope ?? "owned"; + + let folderId: Id<"folders"> | undefined; + if (args.folderPublicId !== undefined) { + const folder = await getFolderByPublicId(ctx, args.folderPublicId); + await assertFolderRole(ctx, folder, "viewer"); + folderId = folder._id; + } + + const strategies = await listStrategiesInFolder( + ctx, + folderId, + user._id, + scope, + ); + return await summarizeStrategies(ctx, strategies, user._id); + }, +}); + +export const listSharedWithMe = query({ + args: {}, + handler: async (ctx) => { + const user = await requireCurrentUser(ctx); + const memberships = await ctx.db + .query("strategyCollaborators") + .withIndex("by_userId", (q) => q.eq("userId", user._id)) + .collect(); + const shared = await Promise.all( + memberships.map((membership) => ctx.db.get(membership.strategyId)), + ); + const strategies = shared.filter( + (strategy): strategy is Doc<"strategies"> => + strategy !== null && + strategy.ownerId !== user._id && + strategy.folderId === undefined, + ); + return await summarizeStrategies(ctx, strategies, user._id); }, }); @@ -133,43 +379,35 @@ export const create = mutation({ }, handler: async (ctx, args) => { const user = await requireCurrentUser(ctx); - const now = Date.now(); - - let folderId; - if (args.folderPublicId !== undefined) { - const folder = await getFolderByPublicId(ctx, args.folderPublicId); - if (folder.ownerId !== user._id) { - throw new Error("Forbidden"); - } - folderId = folder._id; - } - - const existing = await ctx.db - .query("strategies") - .withIndex("by_publicId", (q) => q.eq("publicId", args.publicId)) - .collect(); - const existingOwned = existing.find((item) => item.ownerId === user._id); - if (existingOwned !== undefined) { - return { ok: true, reused: true }; - } - if (existing.length > 0) { - throw new Error(`Strategy publicId already exists: ${args.publicId}`); - } - - await ctx.db.insert("strategies", { - publicId: args.publicId, - ownerId: user._id, - folderId, - name: args.name, - mapData: args.mapData, - sequence: 0, - themeProfileId: args.themeProfileId, - themeOverridePalette: args.themeOverridePalette, - createdAt: now, - updatedAt: now, + return await createStrategyWithInitialPageRecord(ctx, args, user._id, { + publicId: createPublicId(), + name: "Page 1", + isAttack: true, }); + }, +}); - return { ok: true }; +export const createWithInitialPage = mutation({ + args: { + publicId: v.string(), + name: v.string(), + mapData: v.string(), + initialPagePublicId: v.string(), + initialPageName: v.string(), + initialPageIsAttack: v.boolean(), + initialPageSettings: v.optional(v.string()), + folderPublicId: v.optional(v.string()), + themeProfileId: v.optional(v.string()), + themeOverridePalette: v.optional(v.string()), + }, + handler: async (ctx, args) => { + const user = await requireCurrentUser(ctx); + return await createStrategyWithInitialPageRecord(ctx, args, user._id, { + publicId: args.initialPagePublicId, + name: args.initialPageName, + isAttack: args.initialPageIsAttack, + settings: args.initialPageSettings, + }); }, }); @@ -274,14 +512,6 @@ export const deleteStrategy = mutation({ await ctx.db.delete(lineup._id); } - const assets = await ctx.db - .query("imageAssets") - .withIndex("by_pageId", (q) => q.eq("pageId", page._id)) - .collect(); - for (const asset of assets) { - await ctx.db.delete(asset._id); - } - await ctx.db.delete(page._id); } @@ -307,6 +537,3 @@ export const deleteStrategy = mutation({ }); export { deleteStrategy as delete }; - - - diff --git a/docs/cloud_online_release_gaps.md b/docs/cloud_online_release_gaps.md new file mode 100644 index 00000000..04ca1fc4 --- /dev/null +++ b/docs/cloud_online_release_gaps.md @@ -0,0 +1,139 @@ +# Cloud Online Release Gaps + +This note captures the current backend/provider gaps found while auditing the online Icarus experience. The app has a real cloud foundation, but these items should be revisited before a broad public release. + +## Current Recommendation + +Ship as a private beta only until the release blockers below are fixed. These issues affect shared library access, backend confidence, conflict behavior, permission clarity, and media cleanup. + +## Release Blockers + +### Missing Shared-With-Me Backend Function + +- Flutter calls `strategies:listSharedWithMe` from `lib/collab/convex_strategy_repository.dart`. +- The Convex backend currently appears to export `strategies:listForFolder`, but no `listSharedWithMe` function exists in `convex/strategies.ts`. +- Impact: the root "Shared with me" cloud library view may fail unless the deployed backend has an out-of-band function. + +Suggested fix: add `listSharedWithMe` or change the client to use `strategies:listForFolder` with `scope: "shared"` for the root shared view. + +### Convex TypeScript Check Fails + +- `npx tsc --noEmit` reports errors in `convex/pages.ts`. +- Observed errors: + - `current` is possibly `undefined` around page reorder patching. + - `string | undefined` passed where `string` is required around ordered page ids. + +Suggested fix: tighten the reorder loop null checks and ensure undefined page IDs are guarded before use. + +### Targeted Sync Tests Are Not Green + +- Command run: + +```powershell +fvm flutter test test\strategy_op_queue_provider_test.dart test\strategy_page_session_provider_test.dart test\collab_sync_models_test.dart +``` + +- Failures included: + - cloud agent addition did not queue an add op as expected + - cloud map change did not queue a strategy patch op as expected + - Hive boxes missing in two session-provider tests + +Suggested fix: stabilize the test harness first, then verify the cloud queue behavior failures are either expected test drift or real regressions. + +## Conflict Handling Gaps + +### Backend Rejects Stale Writes, But UX Is Thin + +- Backend rejects stale writes with `sequence_mismatch` and `revision_mismatch` in `convex/ops.ts`. +- Client receives rejected acks and pushes `ConflictResolution` objects through `strategyConflictProvider`. +- I did not find a user-facing conflict resolver UI. + +Impact: users may not clearly understand when their edit was rebased, retried, dropped, or overwritten by remote state. + +Suggested fix: add a small visible cloud sync/conflict surface that can show: + +- edit kept and retried +- remote edit won +- local edit needs manual retry +- sync failed and is paused + +### Conflict Provider Is Passive + +- `lib/providers/collab/strategy_conflict_provider.dart` stores conflicts. +- The provider is not enough by itself; it needs a clear consumer in the UI or a documented automatic-resolution behavior. + +Suggested fix: either wire conflicts to UI or remove/replace the provider with explicit automatic conflict policy and telemetry. + +## Permission And Sharing Gaps + +### Effective Folder Role May Be Misreported + +- Backend supports inherited folder roles via `getEffectiveStrategyRoleForUser`. +- Strategy list role display in `convex/strategies.ts` appears to use direct strategy membership first and falls back to `viewer`. + +Impact: a user who has editor access via a shared folder may appear as a viewer in the strategy list, causing UI controls to be hidden or disabled incorrectly. + +Suggested fix: return the effective role from `getEffectiveStrategyRoleForUser` in strategy summaries. + +### Link Revocation Does Not Remove Existing Access + +- `shares:revoke` marks a share link as revoked. +- Existing `strategyCollaborators` / `folderCollaborators` rows created by that link remain. + +Impact: this is okay if "revoke link" only means "stop future joins," but it is not enough for "remove access." + +Suggested fix: make UI copy explicit, or add separate collaborator management with remove/downgrade access. + +### Share Links Never Expire + +- The share dialog says links never expire. +- `inviteTokens` support expiry/revocation, but the visible Flutter share flow uses `shareLinks`, not `invites`. + +Impact: public users may expect expiring links or member management for team content. + +Suggested fix: either add expiration options to share links or reserve public launch for a simpler "private beta link sharing" framing. + +### Invite Token Flow Appears Unused + +- Backend has `convex/invites.ts` with expiry and redemption. +- I did not find a Flutter UX for creating/redeeming those invite tokens. + +Suggested fix: remove/defer this API if not needed, or wire it into the sharing UI. + +## Media Upload And Recovery Gaps + +### Upload Retry Exists + +- `cloud_media_upload_queue_provider.dart` persists jobs in Hive. +- Failed uploads retry with backoff. +- Save state tracks media sync errors. + +This part is a solid foundation. + +### Orphan Storage Risk + +- If the blob upload succeeds but `images:completeUpload` fails, the Convex storage object can be orphaned. + +Suggested fix: add a cleanup path for unattached storage IDs, or store an upload intent before posting the blob so old pending uploads can be swept. + +### Stale Asset Cleanup Is Not Implemented + +- `images:listPotentiallyStale` currently returns an empty list. +- `images:deleteAssetRef` only deletes assets still referenced by the strategy. + +Impact: once an image is removed from a strategy, the current delete path may no longer be able to clean up the asset row/storage object. + +Suggested fix: track asset ownership/strategy association directly on `imageAssets`, or keep a reference table so stale assets can be listed and deleted safely. + +## Follow-Up Checklist + +- [ ] Add or replace `strategies:listSharedWithMe`. +- [ ] Fix `convex/pages.ts` TypeScript errors. +- [ ] Re-run targeted sync tests and fix real failures. +- [ ] Return effective strategy role in cloud strategy summaries. +- [ ] Add visible conflict/sync status UI. +- [ ] Clarify "revoke link" versus "remove collaborator access." +- [ ] Decide whether share links need expiry before public launch. +- [ ] Implement stale/orphan media cleanup. +- [ ] Add backend tests for share redemption, revocation, role inheritance, and stale op rejection. +- [ ] Add client tests for conflict ack handling and media upload failure recovery. diff --git a/docs/cloud_sync_refactor/convex_sync_refactor_plan.md b/docs/cloud_sync_refactor/convex_sync_refactor_plan.md new file mode 100644 index 00000000..8f9e74c7 --- /dev/null +++ b/docs/cloud_sync_refactor/convex_sync_refactor_plan.md @@ -0,0 +1,204 @@ +# Convex Cloud Sync Refactor Plan + +## Summary + +Intent: refactor Icarus Cloud's Convex sync/query/subscription plumbing so it uses Convex more efficiently while preserving the current UI and all existing product behavior. No visual changes, no feature removals, and no intentional workflow changes. Any currently synced editor state must continue to sync; if inspection finds a currently local-only field that should be cloud-backed, add it to the cloud sync path with tests. + +## Scope + +In scope: Convex queries/mutations, Flutter repository/provider data plumbing, typed model helpers, sync coverage audit, backend/client tests, and performance-oriented query shape changes. + +Out of scope: UI redesign, new conflict UI, product behavior changes, changing the sequence/conflict model, and digest-table migrations unless explicitly approved later. + +## Current Problems To Address + +1. `remote_strategy_snapshot_provider.dart` subscribes to granular Convex data but mostly treats updates as dirty flags, then refetches the whole strategy snapshot. +2. Open strategies use per-page `elements:listForPage` and `lineups:listForPage` subscriptions, creating `3 + 2 * pageCount` active subscriptions. +3. Cloud library queries scan broad tables and filter in TypeScript, especially `strategies.ts` and `folders.ts`. +4. Cloud library summaries are computed from source tables each time; a digest table may help later, but should not be the first change. +5. Deferred follow-up: parent `strategy.sequence` / `updatedAt` is a hot invalidation point, but it is also the current remote change clock, so do not change it in this refactor. + +## Public API And Type Changes + +Add Convex public queries: + +- `elements:listForStrategy({ strategyPublicId })` +- `lineups:listForStrategy({ strategyPublicId })` +- `strategies:listSharedWithMe({})` if still missing in the current backend + +Keep existing queries for compatibility: + +- `elements:listForPage` +- `lineups:listForPage` +- `strategies:listForFolder` +- `pages:listForStrategy` +- `images:listForStrategy` +- `strategies:getHeader` + +Add Flutter repository methods: + +- `listElementsForStrategy(strategyPublicId)` +- `listLineupsForStrategy(strategyPublicId)` +- `watchStrategyHeader(strategyPublicId)` already exists; keep it. +- `watchPagesForStrategy(strategyPublicId)` +- `watchImageAssetsForStrategy(strategyPublicId)` +- `watchElementsForStrategy(strategyPublicId)` +- `watchLineupsForStrategy(strategyPublicId)` + +Add model helpers: + +- `RemoteStrategySnapshot.copyWith(...)` +- helper methods that replace header, pages, assets, elements, or lineups without mutating unrelated snapshot sections +- grouping helpers that convert strategy-level element/lineup lists into `elementsByPage` and `lineupsByPage` + +## Implementation Checklist + +### 1. Create The Workflow Doc + +- [x] Create `docs/cloud_sync_refactor/convex_sync_refactor_plan.md` and save this plan there. +- [x] Use this file as the canonical implementation checklist for the workflow. + +### 2. Add Strategy-Level Element And Lineup Queries + +- [x] In `convex/elements.ts`, add `listForStrategy`. +- [x] Use `getStrategyByPublicId`, `assertStrategyRole(ctx, strategy, "viewer")`, query `elements` with `by_strategyId`, and query `pages` with `by_strategyId` to map internal `pageId` values back to page `publicId`. +- [x] Return the same client shape as `listForPage`, including `publicId`, `strategyPublicId`, `pagePublicId`, `elementType`, `payload`, `sortIndex`, `revision`, `deleted`, `createdAt`, and `updatedAt`. +- [x] In `convex/lineups.ts`, add `listForStrategy` with the same authorization and page lookup pattern. +- [x] Do not remove the page-level queries. + +### 3. Refactor Snapshot Fetching + +- [x] Update `ConvexStrategyRepository.fetchSnapshot` so it calls `strategies:getHeader`, `pages:listForStrategy`, `images:listForStrategy`, `elements:listForStrategy`, and `lineups:listForStrategy`. +- [x] Remove the loop that calls `elements:listForPage` and `lineups:listForPage` for every page. +- [x] Group returned elements and lineups by `pagePublicId`. +- [x] Preserve the same `RemoteStrategySnapshot` shape, page ordering, and deleted-row handling downstream. + +### 4. Use Subscription Payloads Directly + +- [x] Update `RemoteStrategySnapshotNotifier` so subscription callbacks decode their payloads and update only the relevant snapshot section. +- [x] Header update replaces only `snapshot.header`. +- [x] Pages update replaces `snapshot.pages`, updates available page IDs, and prunes maps only for pages that no longer exist. +- [x] Assets update replaces only `snapshot.assetsById`. +- [x] Elements update replaces only `snapshot.elementsByPage`. +- [x] Lineups update replaces only `snapshot.lineupsByPage`. +- [x] Initial open still performs a full `fetchSnapshot`. +- [x] Manual `refresh()` still performs a full `fetchSnapshot`. +- [x] Subscription errors still fall back to the existing refresh/error path. +- [x] Auth incident behavior remains unchanged. + +### 5. Collapse Per-Page Subscriptions + +- [x] Replace the per-page element and lineup subscription maps in `RemoteStrategySnapshotNotifier` with one strategy-level element subscription and one strategy-level lineup subscription. +- [x] Active strategy subscription set becomes `strategies:getHeader`, `pages:listForStrategy`, `images:listForStrategy`, `elements:listForStrategy`, and `lineups:listForStrategy`. +- [x] Remove `_syncPageSubscriptions` / `_syncPageWatchersFromIds` after strategy-level subscriptions are working. +- [x] Keep cleanup behavior in `_disposeSubscriptions`. + +### 6. Preserve Current Editor Behavior + +- [ ] Do not change `StrategyPageSessionNotifier` behavior except where needed to consume the updated snapshot shape. +- [ ] Preserve `header.sequence` as the signal that triggers remote page rehydration. +- [ ] Preserve pending local overlays over remote data. +- [ ] Preserve ack reconciliation refresh behavior when needed. +- [ ] Preserve conflict rejects through `strategyConflictProvider`. +- [ ] Preserve page switch flushes before changing active pages. +- [ ] Preserve media asset URL hydration. + +### 7. Fix Cloud Library Query Shapes + +- [ ] Refactor `convex/strategies.ts` to avoid global table scans for normal user-scoped views. +- [ ] Refactor concrete folder strategy listing to resolve the folder and query `strategies` with `by_folderId`. +- [ ] Refactor owned root strategies to query `strategies` with `by_ownerId` and keep only `folderId === undefined`. +- [ ] Refactor direct shared root strategies to query `strategyCollaborators` with `by_userId`, fetch those strategies, and keep non-owned root strategies. +- [ ] Preserve effective role checks through `getEffectiveStrategyRoleForUser`. +- [ ] Preserve returned `CloudStrategySummary` fields and sorting. +- [ ] Refactor `convex/folders.ts` to use `by_ownerId`, `by_parentFolderId`, and `folderCollaborators.by_userId` instead of scanning all folders. +- [ ] Preserve current visible hierarchy semantics unless a test proves existing behavior is broken. +- [ ] Keep inherited folder role behavior by traversing descendants from directly shared folders through `by_parentFolderId`. +- [ ] Add or fix `strategies:listSharedWithMe` so the Flutter repository call has a real backend function. + +### 8. Sync Coverage Audit + +Must remain synced: + +- [ ] strategy metadata: name, map, theme profile, theme override +- [ ] page data: name, order, attack/defense side, settings +- [ ] elements: agents, abilities, drawings, text, images, utilities +- [ ] lineups and lineup image references +- [ ] image asset metadata and URLs +- [ ] deletes, moves, reorder, payload patches +- [ ] role/capability behavior for owner/editor/viewer + +If a currently user-visible strategy/page field is local-only but should be cloud-backed, add serialization, Convex op handling, hydration, and tests in the same refactor. + +### 9. Digest Table Decision + +Do not implement digest tables in the first pass. + +Follow-up design: + +- Candidate table: `strategyDigests` +- Candidate fields: strategy id/public id, owner id, folder id, name, map data, role-facing summary fields, attack label, created/updated timestamps +- Maintenance points: strategy create/update/move/delete, page add/patch/delete/reorder, share/collaborator changes +- Trigger condition: implement only if optimized indexed library queries still show high read bytes or subscription churn + +### 10. Step Five Follow-Up Hint + +`strategy.sequence` and `updatedAt` are currently patched after accepted ops and act as the remote change clock. Splitting high-churn sync metadata away from stable strategy metadata could reduce header/library invalidations, but it must be planned separately because `StrategyPageSessionNotifier` depends on `header.sequence` for rehydration. Do not change this in the current refactor. + +## Tests And Verification + +Add or update Dart unit tests for snapshot replacement helpers: + +- [ ] header update preserves pages/assets/elements/lineups +- [ ] pages update preserves unchanged page maps and prunes removed pages +- [ ] strategy-level elements are grouped by page +- [ ] strategy-level lineups are grouped by page +- [ ] deleted elements/lineups remain present in remote data but are ignored during hydration as today + +Add or update provider tests: + +- [ ] opening a cloud strategy does one full fetch then uses subscription payloads +- [ ] a header update triggers the same rehydration behavior as before +- [ ] an element update on the active page updates remote snapshot without full refetch +- [ ] a lineup update on the active page updates remote snapshot without full refetch +- [ ] page deletion/reorder keeps active page resolution behavior unchanged +- [ ] ack rejection still records a conflict and refreshes/rebases as before + +Add Convex tests if the test harness is introduced for this work: + +- [ ] `elements:listForStrategy` enforces viewer access +- [ ] `lineups:listForStrategy` enforces viewer access +- [ ] strategy-level queries return page public IDs correctly +- [ ] `strategies:listForFolder` does not expose unauthorized strategies +- [ ] `strategies:listSharedWithMe` returns direct shared strategies +- [ ] folder-shared access still works through inherited folder roles + +Run verification commands: + +```powershell +npx tsc --noEmit +fvm flutter test test\strategy_page_session_provider_test.dart test\strategy_op_queue_provider_test.dart test\collab_sync_models_test.dart test\cloud_ui_parity_helpers_test.dart +fvm flutter analyze +``` + +Expected `fvm flutter analyze` result: no errors; pre-existing warnings/infos may remain. + +## Acceptance Criteria + +- [ ] No visible UI changes. +- [ ] No feature removal. +- [ ] Opening, editing, page switching, collaboration updates, media hydration, conflict handling, and library browsing behave the same as before. +- [ ] Active strategy subscriptions no longer scale with page count. +- [ ] Subscription payloads update local snapshot state directly instead of forcing full snapshot refreshes. +- [ ] Full snapshot refresh remains available for initial load, manual refresh, auth recovery, and error recovery. +- [ ] Cloud library queries no longer scan all strategies or all folders for normal user-scoped views. +- [ ] The saved plan contains a clear deferred note for the sequence/update hot-write concern. + +## Assumptions And Defaults + +- Scope is data plumbing only. +- Target documentation location is `docs/cloud_sync_refactor/convex_sync_refactor_plan.md`. +- Keep current UI exactly as-is. +- Keep `strategy.sequence` as the remote change clock for this refactor. +- Do not implement digest tables until after indexed query cleanup is measured. +- Preserve current backend function names where possible; only add new functions for better Convex query shapes. diff --git a/lib/collab/cloud_media_models.dart b/lib/collab/cloud_media_models.dart new file mode 100644 index 00000000..734cc957 --- /dev/null +++ b/lib/collab/cloud_media_models.dart @@ -0,0 +1,139 @@ +import 'package:hive_ce/hive.dart'; +import 'package:icarus/const/line_provider.dart'; +import 'package:icarus/const/placed_classes.dart'; + +enum CloudMediaJobState { pendingUpload, pendingAttach, failed } + +String normalizeImageExtension(String extension) { + if (extension.isEmpty) { + return extension; + } + return extension.startsWith('.') + ? extension.toLowerCase() + : '.${extension.toLowerCase()}'; +} + +String mimeTypeForImageExtension(String extension) { + switch (normalizeImageExtension(extension)) { + case '.png': + return 'image/png'; + case '.jpg': + case '.jpeg': + return 'image/jpeg'; + case '.gif': + return 'image/gif'; + case '.webp': + return 'image/webp'; + case '.bmp': + return 'image/bmp'; + default: + return 'application/octet-stream'; + } +} + +class CloudMediaUploadJob extends HiveObject { + CloudMediaUploadJob({ + required this.jobId, + required this.strategyPublicId, + required this.assetPublicId, + required this.fileExtension, + required this.mimeType, + required this.state, + required this.attempts, + required this.updatedAt, + this.width, + this.height, + this.storageId, + this.lastError, + }); + + final String jobId; + final String strategyPublicId; + final String assetPublicId; + final String fileExtension; + final String mimeType; + final int? width; + final int? height; + final String? storageId; + final CloudMediaJobState state; + final int attempts; + final String? lastError; + final DateTime updatedAt; + + bool get isFailed => state == CloudMediaJobState.failed; + + CloudMediaUploadJob copyWith({ + String? jobId, + String? strategyPublicId, + String? assetPublicId, + String? fileExtension, + String? mimeType, + int? width, + int? height, + Object? storageId = _noChange, + CloudMediaJobState? state, + int? attempts, + Object? lastError = _noChange, + DateTime? updatedAt, + }) { + return CloudMediaUploadJob( + jobId: jobId ?? this.jobId, + strategyPublicId: strategyPublicId ?? this.strategyPublicId, + assetPublicId: assetPublicId ?? this.assetPublicId, + fileExtension: fileExtension ?? this.fileExtension, + mimeType: mimeType ?? this.mimeType, + width: width ?? this.width, + height: height ?? this.height, + storageId: identical(storageId, _noChange) + ? this.storageId + : storageId as String?, + state: state ?? this.state, + attempts: attempts ?? this.attempts, + lastError: identical(lastError, _noChange) + ? this.lastError + : lastError as String?, + updatedAt: updatedAt ?? this.updatedAt, + ); + } +} + +Map cloudImagePayloadFromPlacedImage(PlacedImage image) { + final payload = Map.from(image.toJson()); + payload['link'] = ''; + return payload; +} + +Map cloudLineupPayload(LineUp lineup) { + return { + ...lineup.toJson(), + 'images': [ + for (final image in lineup.images) image.toJson(), + ], + }; +} + +Set collectStrategyImageAssetIds(StrategyDataLike strategy) { + final assetIds = {}; + for (final page in strategy.pages) { + for (final image in page.imageData) { + assetIds.add(image.id); + } + for (final lineup in page.lineUps) { + for (final image in lineup.images) { + assetIds.add(image.id); + } + } + } + return assetIds; +} + +abstract class StrategyDataLike { + Iterable get pages; +} + +abstract class StrategyPageLike { + Iterable get imageData; + Iterable get lineUps; +} + +const _noChange = Object(); diff --git a/lib/collab/collab_models.dart b/lib/collab/collab_models.dart index 1090468e..975aefca 100644 --- a/lib/collab/collab_models.dart +++ b/lib/collab/collab_models.dart @@ -290,18 +290,127 @@ class RemoteLineup { } } +class RemoteImageAsset { + const RemoteImageAsset({ + required this.publicId, + required this.fileExtension, + required this.width, + required this.height, + required this.url, + required this.legacyStoragePath, + this.mimeType, + }); + + final String publicId; + final String fileExtension; + final String? mimeType; + final int? width; + final int? height; + final String? url; + final String? legacyStoragePath; + + factory RemoteImageAsset.fromJson(Map json) { + return RemoteImageAsset( + publicId: json['publicId'] as String, + fileExtension: json['fileExtension'] as String? ?? '', + mimeType: json['mimeType'] as String?, + width: (json['width'] as num?)?.toInt(), + height: (json['height'] as num?)?.toInt(), + url: json['url'] as String?, + legacyStoragePath: json['legacyStoragePath'] as String?, + ); + } +} + class RemoteStrategySnapshot { const RemoteStrategySnapshot({ required this.header, required this.pages, required this.elementsByPage, required this.lineupsByPage, + required this.assetsById, }); final RemoteStrategyHeader header; final List pages; final Map> elementsByPage; final Map> lineupsByPage; + final Map assetsById; + + RemoteStrategySnapshot copyWith({ + RemoteStrategyHeader? header, + List? pages, + Map>? elementsByPage, + Map>? lineupsByPage, + Map? assetsById, + }) { + return RemoteStrategySnapshot( + header: header ?? this.header, + pages: pages ?? this.pages, + elementsByPage: elementsByPage ?? this.elementsByPage, + lineupsByPage: lineupsByPage ?? this.lineupsByPage, + assetsById: assetsById ?? this.assetsById, + ); + } + + RemoteStrategySnapshot replaceHeader(RemoteStrategyHeader next) { + return copyWith(header: next); + } + + RemoteStrategySnapshot replacePages(List next) { + final pageIds = next.map((page) => page.publicId).toSet(); + return copyWith( + pages: next, + elementsByPage: Map>.fromEntries( + elementsByPage.entries.where((entry) => pageIds.contains(entry.key)), + ), + lineupsByPage: Map>.fromEntries( + lineupsByPage.entries.where((entry) => pageIds.contains(entry.key)), + ), + ); + } + + RemoteStrategySnapshot replaceAssets(List next) { + return copyWith( + assetsById: { + for (final asset in next) asset.publicId: asset, + }, + ); + } + + RemoteStrategySnapshot replaceElements(List next) { + return copyWith(elementsByPage: groupElementsByPage(next)); + } + + RemoteStrategySnapshot replaceLineups(List next) { + return copyWith(lineupsByPage: groupLineupsByPage(next)); + } + + static Map> groupElementsByPage( + Iterable elements, + ) { + final grouped = >{}; + for (final element in elements) { + (grouped[element.pagePublicId] ??= []).add(element); + } + for (final elements in grouped.values) { + elements.sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + } + return grouped; + } + + static Map> groupLineupsByPage( + Iterable lineups, + ) { + final grouped = >{}; + for (final lineup in lineups) { + (grouped[lineup.pagePublicId] ??= []).add(lineup); + } + for (final lineups in grouped.values) { + lineups.sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + } + return grouped; + } } class CloudStrategySummary { @@ -349,6 +458,7 @@ class CloudFolderSummary { required this.name, required this.createdAt, required this.updatedAt, + this.role, this.parentFolderPublicId, this.iconCodePoint, this.iconFontFamily, @@ -361,6 +471,7 @@ class CloudFolderSummary { final String name; final DateTime createdAt; final DateTime updatedAt; + final String? role; final String? parentFolderPublicId; final int? iconCodePoint; final String? iconFontFamily; @@ -378,6 +489,7 @@ class CloudFolderSummary { updatedAt: DateTime.fromMillisecondsSinceEpoch( (json['updatedAt'] as num?)?.toInt() ?? 0, ), + role: json['role'] as String?, parentFolderPublicId: json['parentFolderPublicId'] as String?, iconCodePoint: (json['iconCodePoint'] as num?)?.toInt(), iconFontFamily: json['iconFontFamily'] as String?, @@ -387,3 +499,34 @@ class CloudFolderSummary { ); } } + +class ShareLinkSummary { + const ShareLinkSummary({ + required this.token, + required this.role, + required this.createdAt, + this.revokedAt, + }); + + final String token; + final String role; + final DateTime createdAt; + final DateTime? revokedAt; + + bool get isRevoked => revokedAt != null; + + factory ShareLinkSummary.fromJson(Map json) { + return ShareLinkSummary( + token: json['token'] as String, + role: json['role'] as String, + createdAt: DateTime.fromMillisecondsSinceEpoch( + (json['createdAt'] as num?)?.toInt() ?? 0, + ), + revokedAt: json['revokedAt'] == null + ? null + : DateTime.fromMillisecondsSinceEpoch( + (json['revokedAt'] as num).toInt(), + ), + ); + } +} diff --git a/lib/collab/convex_strategy_repository.dart b/lib/collab/convex_strategy_repository.dart index c2ab6e28..f80b93ce 100644 --- a/lib/collab/convex_strategy_repository.dart +++ b/lib/collab/convex_strategy_repository.dart @@ -52,19 +52,22 @@ class ConvexStrategyRepository { } Future> listFoldersForParent( - String? parentFolderPublicId, - ) async { + String? parentFolderPublicId, { + String scope = 'owned', + }) async { final response = await _client.query('folders:listForParent', { if (parentFolderPublicId != null) 'parentFolderPublicId': parentFolderPublicId, + 'scope': scope, }); return _decodeObjectList(response) .map(CloudFolderSummary.fromJson) .toList(growable: false); } - Future> listAllFolders() async { - final response = await _client.query('folders:listAll', {}); + Future> listAllFolders( + {String scope = 'all'}) async { + final response = await _client.query('folders:listAll', {'scope': scope}); return _decodeObjectList(response) .map(CloudFolderSummary.fromJson) .toList(growable: false); @@ -83,7 +86,7 @@ class ConvexStrategyRepository { subscription = await _client.subscribe( name: 'folders:listAll', - args: const {}, + args: const {'scope': 'all'}, onUpdate: (value) { try { final mapped = _decodeObjectList(value) @@ -111,25 +114,36 @@ class ConvexStrategyRepository { } Future> listStrategiesForFolder( - String? folderPublicId, - ) async { + String? folderPublicId, { + String scope = 'owned', + }) async { final response = await _client.query('strategies:listForFolder', { if (folderPublicId != null) 'folderPublicId': folderPublicId, + 'scope': scope, }); return _decodeObjectList(response) .map(CloudStrategySummary.fromJson) .toList(growable: false); } + Future> listSharedStrategies() async { + final response = await _client.query('strategies:listSharedWithMe', {}); + return _decodeObjectList(response) + .map(CloudStrategySummary.fromJson) + .toList(growable: false); + } + Stream> watchFoldersForParent( - String? parentFolderPublicId, - ) { + String? parentFolderPublicId, { + String scope = 'owned', + }) { final controller = StreamController>.broadcast(); dynamic subscription; Future start() async { try { - controller.add(await listFoldersForParent(parentFolderPublicId)); + controller.add( + await listFoldersForParent(parentFolderPublicId, scope: scope)); } catch (error, stackTrace) { controller.addError(error, stackTrace); } @@ -139,6 +153,7 @@ class ConvexStrategyRepository { args: { if (parentFolderPublicId != null) 'parentFolderPublicId': parentFolderPublicId, + 'scope': scope, }, onUpdate: (value) { try { @@ -168,14 +183,16 @@ class ConvexStrategyRepository { } Stream> watchStrategiesForFolder( - String? folderPublicId, - ) { + String? folderPublicId, { + String scope = 'owned', + }) { final controller = StreamController>.broadcast(); dynamic subscription; Future start() async { try { - controller.add(await listStrategiesForFolder(folderPublicId)); + controller + .add(await listStrategiesForFolder(folderPublicId, scope: scope)); } catch (error, stackTrace) { controller.addError(error, stackTrace); } @@ -184,6 +201,7 @@ class ConvexStrategyRepository { name: 'strategies:listForFolder', args: { if (folderPublicId != null) 'folderPublicId': folderPublicId, + 'scope': scope, }, onUpdate: (value) { try { @@ -213,6 +231,48 @@ class ConvexStrategyRepository { return controller.stream; } + Stream> watchSharedStrategies() { + final controller = StreamController>.broadcast(); + dynamic subscription; + + Future start() async { + try { + controller.add(await listSharedStrategies()); + } catch (error, stackTrace) { + controller.addError(error, stackTrace); + } + + subscription = await _client.subscribe( + name: 'strategies:listSharedWithMe', + args: const {}, + onUpdate: (value) { + try { + final mapped = _decodeObjectList(value) + .map(CloudStrategySummary.fromJson) + .toList(growable: false); + controller.add(mapped); + } catch (error, stackTrace) { + controller.addError(error, stackTrace); + } + }, + onError: (message, value) { + controller.addError( + Exception('strategies:listSharedWithMe error: $message')); + }, + ); + } + + start(); + + controller.onCancel = () { + try { + subscription?.cancel(); + } catch (_) {} + }; + + return controller.stream; + } + Stream watchStrategyHeader(String strategyPublicId) { final controller = StreamController.broadcast(); dynamic subscription; @@ -245,52 +305,196 @@ class ConvexStrategyRepository { return controller.stream; } - Future fetchSnapshot(String strategyPublicId) async { - final headerRaw = await _client.query('strategies:getHeader', { + Future> listPagesForStrategy(String strategyPublicId) async { + final response = await _client.query('pages:listForStrategy', { 'strategyPublicId': strategyPublicId, }); - final header = RemoteStrategyHeader.fromJson(_decodeObject(headerRaw)); + return _decodeObjectList(response) + .map(RemotePage.fromJson) + .toList(growable: false) + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + } - final pagesRaw = await _client.query('pages:listForStrategy', { + Future> listImageAssetsForStrategy( + String strategyPublicId, + ) async { + final response = await _client.query('images:listForStrategy', { 'strategyPublicId': strategyPublicId, }); + return _decodeObjectList(response) + .map(RemoteImageAsset.fromJson) + .toList(growable: false); + } - final pages = _decodeObjectList(pagesRaw) - .map(RemotePage.fromJson) + Future> listElementsForStrategy( + String strategyPublicId, + ) async { + final response = await _client.query('elements:listForStrategy', { + 'strategyPublicId': strategyPublicId, + }); + return _decodeObjectList(response) + .map(RemoteElement.fromJson) + .toList(growable: false) + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + } + + Future> listLineupsForStrategy( + String strategyPublicId, + ) async { + final response = await _client.query('lineups:listForStrategy', { + 'strategyPublicId': strategyPublicId, + }); + return _decodeObjectList(response) + .map(RemoteLineup.fromJson) .toList(growable: false) ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + } - final elementsByPage = >{}; - final lineupsByPage = >{}; + Stream> _watchList({ + required String name, + required Map args, + required T Function(Map) fromJson, + }) { + final controller = StreamController>.broadcast(); + dynamic subscription; - for (final page in pages) { - final elementsRaw = await _client.query('elements:listForPage', { - 'strategyPublicId': strategyPublicId, - 'pagePublicId': page.publicId, - }); - final elements = _decodeObjectList(elementsRaw) - .map(RemoteElement.fromJson) - .toList(growable: false) - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - elementsByPage[page.publicId] = elements; - - final lineupsRaw = await _client.query('lineups:listForPage', { - 'strategyPublicId': strategyPublicId, - 'pagePublicId': page.publicId, - }); - final lineups = _decodeObjectList(lineupsRaw) - .map(RemoteLineup.fromJson) - .toList(growable: false) - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - lineupsByPage[page.publicId] = lineups; + Future start() async { + subscription = await _client.subscribe( + name: name, + args: args, + onUpdate: (value) { + try { + final mapped = + _decodeObjectList(value).map(fromJson).toList(growable: false); + controller.add(mapped); + } catch (error, stackTrace) { + controller.addError(error, stackTrace); + } + }, + onError: (message, value) { + controller.addError(Exception('$name error: $message')); + }, + ); } + start(); + controller.onCancel = () { + try { + subscription?.cancel(); + } catch (_) {} + }; + + return controller.stream; + } + + Stream> watchPagesForStrategy(String strategyPublicId) { + return _watchList( + name: 'pages:listForStrategy', + args: {'strategyPublicId': strategyPublicId}, + fromJson: RemotePage.fromJson, + ).map((pages) => pages..sort((a, b) => a.sortIndex.compareTo(b.sortIndex))); + } + + Stream> watchImageAssetsForStrategy( + String strategyPublicId, + ) { + return _watchList( + name: 'images:listForStrategy', + args: {'strategyPublicId': strategyPublicId}, + fromJson: RemoteImageAsset.fromJson, + ); + } + + Stream> watchElementsForStrategy( + String strategyPublicId, + ) { + return _watchList( + name: 'elements:listForStrategy', + args: {'strategyPublicId': strategyPublicId}, + fromJson: RemoteElement.fromJson, + ).map((elements) => + elements..sort((a, b) => a.sortIndex.compareTo(b.sortIndex))); + } + + Stream> watchLineupsForStrategy( + String strategyPublicId, + ) { + return _watchList( + name: 'lineups:listForStrategy', + args: {'strategyPublicId': strategyPublicId}, + fromJson: RemoteLineup.fromJson, + ).map((lineups) => + lineups..sort((a, b) => a.sortIndex.compareTo(b.sortIndex))); + } + + Future fetchSnapshot(String strategyPublicId) async { + final headerRaw = await _client.query('strategies:getHeader', { + 'strategyPublicId': strategyPublicId, + }); + final header = RemoteStrategyHeader.fromJson(_decodeObject(headerRaw)); + + final pages = await listPagesForStrategy(strategyPublicId); + final assets = await listImageAssetsForStrategy(strategyPublicId); + final elements = await listElementsForStrategy(strategyPublicId); + final lineups = await listLineupsForStrategy(strategyPublicId); + final assetsById = { + for (final asset in assets) asset.publicId: asset, + }; + return RemoteStrategySnapshot( header: header, pages: pages, - elementsByPage: elementsByPage, - lineupsByPage: lineupsByPage, + elementsByPage: RemoteStrategySnapshot.groupElementsByPage(elements), + lineupsByPage: RemoteStrategySnapshot.groupLineupsByPage(lineups), + assetsById: assetsById, + ); + } + + Future generateImageUploadUrl(String strategyPublicId) async { + final response = await _client.mutation( + name: 'images:generateUploadUrl', + args: { + 'strategyPublicId': strategyPublicId, + }, + ); + return (_decodeObject(response)['uploadUrl'] as String?) ?? ''; + } + + Future completeImageUpload({ + required String strategyPublicId, + required String assetPublicId, + required String storageId, + String? mimeType, + String? fileExtension, + int? width, + int? height, + }) async { + await _client.mutation( + name: 'images:completeUpload', + args: { + 'strategyPublicId': strategyPublicId, + 'assetPublicId': assetPublicId, + 'storageId': storageId, + if (mimeType != null) 'mimeType': mimeType, + if (fileExtension != null) 'fileExtension': fileExtension, + if (width != null) 'width': width, + if (height != null) 'height': height, + }, + ); + } + + Future getImageAssetUrl({ + required String strategyPublicId, + required String assetPublicId, + }) async { + final response = await _client.query( + 'images:getAssetUrl', + { + 'strategyPublicId': strategyPublicId, + 'assetPublicId': assetPublicId, + }, ); + return _decodeObject(response)['url'] as String?; } Future> applyBatch({ @@ -366,4 +570,88 @@ class ConvexStrategyRepository { }, ); } + + Future createStrategyWithInitialPage({ + required String publicId, + required String name, + required String mapData, + required String initialPagePublicId, + required String initialPageName, + required bool initialPageIsAttack, + String? folderPublicId, + String? themeProfileId, + String? themeOverridePalette, + String? initialPageSettings, + }) async { + await _client.mutation( + name: 'strategies:createWithInitialPage', + args: { + 'publicId': publicId, + 'name': name, + 'mapData': mapData, + 'initialPagePublicId': initialPagePublicId, + 'initialPageName': initialPageName, + 'initialPageIsAttack': initialPageIsAttack, + if (folderPublicId != null) 'folderPublicId': folderPublicId, + if (themeProfileId != null) 'themeProfileId': themeProfileId, + if (themeOverridePalette != null) + 'themeOverridePalette': themeOverridePalette, + if (initialPageSettings != null) + 'initialPageSettings': initialPageSettings, + }, + ); + } + + Future> listShareLinks({ + required String targetType, + required String targetPublicId, + }) async { + final response = await _client.query('shares:list', { + 'targetType': targetType, + 'targetPublicId': targetPublicId, + }); + return _decodeObjectList(response) + .map(ShareLinkSummary.fromJson) + .toList(growable: false); + } + + Future createShareLink({ + required String targetType, + required String targetPublicId, + required String token, + required String role, + }) async { + await _client.mutation( + name: 'shares:create', + args: { + 'targetType': targetType, + 'targetPublicId': targetPublicId, + 'token': token, + 'role': role, + }, + ); + } + + Future revokeShareLink({ + required String targetType, + required String targetPublicId, + required String token, + }) async { + await _client.mutation( + name: 'shares:revoke', + args: { + 'targetType': targetType, + 'targetPublicId': targetPublicId, + 'token': token, + }, + ); + } + + Future> redeemShareLink(String token) async { + final response = await _client.mutation( + name: 'shares:redeem', + args: {'token': token}, + ); + return _decodeObject(response); + } } diff --git a/lib/const/hive_boxes.dart b/lib/const/hive_boxes.dart index b1460824..53e6fc1a 100644 --- a/lib/const/hive_boxes.dart +++ b/lib/const/hive_boxes.dart @@ -1,6 +1,7 @@ class HiveBoxNames { static const strategiesBox = "strategy_box"; static const foldersBox = "folder_box"; + static const mediaUploadJobsBox = "media_upload_jobs_box"; static const mapThemeProfilesBox = "map_theme_profiles_box"; static const appPreferencesBox = "app_preferences_box"; static const favoriteAgentsBox = "favorite_agents_box"; diff --git a/lib/const/placed_media_dimensions.dart b/lib/const/placed_media_dimensions.dart new file mode 100644 index 00000000..daa2c3ed --- /dev/null +++ b/lib/const/placed_media_dimensions.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; +import 'package:icarus/const/coordinate_system.dart'; +import 'package:icarus/const/image_scale_policy.dart'; + +abstract final class PlacedImageDimensions { + static const double tagWidth = 10.0; + static const double tagGap = 2.0; + static const double imagePadding = 5.0; + + static Size screenSize({ + required CoordinateSystem coordinateSystem, + required double scale, + required double aspectRatio, + }) { + final safeAspectRatio = aspectRatio <= 0 ? 1.0 : aspectRatio; + final totalWidth = + coordinateSystem.worldWidthToScreen(ImageScalePolicy.clamp(scale)); + final cardWidth = + (totalWidth - tagWidth - tagGap).clamp(1.0, double.infinity); + final contentWidth = + (cardWidth - (imagePadding * 2)).clamp(1.0, double.infinity); + final totalHeight = (contentWidth / safeAspectRatio) + (imagePadding * 2); + + return Size(totalWidth, totalHeight); + } +} + +abstract final class PlacedTextDimensions { + static const double tagWidth = 6.0; + static const double tagGap = 2.0; + static const double cardHorizontalPadding = 5.0; + static const double cardVerticalPadding = 6.0; + static const String emptyTextPlaceholder = 'Write here...'; + + static Size screenSize({ + required CoordinateSystem coordinateSystem, + required double widthWorld, + required double fontSizeWorld, + required String text, + }) { + final totalWidth = coordinateSystem.worldWidthToScreen(widthWorld); + final maxContentWidth = contentWidth( + coordinateSystem: coordinateSystem, + widthWorld: widthWorld, + ); + + final displayText = text.isEmpty ? ' ' : _withBreakOpportunities(text); + final style = textStyle( + coordinateSystem: coordinateSystem, + fontSizeWorld: fontSizeWorld, + ); + + final painter = TextPainter( + text: TextSpan( + text: displayText, + style: style, + ), + maxLines: null, + textDirection: TextDirection.ltr, + textScaler: TextScaler.noScaling, + )..layout(minWidth: maxContentWidth, maxWidth: maxContentWidth); + + final lineMetrics = painter.computeLineMetrics(); + // EditableText can keep one extra wrapped line in its scroll extent. + final wrappedTextSlack = lineMetrics.length > 1 && lineMetrics.isNotEmpty + ? lineMetrics.last.height.ceilToDouble() + : 0.0; + final totalHeight = painter.height.ceilToDouble() + + wrappedTextSlack + + (cardVerticalPadding * 2); + return Size(totalWidth, totalHeight); + } + + static double contentWidth({ + required CoordinateSystem coordinateSystem, + required double widthWorld, + }) { + final totalWidth = coordinateSystem.worldWidthToScreen(widthWorld); + return (totalWidth - tagWidth - tagGap - (cardHorizontalPadding * 2)) + .clamp(1.0, double.infinity); + } + + static double fontSizePx({ + required CoordinateSystem coordinateSystem, + required double fontSizeWorld, + }) { + return coordinateSystem.worldHeightToScreen(fontSizeWorld); + } + + static TextStyle textStyle({ + required CoordinateSystem coordinateSystem, + required double fontSizeWorld, + }) { + final fontSizePx = PlacedTextDimensions.fontSizePx( + coordinateSystem: coordinateSystem, + fontSizeWorld: fontSizeWorld, + ); + return TextStyle(fontSize: fontSizePx, height: 1.0); + } + + static String _withBreakOpportunities(String text) { + final buffer = StringBuffer(); + for (final rune in text.runes) { + buffer + ..writeCharCode(rune) + ..write('\u200B'); + } + return buffer.toString(); + } +} diff --git a/lib/hive/hive_adapters.dart b/lib/hive/hive_adapters.dart index 8d0d0c02..c88218d2 100644 --- a/lib/hive/hive_adapters.dart +++ b/lib/hive/hive_adapters.dart @@ -5,6 +5,7 @@ import 'dart:ui' show Offset; import 'package:flutter/material.dart'; import 'package:hive_ce/hive.dart'; +import 'package:icarus/collab/cloud_media_models.dart'; import 'package:icarus/const/agents.dart'; import 'package:icarus/const/bounding_box.dart'; import 'package:icarus/const/drawing_element.dart'; @@ -42,6 +43,8 @@ import 'package:icarus/strategy/strategy_models.dart'; AdapterSpec(), AdapterSpec(), AdapterSpec(), + AdapterSpec(), + AdapterSpec(), AdapterSpec(), AdapterSpec(), AdapterSpec(), diff --git a/lib/hive/hive_adapters.g.dart b/lib/hive/hive_adapters.g.dart index 28e96733..22623a17 100644 --- a/lib/hive/hive_adapters.g.dart +++ b/lib/hive/hive_adapters.g.dart @@ -1708,3 +1708,111 @@ class AbilityVisualStateAdapter extends TypeAdapter { runtimeType == other.runtimeType && typeId == other.typeId; } + +class CloudMediaJobStateAdapter extends TypeAdapter { + @override + final typeId = 34; + + @override + CloudMediaJobState read(BinaryReader reader) { + switch (reader.readByte()) { + case 0: + return CloudMediaJobState.pendingUpload; + case 1: + return CloudMediaJobState.pendingAttach; + case 2: + return CloudMediaJobState.failed; + default: + return CloudMediaJobState.pendingUpload; + } + } + + @override + void write(BinaryWriter writer, CloudMediaJobState obj) { + switch (obj) { + case CloudMediaJobState.pendingUpload: + writer.writeByte(0); + case CloudMediaJobState.pendingAttach: + writer.writeByte(1); + case CloudMediaJobState.failed: + writer.writeByte(2); + } + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CloudMediaJobStateAdapter && + runtimeType == other.runtimeType && + typeId == other.typeId; +} + +class CloudMediaUploadJobAdapter extends TypeAdapter { + @override + final typeId = 35; + + @override + CloudMediaUploadJob read(BinaryReader reader) { + final numOfFields = reader.readByte(); + final fields = { + for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), + }; + return CloudMediaUploadJob( + jobId: fields[0] as String, + strategyPublicId: fields[1] as String, + assetPublicId: fields[5] as String, + fileExtension: fields[6] as String, + mimeType: fields[7] as String, + state: fields[11] as CloudMediaJobState, + attempts: (fields[12] as num).toInt(), + updatedAt: fields[14] as DateTime, + width: (fields[8] as num?)?.toInt(), + height: (fields[9] as num?)?.toInt(), + storageId: fields[10] as String?, + lastError: fields[13] as String?, + ); + } + + @override + void write(BinaryWriter writer, CloudMediaUploadJob obj) { + writer + ..writeByte(12) + ..writeByte(0) + ..write(obj.jobId) + ..writeByte(1) + ..write(obj.strategyPublicId) + ..writeByte(5) + ..write(obj.assetPublicId) + ..writeByte(6) + ..write(obj.fileExtension) + ..writeByte(7) + ..write(obj.mimeType) + ..writeByte(8) + ..write(obj.width) + ..writeByte(9) + ..write(obj.height) + ..writeByte(10) + ..write(obj.storageId) + ..writeByte(11) + ..write(obj.state) + ..writeByte(12) + ..write(obj.attempts) + ..writeByte(13) + ..write(obj.lastError) + ..writeByte(14) + ..write(obj.updatedAt); + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CloudMediaUploadJobAdapter && + runtimeType == other.runtimeType && + typeId == other.typeId; +} diff --git a/lib/hive/hive_adapters.g.yaml b/lib/hive/hive_adapters.g.yaml index cc067d37..b79950f8 100644 --- a/lib/hive/hive_adapters.g.yaml +++ b/lib/hive/hive_adapters.g.yaml @@ -1,7 +1,7 @@ # Generated by Hive CE # Manual modifications may be necessary for certain migrations # Check in to version control -nextTypeId: 33 +nextTypeId: 36 types: StrategyData: typeId: 0 @@ -585,3 +585,41 @@ types: index: 4 showInnerFill: index: 5 + CloudMediaJobState: + typeId: 34 + nextIndex: 3 + fields: + pendingUpload: + index: 0 + pendingAttach: + index: 1 + failed: + index: 2 + CloudMediaUploadJob: + typeId: 35 + nextIndex: 15 + fields: + jobId: + index: 0 + strategyPublicId: + index: 1 + assetPublicId: + index: 5 + fileExtension: + index: 6 + mimeType: + index: 7 + width: + index: 8 + height: + index: 9 + storageId: + index: 10 + state: + index: 11 + attempts: + index: 12 + lastError: + index: 13 + updatedAt: + index: 14 diff --git a/lib/hive/hive_registrar.g.dart b/lib/hive/hive_registrar.g.dart index 6ad54fa5..cd9b0757 100644 --- a/lib/hive/hive_registrar.g.dart +++ b/lib/hive/hive_registrar.g.dart @@ -14,6 +14,8 @@ extension HiveRegistrar on HiveInterface { registerAdapter(AgentTypeAdapter()); registerAdapter(AppPreferencesAdapter()); registerAdapter(BoundingBoxAdapter()); + registerAdapter(CloudMediaJobStateAdapter()); + registerAdapter(CloudMediaUploadJobAdapter()); registerAdapter(EllipseDrawingAdapter()); registerAdapter(FolderColorAdapter()); registerAdapter(FreeDrawingAdapter()); @@ -50,6 +52,8 @@ extension IsolatedHiveRegistrar on IsolatedHiveInterface { registerAdapter(AgentTypeAdapter()); registerAdapter(AppPreferencesAdapter()); registerAdapter(BoundingBoxAdapter()); + registerAdapter(CloudMediaJobStateAdapter()); + registerAdapter(CloudMediaUploadJobAdapter()); registerAdapter(EllipseDrawingAdapter()); registerAdapter(FolderColorAdapter()); registerAdapter(FreeDrawingAdapter()); diff --git a/lib/main.dart b/lib/main.dart index 5af6387f..b39b1380 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -11,6 +11,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:hive_ce_flutter/adapters.dart'; +import 'package:icarus/collab/cloud_media_models.dart'; import 'package:icarus/services/deep_link_registrar.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; @@ -24,8 +25,10 @@ import 'package:icarus/const/second_instance_args.dart'; import 'package:icarus/const/settings.dart' show Settings; import 'package:icarus/hive/hive_registration.dart'; import 'package:icarus/providers/auth_provider.dart'; +import 'package:icarus/providers/collab/cloud_media_cache_provider.dart'; +import 'package:icarus/providers/collab/cloud_media_upload_queue_provider.dart'; +import 'package:icarus/providers/share_link_provider.dart'; import 'package:icarus/providers/folder_provider.dart'; -import 'package:icarus/providers/in_app_debug_provider.dart'; import 'package:icarus/providers/map_theme_provider.dart'; import 'package:icarus/services/app_error_reporter.dart'; import 'package:icarus/strategy/strategy_import_export.dart'; @@ -82,7 +85,13 @@ Future _initializeDeepLinkHandling() async { } void _publishDeepLink(Uri uri, {required String source}) { - developer.log('Deep link received [$source]: $uri', name: 'deep_link'); + final redactedUri = redactAuthUri(uri); + developer.log('Deep link received [$source]: $redactedUri', + name: 'deep_link'); + AppErrorReporter.reportInfo( + 'Deep link received [$source]: $redactedUri', + source: 'deep_link', + ); if (!_hasDeepLinkListener) { _bufferedDeepLinks.add(uri); return; @@ -134,6 +143,7 @@ Future main(List args) async { await Hive.openBox(HiveBoxNames.strategiesBox); await Hive.openBox(HiveBoxNames.foldersBox); + await Hive.openBox(HiveBoxNames.mediaUploadJobsBox); await Hive.openBox(HiveBoxNames.mapThemeProfilesBox); await Hive.openBox(HiveBoxNames.appPreferencesBox); await Hive.openBox(HiveBoxNames.favoriteAgentsBox); @@ -336,28 +346,39 @@ class _MyAppState extends ConsumerState { final uriText = uri.toString(); if (!_processedDeepLinks.add(uriText)) { developer.log( - 'Ignoring duplicate deep link [$source]: $uriText', + 'Ignoring duplicate deep link [$source]: ${redactAuthUri(uri)}', name: 'deep_link', ); return; } - developer.log('Handling deep link [$source]: $uriText', name: 'deep_link'); - ref - .read(inAppDebugProvider.notifier) - .bulkAddLogs(['Deep link [$source]: $uriText']); + final redactedUri = redactAuthUri(uri); + developer.log('Handling deep link [$source]: $redactedUri', + name: 'deep_link'); + AppErrorReporter.reportInfo( + 'Handling deep link [$source]: $redactedUri', + source: 'deep_link', + ); - unawaited( - ref + unawaited(() async { + final handledAuth = await ref .read(authProvider.notifier) - .handleAuthCallbackUri(uri, source: source), - ); + .handleAuthCallbackUri(uri, source: source); + if (handledAuth) { + return; + } + await ref + .read(shareLinkControllerProvider.notifier) + .handleIncomingUri(uri, source: source); + }()); } @override void initState() { super.initState(); ref.read(authProvider); + ref.read(cloudMediaUploadQueueProvider); + ref.read(cloudMediaCacheProvider); WidgetsBinding.instance.addPostFrameCallback((_) { unawaited(warmUpWebViewEnvironment()); @@ -408,6 +429,16 @@ class _MyAppState extends ConsumerState { @override Widget build(BuildContext context) { + ref.listen(authProvider, (_, next) { + if (next.isAuthenticated && next.isConvexUserReady) { + unawaited( + ref + .read(shareLinkControllerProvider.notifier) + .redeemPendingIfPossible(), + ); + } + }); + return ToastificationWrapper( config: const ToastificationConfig( alignment: Alignment.bottomCenter, diff --git a/lib/providers/action_history_models.dart b/lib/providers/action_history_models.dart index 1c43d691..917836ce 100644 --- a/lib/providers/action_history_models.dart +++ b/lib/providers/action_history_models.dart @@ -5,20 +5,17 @@ import 'package:icarus/const/coordinate_system.dart'; import 'package:icarus/const/drawing_element.dart'; import 'package:icarus/const/line_provider.dart'; import 'package:icarus/const/placed_classes.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; class ActionHistoryTransformContext { final double agentSize; final double abilitySize; final double mapScale; - final Map imageSizes; - final Map textHeights; const ActionHistoryTransformContext({ required this.agentSize, required this.abilitySize, required this.mapScale, - required this.imageSizes, - required this.textHeights, }); } @@ -51,8 +48,7 @@ class ActionObjectState { agent: clonePlacedAgentNode(value), ); - factory ActionObjectState.ability(PlacedAbility value) => - ActionObjectState._( + factory ActionObjectState.ability(PlacedAbility value) => ActionObjectState._( id: value.id, kind: ActionObjectKind.ability, ability: clonePlacedAbility(value), @@ -116,14 +112,8 @@ class ActionObjectState { ActionObjectKind.drawing => ActionObjectState.drawing( switchDrawingElementSides(cloneDrawingElement(drawing!)), ), - ActionObjectKind.text => ActionObjectState.text( - clonePlacedText(text!) - ..switchSides(context.textHeights[text!.id] ?? Offset.zero), - ), - ActionObjectKind.image => ActionObjectState.image( - clonePlacedImage(image!) - ..switchSides(context.imageSizes[image!.id] ?? Offset.zero), - ), + ActionObjectKind.text => _switchTextSides(), + ActionObjectKind.image => _switchImageSides(), ActionObjectKind.utility => ActionObjectState.utility( clonePlacedUtility(utility!) ..switchSides( @@ -142,6 +132,33 @@ class ActionObjectState { ), }; } + + ActionObjectState _switchTextSides() { + final value = clonePlacedText(text!); + final size = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: value.size, + fontSizeWorld: value.fontSize, + text: value.text, + ); + + return ActionObjectState.text( + value..switchSides(Offset(size.width, size.height)), + ); + } + + ActionObjectState _switchImageSides() { + final value = clonePlacedImage(image!); + final size = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: value.scale, + aspectRatio: value.aspectRatio, + ); + + return ActionObjectState.image( + value..switchSides(Offset(size.width, size.height)), + ); + } } enum ActionObjectKind { @@ -157,18 +174,10 @@ enum ActionObjectKind { class ObjectHistoryDelta { final ActionObjectState? before; final ActionObjectState? after; - final Map beforeImageSizes; - final Map afterImageSizes; - final Map beforeTextHeights; - final Map afterTextHeights; const ObjectHistoryDelta({ this.before, this.after, - this.beforeImageSizes = const {}, - this.afterImageSizes = const {}, - this.beforeTextHeights = const {}, - this.afterTextHeights = const {}, }); String get id => after?.id ?? before!.id; @@ -177,10 +186,6 @@ class ObjectHistoryDelta { return ObjectHistoryDelta( before: before?.clone(), after: after?.clone(), - beforeImageSizes: Map.from(beforeImageSizes), - afterImageSizes: Map.from(afterImageSizes), - beforeTextHeights: Map.from(beforeTextHeights), - afterTextHeights: Map.from(afterTextHeights), ); } @@ -188,10 +193,6 @@ class ObjectHistoryDelta { return ObjectHistoryDelta( before: before?.switchSides(context), after: after?.switchSides(context), - beforeImageSizes: Map.from(beforeImageSizes), - afterImageSizes: Map.from(afterImageSizes), - beforeTextHeights: Map.from(beforeTextHeights), - afterTextHeights: Map.from(afterTextHeights), ); } } diff --git a/lib/providers/action_provider.dart b/lib/providers/action_provider.dart index b7fc222a..5e53c012 100644 --- a/lib/providers/action_provider.dart +++ b/lib/providers/action_provider.dart @@ -1,5 +1,3 @@ -import 'dart:ui'; - import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/drawing_element.dart'; import 'package:icarus/const/line_provider.dart'; @@ -10,12 +8,9 @@ import 'package:icarus/providers/ability_provider.dart'; import 'package:icarus/providers/agent_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; import 'package:icarus/providers/image_provider.dart'; -import 'package:icarus/providers/image_widget_size_provider.dart'; import 'package:icarus/providers/map_provider.dart'; -import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/providers/strategy_settings_provider.dart'; import 'package:icarus/providers/text_provider.dart'; -import 'package:icarus/providers/text_widget_height_provider.dart'; import 'package:icarus/providers/utility_provider.dart'; import 'package:icarus/const/maps.dart'; import 'package:uuid/uuid.dart'; @@ -78,8 +73,6 @@ class BulkActionSnapshot { final PlacedImageProviderSnapshot? imageSnapshot; final UtilityProviderSnapshot? utilitySnapshot; final LineUpProviderSnapshot? lineUpSnapshot; - final Map imageSizeSnapshot; - final Map textHeightSnapshot; const BulkActionSnapshot({ required this.targetGroups, @@ -92,14 +85,13 @@ class BulkActionSnapshot { this.imageSnapshot, this.utilitySnapshot, this.lineUpSnapshot, - this.imageSizeSnapshot = const {}, - this.textHeightSnapshot = const {}, }); BulkActionSnapshot copy() { return BulkActionSnapshot( targetGroups: [...targetGroups], - actionStateBefore: actionStateBefore.map((action) => action.copy()).toList(), + actionStateBefore: + actionStateBefore.map((action) => action.copy()).toList(), redoStateBefore: redoStateBefore.map((action) => action.copy()).toList(), agentSnapshot: agentSnapshot == null ? null @@ -131,7 +123,8 @@ class BulkActionSnapshot { updateCounter: drawingSnapshot!.state.updateCounter, currentElement: drawingSnapshot!.state.currentElement == null ? null - : cloneDrawingElement(drawingSnapshot!.state.currentElement!), + : cloneDrawingElement( + drawingSnapshot!.state.currentElement!), ), poppedElements: drawingSnapshot!.poppedElements .map((element) => cloneDrawingElement(element)) @@ -140,8 +133,9 @@ class BulkActionSnapshot { textSnapshot: textSnapshot == null ? null : TextProviderSnapshot( - texts: - textSnapshot!.texts.map((text) => clonePlacedText(text)).toList(), + texts: textSnapshot!.texts + .map((text) => clonePlacedText(text)) + .toList(), poppedText: textSnapshot!.poppedText .map((text) => clonePlacedText(text)) .toList(), @@ -176,16 +170,15 @@ class BulkActionSnapshot { .map((lineUp) => cloneLineUp(lineUp)) .toList(), ), - imageSizeSnapshot: Map.from(imageSizeSnapshot), - textHeightSnapshot: Map.from(textHeightSnapshot), ); } BulkActionSnapshot switchSides(ActionHistoryTransformContext context) { return BulkActionSnapshot( targetGroups: [...targetGroups], - actionStateBefore: - actionStateBefore.map((action) => action.switchSides(context)).toList(), + actionStateBefore: actionStateBefore + .map((action) => action.switchSides(context)) + .toList(), redoStateBefore: redoStateBefore.map((action) => action.switchSides(context)).toList(), agentSnapshot: agentSnapshot == null @@ -193,14 +186,14 @@ class BulkActionSnapshot { : AgentProviderSnapshot( agents: agentSnapshot!.agents .map( - (agent) => - clonePlacedAgentNode(agent)..switchSides(context.agentSize), + (agent) => clonePlacedAgentNode(agent) + ..switchSides(context.agentSize), ) .toList(), poppedAgents: agentSnapshot!.poppedAgents .map( - (agent) => - clonePlacedAgentNode(agent)..switchSides(context.agentSize), + (agent) => clonePlacedAgentNode(agent) + ..switchSides(context.agentSize), ) .toList(), ), @@ -249,18 +242,14 @@ class BulkActionSnapshot { : TextProviderSnapshot( texts: textSnapshot!.texts .map( - (text) => clonePlacedText(text) - ..switchSides( - context.textHeights[text.id] ?? Offset.zero, - ), + (text) => + ActionObjectState.text(text).switchSides(context).text!, ) .toList(), poppedText: textSnapshot!.poppedText .map( - (text) => clonePlacedText(text) - ..switchSides( - context.textHeights[text.id] ?? Offset.zero, - ), + (text) => + ActionObjectState.text(text).switchSides(context).text!, ) .toList(), ), @@ -269,14 +258,16 @@ class BulkActionSnapshot { : PlacedImageProviderSnapshot( images: imageSnapshot!.images .map( - (image) => clonePlacedImage(image) - ..switchSides(context.imageSizes[image.id] ?? Offset.zero), + (image) => ActionObjectState.image(image) + .switchSides(context) + .image!, ) .toList(), poppedImages: imageSnapshot!.poppedImages .map( - (image) => clonePlacedImage(image) - ..switchSides(context.imageSizes[image.id] ?? Offset.zero), + (image) => ActionObjectState.image(image) + .switchSides(context) + .image!, ) .toList(), ), @@ -328,8 +319,6 @@ class BulkActionSnapshot { ) .toList(), ), - imageSizeSnapshot: Map.from(imageSizeSnapshot), - textHeightSnapshot: Map.from(textHeightSnapshot), ); } } @@ -409,7 +398,6 @@ class ActionProvider extends Notifier> { if (_recordingDisabled) { return; } - ref.read(strategyProvider.notifier).setUnsaved(); if (action.group != ActionGroup.ability) { ref .read(abilityBarProvider.notifier) @@ -458,9 +446,6 @@ class ActionProvider extends Notifier> { final newState = [...state]; newState.add(poppedItems.removeLast()); - - ref.read(strategyProvider.notifier).setUnsaved(); - state = newState; // log("\n Current state \n ${state.toString()}"); } @@ -500,9 +485,6 @@ class ActionProvider extends Notifier> { // log("Undo action was called"); final newState = [...state]; poppedItems.add(newState.removeLast()); - - ref.read(strategyProvider.notifier).setUnsaved(); - state = newState; // log("\n Current state \n ${state.toString()}"); @@ -520,17 +502,11 @@ class ActionProvider extends Notifier> { ref.read(utilityProvider.notifier).clearAll(); ref.read(lineUpProvider.notifier).clearAll(); - ref.read(imageWidgetSizeProvider.notifier).clearAll(); - ref.read(textWidgetHeightProvider.notifier).clearAll(); - ref.read(strategyProvider.notifier).setUnsaved(); state = []; } - void clearActionHistory({bool markUnsaved = false}) { + void clearActionHistory() { poppedItems = []; - if (markUnsaved) { - ref.read(strategyProvider.notifier).setUnsaved(); - } state = []; } @@ -545,11 +521,10 @@ class ActionProvider extends Notifier> { agentSize: ref.read(strategySettingsProvider).agentSize, abilitySize: ref.read(strategySettingsProvider).abilitySize, mapScale: Maps.mapScale[mapState.currentMap] ?? 1.0, - imageSizes: Map.from(ref.read(imageWidgetSizeProvider)), - textHeights: Map.from(ref.read(textWidgetHeightProvider)), ); state = state.map((action) => action.switchSides(context)).toList(); - poppedItems = poppedItems.map((action) => action.switchSides(context)).toList(); + poppedItems = + poppedItems.map((action) => action.switchSides(context)).toList(); } void clearAllAsAction() { @@ -619,7 +594,6 @@ class ActionProvider extends Notifier> { ); _clearProvidersForGroups(targetGroups); - _clearAncillaryState(snapshot); state = filteredActions; addAction( @@ -657,13 +631,6 @@ class ActionProvider extends Notifier> { } BulkActionSnapshot _captureBulkSnapshot(List groups) { - final imageIds = groups.contains(ActionGroup.image) - ? ref.read(placedImageProvider).images.map((image) => image.id) - : const []; - final textIds = groups.contains(ActionGroup.text) - ? ref.read(textProvider).map((text) => text.id) - : const []; - return BulkActionSnapshot( targetGroups: [...groups], actionStateBefore: state.map((action) => action.copy()).toList(), @@ -689,12 +656,6 @@ class ActionProvider extends Notifier> { lineUpSnapshot: groups.contains(ActionGroup.lineUp) ? ref.read(lineUpProvider.notifier).takeSnapshot() : null, - imageSizeSnapshot: ref - .read(imageWidgetSizeProvider.notifier) - .takeSnapshotForIds(imageIds), - textHeightSnapshot: ref - .read(textWidgetHeightProvider.notifier) - .takeSnapshotForIds(textIds), ); } @@ -749,19 +710,6 @@ class ActionProvider extends Notifier> { } } - void _clearAncillaryState(BulkActionSnapshot snapshot) { - if (snapshot.imageSizeSnapshot.isNotEmpty) { - ref - .read(imageWidgetSizeProvider.notifier) - .clearEntries(snapshot.imageSizeSnapshot.keys); - } - if (snapshot.textHeightSnapshot.isNotEmpty) { - ref - .read(textWidgetHeightProvider.notifier) - .clearEntries(snapshot.textHeightSnapshot.keys); - } - } - void _restoreBulkSnapshot(BulkActionSnapshot snapshot) { if (snapshot.agentSnapshot != null) { ref.read(agentProvider.notifier).restoreSnapshot(snapshot.agentSnapshot!); @@ -794,17 +742,6 @@ class ActionProvider extends Notifier> { .read(lineUpProvider.notifier) .restoreSnapshot(snapshot.lineUpSnapshot!); } - - if (snapshot.imageSizeSnapshot.isNotEmpty) { - ref - .read(imageWidgetSizeProvider.notifier) - .restoreSnapshot(snapshot.imageSizeSnapshot); - } - if (snapshot.textHeightSnapshot.isNotEmpty) { - ref - .read(textWidgetHeightProvider.notifier) - .restoreSnapshot(snapshot.textHeightSnapshot); - } } void _undoBulkAction(UserAction action) { @@ -813,7 +750,6 @@ class ActionProvider extends Notifier> { _restoreBulkSnapshot(snapshot); poppedItems.add(action); - ref.read(strategyProvider.notifier).setUnsaved(); state = snapshot.actionStateBefore.map((item) => item.copy()).toList(); } @@ -822,12 +758,10 @@ class ActionProvider extends Notifier> { if (snapshot == null) return; _clearProvidersForGroups(snapshot.targetGroups); - _clearAncillaryState(snapshot); final newState = _filterActionsForGroups(state, snapshot.targetGroups) ..add(poppedItems.removeLast()); - ref.read(strategyProvider.notifier).setUnsaved(); ref.read(abilityBarProvider.notifier).updateData(null); state = newState; } @@ -839,7 +773,6 @@ class ActionProvider extends Notifier> { _restoreBulkSnapshot(snapshot.before); final newState = [...state]; poppedItems.add(newState.removeLast()); - ref.read(strategyProvider.notifier).setUnsaved(); state = newState; } @@ -850,7 +783,6 @@ class ActionProvider extends Notifier> { _restoreBulkSnapshot(snapshot.after); final newState = [...state]; newState.add(poppedItems.removeLast()); - ref.read(strategyProvider.notifier).setUnsaved(); ref.read(abilityBarProvider.notifier).updateData(null); state = newState; } @@ -869,7 +801,8 @@ class ActionProvider extends Notifier> { } bool _canKeepEditAction(ObjectHistoryDelta delta) { - final current = _currentObjectState(delta.id, delta.before?.kind ?? delta.after?.kind); + final current = + _currentObjectState(delta.id, delta.before?.kind ?? delta.after?.kind); if (current == null) { return false; } @@ -891,9 +824,11 @@ class ActionProvider extends Notifier> { if (index < 0) return null; return ActionObjectState.ability(ref.read(abilityProvider)[index]); case ActionObjectKind.drawing: - final index = DrawingElement.getIndexByID(id, ref.read(drawingProvider).elements); + final index = + DrawingElement.getIndexByID(id, ref.read(drawingProvider).elements); if (index < 0) return null; - return ActionObjectState.drawing(ref.read(drawingProvider).elements[index]); + return ActionObjectState.drawing( + ref.read(drawingProvider).elements[index]); case ActionObjectKind.text: final index = PlacedWidget.getIndexByID(id, ref.read(textProvider)); if (index < 0) return null; diff --git a/lib/providers/agent_provider.dart b/lib/providers/agent_provider.dart index 253a63f5..236077eb 100644 --- a/lib/providers/agent_provider.dart +++ b/lib/providers/agent_provider.dart @@ -36,6 +36,8 @@ class AgentProvider extends Notifier> { } void addAgent(PlacedAgentNode placedAgent) { + state = [...state, placedAgent]; + final action = UserAction( type: ActionType.addition, id: placedAgent.id, @@ -46,7 +48,6 @@ class AgentProvider extends Notifier> { ); ref.read(actionProvider.notifier).addAction(action); - state = [...state, placedAgent]; } void removeAgent(String id) { diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart index e31ace7a..7a82c88c 100644 --- a/lib/providers/auth_provider.dart +++ b/lib/providers/auth_provider.dart @@ -5,6 +5,7 @@ import 'package:convex_flutter/convex_flutter.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/app_navigator.dart'; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; final authProvider = @@ -49,6 +50,50 @@ bool isConvexUnauthenticatedError(Object error) { return isConvexUnauthenticatedMessage(error.toString()); } +String redactAuthUri(Uri uri) { + const sensitiveKeys = { + 'access_token', + 'refresh_token', + 'provider_token', + 'provider_refresh_token', + 'code', + 'code_verifier', + }; + + String redactFragment(String fragment) { + if (fragment.isEmpty) { + return fragment; + } + + final params = Uri.splitQueryString(fragment); + if (params.isEmpty) { + return ''; + } + + return params.entries.map((entry) { + final value = sensitiveKeys.contains(entry.key.toLowerCase()) + ? '' + : entry.value; + return '${Uri.encodeQueryComponent(entry.key)}=' + '${Uri.encodeQueryComponent(value)}'; + }).join('&'); + } + + final queryParameters = {}; + for (final entry in uri.queryParameters.entries) { + queryParameters[entry.key] = sensitiveKeys.contains(entry.key.toLowerCase()) + ? '' + : entry.value; + } + + return uri + .replace( + queryParameters: queryParameters.isEmpty ? null : queryParameters, + fragment: redactFragment(uri.fragment), + ) + .toString(); +} + class AppAuthState { const AppAuthState({ required this.isLoading, @@ -628,9 +673,18 @@ class AuthProvider extends Notifier { Future handleAuthCallbackUri(Uri uri, {required String source}) async { if (!isAuthCallbackUri(uri)) { + AppErrorReporter.reportInfo( + 'Deep link was not an auth callback [$source]: ${redactAuthUri(uri)}', + source: 'auth', + ); return false; } + AppErrorReporter.reportInfo( + 'Handling auth callback [$source]: ${redactAuthUri(uri)}', + source: 'auth', + ); + state = state.copyWith( isLoading: true, isConvexUserReady: false, @@ -641,7 +695,14 @@ class AuthProvider extends Notifier { try { await _supabaseApi.getSessionFromUrl(uri); state = state.copyWith(isLoading: false); - log('Handled auth callback [$source]: $uri', name: 'auth'); + log( + 'Handled auth callback [$source]: ${redactAuthUri(uri)}', + name: 'auth', + ); + AppErrorReporter.reportInfo( + 'Handled auth callback [$source]', + source: 'auth', + ); return true; } catch (error, stackTrace) { log( @@ -650,6 +711,12 @@ class AuthProvider extends Notifier { error: error, stackTrace: stackTrace, ); + AppErrorReporter.reportError( + 'Failed auth callback [$source]: ${redactAuthUri(uri)}', + source: 'auth', + error: error, + stackTrace: stackTrace, + ); state = state.copyWith( isLoading: false, isConvexUserReady: false, diff --git a/lib/providers/collab/active_page_live_sync_models.dart b/lib/providers/collab/active_page_live_sync_models.dart index 3fef43e9..4e2ef82e 100644 --- a/lib/providers/collab/active_page_live_sync_models.dart +++ b/lib/providers/collab/active_page_live_sync_models.dart @@ -4,20 +4,25 @@ typedef EntitySyncKey = String; enum ActivePageOverlayEntityType { pageSettings, element, lineup } -EntitySyncKey pageSettingsEntityKey(String pageId) => 'page:$pageId:settings'; +String _encodeEntityKeyPart(String value) => Uri.encodeComponent(value); + +String _decodeEntityKeyPart(String value) => Uri.decodeComponent(value); + +EntitySyncKey pageSettingsEntityKey(String pageId) => + 'page:${_encodeEntityKeyPart(pageId)}:settings'; EntitySyncKey elementEntityKey(String pageId, String elementId) => - 'element:$pageId:$elementId'; + 'element:${_encodeEntityKeyPart(pageId)}:${_encodeEntityKeyPart(elementId)}'; EntitySyncKey lineupEntityKey(String pageId, String lineupId) => - 'lineup:$pageId:$lineupId'; + 'lineup:${_encodeEntityKeyPart(pageId)}:${_encodeEntityKeyPart(lineupId)}'; String? pageIdForEntityKey(EntitySyncKey entityKey) { final parts = entityKey.split(':'); if (parts.length < 2) { return null; } - return parts[1]; + return _decodeEntityKeyPart(parts[1]); } String? entityIdForEntityKey(EntitySyncKey entityKey) { @@ -25,7 +30,7 @@ String? entityIdForEntityKey(EntitySyncKey entityKey) { if (parts.length < 3) { return null; } - return parts[2]; + return _decodeEntityKeyPart(parts[2]); } ActivePageOverlayEntityType? overlayEntityTypeForKey(EntitySyncKey entityKey) { diff --git a/lib/providers/collab/active_page_live_sync_provider.dart b/lib/providers/collab/active_page_live_sync_provider.dart index 0fd46539..1cdc7687 100644 --- a/lib/providers/collab/active_page_live_sync_provider.dart +++ b/lib/providers/collab/active_page_live_sync_provider.dart @@ -3,6 +3,7 @@ import 'dart:developer'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/collab/cloud_media_models.dart'; import 'package:icarus/const/line_provider.dart'; import 'package:icarus/providers/ability_provider.dart'; import 'package:icarus/providers/agent_provider.dart'; @@ -439,7 +440,7 @@ class ActivePageLiveSyncNotifier extends Notifier { entities[key] = _NormalizedEntity( key: key, overlayEntityType: ActivePageOverlayEntityType.lineup, - payload: jsonEncode(lineup.toJson()), + payload: jsonEncode(cloudLineupPayload(lineup)), sortIndex: index, revision: 0, deleted: false, @@ -499,7 +500,9 @@ class ActivePageLiveSyncNotifier extends Notifier { } for (final image in ref.read(placedImageProvider).images) { - final payload = Map.from(image.toJson()) + final payload = Map.from( + cloudImagePayloadFromPlacedImage(image), + ) ..putIfAbsent('elementType', () => 'image'); envelopes.add( _CollabElementEnvelope( diff --git a/lib/providers/collab/cloud_media_cache_provider.dart b/lib/providers/collab/cloud_media_cache_provider.dart new file mode 100644 index 00000000..1526dec9 --- /dev/null +++ b/lib/providers/collab/cloud_media_cache_provider.dart @@ -0,0 +1,218 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; +import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/collab/convex_strategy_repository.dart'; +import 'package:icarus/providers/image_provider.dart'; + +class CloudMediaCacheState { + const CloudMediaCacheState({ + this.strategyPublicId, + this.cachedAssetIds = const {}, + this.inFlightAssetIds = const {}, + this.lastErrorByAssetId = const {}, + }); + + final String? strategyPublicId; + final Set cachedAssetIds; + final Set inFlightAssetIds; + final Map lastErrorByAssetId; + + CloudMediaCacheState copyWith({ + String? strategyPublicId, + bool clearStrategyPublicId = false, + Set? cachedAssetIds, + Set? inFlightAssetIds, + Map? lastErrorByAssetId, + }) { + return CloudMediaCacheState( + strategyPublicId: + clearStrategyPublicId ? null : (strategyPublicId ?? this.strategyPublicId), + cachedAssetIds: cachedAssetIds ?? this.cachedAssetIds, + inFlightAssetIds: inFlightAssetIds ?? this.inFlightAssetIds, + lastErrorByAssetId: lastErrorByAssetId ?? this.lastErrorByAssetId, + ); + } +} + +final cloudMediaCacheProvider = + NotifierProvider( + CloudMediaCacheNotifier.new, +); + +class CloudMediaCacheNotifier extends Notifier { + @override + CloudMediaCacheState build() { + return const CloudMediaCacheState(); + } + + Future localAssetPath({ + required String strategyId, + required String assetId, + required String fileExtension, + }) async { + final imageFolder = await PlacedImageProvider.getImageFolder(strategyId); + return PlacedImageProvider.buildImageFilePath( + imageFolder.path, + assetId, + fileExtension, + ); + } + + Future localFileForAsset({ + required String strategyId, + required RemoteImageAsset asset, + }) async { + final file = File( + await localAssetPath( + strategyId: strategyId, + assetId: asset.publicId, + fileExtension: asset.fileExtension, + ), + ); + if (await file.exists()) { + _markCached(asset.publicId); + return file; + } + return null; + } + + Future ensureAssetsCached({ + required String strategyId, + required String strategyPublicId, + required Iterable assets, + }) async { + final uniqueAssets = { + for (final asset in assets) asset.publicId: asset, + }.values.toList(growable: false); + for (final asset in uniqueAssets) { + await ensureAssetCached( + strategyId: strategyId, + strategyPublicId: strategyPublicId, + asset: asset, + ); + } + } + + Future ensureAssetCached({ + required String strategyId, + required String strategyPublicId, + required RemoteImageAsset asset, + }) async { + final existing = await localFileForAsset(strategyId: strategyId, asset: asset); + if (existing != null) { + return existing; + } + + if (asset.url == null || asset.url!.isEmpty) { + _recordError(asset.publicId, 'Missing remote asset URL.'); + return null; + } + + if (state.inFlightAssetIds.contains(asset.publicId)) { + return null; + } + + _markInFlight(asset.publicId, strategyPublicId); + try { + var response = await http.get(Uri.parse(asset.url!)); + if (_shouldRefreshSignedUrl(response.statusCode)) { + final refreshed = await ref + .read(convexStrategyRepositoryProvider) + .getImageAssetUrl( + strategyPublicId: strategyPublicId, + assetPublicId: asset.publicId, + ); + if (refreshed != null && refreshed.isNotEmpty) { + response = await http.get(Uri.parse(refreshed)); + } + } + + if (response.statusCode < 200 || response.statusCode >= 300) { + _recordError( + asset.publicId, + 'Failed to cache asset (${response.statusCode}).', + ); + return null; + } + + final output = File( + await localAssetPath( + strategyId: strategyId, + assetId: asset.publicId, + fileExtension: asset.fileExtension, + ), + ); + await output.parent.create(recursive: true); + await output.writeAsBytes(response.bodyBytes, flush: true); + _markCached(asset.publicId); + return output; + } catch (error) { + _recordError(asset.publicId, '$error'); + return null; + } finally { + _clearInFlight(asset.publicId); + } + } + + Future ensureAssetIdsCached({ + required String strategyId, + required String strategyPublicId, + required Map assetsById, + required Iterable assetIds, + }) async { + for (final assetId in assetIds.toSet()) { + final asset = assetsById[assetId]; + if (asset == null) { + return false; + } + final file = await ensureAssetCached( + strategyId: strategyId, + strategyPublicId: strategyPublicId, + asset: asset, + ); + if (file == null || !await file.exists()) { + return false; + } + } + return true; + } + + bool _shouldRefreshSignedUrl(int statusCode) { + return statusCode == 401 || statusCode == 403 || statusCode == 404; + } + + void resetStrategy(String? strategyPublicId) { + state = CloudMediaCacheState(strategyPublicId: strategyPublicId); + } + + void _markCached(String assetId) { + final cached = {...state.cachedAssetIds, assetId}; + final errors = Map.from(state.lastErrorByAssetId) + ..remove(assetId); + state = state.copyWith( + cachedAssetIds: cached, + lastErrorByAssetId: errors, + ); + } + + void _markInFlight(String assetId, String strategyPublicId) { + state = state.copyWith( + strategyPublicId: strategyPublicId, + inFlightAssetIds: {...state.inFlightAssetIds, assetId}, + ); + } + + void _clearInFlight(String assetId) { + final next = {...state.inFlightAssetIds}..remove(assetId); + state = state.copyWith(inFlightAssetIds: next); + } + + void _recordError(String assetId, String error) { + final errors = Map.from(state.lastErrorByAssetId) + ..[assetId] = error; + state = state.copyWith(lastErrorByAssetId: errors); + } +} diff --git a/lib/providers/collab/cloud_media_upload_queue_provider.dart b/lib/providers/collab/cloud_media_upload_queue_provider.dart new file mode 100644 index 00000000..78e942fa --- /dev/null +++ b/lib/providers/collab/cloud_media_upload_queue_provider.dart @@ -0,0 +1,450 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:convex_flutter/convex_flutter.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:hive_ce/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:icarus/collab/cloud_media_models.dart'; +import 'package:icarus/collab/convex_strategy_repository.dart'; +import 'package:icarus/const/hive_boxes.dart'; +import 'package:icarus/const/line_provider.dart'; +import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/auth_provider.dart'; +import 'package:icarus/providers/collab/cloud_collab_provider.dart'; +import 'package:icarus/providers/image_provider.dart'; +import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/strategy/strategy_page_models.dart'; + +class CloudMediaUploadQueueState { + const CloudMediaUploadQueueState({ + required this.jobs, + required this.isProcessing, + }); + + final List jobs; + final bool isProcessing; + + List jobsForStrategy(String? strategyPublicId) { + if (strategyPublicId == null) { + return const []; + } + return jobs + .where((job) => job.strategyPublicId == strategyPublicId) + .toList(growable: false); + } + + int pendingCountForStrategy(String? strategyPublicId) { + return jobsForStrategy(strategyPublicId).length; + } + + int errorCountForStrategy(String? strategyPublicId) { + return jobsForStrategy(strategyPublicId) + .where((job) => job.state == CloudMediaJobState.failed) + .length; + } + + CloudMediaUploadQueueState copyWith({ + List? jobs, + bool? isProcessing, + }) { + return CloudMediaUploadQueueState( + jobs: jobs ?? this.jobs, + isProcessing: isProcessing ?? this.isProcessing, + ); + } +} + +final cloudMediaUploadQueueProvider = + NotifierProvider( + CloudMediaUploadQueueNotifier.new, +); + +class CloudMediaUploadQueueNotifier + extends Notifier { + Timer? _retryTimer; + + Box get _box => + Hive.box(HiveBoxNames.mediaUploadJobsBox); + + ConvexStrategyRepository get _repo => + ref.read(convexStrategyRepositoryProvider); + + @override + CloudMediaUploadQueueState build() { + ref.onDispose(() { + _retryTimer?.cancel(); + }); + + ref.listen(authProvider, (previous, next) { + final becameReady = + !(previous?.isConvexUserReady ?? false) && next.isConvexUserReady; + final authRecovered = (previous?.hasActiveAuthIncident ?? false) && + !next.hasActiveAuthIncident; + if (becameReady || authRecovered) { + retryNow(ignoreBackoff: true); + } + }); + + final initialJobs = _readJobs(); + if (initialJobs.isNotEmpty) { + Future.microtask(() => retryNow()); + } + return CloudMediaUploadQueueState( + jobs: initialJobs, + isProcessing: false, + ); + } + + Future enqueuePlacedImageUpload({ + required String imagePublicId, + String? strategyPublicId, + String? fileExtension, + String? mimeType, + int? width, + int? height, + }) async { + final strategyState = ref.read(strategyProvider); + final resolvedStrategyId = strategyPublicId ?? strategyState.strategyId; + if (strategyState.source != StrategySource.cloud || + resolvedStrategyId == null) { + return; + } + + final normalizedExtension = normalizeImageExtension(fileExtension ?? ''); + await _upsertJob( + CloudMediaUploadJob( + jobId: imagePublicId, + strategyPublicId: resolvedStrategyId, + assetPublicId: imagePublicId, + fileExtension: normalizedExtension, + mimeType: mimeType ?? mimeTypeForImageExtension(normalizedExtension), + width: width, + height: height, + state: CloudMediaJobState.pendingUpload, + attempts: 0, + updatedAt: DateTime.now(), + ), + ); + retryNow(ignoreBackoff: true); + } + + Future enqueueJobForLocalFile({ + required String strategyPublicId, + required String assetPublicId, + required String fileExtension, + String? mimeType, + int? width, + int? height, + }) async { + final normalizedExtension = normalizeImageExtension(fileExtension); + await _upsertJob( + CloudMediaUploadJob( + jobId: assetPublicId, + strategyPublicId: strategyPublicId, + assetPublicId: assetPublicId, + fileExtension: normalizedExtension, + mimeType: mimeType ?? mimeTypeForImageExtension(normalizedExtension), + width: width, + height: height, + state: CloudMediaJobState.pendingUpload, + attempts: 0, + updatedAt: DateTime.now(), + ), + ); + retryNow(ignoreBackoff: true); + } + + Future enqueueLineupMediaJobs({ + required String strategyPublicId, + required Iterable images, + }) async { + for (final image in images) { + final normalizedExtension = normalizeImageExtension(image.fileExtension); + await _upsertJob( + CloudMediaUploadJob( + jobId: image.id, + strategyPublicId: strategyPublicId, + assetPublicId: image.id, + fileExtension: normalizedExtension, + mimeType: mimeTypeForImageExtension(normalizedExtension), + state: CloudMediaJobState.pendingUpload, + attempts: 0, + updatedAt: DateTime.now(), + ), + ); + } + retryNow(ignoreBackoff: true); + } + + Future retryNow({bool ignoreBackoff = false}) async { + _retryTimer?.cancel(); + unawaited(_processNextJob(ignoreBackoff: ignoreBackoff)); + } + + Future setActiveStrategy(String? strategyPublicId) async { + _retryTimer?.cancel(); + _refreshState(); + if (strategyPublicId != null) { + await retryNow(ignoreBackoff: true); + } + } + + Future clearJobsForStrategy(String strategyPublicId) async { + final jobs = _readJobs() + .where((job) => job.strategyPublicId == strategyPublicId) + .toList(growable: false); + for (final job in jobs) { + await _box.delete(job.jobId); + } + _refreshState(); + } + + Future _processNextJob({bool ignoreBackoff = false}) async { + if (state.isProcessing) { + return; + } + + final nextJob = _nextRunnableJob(ignoreBackoff: ignoreBackoff); + if (nextJob == null) { + _scheduleRetryForNextEligibleJob(); + return; + } + + state = state.copyWith(isProcessing: true); + try { + await _processJob(nextJob); + } finally { + _refreshState(isProcessing: false); + } + + if (_readJobs().isNotEmpty) { + // Only bypass backoff for the initial user-triggered kick. Follow-up + // attempts must honor retry timing so transient attach failures do not + // hammer Convex in a tight loop. + unawaited(_processNextJob(ignoreBackoff: false)); + } + } + + CloudMediaUploadJob? _nextRunnableJob({required bool ignoreBackoff}) { + final jobs = _readJobs() + ..sort((a, b) => a.updatedAt.compareTo(b.updatedAt)); + final now = DateTime.now(); + for (final job in jobs) { + if (ignoreBackoff || !_nextAttemptAt(job).isAfter(now)) { + return job; + } + } + return null; + } + + Future _processJob(CloudMediaUploadJob job) async { + final mode = ref.read(cloudCollabModeProvider); + final auth = ref.read(authProvider); + if (!mode.featureFlagEnabled || mode.forceLocalFallback) { + _scheduleRetryForNextEligibleJob(); + return; + } + if (!auth.isAuthenticated || + !auth.isConvexUserReady || + auth.hasActiveAuthIncident || + !ConvexClient.instance.isConnected) { + _scheduleRetryForNextEligibleJob(); + return; + } + + if (job.state == CloudMediaJobState.pendingUpload || + job.storageId == null) { + await _uploadJobBlob(job); + return; + } + + await _attachUploadedJob(job); + } + + Future _uploadJobBlob(CloudMediaUploadJob job) async { + try { + final file = await PlacedImageProvider.getImageFile( + strategyID: job.strategyPublicId, + imageID: job.assetPublicId, + fileExtension: job.fileExtension, + ); + if (!await file.exists()) { + await _markJobFailed( + job, + 'Local media file is missing.', + showToast: job.attempts == 0, + ); + return; + } + + final uploadUrl = + await _repo.generateImageUploadUrl(job.strategyPublicId); + if (uploadUrl.isEmpty) { + throw StateError('Empty Convex upload URL'); + } + + final response = await http.post( + Uri.parse(uploadUrl), + headers: { + 'Content-Type': job.mimeType, + }, + body: await file.readAsBytes(), + ); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw StateError( + 'Upload failed (${response.statusCode}): ${response.body}', + ); + } + + final storageId = _parseStorageId(response.body); + await _box.put( + job.jobId, + job.copyWith( + storageId: storageId, + state: CloudMediaJobState.pendingAttach, + attempts: 0, + lastError: null, + updatedAt: DateTime.now(), + ), + ); + _refreshState(); + } catch (error) { + await _markJobFailed( + job, + '$error', + showToast: job.attempts == 0, + ); + } + } + + Future _attachUploadedJob(CloudMediaUploadJob job) async { + try { + await _repo.completeImageUpload( + strategyPublicId: job.strategyPublicId, + assetPublicId: job.assetPublicId, + storageId: job.storageId!, + mimeType: job.mimeType, + fileExtension: job.fileExtension, + width: job.width, + height: job.height, + ); + await _box.delete(job.jobId); + _refreshState(); + } catch (error) { + await _markJobFailed( + job, + '$error', + showToast: job.attempts == 0, + ); + } + } + + Future _markJobFailed( + CloudMediaUploadJob job, + String errorMessage, { + required bool showToast, + }) async { + await _box.put( + job.jobId, + job.copyWith( + state: CloudMediaJobState.failed, + attempts: job.attempts + 1, + lastError: errorMessage, + updatedAt: DateTime.now(), + ), + ); + _refreshState(); + if (showToast) { + Settings.showToast( + message: 'Media upload failed. Tap Save to retry cloud sync.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + } + _scheduleRetryForNextEligibleJob(); + } + + DateTime _nextAttemptAt(CloudMediaUploadJob job) { + if (job.attempts <= 0) { + return job.updatedAt; + } + + final baseSeconds = 5 * (1 << (job.attempts - 1).clamp(0, 5)); + final cappedSeconds = baseSeconds > 300 ? 300 : baseSeconds; + return job.updatedAt.add(Duration(seconds: cappedSeconds)); + } + + void _scheduleRetryForNextEligibleJob() { + _retryTimer?.cancel(); + final jobs = _readJobs(); + if (jobs.isEmpty) { + return; + } + + final now = DateTime.now(); + DateTime? earliest; + for (final job in jobs) { + final candidate = _nextAttemptAt(job); + if (earliest == null || candidate.isBefore(earliest)) { + earliest = candidate; + } + } + + if (earliest == null) { + return; + } + + final delay = + earliest.isAfter(now) ? earliest.difference(now) : Duration.zero; + _retryTimer = Timer(delay, () { + unawaited(_processNextJob(ignoreBackoff: false)); + }); + } + + Future _upsertJob(CloudMediaUploadJob nextJob) async { + final existing = _box.get(nextJob.jobId); + if (existing != null) { + final merged = existing.copyWith( + strategyPublicId: nextJob.strategyPublicId, + assetPublicId: nextJob.assetPublicId, + fileExtension: nextJob.fileExtension, + mimeType: nextJob.mimeType, + width: nextJob.width, + height: nextJob.height, + ); + await _box.put(nextJob.jobId, merged); + } else { + await _box.put(nextJob.jobId, nextJob); + } + _refreshState(); + } + + List _readJobs() { + return _box.values.toList(growable: false); + } + + void _refreshState({bool? isProcessing}) { + state = state.copyWith( + jobs: _readJobs(), + isProcessing: isProcessing ?? state.isProcessing, + ); + } + + String _parseStorageId(String responseBody) { + final decoded = jsonDecode(responseBody); + if (decoded is Map) { + final storageId = decoded['storageId']; + if (storageId is String && storageId.isNotEmpty) { + return storageId; + } + } + if (decoded is Map) { + final storageId = decoded['storageId']; + if (storageId is String && storageId.isNotEmpty) { + return storageId; + } + } + throw const FormatException( + 'Convex upload response did not include storageId'); + } +} diff --git a/lib/providers/collab/cloud_migration_provider.dart b/lib/providers/collab/cloud_migration_provider.dart index 7ac69b47..ef0629c4 100644 --- a/lib/providers/collab/cloud_migration_provider.dart +++ b/lib/providers/collab/cloud_migration_provider.dart @@ -50,11 +50,21 @@ class CloudMigrationNotifier extends Notifier { } for (final strategy in strategies) { + final pages = [...strategy.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + final firstPage = pages.isNotEmpty ? pages.first : null; + final fallbackPageId = const Uuid().v4(); try { - await repo.createStrategy( + await repo.createStrategyWithInitialPage( publicId: strategy.id, name: strategy.name, mapData: Maps.mapNames[strategy.mapData] ?? 'ascent', + initialPagePublicId: firstPage?.id ?? fallbackPageId, + initialPageName: firstPage?.name ?? 'Page 1', + initialPageIsAttack: firstPage?.isAttack ?? true, + initialPageSettings: firstPage == null + ? ref.read(strategySettingsProvider.notifier).toJson() + : StrategySettingsProvider.objectToJson(firstPage.settings), folderPublicId: strategy.folderID, themeProfileId: strategy.themeProfileId, themeOverridePalette: strategy.themeOverridePalette == null @@ -69,13 +79,20 @@ class CloudMigrationNotifier extends Notifier { ); } - final pages = [...strategy.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - final allOps = []; final usedElementIds = {}; final usedLineupIds = {}; - for (final page in pages) { + for (var i = 0; i < pages.length; i++) { + final page = pages[i]; + if (i == 0) { + appendMigratedPageOps( + allOps, + page, + usedElementIds: usedElementIds, + usedLineupIds: usedLineupIds, + ); + continue; + } try { await ConvexClient.instance.mutation(name: 'pages:add', args: { 'strategyPublicId': strategy.id, diff --git a/lib/providers/collab/remote_library_provider.dart b/lib/providers/collab/remote_library_provider.dart index 8417b261..80ba3b4b 100644 --- a/lib/providers/collab/remote_library_provider.dart +++ b/lib/providers/collab/remote_library_provider.dart @@ -17,10 +17,14 @@ final cloudFoldersProvider = return; } + final section = ref.watch(cloudLibrarySectionProvider); final parentFolderId = ref.watch(folderProvider); final repo = ref.watch(convexStrategyRepositoryProvider); try { - await for (final folders in repo.watchFoldersForParent(parentFolderId)) { + await for (final folders in repo.watchFoldersForParent( + parentFolderId, + scope: section == CloudLibrarySection.sharedWithMe ? 'shared' : 'owned', + )) { yield folders; } } catch (error, stackTrace) { @@ -55,14 +59,21 @@ final cloudStrategiesProvider = return; } + final section = ref.watch(cloudLibrarySectionProvider); final folderId = ref.watch(folderProvider); final repo = ref.watch(convexStrategyRepositoryProvider); try { - await for (final strategies in repo.watchStrategiesForFolder(folderId)) { + final stream = section == CloudLibrarySection.sharedWithMe + ? (folderId == null + ? repo.watchSharedStrategies() + : repo.watchStrategiesForFolder(folderId, scope: 'shared')) + : repo.watchStrategiesForFolder(folderId, scope: 'owned'); + await for (final strategies in stream) { yield strategies; } } catch (error, stackTrace) { - if (_isInvalidFolderError(error)) { + if (section != CloudLibrarySection.sharedWithMe && + _isInvalidFolderError(error)) { ref .read(folderProvider.notifier) .updateWorkspaceFolderId(LibraryWorkspace.cloud, null); diff --git a/lib/providers/collab/remote_strategy_snapshot_provider.dart b/lib/providers/collab/remote_strategy_snapshot_provider.dart index 491fece3..2c13ed96 100644 --- a/lib/providers/collab/remote_strategy_snapshot_provider.dart +++ b/lib/providers/collab/remote_strategy_snapshot_provider.dart @@ -1,8 +1,6 @@ import 'dart:async'; -import 'dart:convert'; import 'dart:developer'; -import 'package:convex_flutter/convex_flutter.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/collab/collab_models.dart'; import 'package:icarus/collab/convex_strategy_repository.dart'; @@ -17,10 +15,11 @@ final remoteStrategySnapshotProvider = AsyncNotifierProvider< class RemoteStrategySnapshotNotifier extends AsyncNotifier { String? _activeStrategyPublicId; - dynamic _headerSubscription; - dynamic _pagesSubscription; - final Map _elementSubscriptions = {}; - final Map _lineupSubscriptions = {}; + StreamSubscription? _headerSubscription; + StreamSubscription>? _pagesSubscription; + StreamSubscription>? _assetsSubscription; + StreamSubscription>? _elementsSubscription; + StreamSubscription>? _lineupsSubscription; Timer? _refreshDebounce; @override @@ -33,7 +32,9 @@ class RemoteStrategySnapshotNotifier Future openStrategy(String strategyPublicId) async { _activeStrategyPublicId = strategyPublicId; - ref.read(strategyOpQueueProvider.notifier).setActiveStrategy(strategyPublicId); + ref + .read(strategyOpQueueProvider.notifier) + .setActiveStrategy(strategyPublicId); state = const AsyncLoading(); await _refreshFromServer(); @@ -71,7 +72,6 @@ class RemoteStrategySnapshotNotifier .read(convexStrategyRepositoryProvider) .fetchSnapshot(strategyPublicId); state = AsyncData(snapshot); - await _syncPageSubscriptions(snapshot); } catch (error, stackTrace) { if (isConvexUnauthenticatedError(error)) { unawaited( @@ -93,150 +93,109 @@ class RemoteStrategySnapshotNotifier Future _startSubscriptions(String strategyPublicId) async { _disposeSubscriptions(); - - _headerSubscription = await ConvexClient.instance.subscribe( - name: 'strategies:getHeader', - args: {'strategyPublicId': strategyPublicId}, - onUpdate: (_) => _scheduleRefresh(), - onError: (message, _) => _handleSubscriptionError( - source: 'remote_snapshot:header_subscription', - message: message, - ), - ); - - _pagesSubscription = await ConvexClient.instance.subscribe( - name: 'pages:listForStrategy', - args: {'strategyPublicId': strategyPublicId}, - onUpdate: (value) { - try { - final pageIds = _decodePageIds(value); - _syncPageWatchersFromIds(strategyPublicId, pageIds); - _scheduleRefresh(); - } catch (error, stackTrace) { - log( - 'Failed to decode pages subscription payload: $error', - name: 'remote_snapshot', + final repository = ref.read(convexStrategyRepositoryProvider); + + _headerSubscription = repository + .watchStrategyHeader(strategyPublicId) + .listen( + (header) => + _replaceSnapshot((snapshot) => snapshot.replaceHeader(header)), + onError: (error, stackTrace) => _handleSubscriptionError( + source: 'remote_snapshot:header_subscription', error: error, stackTrace: stackTrace, - ); - _scheduleRefresh(); - } - }, - onError: (message, _) => _handleSubscriptionError( - source: 'remote_snapshot:pages_subscription', - message: message, - ), - ); - } + ), + ); - Set _decodePageIds(dynamic value) { - final decoded = value is String ? jsonDecode(value) : value; - if (decoded is! List) { - throw FormatException( - 'Expected list payload for pages subscription, got ${decoded.runtimeType}', - ); - } + _pagesSubscription = + repository.watchPagesForStrategy(strategyPublicId).listen( + (pages) => + _replaceSnapshot((snapshot) => snapshot.replacePages(pages)), + onError: (error, stackTrace) => _handleSubscriptionError( + source: 'remote_snapshot:pages_subscription', + error: error, + stackTrace: stackTrace, + ), + ); - return decoded - .map((item) => item is String ? jsonDecode(item) : item) - .whereType() - .map((item) => Map.from(item)) - .map((item) => item['publicId'] as String?) - .whereType() - .toSet(); - } + _assetsSubscription = + repository.watchImageAssetsForStrategy(strategyPublicId).listen( + (assets) => _replaceSnapshot( + (snapshot) => snapshot.replaceAssets(assets), + ), + onError: (error, stackTrace) => _handleSubscriptionError( + source: 'remote_snapshot:assets_subscription', + error: error, + stackTrace: stackTrace, + ), + ); - Future _syncPageSubscriptions(RemoteStrategySnapshot snapshot) async { - final strategyPublicId = _activeStrategyPublicId; - if (strategyPublicId == null) { - return; - } + _elementsSubscription = + repository.watchElementsForStrategy(strategyPublicId).listen( + (elements) => _replaceSnapshot( + (snapshot) => snapshot.replaceElements(elements), + ), + onError: (error, stackTrace) => _handleSubscriptionError( + source: 'remote_snapshot:elements_subscription', + error: error, + stackTrace: stackTrace, + ), + ); - final pageIds = snapshot.pages.map((page) => page.publicId).toSet(); - _syncPageWatchersFromIds(strategyPublicId, pageIds); + _lineupsSubscription = + repository.watchLineupsForStrategy(strategyPublicId).listen( + (lineups) => _replaceSnapshot( + (snapshot) => snapshot.replaceLineups(lineups), + ), + onError: (error, stackTrace) => _handleSubscriptionError( + source: 'remote_snapshot:lineups_subscription', + error: error, + stackTrace: stackTrace, + ), + ); } - void _syncPageWatchersFromIds( - String strategyPublicId, - Set pageIds, + void _replaceSnapshot( + RemoteStrategySnapshot Function(RemoteStrategySnapshot snapshot) replace, ) { - final existingElementPageIds = _elementSubscriptions.keys.toSet(); - final existingLineupPageIds = _lineupSubscriptions.keys.toSet(); - - for (final pageId in existingElementPageIds.difference(pageIds)) { - _cancelSubscription(_elementSubscriptions.remove(pageId)); + if (_activeStrategyPublicId == null) { + return; } - for (final pageId in existingLineupPageIds.difference(pageIds)) { - _cancelSubscription(_lineupSubscriptions.remove(pageId)); + if (ref.read(authProvider).hasActiveAuthIncident) { + return; } - for (final pageId in pageIds) { - if (!_elementSubscriptions.containsKey(pageId)) { - _elementSubscriptions[pageId] = true; - ConvexClient.instance - .subscribe( - name: 'elements:listForPage', - args: { - 'strategyPublicId': strategyPublicId, - 'pagePublicId': pageId, - }, - onUpdate: (_) => _scheduleRefresh(), - onError: (message, _) => _handleSubscriptionError( - source: 'remote_snapshot:elements_subscription', - message: message, - ), - ) - .then((subscription) { - final current = _elementSubscriptions[pageId]; - if (current == null) { - _cancelSubscription(subscription); - return; - } - _elementSubscriptions[pageId] = subscription; - }); - } - - if (!_lineupSubscriptions.containsKey(pageId)) { - _lineupSubscriptions[pageId] = true; - ConvexClient.instance - .subscribe( - name: 'lineups:listForPage', - args: { - 'strategyPublicId': strategyPublicId, - 'pagePublicId': pageId, - }, - onUpdate: (_) => _scheduleRefresh(), - onError: (message, _) => _handleSubscriptionError( - source: 'remote_snapshot:lineups_subscription', - message: message, - ), - ) - .then((subscription) { - final current = _lineupSubscriptions[pageId]; - if (current == null) { - _cancelSubscription(subscription); - return; - } - _lineupSubscriptions[pageId] = subscription; - }); - } + final current = state.valueOrNull; + if (current == null) { + _scheduleRefresh(); + return; } + state = AsyncData(replace(current)); } void _handleSubscriptionError({ required String source, - required String message, + required Object error, + StackTrace? stackTrace, }) { + final message = error.toString(); if (isConvexUnauthenticatedMessage(message)) { unawaited( ref.read(authProvider.notifier).reportConvexUnauthenticated( source: source, - error: Exception(message), + error: error, + stackTrace: stackTrace, ), ); return; } + log( + 'Remote snapshot subscription failed: $message', + name: 'remote_snapshot', + error: error, + stackTrace: stackTrace, + ); _scheduleRefresh(); } @@ -259,28 +218,19 @@ class RemoteStrategySnapshotNotifier _refreshDebounce?.cancel(); _refreshDebounce = null; - _cancelSubscription(_headerSubscription); + unawaited(_headerSubscription?.cancel()); _headerSubscription = null; - _cancelSubscription(_pagesSubscription); + unawaited(_pagesSubscription?.cancel()); _pagesSubscription = null; - for (final subscription in _elementSubscriptions.values) { - _cancelSubscription(subscription); - } - _elementSubscriptions.clear(); + unawaited(_assetsSubscription?.cancel()); + _assetsSubscription = null; - for (final subscription in _lineupSubscriptions.values) { - _cancelSubscription(subscription); - } - _lineupSubscriptions.clear(); - } + unawaited(_elementsSubscription?.cancel()); + _elementsSubscription = null; - void _cancelSubscription(dynamic subscription) { - try { - subscription?.cancel(); - } catch (_) { - // Best-effort cleanup. - } + unawaited(_lineupsSubscription?.cancel()); + _lineupsSubscription = null; } } diff --git a/lib/providers/collab/strategy_capabilities_provider.dart b/lib/providers/collab/strategy_capabilities_provider.dart index 49ef6b01..ee3fdf71 100644 --- a/lib/providers/collab/strategy_capabilities_provider.dart +++ b/lib/providers/collab/strategy_capabilities_provider.dart @@ -67,15 +67,16 @@ class StrategyCapabilities { canRenamePage: canEdit, canDeletePage: canEdit, canReorderPages: canEdit, - canCreateFolder: true, - canEditFolder: true, - canDeleteFolder: true, - canMoveFolder: true, + canCreateFolder: isOwner, + canEditFolder: isOwner, + canDeleteFolder: isOwner, + canMoveFolder: isOwner, ); } } -final currentStrategyCapabilitiesProvider = Provider((ref) { +final currentStrategyCapabilitiesProvider = + Provider((ref) { final strategySource = ref.watch(strategyProvider.select((value) => value.source)); if (strategySource != StrategySource.cloud || @@ -86,4 +87,3 @@ final currentStrategyCapabilitiesProvider = Provider((ref) ref.watch(remoteStrategySnapshotProvider).valueOrNull?.header.role; return StrategyCapabilities.fromCloudRole(role); }); - diff --git a/lib/providers/collab/strategy_op_queue_provider.dart b/lib/providers/collab/strategy_op_queue_provider.dart index 61658364..aaddec92 100644 --- a/lib/providers/collab/strategy_op_queue_provider.dart +++ b/lib/providers/collab/strategy_op_queue_provider.dart @@ -163,8 +163,8 @@ class StrategyOpQueueNotifier extends Notifier { ); continue; } - opsByPage.putIfAbsent(pageId, () => {})[entityKey] = - op; + opsByPage.putIfAbsent( + pageId, () => {})[entityKey] = op; } if (!mapEquals(genericQueued, state.queuedByEntityKey)) { @@ -185,6 +185,75 @@ class StrategyOpQueueNotifier extends Notifier { _scheduleFlush(flushImmediately: flushImmediately); } + void syncDesiredGenericOp({ + required EntitySyncKey entityKey, + required StrategyOp? desiredOp, + bool flushImmediately = false, + }) { + final queued = Map.from( + state.queuedByEntityKey, + ); + final existingQueued = queued[entityKey]; + final inFlight = state.inFlightByEntityKey[entityKey]?.pending.op; + + if (desiredOp == null) { + if (queued.remove(entityKey) == null) { + return; + } + state = state.copyWith( + queuedByEntityKey: queued, + clearError: true, + ); + return; + } + + if (inFlight != null && _sameIntent(desiredOp, inFlight)) { + if (queued.remove(entityKey) == null) { + return; + } + state = state.copyWith( + queuedByEntityKey: queued, + clearError: true, + ); + return; + } + + if (existingQueued != null && + _sameIntent(existingQueued.pending.op, desiredOp)) { + return; + } + + final mergedDesired = existingQueued == null + ? desiredOp + : _mergeQueuedIntent(existingQueued.pending.op, desiredOp); + if (mergedDesired == null) { + if (queued.remove(entityKey) == null) { + return; + } + state = state.copyWith( + queuedByEntityKey: queued, + clearError: true, + ); + return; + } + + queued[entityKey] = QueuedEntityIntent( + entityKey: entityKey, + pending: PendingOp( + op: mergedDesired, + clientId: state.clientId ?? const Uuid().v4(), + attempts: existingQueued?.pending.attempts ?? 0, + lastAttemptAt: existingQueued?.pending.lastAttemptAt, + ), + ); + + state = state.copyWith( + queuedByEntityKey: queued, + clearError: true, + ); + _scheduleFlush(flushImmediately: flushImmediately); + } + void syncDesiredOpsForPage({ required String pageId, required Map desiredOpsByEntityKey, @@ -223,7 +292,8 @@ class StrategyOpQueueNotifier extends Notifier { continue; } - if (existingQueued != null && _sameIntent(existingQueued.pending.op, desired)) { + if (existingQueued != null && + _sameIntent(existingQueued.pending.op, desired)) { continue; } @@ -307,12 +377,14 @@ class StrategyOpQueueNotifier extends Notifier { ? 'Cloud user setup is not ready.' : 'Cloud connection is offline.'), ); - _scheduleRetry(incremented.values.map((intent) => intent.pending).toList()); + _scheduleRetry( + incremented.values.map((intent) => intent.pending).toList()); return; } final batch = state.queuedByEntityKey.values - .where((intent) => !state.inFlightByEntityKey.containsKey(intent.entityKey)) + .where((intent) => + !state.inFlightByEntityKey.containsKey(intent.entityKey)) .take(_maxBatchSize) .toList(growable: false); if (batch.isEmpty) { @@ -335,7 +407,8 @@ class StrategyOpQueueNotifier extends Notifier { sentAt: sentAt, ); batchByOpId[intent.pending.op.opId] = intent; - _debugLog('inflight.send ${intent.entityKey} op=${intent.pending.op.opId}'); + _debugLog( + 'inflight.send ${intent.entityKey} op=${intent.pending.op.opId}'); } state = state.copyWith( @@ -500,7 +573,8 @@ class StrategyOpQueueNotifier extends Notifier { return null; } - if (existing.kind == StrategyOpKind.add && desired.kind == StrategyOpKind.patch) { + if (existing.kind == StrategyOpKind.add && + desired.kind == StrategyOpKind.patch) { return StrategyOp( opId: existing.opId, kind: StrategyOpKind.add, diff --git a/lib/providers/folder_provider.dart b/lib/providers/folder_provider.dart index 10b0a2a3..73f5e67b 100644 --- a/lib/providers/folder_provider.dart +++ b/lib/providers/folder_provider.dart @@ -208,7 +208,8 @@ class FolderProvider extends Notifier { } } - await Hive.box(HiveBoxNames.foldersBox).put(newFolder.id, newFolder); + await Hive.box(HiveBoxNames.foldersBox) + .put(newFolder.id, newFolder); return newFolder; } @@ -342,7 +343,8 @@ class FolderProvider extends Notifier { 'customColorValue': newCustomColor.toARGB32(), if (newCustomColor == null) 'clearCustomColorValue': true, }; - await ConvexClient.instance.mutation(name: 'folders:update', args: args); + await ConvexClient.instance + .mutation(name: 'folders:update', args: args); ref.invalidate(cloudFoldersProvider); ref.invalidate(cloudAllFoldersProvider); } catch (error, stackTrace) { @@ -398,6 +400,7 @@ class FolderProvider extends Notifier { return switch (workspace) { LibraryWorkspace.local => _localCurrentFolderId, LibraryWorkspace.cloud => _cloudCurrentFolderId, + LibraryWorkspace.community => null, }; } @@ -406,6 +409,9 @@ class FolderProvider extends Notifier { _localCurrentFolderId = id; return; } + if (workspace == LibraryWorkspace.community) { + return; + } _cloudCurrentFolderId = id; } diff --git a/lib/providers/image_provider.dart b/lib/providers/image_provider.dart index 0e30d4b3..46553731 100644 --- a/lib/providers/image_provider.dart +++ b/lib/providers/image_provider.dart @@ -1,19 +1,20 @@ import 'dart:convert'; import 'dart:io'; +import 'dart:ui' as ui; +import 'dart:async' show Completer; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:icarus/const/coordinate_system.dart'; import 'package:icarus/const/image_scale_policy.dart'; -import 'package:icarus/providers/image_widget_size_provider.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; +import 'package:icarus/providers/collab/cloud_media_upload_queue_provider.dart'; import 'package:icarus/services/app_error_reporter.dart'; import 'package:image/image.dart' as img; -import 'dart:ui' as ui; -import 'dart:async' show Completer; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/providers/action_provider.dart'; import 'package:icarus/providers/action_history_models.dart'; import 'package:icarus/const/placed_classes.dart'; -import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/strategy/strategy_page_models.dart'; import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; import 'package:uuid/uuid.dart'; @@ -131,15 +132,20 @@ class PlacedImageProvider extends Notifier { Future addImage( {required Uint8List imageBytes, + required String? strategyId, + required StrategySource? strategySource, required String fileExtension, Offset? position, double? aspectRatio, int? tagColorValue}) async { final imageID = const Uuid().v4(); - await ref - .read(placedImageProvider.notifier) - .saveSecureImage(imageBytes, imageID, fileExtension); + await saveSecureImage( + imageBytes, + imageID, + fileExtension, + strategyId: strategyId, + ); final effectiveAspectRatio = aspectRatio ?? await getImageAspectRatio(imageBytes); @@ -159,14 +165,24 @@ class PlacedImageProvider extends Notifier { group: ActionGroup.image, objectDelta: ObjectHistoryDelta( after: ActionObjectState.image(placedImage), - afterImageSizes: - ref.read(imageWidgetSizeProvider.notifier).takeSnapshotForIds([imageID]), ), ); ref.read(actionProvider.notifier).addAction(action); state = state.copyWith(images: [...state.images, placedImage]); + + if (strategySource == StrategySource.cloud && strategyId != null) { + await ref + .read(cloudMediaUploadQueueProvider.notifier) + .enqueuePlacedImageUpload( + strategyPublicId: strategyId, + imagePublicId: placedImage.id, + fileExtension: fileExtension, + width: null, + height: null, + ); + } } void removeImageAsAction(String id) { @@ -180,9 +196,6 @@ class PlacedImageProvider extends Notifier { group: ActionGroup.image, objectDelta: ObjectHistoryDelta( before: ActionObjectState.image(state.images[index]), - beforeImageSizes: ref - .read(imageWidgetSizeProvider.notifier) - .takeSnapshotForIds([id]), ), ), ); @@ -218,10 +231,6 @@ class PlacedImageProvider extends Notifier { objectDelta: ObjectHistoryDelta( before: before, after: ActionObjectState.image(temp), - beforeImageSizes: - ref.read(imageWidgetSizeProvider.notifier).takeSnapshotForIds([id]), - afterImageSizes: - ref.read(imageWidgetSizeProvider.notifier).takeSnapshotForIds([id]), ), ); ref.read(actionProvider.notifier).addAction(action); @@ -241,16 +250,24 @@ class PlacedImageProvider extends Notifier { void switchSides() { final newImages = [...state.images]; for (final image in newImages) { - image.switchSides( - ref.read(imageWidgetSizeProvider.notifier).getSize(image.id)); + image.switchSides(_switchSizeForImage(image)); } for (final image in poppedImages) { - image.switchSides( - ref.read(imageWidgetSizeProvider.notifier).getSize(image.id)); + image.switchSides(_switchSizeForImage(image)); } state = state.copyWith(images: newImages); } + Offset _switchSizeForImage(PlacedImage image) { + final size = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: image.scale, + aspectRatio: image.aspectRatio, + ); + + return Offset(size.width, size.height); + } + void undoAction(UserAction action) { final delta = action.objectDelta; if (delta == null) { @@ -276,7 +293,6 @@ class PlacedImageProvider extends Notifier { } switch (action.type) { case ActionType.addition: - _clearImageSizes(delta.afterImageSizes.keys); removeImage(action.id); return; case ActionType.deletion: @@ -285,13 +301,11 @@ class PlacedImageProvider extends Notifier { return; } _upsertImage(clonePlacedImage(before)); - _restoreImageSizes(delta.beforeImageSizes); return; case ActionType.edit: final before = delta.before?.image; if (before == null) return; _upsertImage(clonePlacedImage(before)); - _restoreImageSizes(delta.beforeImageSizes); return; case ActionType.bulkDeletion: case ActionType.transaction: @@ -327,17 +341,14 @@ class PlacedImageProvider extends Notifier { final after = delta.after?.image; if (after == null) return; _upsertImage(clonePlacedImage(after)); - _restoreImageSizes(delta.afterImageSizes); return; case ActionType.deletion: - _clearImageSizes(delta.beforeImageSizes.keys); removeImage(action.id); return; case ActionType.edit: final after = delta.after?.image; if (after == null) return; _upsertImage(clonePlacedImage(after)); - _restoreImageSizes(delta.afterImageSizes); return; case ActionType.bulkDeletion: case ActionType.transaction: @@ -372,6 +383,41 @@ class PlacedImageProvider extends Notifier { return imagesDirectory; } + static String buildImageFilePath( + String imagesDirectoryPath, + String imageID, + String fileExtension, + ) { + return path.join(imagesDirectoryPath, '$imageID$fileExtension'); + } + + static Future getImageFile({ + required String strategyID, + required String imageID, + required String fileExtension, + }) async { + final imageFolder = await getImageFolder(strategyID); + return File(buildImageFilePath(imageFolder.path, imageID, fileExtension)); + } + + static Future writeImageBytes({ + required Uint8List imageBytes, + required String strategyID, + required String imageID, + required String fileExtension, + }) async { + if (kIsWeb) return; + final file = await getImageFile( + strategyID: strategyID, + imageID: imageID, + fileExtension: fileExtension, + ); + if (!await file.parent.exists()) { + await file.parent.create(recursive: true); + } + await file.writeAsBytes(imageBytes); + } + Future toJson(String strategyID) async { // Asynchronously convert each image using the custom serializer. final List> jsonList = @@ -427,39 +473,15 @@ class PlacedImageProvider extends Notifier { } Future saveSecureImage( - Uint8List imageBytes, - String imageID, - String fileExtenstion, - ) async { - final strategyID = ref.read(strategyProvider).strategyId; - // Get the system's application support directory. - if (kIsWeb) return; - final directory = await getApplicationSupportDirectory(); - - // Create a custom directory inside the application support directory. - - final customDirectory = Directory(path.join(directory.path, strategyID)); - - if (!await customDirectory.exists()) { - await customDirectory.create(recursive: true); - } - - // Now create the full file path. - final filePath = path.join( - customDirectory.path, - 'images', - '$imageID$fileExtenstion', + Uint8List imageBytes, String imageID, String fileExtenstion, + {required String? strategyId}) async { + if (strategyId == null) return; + await writeImageBytes( + imageBytes: imageBytes, + strategyID: strategyId, + imageID: imageID, + fileExtension: fileExtenstion, ); - - // Ensure the images subdirectory exists. - final imagesDir = Directory(path.join(customDirectory.path, 'images')); - if (!await imagesDir.exists()) { - await imagesDir.create(recursive: true); - } - - // Write the file. - final file = File(filePath); - await file.writeAsBytes(imageBytes); } static List deepCopyWith(List images) { @@ -504,16 +526,6 @@ class PlacedImageProvider extends Notifier { } state = state.copyWith(images: newImages); } - - void _restoreImageSizes(Map snapshot) { - if (snapshot.isEmpty) return; - ref.read(imageWidgetSizeProvider.notifier).restoreSnapshot(snapshot); - } - - void _clearImageSizes(Iterable ids) { - if (ids.isEmpty) return; - ref.read(imageWidgetSizeProvider.notifier).clearEntries(ids); - } } /// A helper class to handle the asynchronous conversion of [PlacedImage]. diff --git a/lib/providers/image_widget_size_provider.dart b/lib/providers/image_widget_size_provider.dart deleted file mode 100644 index cdf30892..00000000 --- a/lib/providers/image_widget_size_provider.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -final imageWidgetSizeProvider = - NotifierProvider>( - ImageWidgetSizeProvider.new, -); - -class ImageWidgetSizeProvider extends Notifier> { - @override - Map build() { - return {}; - } - - void updateSize(String id, Offset size) { - state = {...state, id: size}; - } - - Offset getSize(String id) { - return state[id] ?? Offset.zero; - } - - Map takeSnapshotForIds(Iterable ids) { - return { - for (final id in ids) - if (state.containsKey(id)) id: state[id]!, - }; - } - - void clearEntries(Iterable ids) { - final newState = {...state}; - for (final id in ids) { - newState.remove(id); - } - state = newState; - } - - void restoreSnapshot(Map snapshot) { - state = { - ...state, - ...snapshot, - }; - } - - void clearAll() { - state = {}; - } -} diff --git a/lib/providers/library_rail_hover_provider.dart b/lib/providers/library_rail_hover_provider.dart new file mode 100644 index 00000000..1733a4a5 --- /dev/null +++ b/lib/providers/library_rail_hover_provider.dart @@ -0,0 +1,3 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +final suppressLibraryRailHoverProvider = StateProvider((ref) => false); diff --git a/lib/providers/library_workspace_provider.dart b/lib/providers/library_workspace_provider.dart index dd4ea91e..250a7130 100644 --- a/lib/providers/library_workspace_provider.dart +++ b/lib/providers/library_workspace_provider.dart @@ -4,6 +4,12 @@ import 'package:icarus/providers/auth_provider.dart'; enum LibraryWorkspace { local, cloud, + community, +} + +enum CloudLibrarySection { + home, + sharedWithMe, } final isCloudWorkspaceAvailableProvider = Provider((ref) { @@ -20,6 +26,11 @@ final isCloudWorkspaceSelectedProvider = Provider((ref) { return ref.watch(libraryWorkspaceProvider) == LibraryWorkspace.cloud; }); +final cloudLibrarySectionProvider = + NotifierProvider( + CloudLibrarySectionNotifier.new, +); + class LibraryWorkspaceNotifier extends Notifier { @override LibraryWorkspace build() { @@ -40,3 +51,19 @@ class LibraryWorkspaceNotifier extends Notifier { state = workspace; } } + +class CloudLibrarySectionNotifier extends Notifier { + @override + CloudLibrarySection build() { + ref.listen(libraryWorkspaceProvider, (_, workspace) { + if (workspace != LibraryWorkspace.cloud) { + state = CloudLibrarySection.home; + } + }); + return CloudLibrarySection.home; + } + + void select(CloudLibrarySection section) { + state = section; + } +} diff --git a/lib/providers/map_provider.dart b/lib/providers/map_provider.dart index b29584fe..37384d4f 100644 --- a/lib/providers/map_provider.dart +++ b/lib/providers/map_provider.dart @@ -9,8 +9,8 @@ import 'package:icarus/providers/agent_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; import 'package:icarus/providers/image_provider.dart'; import 'package:icarus/providers/text_provider.dart'; +import 'package:icarus/providers/text_draft_provider.dart'; import 'package:icarus/providers/utility_provider.dart'; -import 'package:icarus/providers/strategy_provider.dart'; final mapProvider = NotifierProvider(MapProvider.new); @@ -54,7 +54,6 @@ class MapProvider extends Notifier { void updateMap(MapValue map) { state = state.copyWith(currentMap: map); - ref.read(strategyProvider.notifier).setUnsaved(); } void fromHive(MapValue map, bool isAttack) { @@ -74,6 +73,8 @@ class MapProvider extends Notifier { } void switchSide() { + ref.read(textDraftProvider.notifier).commitAllDrafts(); + // Flip all placed agents to mirror positions before toggling the side ref.read(agentProvider.notifier).switchSides(); ref.read(abilityProvider.notifier).switchSides(); @@ -84,12 +85,10 @@ class MapProvider extends Notifier { ref.read(placedImageProvider.notifier).switchSides(); ref.read(actionProvider.notifier).switchSides(); state = state.copyWith(isAttack: !state.isAttack); - ref.read(strategyProvider.notifier).setUnsaved(); } void setAttack(bool isAttack) { state = state.copyWith(isAttack: isAttack); - ref.read(strategyProvider.notifier).setUnsaved(); } String toJson() { @@ -105,5 +104,3 @@ class MapProvider extends Notifier { return mapValue; } } - - diff --git a/lib/providers/share_link_provider.dart b/lib/providers/share_link_provider.dart new file mode 100644 index 00000000..9edc8b24 --- /dev/null +++ b/lib/providers/share_link_provider.dart @@ -0,0 +1,96 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icarus/collab/convex_strategy_repository.dart'; +import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/auth_provider.dart'; +import 'package:icarus/providers/folder_provider.dart'; +import 'package:icarus/providers/library_workspace_provider.dart'; + +final shareLinkControllerProvider = + NotifierProvider(ShareLinkController.new); + +class ShareLinkController extends Notifier { + Future handleIncomingUri(Uri uri, {required String source}) async { + final isShareLink = uri.scheme.toLowerCase() == 'icarus' && + (uri.host.toLowerCase() == 'share' || + uri.pathSegments.contains('share')); + if (!isShareLink) { + return false; + } + + final token = uri.queryParameters['token']; + if (token == null || token.isEmpty) { + Settings.showToast( + message: 'That share link is missing a token.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + return true; + } + + state = token; + await redeemPendingIfPossible(source: source); + return true; + } + + Future redeemPendingIfPossible({String source = 'pending'}) async { + final token = state; + if (token == null || token.isEmpty) { + return; + } + + final auth = ref.read(authProvider); + if (!auth.isAuthenticated || !auth.isConvexUserReady) { + Settings.showToast( + message: 'Sign in to redeem shared links.', + backgroundColor: Settings.tacticalVioletTheme.primary, + ); + return; + } + + try { + final response = await ref + .read(convexStrategyRepositoryProvider) + .redeemShareLink(token); + state = null; + + ref + .read(libraryWorkspaceProvider.notifier) + .select(LibraryWorkspace.cloud); + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.sharedWithMe); + ref.read(folderProvider.notifier).updateWorkspaceFolderId( + LibraryWorkspace.cloud, + response['folderPublicId'] as String?, + ); + + final targetType = response['targetType'] as String? ?? 'item'; + Settings.showToast( + message: targetType == 'folder' + ? 'Shared folder added to your library.' + : 'Shared strategy added to your library.', + backgroundColor: Settings.tacticalVioletTheme.primary, + ); + } catch (error, stackTrace) { + if (isConvexUnauthenticatedError(error)) { + await ref.read(authProvider.notifier).reportConvexUnauthenticated( + source: 'share_link:$source', + error: error, + stackTrace: stackTrace, + ); + return; + } + Settings.showToast( + message: 'Failed to redeem share link.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + } + } + + Future redeemToken(String token) async { + state = token; + await redeemPendingIfPossible(source: 'manual'); + } + + @override + String? build() => null; +} diff --git a/lib/providers/strategy_page_session_provider.dart b/lib/providers/strategy_page_session_provider.dart index c8d900dc..205de576 100644 --- a/lib/providers/strategy_page_session_provider.dart +++ b/lib/providers/strategy_page_session_provider.dart @@ -67,16 +67,53 @@ class StrategyPageSessionState { } } +class _RemotePageHydrationKey { + const _RemotePageHydrationKey({ + required this.strategyPublicId, + required this.sequence, + required this.pageId, + required this.fingerprint, + }); + + final String strategyPublicId; + final int sequence; + final String pageId; + final String fingerprint; + + bool sameTargetAs(_RemotePageHydrationKey other) { + return strategyPublicId == other.strategyPublicId && + sequence == other.sequence && + pageId == other.pageId; + } + + @override + bool operator ==(Object other) { + return other is _RemotePageHydrationKey && + strategyPublicId == other.strategyPublicId && + sequence == other.sequence && + pageId == other.pageId && + fingerprint == other.fingerprint; + } + + @override + int get hashCode => Object.hash( + strategyPublicId, + sequence, + pageId, + fingerprint, + ); +} + final strategyPageSessionProvider = NotifierProvider( StrategyPageSessionNotifier.new, ); class StrategyPageSessionNotifier extends Notifier { - int? _lastHydratedRemoteSequence; - String? _lastHydratedRemoteStrategyId; - String? _lastHydratedRemotePageId; + _RemotePageHydrationKey? _lastHydratedRemotePageKey; + _RemotePageHydrationKey? _lastSequenceAdvancedHydrationKey; bool _pendingRemoteReapply = false; + bool _pendingRemoteSequenceAdvanced = false; @override StrategyPageSessionState build() { @@ -102,46 +139,52 @@ class StrategyPageSessionNotifier extends Notifier { state = state.copyWith(availablePageIds: orderedIds); } - final prevSequence = previous?.valueOrNull?.header.sequence; - final sequenceChanged = - prevSequence == null || prevSequence != snapshot.header.sequence; - if (!sequenceChanged) { + final targetPageId = _resolveHydrationTargetPage(snapshot); + if (targetPageId == null) { return; } - final targetPageId = _resolveHydrationTargetPage(snapshot); - if (targetPageId == null) { + final hydrationKey = + _buildRemotePageHydrationKey(snapshot, targetPageId); + if (hydrationKey == null) { return; } - final alreadyHydrated = - _lastHydratedRemoteStrategyId == snapshot.header.publicId && - _lastHydratedRemoteSequence == snapshot.header.sequence && - _lastHydratedRemotePageId == targetPageId; - if (alreadyHydrated) { + final prevSequence = previous?.valueOrNull?.header.sequence; + final sequenceChanged = + prevSequence == null || prevSequence != snapshot.header.sequence; + final sequenceAdvanced = + prevSequence != null && prevSequence != snapshot.header.sequence; + + if (sequenceChanged) { + if (_lastHydratedRemotePageKey == hydrationKey) { + return; + } + _requestRemoteRehydrate( + targetPageId, + hydrationKey: hydrationKey, + sequenceAdvanced: sequenceAdvanced, + ); return; } - if (_canSafelyReapplyRemotePage()) { - unawaited(_rehydrateActivePageFromSource(targetPageId)); - } else { - _pendingRemoteReapply = true; + if (_shouldRehydrateLateSectionReplacement(hydrationKey)) { + _requestRemoteRehydrate( + targetPageId, + hydrationKey: hydrationKey, + sequenceAdvanced: false, + ); } }, ); ref.listen(strategySaveStateProvider, (_, __) { - if (_pendingRemoteReapply && _canSafelyReapplyRemotePage()) { - _pendingRemoteReapply = false; - final pageId = state.activePageId; - if (pageId != null) { - unawaited(_rehydrateActivePageFromSource(pageId)); - } - } + _resumePendingRemoteReapplyIfPossible(); }); ref.listen(strategyOpQueueProvider, (previous, next) { - final previousAckBatch = previous?.lastAckBatch ?? const []; + final previousAckBatch = + previous?.lastAckBatch ?? const []; if (next.lastAckBatch.isEmpty || identical(previousAckBatch, next.lastAckBatch)) { return; @@ -307,10 +350,10 @@ class StrategyPageSessionNotifier extends Notifier { transitionState: PageTransitionState.idle, isApplyingPage: false, ); - _lastHydratedRemoteSequence = null; - _lastHydratedRemoteStrategyId = null; - _lastHydratedRemotePageId = null; + _lastHydratedRemotePageKey = null; + _lastSequenceAdvancedHydrationKey = null; _pendingRemoteReapply = false; + _pendingRemoteSequenceAdvanced = false; ref.read(activePageLiveSyncProvider.notifier).reset(); } @@ -348,7 +391,11 @@ class StrategyPageSessionNotifier extends Notifier { } } - Future _rehydrateActivePageFromSource(String pageId) async { + Future _rehydrateActivePageFromSource( + String pageId, { + _RemotePageHydrationKey? hydrationKey, + bool sequenceAdvanced = false, + }) async { final strategyState = ref.read(strategyProvider); final strategyId = strategyState.strategyId; final source = strategyState.source; @@ -360,11 +407,14 @@ class StrategyPageSessionNotifier extends Notifier { strategyPublicId: strategyId, activePageId: pageId, ); - final pageData = await _resolvePageSource(strategyId, source).loadPage(pageId); + final pageData = + await _resolvePageSource(strategyId, source).loadPage(pageId); await _applyLoadedPageData( pageData, strategyId: strategyId, source: source, + hydrationKey: hydrationKey, + sequenceAdvanced: sequenceAdvanced, ); } @@ -372,10 +422,12 @@ class StrategyPageSessionNotifier extends Notifier { StrategyEditorPageData pageData, { required String strategyId, required StrategySource source, + _RemotePageHydrationKey? hydrationKey, + bool sequenceAdvanced = false, }) async { final preserveHistory = source == StrategySource.cloud && - _lastHydratedRemoteStrategyId == strategyId && - _lastHydratedRemotePageId == pageData.pageId; + _lastHydratedRemotePageKey?.strategyPublicId == strategyId && + _lastHydratedRemotePageKey?.pageId == pageData.pageId; final themeProfileId = _resolveThemeProfileId(source, strategyId); final themeOverridePalette = _resolveThemeOverridePalette(source, strategyId); @@ -395,7 +447,11 @@ class StrategyPageSessionNotifier extends Notifier { themeOverridePalette: themeOverridePalette, preserveHistory: preserveHistory, ); - _updateHydrationBookkeeping(pageData.pageId); + _updateHydrationBookkeeping( + pageData.pageId, + hydrationKey: hydrationKey, + sequenceAdvanced: sequenceAdvanced, + ); } finally { state = state.copyWith( activePageId: pageData.pageId, @@ -476,6 +532,26 @@ class StrategyPageSessionNotifier extends Notifier { state.transitionState == PageTransitionState.idle; } + void _requestRemoteRehydrate( + String pageId, { + required _RemotePageHydrationKey hydrationKey, + required bool sequenceAdvanced, + }) { + if (_canSafelyReapplyRemotePage()) { + unawaited( + _rehydrateActivePageFromSource( + pageId, + hydrationKey: hydrationKey, + sequenceAdvanced: sequenceAdvanced, + ), + ); + } else { + _pendingRemoteReapply = true; + _pendingRemoteSequenceAdvanced = + _pendingRemoteSequenceAdvanced || sequenceAdvanced; + } + } + String? _resolveHydrationTargetPage(RemoteStrategySnapshot snapshot) { if (snapshot.pages.isEmpty) { return null; @@ -492,14 +568,131 @@ class StrategyPageSessionNotifier extends Notifier { return pages.first.publicId; } - void _updateHydrationBookkeeping(String pageId) { + void _updateHydrationBookkeeping( + String pageId, { + _RemotePageHydrationKey? hydrationKey, + bool sequenceAdvanced = false, + }) { + final key = hydrationKey ?? _currentRemotePageHydrationKey(pageId); + if (key == null) { + return; + } + _lastHydratedRemotePageKey = key; + if (sequenceAdvanced) { + _lastSequenceAdvancedHydrationKey = key; + } + } + + _RemotePageHydrationKey? _currentRemotePageHydrationKey(String pageId) { final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; if (snapshot == null) { - return; + return null; + } + return _buildRemotePageHydrationKey(snapshot, pageId); + } + + _RemotePageHydrationKey? _buildRemotePageHydrationKey( + RemoteStrategySnapshot snapshot, + String pageId, + ) { + RemotePage? page; + for (final candidate in snapshot.pages) { + if (candidate.publicId == pageId) { + page = candidate; + break; + } + } + if (page == null) { + return null; + } + + final elements = [ + ...snapshot.elementsByPage[pageId] ?? const [] + ]..sort(_compareRemoteElements); + final lineups = [ + ...snapshot.lineupsByPage[pageId] ?? const [] + ]..sort(_compareRemoteLineups); + final assets = snapshot.assetsById.values.toList() + ..sort((a, b) => a.publicId.compareTo(b.publicId)); + + final fingerprint = jsonEncode({ + 'page': { + 'publicId': page.publicId, + 'name': page.name, + 'sortIndex': page.sortIndex, + 'isAttack': page.isAttack, + 'revision': page.revision, + 'settings': page.settings, + }, + 'elements': [ + for (final element in elements) + { + 'publicId': element.publicId, + 'elementType': element.elementType, + 'payload': element.payload, + 'sortIndex': element.sortIndex, + 'revision': element.revision, + 'deleted': element.deleted, + }, + ], + 'lineups': [ + for (final lineup in lineups) + { + 'publicId': lineup.publicId, + 'payload': lineup.payload, + 'sortIndex': lineup.sortIndex, + 'revision': lineup.revision, + 'deleted': lineup.deleted, + }, + ], + 'assets': [ + for (final asset in assets) + { + 'publicId': asset.publicId, + 'fileExtension': asset.fileExtension, + 'mimeType': asset.mimeType, + 'width': asset.width, + 'height': asset.height, + 'url': asset.url, + 'legacyStoragePath': asset.legacyStoragePath, + }, + ], + }); + + return _RemotePageHydrationKey( + strategyPublicId: snapshot.header.publicId, + sequence: snapshot.header.sequence, + pageId: pageId, + fingerprint: fingerprint, + ); + } + + int _compareRemoteElements(RemoteElement a, RemoteElement b) { + final sortCompare = a.sortIndex.compareTo(b.sortIndex); + if (sortCompare != 0) { + return sortCompare; + } + return a.publicId.compareTo(b.publicId); + } + + int _compareRemoteLineups(RemoteLineup a, RemoteLineup b) { + final sortCompare = a.sortIndex.compareTo(b.sortIndex); + if (sortCompare != 0) { + return sortCompare; } - _lastHydratedRemoteStrategyId = snapshot.header.publicId; - _lastHydratedRemoteSequence = snapshot.header.sequence; - _lastHydratedRemotePageId = pageId; + return a.publicId.compareTo(b.publicId); + } + + bool _shouldRehydrateLateSectionReplacement( + _RemotePageHydrationKey hydrationKey, + ) { + final lastHydratedKey = _lastHydratedRemotePageKey; + final sequenceAdvancedKey = _lastSequenceAdvancedHydrationKey; + return lastHydratedKey != null && + sequenceAdvancedKey != null && + hydrationKey.sameTargetAs(lastHydratedKey) && + hydrationKey.sameTargetAs(sequenceAdvancedKey) && + hydrationKey.fingerprint != lastHydratedKey.fingerprint; } Future _reconcileAcks( @@ -570,10 +763,17 @@ class StrategyPageSessionNotifier extends Notifier { if (!_pendingRemoteReapply || !_canSafelyReapplyRemotePage()) { return; } + final sequenceAdvanced = _pendingRemoteSequenceAdvanced; _pendingRemoteReapply = false; + _pendingRemoteSequenceAdvanced = false; final pageId = state.activePageId; if (pageId != null) { - unawaited(_rehydrateActivePageFromSource(pageId)); + unawaited( + _rehydrateActivePageFromSource( + pageId, + sequenceAdvanced: sequenceAdvanced, + ), + ); } } diff --git a/lib/providers/strategy_provider.dart b/lib/providers/strategy_provider.dart index 3bdd4242..d1f216c1 100644 --- a/lib/providers/strategy_provider.dart +++ b/lib/providers/strategy_provider.dart @@ -33,6 +33,7 @@ import 'package:uuid/uuid.dart'; import 'package:icarus/collab/collab_models.dart'; import 'package:icarus/collab/convex_strategy_repository.dart'; import 'package:icarus/providers/collab/remote_library_provider.dart'; +import 'package:icarus/providers/collab/cloud_media_upload_queue_provider.dart'; import 'package:icarus/providers/auth_provider.dart'; import 'package:icarus/providers/collab/remote_strategy_snapshot_provider.dart'; import 'package:icarus/providers/collab/strategy_op_queue_provider.dart'; @@ -45,9 +46,51 @@ import 'package:icarus/strategy/strategy_page_models.dart'; final strategyProvider = NotifierProvider(StrategyProvider.new); +void _logStrategyProviderDebug({ + required String runId, + required String hypothesisId, + required String location, + required String message, + Map data = const {}, +}) { + unawaited( + File(r'E:\Projects\icarus-cloud\debug-16ee23.log').writeAsString( + '${jsonEncode({ + 'sessionId': '16ee23', + 'runId': runId, + 'hypothesisId': hypothesisId, + 'location': location, + 'message': message, + 'data': data, + 'timestamp': DateTime.now().millisecondsSinceEpoch, + })}\n', + mode: FileMode.append, + flush: true, + ), + ); +} + class StrategyProvider extends Notifier { @override StrategyState build() { + _registerPersistenceTrackingListeners(); + ref.listen(authProvider, (previous, next) { + final strategyId = state.strategyId; + if (state.source != StrategySource.cloud || strategyId == null) { + return; + } + final becameReady = + !(previous?.isConvexUserReady ?? false) && next.isConvexUserReady; + if (!becameReady) { + return; + } + unawaited( + ref.read(cloudMediaUploadQueueProvider.notifier).retryNow( + ignoreBackoff: true, + ), + ); + }); + return const StrategyState( strategyId: null, strategyName: null, @@ -61,6 +104,67 @@ class StrategyProvider extends Notifier { bool _saveInProgress = false; bool _pendingSave = false; + bool _cloudMutationSyncScheduled = false; + bool _cloudStrategyMutationSyncScheduled = false; + int _persistenceTrackingSuspensionCount = 0; + + void _registerPersistenceTrackingListeners() { + _listenForPageBackedState(agentProvider); + _listenForPageBackedState(abilityProvider); + _listenForPageBackedState( + drawingProvider.select((drawing) => drawing.elements), + ); + _listenForPageBackedState(textProvider); + _listenForPageBackedState( + placedImageProvider.select((images) => images.images), + ); + _listenForPageBackedState(utilityProvider); + _listenForPageBackedState( + lineUpProvider.select((lineups) => lineups.lineUps), + ); + _listenForPageBackedState(strategySettingsProvider); + _listenForPageBackedState(mapProvider.select((map) => map.isAttack)); + + _listenForStrategyBackedState(mapProvider.select((map) => map.currentMap)); + _listenForStrategyBackedState(strategyThemeProvider); + } + + void _listenForPageBackedState(ProviderListenable provider) { + ref.listen(provider, (_, __) { + if (!_shouldTrackPersistedEditorMutation()) { + return; + } + setUnsaved(); + }); + } + + void _listenForStrategyBackedState(ProviderListenable provider) { + ref.listen(provider, (_, __) { + if (!_shouldTrackPersistedEditorMutation()) { + return; + } + _markStrategyBackedStateUnsaved(); + }); + } + + bool _shouldTrackPersistedEditorMutation() { + if (_persistenceTrackingSuspensionCount > 0) { + return false; + } + if (!state.isOpen || state.strategyId == null || state.source == null) { + return false; + } + return !ref.read(strategyPageSessionProvider).isApplyingPage; + } + + T _withoutPersistenceTracking(T Function() callback) { + _persistenceTrackingSuspensionCount += 1; + try { + return callback(); + } finally { + _persistenceTrackingSuspensionCount -= 1; + } + } //Used For Images void setFromState(StrategyState newState) { @@ -149,11 +253,14 @@ class StrategyProvider extends Notifier { return; } + final storageDirectory = kIsWeb + ? null + : (await setStorageDirectory(snapshot.header.publicId)).path; state = state.copyWith( strategyId: snapshot.header.publicId, strategyName: snapshot.header.name, source: StrategySource.cloud, - storageDirectory: null, + storageDirectory: storageDirectory, isOpen: true, ); @@ -162,6 +269,11 @@ class StrategyProvider extends Notifier { source: StrategySource.cloud, selectFirstPageIfNeeded: true, ); + unawaited( + ref.read(cloudMediaUploadQueueProvider.notifier).setActiveStrategy( + snapshot.header.publicId, + ), + ); } Future switchPage(String pageID) async { @@ -193,6 +305,7 @@ class StrategyProvider extends Notifier { } Future notifyCloudMutation({bool flushImmediately = false}) async { + _cloudMutationSyncScheduled = false; if (!_currentStrategyIsCloud()) { return; } @@ -206,7 +319,60 @@ class StrategyProvider extends Notifier { .flushCurrentPage(flushImmediately: flushImmediately); } - void setUnsaved() async { + Future notifyCloudStrategyMutation({ + bool flushImmediately = false, + }) async { + _cloudStrategyMutationSyncScheduled = false; + if (!_currentStrategyIsCloud()) { + return; + } + + ref.read(strategySaveStateProvider.notifier) + ..markDirty() + ..setPendingCloudSync(true) + ..setCloudSyncError(null); + + final desiredOp = _buildDesiredStrategySyncOp(); + ref.read(strategyOpQueueProvider.notifier).syncDesiredGenericOp( + entityKey: 'strategy', + desiredOp: desiredOp, + flushImmediately: flushImmediately, + ); + if (flushImmediately) { + await ref.read(strategyOpQueueProvider.notifier).flushNow(); + } + } + + void _scheduleCloudMutationSync() { + if (_cloudMutationSyncScheduled) { + return; + } + _cloudMutationSyncScheduled = true; + scheduleMicrotask(() async { + if (!_cloudMutationSyncScheduled) { + return; + } + await notifyCloudMutation(flushImmediately: false); + }); + } + + void _scheduleCloudStrategySync() { + if (_cloudStrategyMutationSyncScheduled) { + return; + } + _cloudStrategyMutationSyncScheduled = true; + scheduleMicrotask(() async { + if (!_cloudStrategyMutationSyncScheduled) { + return; + } + await notifyCloudStrategyMutation(flushImmediately: false); + }); + } + + void _markStrategyBackedStateUnsaved() { + if (!state.isOpen || state.strategyId == null || state.source == null) { + return; + } if (ref.read(strategyPageSessionProvider).isApplyingPage) { return; } @@ -216,7 +382,69 @@ class StrategyProvider extends Notifier { ..markDirty() ..setPendingCloudSync(true) ..setCloudSyncError(null); - unawaited(notifyCloudMutation(flushImmediately: false)); + _scheduleCloudStrategySync(); + return; + } + + ref.read(strategySaveStateProvider.notifier).markDirty(); + refreshAutosaveScheduling(); + } + + StrategyOp? _buildDesiredStrategySyncOp() { + final strategyId = state.strategyId; + final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; + if (strategyId == null || + snapshot == null || + snapshot.header.publicId != strategyId) { + return null; + } + + final strategyTheme = ref.read(strategyThemeProvider); + final localMapData = Maps.mapNames[ref.read(mapProvider).currentMap] ?? + snapshot.header.mapData; + final localThemeProfileId = strategyTheme.profileId; + final localThemeOverridePalette = strategyTheme.overridePalette == null + ? null + : jsonEncode(strategyTheme.overridePalette!.toJson()); + + final matchesRemote = snapshot.header.mapData == localMapData && + snapshot.header.themeProfileId == localThemeProfileId && + snapshot.header.themeOverridePalette == localThemeOverridePalette; + if (matchesRemote) { + return null; + } + + return StrategyOp( + opId: const Uuid().v4(), + kind: StrategyOpKind.patch, + entityType: StrategyOpEntityType.strategy, + entityPublicId: strategyId, + payload: jsonEncode({ + 'mapData': localMapData, + if (localThemeProfileId != null) 'themeProfileId': localThemeProfileId, + if (localThemeProfileId == null) 'clearThemeProfileId': true, + if (localThemeOverridePalette != null) + 'themeOverridePalette': localThemeOverridePalette, + if (localThemeOverridePalette == null) + 'clearThemeOverridePalette': true, + }), + ); + } + + void setUnsaved() { + if (!state.isOpen || state.strategyId == null || state.source == null) { + return; + } + if (ref.read(strategyPageSessionProvider).isApplyingPage) { + return; + } + + if (_currentStrategyIsCloud()) { + ref.read(strategySaveStateProvider.notifier) + ..markDirty() + ..setPendingCloudSync(true) + ..setCloudSyncError(null); + _scheduleCloudMutationSync(); return; } @@ -246,6 +474,7 @@ class StrategyProvider extends Notifier { ref.read(autoSaveProvider.notifier).ping(); // UI: Saving... ref.read(strategySaveStateProvider.notifier).markSaving(true); if (_currentStrategyIsCloud()) { + await notifyCloudStrategyMutation(flushImmediately: true); await ref .read(strategyPageSessionProvider.notifier) .flushCurrentPage(flushImmediately: true); @@ -283,6 +512,19 @@ class StrategyProvider extends Notifier { } Future clearCurrentStrategy() async { + // #region agent log + _logStrategyProviderDebug( + runId: 'pre-fix', + hypothesisId: 'H2', + location: 'strategy_provider.dart:311', + message: 'clearCurrentStrategy start', + data: { + 'previousStrategyId': state.strategyId, + 'previousSource': state.source?.name, + 'previousIsOpen': state.isOpen, + }, + ); + // #endregion cancelPendingSave(); ref.read(strategyThemeProvider.notifier).fromStrategy(); ref.read(strategySaveStateProvider.notifier).reset(); @@ -294,7 +536,23 @@ class StrategyProvider extends Notifier { storageDirectory: state.storageDirectory, isOpen: false, ); + // #region agent log + _logStrategyProviderDebug( + runId: 'pre-fix', + hypothesisId: 'H2', + location: 'strategy_provider.dart:323', + message: 'clearCurrentStrategy state cleared', + data: { + 'strategyId': state.strategyId, + 'source': state.source?.name, + 'isOpen': state.isOpen, + }, + ); + // #endregion ref.read(remoteStrategySnapshotProvider.notifier).clear(); + unawaited( + ref.read(cloudMediaUploadQueueProvider.notifier).setActiveStrategy(null), + ); } // Switch active page: flush old page first, then hydrate new @@ -601,7 +859,9 @@ class StrategyProvider extends Notifier { if (newStrat == null) { return; } - ref.read(actionProvider.notifier).resetActionState(); + _withoutPersistenceTracking(() { + ref.read(actionProvider.notifier).resetActionState(); + }); List pageImageData = []; for (final page in newStrat.pages) { @@ -655,21 +915,18 @@ class StrategyProvider extends Notifier { final defaultThemeProfileId = ref.read(mapThemeProfilesProvider).defaultProfileIdForNewStrategies; try { - await ref.read(convexStrategyRepositoryProvider).createStrategy( + await ref + .read(convexStrategyRepositoryProvider) + .createStrategyWithInitialPage( publicId: newID, name: name, mapData: Maps.mapNames[MapValue.ascent] ?? "ascent", + initialPagePublicId: pageID, + initialPageName: "Page 1", + initialPageIsAttack: true, folderPublicId: ref.read(folderProvider), themeProfileId: defaultThemeProfileId, ); - await ConvexClient.instance.mutation(name: "pages:add", args: { - "strategyPublicId": newID, - "pagePublicId": pageID, - "name": "Page 1", - "sortIndex": 0, - "isAttack": true, - "settings": ref.read(strategySettingsProvider.notifier).toJson(), - }); } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:create_new', @@ -727,17 +984,14 @@ class StrategyProvider extends Notifier { void setThemeProfileForCurrentStrategy(String profileId) { ref.read(strategyThemeProvider.notifier).setProfile(profileId); - setUnsaved(); } void setThemeOverrideForCurrentStrategy(MapThemePalette palette) { ref.read(strategyThemeProvider.notifier).setOverride(palette); - setUnsaved(); } void clearThemeOverrideForCurrentStrategy() { ref.read(strategyThemeProvider.notifier).clearOverride(); - setUnsaved(); } Future renameStrategy( @@ -795,20 +1049,31 @@ class StrategyProvider extends Notifier { .read(convexStrategyRepositoryProvider) .fetchSnapshot(strategyID); final newStrategyID = const Uuid().v4(); - await ref.read(convexStrategyRepositoryProvider).createStrategy( + final pages = [...snapshot.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + final firstPage = pages.isNotEmpty ? pages.first : null; + final firstPageId = const Uuid().v4(); + await ref + .read(convexStrategyRepositoryProvider) + .createStrategyWithInitialPage( publicId: newStrategyID, name: "${snapshot.header.name} (Copy)", mapData: snapshot.header.mapData, + initialPagePublicId: firstPageId, + initialPageName: firstPage?.name ?? "Page 1", + initialPageIsAttack: firstPage?.isAttack ?? true, + initialPageSettings: firstPage?.settings, folderPublicId: ref.read(folderProvider), themeProfileId: snapshot.header.themeProfileId, themeOverridePalette: snapshot.header.themeOverridePalette, ); - final pages = [...snapshot.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - final pageIdMap = {}; - for (final page in pages) { + if (firstPage != null) { + pageIdMap[firstPage.publicId] = firstPageId; + } + for (var i = firstPage == null ? 0 : 1; i < pages.length; i++) { + final page = pages[i]; final newPageId = const Uuid().v4(); pageIdMap[page.publicId] = newPageId; await ConvexClient.instance.mutation(name: "pages:add", args: { diff --git a/lib/providers/strategy_save_state_provider.dart b/lib/providers/strategy_save_state_provider.dart index f4212849..1cb40986 100644 --- a/lib/providers/strategy_save_state_provider.dart +++ b/lib/providers/strategy_save_state_provider.dart @@ -1,4 +1,5 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icarus/providers/collab/cloud_media_upload_queue_provider.dart'; import 'package:icarus/providers/collab/strategy_op_queue_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/strategy/strategy_page_models.dart'; @@ -9,6 +10,8 @@ class StrategySaveState { required this.isSaving, required this.hasPendingCloudSync, required this.cloudSyncError, + required this.hasPendingMediaSync, + required this.mediaSyncErrorCount, required this.lastPersistedAt, }); @@ -16,16 +19,25 @@ class StrategySaveState { final bool isSaving; final bool hasPendingCloudSync; final String? cloudSyncError; + final bool hasPendingMediaSync; + final int mediaSyncErrorCount; final DateTime? lastPersistedAt; bool get canLeaveSafely => - !isDirty && !isSaving && !hasPendingCloudSync && cloudSyncError == null; + !isDirty && + !isSaving && + !hasPendingCloudSync && + !hasPendingMediaSync && + cloudSyncError == null && + mediaSyncErrorCount == 0; StrategySaveState copyWith({ bool? isDirty, bool? isSaving, bool? hasPendingCloudSync, String? cloudSyncError, + bool? hasPendingMediaSync, + int? mediaSyncErrorCount, bool clearCloudSyncError = false, DateTime? lastPersistedAt, }) { @@ -35,6 +47,8 @@ class StrategySaveState { hasPendingCloudSync: hasPendingCloudSync ?? this.hasPendingCloudSync, cloudSyncError: clearCloudSyncError ? null : (cloudSyncError ?? this.cloudSyncError), + hasPendingMediaSync: hasPendingMediaSync ?? this.hasPendingMediaSync, + mediaSyncErrorCount: mediaSyncErrorCount ?? this.mediaSyncErrorCount, lastPersistedAt: lastPersistedAt ?? this.lastPersistedAt, ); } @@ -71,11 +85,41 @@ class StrategySaveStateNotifier extends Notifier { } }); + ref.listen(cloudMediaUploadQueueProvider, ( + previous, + next, + ) { + final source = ref.read(strategyProvider).source; + if (source != StrategySource.cloud) { + return; + } + + final failedJobs = next.jobs.where((job) => job.isFailed).length; + final hasPendingMedia = next.jobs.isNotEmpty; + final hasPendingCloudSync = state.hasPendingCloudSync || hasPendingMedia; + state = state.copyWith( + hasPendingMediaSync: hasPendingMedia, + mediaSyncErrorCount: failedJobs, + isDirty: hasPendingCloudSync ? true : state.isDirty, + ); + + if (!hasPendingCloudSync && + state.cloudSyncError == null && + failedJobs == 0) { + state = state.copyWith( + isDirty: false, + lastPersistedAt: DateTime.now(), + ); + } + }); + return const StrategySaveState( isDirty: false, isSaving: false, hasPendingCloudSync: false, cloudSyncError: null, + hasPendingMediaSync: false, + mediaSyncErrorCount: 0, lastPersistedAt: null, ); } @@ -86,6 +130,8 @@ class StrategySaveStateNotifier extends Notifier { isSaving: false, hasPendingCloudSync: false, cloudSyncError: null, + hasPendingMediaSync: false, + mediaSyncErrorCount: 0, lastPersistedAt: null, ); } @@ -117,6 +163,8 @@ class StrategySaveStateNotifier extends Notifier { isDirty: false, isSaving: false, hasPendingCloudSync: false, + hasPendingMediaSync: false, + mediaSyncErrorCount: 0, clearCloudSyncError: true, lastPersistedAt: DateTime.now(), ); diff --git a/lib/providers/text_provider.dart b/lib/providers/text_provider.dart index 055d0c93..05a13fb0 100644 --- a/lib/providers/text_provider.dart +++ b/lib/providers/text_provider.dart @@ -3,10 +3,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/coordinate_system.dart'; import 'package:icarus/const/placed_classes.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; import 'package:icarus/providers/action_provider.dart'; import 'package:icarus/providers/action_history_models.dart'; import 'package:icarus/providers/text_draft_provider.dart'; -import 'package:icarus/providers/text_widget_height_provider.dart'; final textProvider = NotifierProvider>(TextProvider.new); @@ -51,8 +51,6 @@ class TextProvider extends Notifier> { group: ActionGroup.text, objectDelta: ObjectHistoryDelta( after: ActionObjectState.text(text), - afterTextHeights: - ref.read(textWidgetHeightProvider.notifier).takeSnapshotForIds([text.id]), ), ); @@ -72,9 +70,6 @@ class TextProvider extends Notifier> { group: ActionGroup.text, objectDelta: ObjectHistoryDelta( before: ActionObjectState.text(state[index]), - beforeTextHeights: ref - .read(textWidgetHeightProvider.notifier) - .takeSnapshotForIds([id]), ), ), ); @@ -101,10 +96,6 @@ class TextProvider extends Notifier> { objectDelta: ObjectHistoryDelta( before: before, after: ActionObjectState.text(temp), - beforeTextHeights: - ref.read(textWidgetHeightProvider.notifier).takeSnapshotForIds([id]), - afterTextHeights: - ref.read(textWidgetHeightProvider.notifier).takeSnapshotForIds([id]), ), ); ref.read(actionProvider.notifier).addAction(action); @@ -115,18 +106,31 @@ class TextProvider extends Notifier> { void switchSides() { final newState = [...state]; for (final text in newState) { - text.switchSides( - ref.read(textWidgetHeightProvider.notifier).getOffset(text.id)); + text.switchSides(_switchSizeForText(text)); } for (final text in poppedText) { - text.switchSides( - ref.read(textWidgetHeightProvider.notifier).getOffset(text.id)); + text.switchSides(_switchSizeForText(text)); } state = newState; } + Offset _switchSizeForText(PlacedText text) { + final size = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: text.size, + fontSizeWorld: text.fontSize, + text: text.text, + ); + + return Offset(size.width, size.height); + } + + Offset switchSizeForText(PlacedText text) { + return _switchSizeForText(text); + } + void commitText(String id, String nextText) { final newState = [...state]; final index = PlacedWidget.getIndexByID(id, newState); @@ -144,12 +148,6 @@ class TextProvider extends Notifier> { objectDelta: ObjectHistoryDelta( before: before, after: ActionObjectState.text(newState[index]), - beforeTextHeights: ref - .read(textWidgetHeightProvider.notifier) - .takeSnapshotForIds([id]), - afterTextHeights: ref - .read(textWidgetHeightProvider.notifier) - .takeSnapshotForIds([id]), ), ), ); @@ -190,21 +188,18 @@ class TextProvider extends Notifier> { } switch (action.type) { case ActionType.addition: - _clearTextHeights(delta.afterTextHeights.keys); removeText(action.id); return; case ActionType.deletion: final before = delta.before?.text; if (before == null) return; _upsertText(clonePlacedText(before)); - _restoreTextHeights(delta.beforeTextHeights); return; case ActionType.edit: final before = delta.before?.text; if (before == null) return; _upsertText(clonePlacedText(before)); - _restoreTextHeights(delta.beforeTextHeights); return; case ActionType.bulkDeletion: case ActionType.transaction: @@ -240,17 +235,14 @@ class TextProvider extends Notifier> { final after = delta.after?.text; if (after == null) return; _upsertText(clonePlacedText(after)); - _restoreTextHeights(delta.afterTextHeights); return; case ActionType.deletion: - _clearTextHeights(delta.beforeTextHeights.keys); removeText(action.id); return; case ActionType.edit: final after = delta.after?.text; if (after == null) return; _upsertText(clonePlacedText(after)); - _restoreTextHeights(delta.afterTextHeights); return; case ActionType.bulkDeletion: case ActionType.transaction: @@ -341,7 +333,8 @@ class TextProvider extends Notifier> { void restoreSnapshot(TextProviderSnapshot snapshot) { ref.read(textDraftProvider.notifier).clearAllDrafts(); - poppedText = snapshot.poppedText.map((text) => clonePlacedText(text)).toList(); + poppedText = + snapshot.poppedText.map((text) => clonePlacedText(text)).toList(); state = snapshot.texts.map((text) => clonePlacedText(text)).toList(); } @@ -355,14 +348,4 @@ class TextProvider extends Notifier> { } state = newState; } - - void _restoreTextHeights(Map snapshot) { - if (snapshot.isEmpty) return; - ref.read(textWidgetHeightProvider.notifier).restoreSnapshot(snapshot); - } - - void _clearTextHeights(Iterable ids) { - if (ids.isEmpty) return; - ref.read(textWidgetHeightProvider.notifier).clearEntries(ids); - } } diff --git a/lib/providers/text_widget_height_provider.dart b/lib/providers/text_widget_height_provider.dart deleted file mode 100644 index 91896068..00000000 --- a/lib/providers/text_widget_height_provider.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -final textWidgetHeightProvider = - NotifierProvider>( - TextWidgetHeightProvider.new, -); - -class TextWidgetHeightProvider extends Notifier> { - @override - Map build() { - return {}; - } - - void updateHeight(String id, Offset offset) { - state = {...state, id: offset}; - } - - Offset getOffset(String id) { - return state[id] ?? Offset.zero; - } - - Map takeSnapshotForIds(Iterable ids) { - return { - for (final id in ids) - if (state.containsKey(id)) id: state[id]!, - }; - } - - void clearEntries(Iterable ids) { - final newState = {...state}; - for (final id in ids) { - newState.remove(id); - } - state = newState; - } - - void restoreSnapshot(Map snapshot) { - state = { - ...state, - ...snapshot, - }; - } - - void clearAll() { - state = {}; - } -} diff --git a/lib/services/unsaved_strategy_guard.dart b/lib/services/unsaved_strategy_guard.dart index 9d1acd11..b778a766 100644 --- a/lib/services/unsaved_strategy_guard.dart +++ b/lib/services/unsaved_strategy_guard.dart @@ -113,9 +113,11 @@ Future _waitForCloudSync( final saveState = ref.read(strategySaveStateProvider); final queueState = ref.read(strategyOpQueueProvider); if (!saveState.hasPendingCloudSync && + !saveState.hasPendingMediaSync && queueState.pending.isEmpty && !queueState.isFlushing && - saveState.cloudSyncError == null) { + saveState.cloudSyncError == null && + saveState.mediaSyncErrorCount == 0) { return true; } await Future.delayed(pollInterval); @@ -134,8 +136,9 @@ Future _guardCloudStrategyExit({ final queueState = ref.read(strategyOpQueueProvider); final authState = ref.read(authProvider); - final hasPendingSync = - saveState.hasPendingCloudSync || queueState.pending.isNotEmpty; + final hasPendingSync = saveState.hasPendingCloudSync || + saveState.hasPendingMediaSync || + queueState.pending.isNotEmpty; final cloudError = saveState.cloudSyncError ?? queueState.lastError; if (!hasPendingSync && cloudError == null) { if (!context.mounted) { @@ -159,7 +162,9 @@ Future _guardCloudStrategyExit({ final decision = await _showCloudSyncBlockedDialog( context, message: cloudError ?? - 'Icarus is still syncing cloud edits. Stay on this screen until sync completes.', + (saveState.mediaSyncErrorCount > 0 + ? 'Some media uploads failed. Retry sync or stay here until the queue clears.' + : 'Icarus is still syncing cloud edits and media. Stay on this screen until sync completes.'), showRetryAuth: authState.hasActiveAuthIncident, ); diff --git a/lib/strategy/strategy_cloud_migration.dart b/lib/strategy/strategy_cloud_migration.dart index acd90b40..4a7b44a0 100644 --- a/lib/strategy/strategy_cloud_migration.dart +++ b/lib/strategy/strategy_cloud_migration.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/collab/cloud_media_models.dart'; import 'package:icarus/providers/drawing_provider.dart'; import 'package:icarus/providers/strategy_page.dart'; import 'package:uuid/uuid.dart'; @@ -51,7 +52,7 @@ void appendMigratedPageOps( for (final image in page.imageData) { final elementId = nextUniqueMigrationId(image.id, usedElementIds); - final payload = Map.from(image.toJson()) + final payload = cloudImagePayloadFromPlacedImage(image) ..putIfAbsent('elementType', () => 'image') ..['id'] = elementId; ops.add(buildMigratedElementOp(page.id, elementId, payload, elementOrder++)); @@ -68,7 +69,7 @@ void appendMigratedPageOps( var lineupOrder = 0; for (final lineup in page.lineUps) { final lineupId = nextUniqueMigrationId(lineup.id, usedLineupIds); - final lineupPayload = Map.from(lineup.toJson()) + final lineupPayload = cloudLineupPayload(lineup) ..['id'] = lineupId; ops.add( StrategyOp( diff --git a/lib/strategy/strategy_import_export.dart b/lib/strategy/strategy_import_export.dart index 764f8108..1e9f5f72 100644 --- a/lib/strategy/strategy_import_export.dart +++ b/lib/strategy/strategy_import_export.dart @@ -22,6 +22,7 @@ import 'package:icarus/providers/agent_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; import 'package:icarus/providers/favorite_agents_provider.dart'; import 'package:icarus/providers/folder_provider.dart'; +import 'package:icarus/providers/collab/cloud_media_cache_provider.dart'; import 'package:icarus/providers/image_provider.dart'; import 'package:icarus/providers/map_provider.dart'; import 'package:icarus/providers/map_theme_provider.dart'; @@ -2359,9 +2360,61 @@ class StrategyImportExportService { return outPath; } + Future _ensureRemoteAssetsCached( + RemoteStrategySnapshot snapshot, + ) async { + final strategyId = snapshot.header.publicId; + final assetIds = {}; + for (final page in snapshot.pages) { + for (final element in snapshot.elementsByPage[page.publicId] ?? const []) { + if (element.deleted || element.elementType != 'image') { + continue; + } + assetIds.add(element.publicId); + } + + for (final lineup in snapshot.lineupsByPage[page.publicId] ?? const []) { + if (lineup.deleted) { + continue; + } + try { + final decoded = jsonDecode(lineup.payload); + final mapped = decoded is Map + ? decoded + : decoded is Map + ? Map.from(decoded) + : null; + if (mapped == null) { + continue; + } + final parsed = LineUp.fromJson(mapped); + for (final image in parsed.images) { + assetIds.add(image.id); + } + } catch (_) { + continue; + } + } + } + + final cacheNotifier = ref.read(cloudMediaCacheProvider.notifier); + final cached = await cacheNotifier.ensureAssetIdsCached( + strategyId: strategyId, + strategyPublicId: strategyId, + assetsById: snapshot.assetsById, + assetIds: assetIds, + ); + if (!cached) { + throw StateError( + 'Unable to cache all remote images for export. Reconnect and retry.', + ); + } + } + Future exportCloudStrategy(String strategyId) async { final snapshot = await ref.read(convexStrategyRepositoryProvider).fetchSnapshot(strategyId); + await _ensureRemoteAssetsCached(snapshot); final strategy = _strategyDataFromRemoteSnapshot(snapshot); final outputFile = await FilePicker.platform.saveFile( type: FileType.custom, diff --git a/lib/strategy/strategy_page_apply.dart b/lib/strategy/strategy_page_apply.dart index 05e0ee56..615567b1 100644 --- a/lib/strategy/strategy_page_apply.dart +++ b/lib/strategy/strategy_page_apply.dart @@ -6,12 +6,10 @@ import 'package:icarus/providers/action_provider.dart'; import 'package:icarus/providers/agent_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; import 'package:icarus/providers/image_provider.dart'; -import 'package:icarus/providers/image_widget_size_provider.dart'; import 'package:icarus/providers/map_provider.dart'; import 'package:icarus/providers/map_theme_provider.dart'; import 'package:icarus/providers/strategy_settings_provider.dart'; import 'package:icarus/providers/text_provider.dart'; -import 'package:icarus/providers/text_widget_height_provider.dart'; import 'package:icarus/providers/utility_provider.dart'; import 'package:icarus/const/line_provider.dart'; import 'package:icarus/strategy/strategy_page_models.dart'; @@ -30,8 +28,6 @@ Future applyStrategyEditorPageData( ref.read(placedImageProvider.notifier).clearAll(); ref.read(utilityProvider.notifier).clearAll(); ref.read(lineUpProvider.notifier).clearAll(); - ref.read(imageWidgetSizeProvider.notifier).clearAll(); - ref.read(textWidgetHeightProvider.notifier).clearAll(); if (!preserveHistory) { ref.read(actionProvider.notifier).clearActionHistory(); } diff --git a/lib/strategy/strategy_page_source.dart b/lib/strategy/strategy_page_source.dart index 3f2f9ad5..cd5821cb 100644 --- a/lib/strategy/strategy_page_source.dart +++ b/lib/strategy/strategy_page_source.dart @@ -12,6 +12,7 @@ import 'package:icarus/providers/ability_provider.dart'; import 'package:icarus/providers/agent_provider.dart'; import 'package:icarus/providers/collab/active_page_live_sync_models.dart'; import 'package:icarus/providers/collab/active_page_live_sync_provider.dart'; +import 'package:icarus/providers/collab/cloud_media_cache_provider.dart'; import 'package:icarus/providers/collab/remote_strategy_snapshot_provider.dart'; import 'package:icarus/providers/collab/strategy_op_queue_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; @@ -24,6 +25,7 @@ import 'package:icarus/providers/utility_provider.dart'; import 'package:icarus/strategy/strategy_migrator.dart'; import 'package:icarus/strategy/strategy_models.dart'; import 'package:icarus/strategy/strategy_page_models.dart'; +import 'package:uuid/uuid.dart'; abstract class StrategyPageSource { Future> listPageIds(); @@ -168,13 +170,16 @@ class CloudStrategyPageSource implements StrategyPageSource { orElse: () => pages.first, ); - final projected = ref.read(activePageLiveSyncProvider.notifier).projectPageState( - strategyPublicId: strategyId, - pageId: page.publicId, - ); + final projected = + ref.read(activePageLiveSyncProvider.notifier).projectPageState( + strategyPublicId: strategyId, + pageId: page.publicId, + ); if (projected != null && (page.publicId == activePageId() || - ref.read(activePageLiveSyncProvider.notifier).hasOverlayForPage(page.publicId))) { + ref + .read(activePageLiveSyncProvider.notifier) + .hasOverlayForPage(page.publicId))) { return _hydrateProjectedPage(snapshot, page, projected); } @@ -211,7 +216,17 @@ class CloudStrategyPageSource implements StrategyPageSource { texts.add(PlacedText.fromJson(payload)); break; case 'image': - images.add(PlacedImage.fromJson(payload)); + final hydrated = PlacedImage.fromJson(payload); + final remoteAsset = snapshot.assetsById[hydrated.id]; + hydrated.link = remoteAsset?.url ?? ''; + images.add(hydrated); + if (remoteAsset != null) { + ref.read(cloudMediaCacheProvider.notifier).ensureAssetCached( + strategyId: strategyId, + strategyPublicId: strategyId, + asset: remoteAsset, + ); + } break; case 'utility': utilities.add(PlacedUtility.fromJson(payload)); @@ -232,7 +247,8 @@ class CloudStrategyPageSource implements StrategyPageSource { if (decoded is Map) { parsedLineups.add(LineUp.fromJson(decoded)); } else if (decoded is Map) { - parsedLineups.add(LineUp.fromJson(Map.from(decoded))); + parsedLineups + .add(LineUp.fromJson(Map.from(decoded))); } } catch (_) { // Ignore malformed payloads during hydration. @@ -247,8 +263,9 @@ class CloudStrategyPageSource implements StrategyPageSource { StrategySettings pageSettings = StrategySettings(); if (page.settings != null && page.settings!.isNotEmpty) { try { - pageSettings = - ref.read(strategySettingsProvider.notifier).fromJson(page.settings!); + pageSettings = ref + .read(strategySettingsProvider.notifier) + .fromJson(page.settings!); } catch (_) { pageSettings = StrategySettings(); } @@ -277,6 +294,8 @@ class CloudStrategyPageSource implements StrategyPageSource { return; } + _syncStrategyMetadata(); + final desiredOpsByEntityKey = ref.read(activePageLiveSyncProvider.notifier).syncLocalPage( strategyPublicId: strategyId, @@ -289,6 +308,63 @@ class CloudStrategyPageSource implements StrategyPageSource { ); } + void _syncStrategyMetadata() { + final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; + if (snapshot == null) { + return; + } + + final currentMapData = Maps.mapNames[ref.read(mapProvider).currentMap]; + if (currentMapData == null) { + return; + } + + final strategyTheme = ref.read(strategyThemeProvider); + final desiredThemeOverride = strategyTheme.overridePalette == null + ? null + : jsonEncode(strategyTheme.overridePalette!.toJson()); + final header = snapshot.header; + + final mapMatches = header.mapData == currentMapData; + final themeProfileMatches = + header.themeProfileId == strategyTheme.profileId; + final themeOverrideMatches = + header.themeOverridePalette == desiredThemeOverride; + + if (mapMatches && themeProfileMatches && themeOverrideMatches) { + ref.read(strategyOpQueueProvider.notifier).syncDesiredGenericOp( + entityKey: 'strategy', + desiredOp: null, + flushImmediately: false, + ); + return; + } + + final payload = { + 'mapData': currentMapData, + if (strategyTheme.profileId != null) + 'themeProfileId': strategyTheme.profileId + else + 'clearThemeProfileId': true, + if (desiredThemeOverride != null) + 'themeOverridePalette': desiredThemeOverride + else + 'clearThemeOverridePalette': true, + }; + + ref.read(strategyOpQueueProvider.notifier).syncDesiredGenericOp( + entityKey: 'strategy', + desiredOp: StrategyOp( + opId: const Uuid().v4(), + kind: StrategyOpKind.patch, + entityType: StrategyOpEntityType.strategy, + payload: jsonEncode(payload), + expectedSequence: header.sequence, + ), + flushImmediately: false, + ); + } + StrategyEditorPageData _hydrateProjectedPage( RemoteStrategySnapshot snapshot, RemotePage page, @@ -321,7 +397,17 @@ class CloudStrategyPageSource implements StrategyPageSource { texts.add(PlacedText.fromJson(payload)); break; case 'image': - images.add(PlacedImage.fromJson(payload)); + final hydrated = PlacedImage.fromJson(payload); + final remoteAsset = snapshot.assetsById[hydrated.id]; + hydrated.link = remoteAsset?.url ?? ''; + images.add(hydrated); + if (remoteAsset != null) { + ref.read(cloudMediaCacheProvider.notifier).ensureAssetCached( + strategyId: strategyId, + strategyPublicId: strategyId, + asset: remoteAsset, + ); + } break; case 'utility': utilities.add(PlacedUtility.fromJson(payload)); @@ -339,7 +425,8 @@ class CloudStrategyPageSource implements StrategyPageSource { if (decoded is Map) { parsedLineups.add(LineUp.fromJson(decoded)); } else if (decoded is Map) { - parsedLineups.add(LineUp.fromJson(Map.from(decoded))); + parsedLineups + .add(LineUp.fromJson(Map.from(decoded))); } } catch (_) { // Ignore malformed payloads during hydration. @@ -394,5 +481,4 @@ class CloudStrategyPageSource implements StrategyPageSource { } return {}; } - } diff --git a/lib/strategy_view.dart b/lib/strategy_view.dart index dbcdc06b..3bfe2352 100644 --- a/lib/strategy_view.dart +++ b/lib/strategy_view.dart @@ -7,6 +7,7 @@ import 'package:icarus/interactive_map.dart'; import 'package:icarus/providers/agent_filter_provider.dart'; import 'package:icarus/providers/delete_menu_provider.dart'; import 'package:icarus/providers/interaction_state_provider.dart'; +import 'package:icarus/providers/library_rail_hover_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/services/unsaved_strategy_guard.dart'; import 'package:icarus/sidebar.dart'; @@ -69,10 +70,11 @@ class _StrategyViewState extends ConsumerState .read(agentFilterProvider.notifier) .updateFilterState(FilterState.all); ref.read(deleteMenuProvider.notifier).requestClose(); - await ref.read(strategyProvider.notifier).clearCurrentStrategy(); if (mounted) { + ref.read(suppressLibraryRailHoverProvider.notifier).state = true; Navigator.pop(context); } + await ref.read(strategyProvider.notifier).clearCurrentStrategy(); }, ); } diff --git a/lib/widgets/current_path_bar.dart b/lib/widgets/current_path_bar.dart index 6bebfb0a..ab311717 100644 --- a/lib/widgets/current_path_bar.dart +++ b/lib/widgets/current_path_bar.dart @@ -16,6 +16,7 @@ class CurrentPathBar extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final workspace = ref.watch(libraryWorkspaceProvider); final isCloud = workspace == LibraryWorkspace.cloud; + final cloudSection = ref.watch(cloudLibrarySectionProvider); final currentFolderId = ref.watch(folderProvider); final cloudFolders = isCloud ? (ref.watch(cloudAllFoldersProvider).valueOrNull ?? const []) @@ -51,8 +52,11 @@ class CurrentPathBar extends ConsumerWidget { children: [ FolderTab( folder: null, - isActive: currentFolder == null, + isActive: currentFolder == null && + cloudSection != CloudLibrarySection.sharedWithMe, ), + if (isCloud && cloudSection == CloudLibrarySection.sharedWithMe) + const _StaticBreadcrumbLink(label: 'Shared with Me'), for (int i = 0; i < pathFolders.length; i++) FolderTab( folder: pathFolders[i], @@ -126,12 +130,39 @@ class FolderTab extends ConsumerWidget { }, ), onPressed: () { + if (ref.read(libraryWorkspaceProvider) == LibraryWorkspace.cloud) { + final targetSection = folder == null + ? CloudLibrarySection.home + : ref.read(cloudLibrarySectionProvider); + ref + .read(cloudLibrarySectionProvider.notifier) + .select(targetSection); + } ref.read(folderProvider.notifier).updateID(folder?.id); }, ); } } +class _StaticBreadcrumbLink extends StatelessWidget { + const _StaticBreadcrumbLink({required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + return ShadBreadcrumbLink( + textStyle: ShadTheme.of(context).textTheme.lead, + normalColor: Settings.tacticalVioletTheme.foreground, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Text(label), + ), + onPressed: () {}, + ); + } +} + extension on Iterable { Folder? get firstOrNull => isEmpty ? null : first; } diff --git a/lib/widgets/dialogs/create_lineup_dialog.dart b/lib/widgets/dialogs/create_lineup_dialog.dart index 751bb7f2..002af270 100644 --- a/lib/widgets/dialogs/create_lineup_dialog.dart +++ b/lib/widgets/dialogs/create_lineup_dialog.dart @@ -5,8 +5,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/line_provider.dart'; import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/collab/cloud_media_upload_queue_provider.dart'; import 'package:icarus/providers/image_provider.dart'; import 'package:icarus/providers/interaction_state_provider.dart'; +import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/strategy/strategy_page_models.dart'; import 'package:icarus/services/clipboard_service.dart'; import 'package:icarus/widgets/dialogs/strategy/line_up_media_page.dart'; import 'package:path/path.dart' as path; @@ -26,6 +29,26 @@ class _CreateLineupDialogState extends ConsumerState { final TextEditingController _notesController = TextEditingController(); final List _imagePaths = []; + Future _enqueueLineupMediaJobs({ + required List images, + }) async { + final strategyState = ref.read(strategyProvider); + if (strategyState.source != StrategySource.cloud || + strategyState.strategyId == null) { + return; + } + + for (final image in images) { + await ref + .read(cloudMediaUploadQueueProvider.notifier) + .enqueueJobForLocalFile( + strategyPublicId: strategyState.strategyId!, + assetPublicId: image.id, + fileExtension: image.fileExtension, + ); + } + } + @override void initState() { super.initState(); @@ -88,6 +111,9 @@ class _CreateLineupDialogState extends ConsumerState { ); ref.read(lineUpProvider.notifier).updateLineUp(lineUp); + await _enqueueLineupMediaJobs( + images: lineUp.images, + ); } else { final id = const Uuid().v4(); @@ -107,6 +133,9 @@ class _CreateLineupDialogState extends ConsumerState { ); ref.read(lineUpProvider.notifier).addLineUp(currentLineUp); + await _enqueueLineupMediaJobs( + images: currentLineUp.images, + ); } ref @@ -136,13 +165,17 @@ class _CreateLineupDialogState extends ConsumerState { final String fileExtension = path.extension(imageFile.path); final Uint8List imageBytes = await imageFile.readAsBytes(); final id = const Uuid().v4(); + final strategyId = ref.read(strategyProvider).strategyId; final SimpleImageData imageData = SimpleImageData(id: id, fileExtension: fileExtension); - await ref - .read(placedImageProvider.notifier) - .saveSecureImage(imageBytes, id, fileExtension); + await ref.read(placedImageProvider.notifier).saveSecureImage( + imageBytes, + id, + fileExtension, + strategyId: strategyId, + ); setState(() { _imagePaths.add(imageData); @@ -171,12 +204,16 @@ class _CreateLineupDialogState extends ConsumerState { } final id = const Uuid().v4(); + final strategyId = ref.read(strategyProvider).strategyId; final SimpleImageData imageData = SimpleImageData(id: id, fileExtension: fileExtension); - await ref - .read(placedImageProvider.notifier) - .saveSecureImage(bytes, id, fileExtension); + await ref.read(placedImageProvider.notifier).saveSecureImage( + bytes, + id, + fileExtension, + strategyId: strategyId, + ); setState(() { _imagePaths.add(imageData); diff --git a/lib/widgets/dialogs/share_links_dialog.dart b/lib/widgets/dialogs/share_links_dialog.dart new file mode 100644 index 00000000..f75c1d10 --- /dev/null +++ b/lib/widgets/dialogs/share_links_dialog.dart @@ -0,0 +1,376 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/collab/convex_strategy_repository.dart'; +import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/share_link_provider.dart'; +import 'package:shadcn_ui/shadcn_ui.dart'; +import 'package:uuid/uuid.dart'; + +String buildIcarusShareLink(String token) => 'icarus://share?token=$token'; + +/// Headline like: Share "My Strategy Name" (`"` in [name] become `'`). +String _shareDialogHeadline(String name) { + final safe = name.replaceAll('"', "'"); + return 'Share "$safe"'; +} + +class ShareLinksDialog extends ConsumerStatefulWidget { + const ShareLinksDialog({ + super.key, + required this.targetType, + required this.targetPublicId, + required this.title, + }); + + final String targetType; + final String targetPublicId; + final String title; + + @override + ConsumerState createState() => _ShareLinksDialogState(); +} + +class _ShareLinksDialogState extends ConsumerState { + List _links = const []; + bool _isLoading = true; + bool _isCreating = false; + String _selectedRole = 'viewer'; + + @override + void initState() { + super.initState(); + _loadLinks(); + } + + Future _loadLinks() async { + setState(() => _isLoading = true); + try { + final links = + await ref.read(convexStrategyRepositoryProvider).listShareLinks( + targetType: widget.targetType, + targetPublicId: widget.targetPublicId, + ); + if (!mounted) return; + setState(() { + _links = links; + _isLoading = false; + }); + } catch (_) { + if (!mounted) return; + setState(() => _isLoading = false); + Settings.showToast( + message: 'Failed to load share links.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + } + } + + Future _createLink() async { + setState(() => _isCreating = true); + final token = const Uuid().v4(); + try { + await ref.read(convexStrategyRepositoryProvider).createShareLink( + targetType: widget.targetType, + targetPublicId: widget.targetPublicId, + token: token, + role: _selectedRole, + ); + await Clipboard.setData(ClipboardData(text: buildIcarusShareLink(token))); + Settings.showToast( + message: 'Share link copied to clipboard.', + backgroundColor: Settings.tacticalVioletTheme.primary, + ); + await _loadLinks(); + } catch (_) { + Settings.showToast( + message: 'Failed to create share link.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + } finally { + if (mounted) { + setState(() => _isCreating = false); + } + } + } + + Future _copyLink(String token) async { + await Clipboard.setData(ClipboardData(text: buildIcarusShareLink(token))); + Settings.showToast( + message: 'Share link copied to clipboard.', + backgroundColor: Settings.tacticalVioletTheme.primary, + ); + } + + Future _revokeLink(String token) async { + try { + await ref.read(convexStrategyRepositoryProvider).revokeShareLink( + targetType: widget.targetType, + targetPublicId: widget.targetPublicId, + token: token, + ); + await _loadLinks(); + } catch (_) { + Settings.showToast( + message: 'Failed to revoke share link.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + } + } + + @override + Widget build(BuildContext context) { + final theme = ShadTheme.of(context); + + return ShadDialog( + title: Text( + _shareDialogHeadline(widget.title), + softWrap: true, + ), + description: const Text( + 'Links never expire. Anyone who opens one can join this item in your cloud library with the access you choose.', + ), + actions: [ + ShadButton.secondary( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Done'), + ), + ], + child: SizedBox( + width: double.infinity, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'New link', + style: theme.textTheme.small.copyWith( + color: theme.colorScheme.mutedForeground, + fontWeight: FontWeight.w600, + letterSpacing: 0.2, + ), + ), + const SizedBox(height: 8), + ShadSelect( + initialValue: _selectedRole, + selectedOptionBuilder: (context, value) => Text( + value == 'editor' ? 'Can edit' : 'View only', + ), + options: const [ + ShadOption(value: 'viewer', child: Text('View only')), + ShadOption(value: 'editor', child: Text('Can edit')), + ], + onChanged: (value) { + if (value != null) { + setState(() => _selectedRole = value); + } + }, + ), + const SizedBox(height: 12), + ShadButton( + onPressed: _isCreating ? null : _createLink, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + LucideIcons.copy, + size: 16, + color: theme.colorScheme.primaryForeground, + ), + const SizedBox(width: 8), + Text( + _isCreating ? 'Creating…' : 'Create link & copy', + ), + ], + ), + ), + const SizedBox(height: 20), + Row( + children: [ + Text( + 'Active links', + style: theme.textTheme.small.copyWith( + color: theme.colorScheme.mutedForeground, + fontWeight: FontWeight.w600, + letterSpacing: 0.2, + ), + ), + if (!_isLoading && _links.isNotEmpty) ...[ + const SizedBox(width: 8), + ShadBadge.secondary( + child: Text('${_links.length}'), + ), + ], + ], + ), + const SizedBox(height: 10), + if (_isLoading) + const Padding( + padding: EdgeInsets.symmetric(vertical: 28), + child: Center(child: CircularProgressIndicator()), + ) + else if (_links.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 20), + child: Text( + 'No links yet. Create one above to invite collaborators.', + style: theme.textTheme.muted, + textAlign: TextAlign.center, + ), + ) + else + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 280), + child: ListView.separated( + shrinkWrap: true, + itemCount: _links.length, + separatorBuilder: (_, __) => const SizedBox(height: 10), + itemBuilder: (context, index) { + final link = _links[index]; + final url = buildIcarusShareLink(link.token); + return DecoratedBox( + decoration: BoxDecoration( + border: Border.all(color: theme.colorScheme.border), + borderRadius: theme.radius, + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Tooltip( + message: url, + child: SelectionArea( + child: Text( + url, + style: theme.textTheme.small.copyWith( + color: theme.colorScheme.mutedForeground, + fontFamily: 'monospace', + fontSize: 11, + height: 1.35, + ), + maxLines: 4, + overflow: TextOverflow.ellipsis, + softWrap: true, + ), + ), + ), + ), + const SizedBox(width: 8), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Tooltip( + message: 'Copy link', + child: ShadButton.ghost( + size: ShadButtonSize.sm, + onPressed: () => _copyLink(link.token), + child: Icon( + LucideIcons.copy, + size: 16, + color: theme.colorScheme.foreground, + ), + ), + ), + Tooltip( + message: link.isRevoked + ? 'Revoked' + : 'Revoke link', + child: ShadButton.ghost( + size: ShadButtonSize.sm, + onPressed: link.isRevoked + ? null + : () => _revokeLink(link.token), + child: Icon( + LucideIcons.trash2, + size: 16, + color: link.isRevoked + ? theme.colorScheme.mutedForeground + : theme.colorScheme.destructive, + ), + ), + ), + ], + ), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ), + ); + } +} + +class JoinShareLinkDialog extends ConsumerStatefulWidget { + const JoinShareLinkDialog({super.key}); + + @override + ConsumerState createState() => + _JoinShareLinkDialogState(); +} + +class _JoinShareLinkDialogState extends ConsumerState { + final TextEditingController _controller = TextEditingController(); + bool _isSubmitting = false; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + String _extractToken(String value) { + final trimmed = value.trim(); + final uri = Uri.tryParse(trimmed); + if (uri != null) { + return uri.queryParameters['token'] ?? trimmed; + } + return trimmed; + } + + Future _submit() async { + final token = _extractToken(_controller.text); + if (token.isEmpty) { + return; + } + setState(() => _isSubmitting = true); + await ref.read(shareLinkControllerProvider.notifier).redeemToken(token); + if (!mounted) return; + setState(() => _isSubmitting = false); + Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) { + return ShadDialog( + title: const Text('Join Shared Item'), + description: const Text( + 'Paste an Icarus share link to add it to your cloud library.'), + actions: [ + ShadButton.secondary( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + ShadButton( + onPressed: _isSubmitting ? null : _submit, + child: Text(_isSubmitting ? 'Joining...' : 'Join'), + ), + ], + child: ShadInput( + controller: _controller, + placeholder: const Text('icarus://share?token=...'), + ), + ); + } +} diff --git a/lib/widgets/dialogs/strategy/line_up_media_page.dart b/lib/widgets/dialogs/strategy/line_up_media_page.dart index ed304258..fcab9674 100644 --- a/lib/widgets/dialogs/strategy/line_up_media_page.dart +++ b/lib/widgets/dialogs/strategy/line_up_media_page.dart @@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/line_provider.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/providers/image_provider.dart'; +import 'package:icarus/providers/collab/remote_strategy_snapshot_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/widgets/custom_text_field.dart'; import 'package:path/path.dart' as path; @@ -234,20 +235,37 @@ class _LineupMediaPageState extends ConsumerState { } Widget _buildImageTile(int index) { - final String fullImagePath = path.join(imageFolderPath!.path, - widget.images[index].id + widget.images[index].fileExtension); + final image = widget.images[index]; + final String fullImagePath = + path.join(imageFolderPath!.path, image.id + image.fileExtension); final file = File(fullImagePath); + final snapshot = ref.watch(remoteStrategySnapshotProvider).valueOrNull; + final fallbackUrl = snapshot?.assetsById[image.id]?.url; + + final ImageProvider? imageProvider = file.existsSync() + ? FileImage(file) + : (fallbackUrl != null && fallbackUrl.isNotEmpty + ? NetworkImage(fallbackUrl) + : null); return Stack( children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), - image: DecorationImage( - image: FileImage(file), // Placeholder - fit: BoxFit.cover, - ), + color: Settings.tacticalVioletTheme.secondary, + image: imageProvider == null + ? null + : DecorationImage( + image: imageProvider, + fit: BoxFit.cover, + ), ), + child: imageProvider == null + ? const Center( + child: Icon(Icons.broken_image, color: Colors.white), + ) + : null, ), Positioned( top: 4, diff --git a/lib/widgets/draggable_widgets/image/image_widget.dart b/lib/widgets/draggable_widgets/image/image_widget.dart index 6df8cf1c..7aed75d8 100644 --- a/lib/widgets/draggable_widgets/image/image_widget.dart +++ b/lib/widgets/draggable_widgets/image/image_widget.dart @@ -4,9 +4,8 @@ import 'dart:ui' show ImageFilter; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/coordinate_system.dart'; -import 'package:icarus/const/image_scale_policy.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; import 'package:icarus/const/settings.dart'; -import 'package:icarus/providers/image_widget_size_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:path/path.dart' as path; import 'package:shadcn_ui/shadcn_ui.dart'; @@ -150,33 +149,21 @@ class ImageWidget extends ConsumerStatefulWidget { } class _ImageWidgetState extends ConsumerState { - @override - void initState() { - super.initState(); - WidgetsBinding.instance.addPostFrameCallback((timeStamp) { - if (widget.isFeedback) return; - RenderObject? renderObject = context.findRenderObject(); - RenderBox? renderBox = renderObject as RenderBox; - // if (renderBox == null) return; - double height = renderBox.size.height; - double width = renderBox.size.width; - - Offset offset = Offset(width, height); - - ref.read(imageWidgetSizeProvider.notifier).updateSize(widget.id, offset); - }); - } - @override Widget build(BuildContext context) { final coordinateSystem = CoordinateSystem.instance; - final clampedScale = ImageScalePolicy.clamp(widget.scale); - const leftChromeWidth = 12.0; // left bar (10) + spacer (2) + final metrics = PlacedImageDimensions.screenSize( + coordinateSystem: coordinateSystem, + scale: widget.scale, + aspectRatio: widget.aspectRatio, + ); final safeAspectRatio = widget.aspectRatio <= 0 ? 1.0 : widget.aspectRatio; - final totalWidth = coordinateSystem.worldWidthToScreen(clampedScale); - final cardWidth = - (totalWidth - leftChromeWidth).clamp(1.0, double.infinity); - final cardHeight = (cardWidth - 10) / safeAspectRatio + 10; + final cardWidth = (metrics.width - + PlacedImageDimensions.tagWidth - + PlacedImageDimensions.tagGap) + .clamp(1.0, double.infinity); + final contentWidth = (cardWidth - (PlacedImageDimensions.imagePadding * 2)) + .clamp(1.0, double.infinity); final file = File(path.join( ref.watch(strategyProvider).storageDirectory!, 'images', @@ -207,71 +194,53 @@ class _ImageWidgetState extends ConsumerState { aspectRatio: widget.aspectRatio, ); }, - child: NotificationListener( - onNotification: (notification) { - if (widget.isFeedback) return true; - RenderObject? renderObject = context.findRenderObject(); - RenderBox? renderBox = renderObject as RenderBox; - double height = renderBox.size.height; - double width = renderBox.size.width; - - Offset offset = Offset(width, height); - WidgetsBinding.instance.addPostFrameCallback((timeStamp) { - ref - .read(imageWidgetSizeProvider.notifier) - .updateSize(widget.id, offset); - }); - return true; - }, - child: SizeChangedLayoutNotifier( - child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: totalWidth, minWidth: 0), - child: Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - //Tag container - width: 10, - height: cardHeight.toDouble(), - decoration: BoxDecoration( - color: Color(widget.tagColorValue ?? 0xFFC5C5C5), - borderRadius: BorderRadius.circular(3), - ), + child: SizedBox( + width: metrics.width, + height: metrics.height, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + //Tag container + width: PlacedImageDimensions.tagWidth, + decoration: BoxDecoration( + color: Color(widget.tagColorValue ?? 0xFFC5C5C5), + borderRadius: BorderRadius.circular(3), + ), + ), + const SizedBox(width: PlacedImageDimensions.tagGap), + Expanded( + child: Card( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(3), ), - const SizedBox(width: 2), - Card( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(3), + margin: EdgeInsets.zero, + color: Colors.black, + child: Padding( + padding: const EdgeInsets.all( + PlacedImageDimensions.imagePadding, ), - margin: EdgeInsets.zero, - color: Colors.black, child: SizedBox( - width: cardWidth.toDouble(), - child: Padding( - padding: const EdgeInsets.all(5), - child: AspectRatio( - aspectRatio: safeAspectRatio, - child: Container( - decoration: BoxDecoration( - color: const Color.fromARGB(255, 20, 20, 20), - borderRadius: BorderRadius.circular(3), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(3), - child: Hero( - tag: 'image_${widget.id}', - child: buildThumb(), - ), - ), + width: contentWidth, + height: contentWidth / safeAspectRatio, + child: Container( + decoration: BoxDecoration( + color: const Color.fromARGB(255, 20, 20, 20), + borderRadius: BorderRadius.circular(3), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(3), + child: Hero( + tag: 'image_${widget.id}', + child: buildThumb(), ), ), ), ), ), - ], + ), ), - ), + ], ), ), ); diff --git a/lib/widgets/draggable_widgets/text/text_widget.dart b/lib/widgets/draggable_widgets/text/text_widget.dart index 5c37bbc0..d0ddf102 100644 --- a/lib/widgets/draggable_widgets/text/text_widget.dart +++ b/lib/widgets/draggable_widgets/text/text_widget.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/coordinate_system.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; import 'package:icarus/const/shortcut_info.dart'; import 'package:icarus/providers/text_draft_provider.dart'; -import 'package:icarus/providers/text_widget_height_provider.dart'; class TextWidget extends ConsumerWidget { const TextWidget({ @@ -45,9 +45,12 @@ class TextWidget extends ConsumerWidget { } const _textFieldDecoration = InputDecoration( - hintText: "Write here...", + hintText: PlacedTextDimensions.emptyTextPlaceholder, hintStyle: TextStyle(color: Colors.grey), + hintMaxLines: 1, border: InputBorder.none, + isCollapsed: true, + contentPadding: EdgeInsets.zero, ); class _EditableTextWidget extends ConsumerStatefulWidget { @@ -86,10 +89,6 @@ class _EditableTextWidgetState extends ConsumerState<_EditableTextWidget> { textDraftProvider, (_, __) => _syncControllerWithExternalState(), ); - - WidgetsBinding.instance.addPostFrameCallback((_) { - _updateMeasuredSize(); - }); } @override @@ -145,43 +144,30 @@ class _EditableTextWidgetState extends ConsumerState<_EditableTextWidget> { ); } - void _updateMeasuredSize() { - if (!mounted) return; - - final renderObject = context.findRenderObject(); - if (renderObject is! RenderBox) return; - - final offset = Offset(renderObject.size.width, renderObject.size.height); - ref.read(textWidgetHeightProvider.notifier).updateHeight(widget.id, offset); - } - @override Widget build(BuildContext context) { + final metrics = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: widget.size, + fontSizeWorld: widget.fontSize, + text: _controller.text, + ); return Shortcuts( shortcuts: ShortcutInfo.textEditingOverrides, - child: NotificationListener( - onNotification: (notification) { - WidgetsBinding.instance.addPostFrameCallback((_) { - _updateMeasuredSize(); - }); - return true; - }, - child: SizeChangedLayoutNotifier( - child: _TextBoxFrame( - size: widget.size, - tagColorValue: widget.tagColorValue, - child: _SharedTextField( - controller: _controller, - focusNode: _focusNode, - fontSize: widget.fontSize, - onChanged: (value) { - _draftNotifier.setDraft(widget.id, value); - }, - onTapOutside: (_) { - _focusNode.unfocus(); - }, - ), - ), + child: _TextBoxFrame( + metrics: metrics, + tagColorValue: widget.tagColorValue, + child: _SharedTextField( + controller: _controller, + focusNode: _focusNode, + fontSize: widget.fontSize, + onChanged: (value) { + _draftNotifier.setDraft(widget.id, value); + setState(() {}); + }, + onTapOutside: (_) { + _focusNode.unfocus(); + }, ), ), ); @@ -232,8 +218,14 @@ class _FeedbackTextWidgetState extends State<_FeedbackTextWidget> { @override Widget build(BuildContext context) { + final metrics = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: widget.size, + fontSizeWorld: widget.fontSize, + text: _controller.text, + ); return _TextBoxFrame( - size: widget.size, + metrics: metrics, tagColorValue: widget.tagColorValue, child: IgnorePointer( child: _SharedTextField( @@ -272,69 +264,77 @@ class _SharedTextField extends StatelessWidget { @override Widget build(BuildContext context) { final coordinateSystem = CoordinateSystem.instance; - return TextField( - focusNode: focusNode, - controller: controller, - readOnly: readOnly, - enableInteractiveSelection: enableInteractiveSelection, - showCursor: showCursor, - style: TextStyle( - fontSize: coordinateSystem.worldHeightToScreen(fontSize), + return MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling), + child: TextField( + focusNode: focusNode, + controller: controller, + readOnly: readOnly, + enableInteractiveSelection: enableInteractiveSelection, + showCursor: showCursor, + style: PlacedTextDimensions.textStyle( + coordinateSystem: coordinateSystem, + fontSizeWorld: fontSize, + ), + decoration: _textFieldDecoration, + maxLines: null, + minLines: 1, + expands: false, + scrollPhysics: const NeverScrollableScrollPhysics(), + scrollPadding: EdgeInsets.zero, + textAlignVertical: TextAlignVertical.top, + keyboardType: TextInputType.multiline, + onChanged: onChanged, + onTapOutside: onTapOutside, ), - decoration: _textFieldDecoration, - maxLines: null, - minLines: null, - expands: true, - onChanged: onChanged, - onTapOutside: onTapOutside, ); } } class _TextBoxFrame extends StatelessWidget { const _TextBoxFrame({ - required this.size, + required this.metrics, required this.child, this.tagColorValue, }); - final double size; + final Size metrics; final Widget child; final int? tagColorValue; @override Widget build(BuildContext context) { - final coordinateSystem = CoordinateSystem.instance; return SizedBox( - width: coordinateSystem.worldWidthToScreen(size), - child: IntrinsicHeight( - child: Row( - children: [ - ClipRRect( - borderRadius: const BorderRadius.all(Radius.circular(2)), - child: Container( - width: 6, - color: Color(tagColorValue ?? 0xFFC5C5C5), - ), + width: metrics.width, + height: metrics.height, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(2)), + child: Container( + width: 6, + color: Color(tagColorValue ?? 0xFFC5C5C5), ), - const SizedBox(width: 2), - Expanded( - child: Card( - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(3)), - ), - margin: const EdgeInsets.all(0), - color: Colors.black, - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 5, - ), - child: child, + ), + const SizedBox(width: 2), + Expanded( + child: Card( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(3)), + ), + margin: const EdgeInsets.all(0), + color: Colors.black, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: PlacedTextDimensions.cardHorizontalPadding, + vertical: PlacedTextDimensions.cardVerticalPadding, ), + child: child, ), ), - ], - ), + ), + ], ), ); } diff --git a/lib/widgets/folder_content.dart b/lib/widgets/folder_content.dart index b8cfb73b..8fe8c028 100644 --- a/lib/widgets/folder_content.dart +++ b/lib/widgets/folder_content.dart @@ -29,15 +29,21 @@ class FolderContent extends ConsumerWidget { return Hive.box(HiveBoxNames.strategiesBox).listenable(); }); - static final foldersListenable = Provider>>((ref) { + static final foldersListenable = + Provider>>((ref) { return Hive.box(HiveBoxNames.foldersBox).listenable(); }); @override Widget build(BuildContext context, WidgetRef ref) { final workspace = ref.watch(libraryWorkspaceProvider); + if (workspace == LibraryWorkspace.community) { + return _buildCommunityPlaceholder(context, ref); + } + final isCloud = workspace == LibraryWorkspace.cloud; if (isCloud) { + final cloudSection = ref.watch(cloudLibrarySectionProvider); final cloudAvailable = ref.watch(isCloudWorkspaceAvailableProvider); if (!cloudAvailable) { return _buildCloudUnavailableState(context, ref); @@ -54,6 +60,12 @@ class FolderContent extends ConsumerWidget { localStrategies: const [], cloudStrategies: _filterCloudStrategies(ref, strategies), isCloud: true, + emptyStateTitle: cloudSection == CloudLibrarySection.sharedWithMe + ? 'No shared items yet' + : 'No cloud strategies yet', + emptyStateSubtitle: cloudSection == CloudLibrarySection.sharedWithMe + ? 'Shared folders and strategies will appear here' + : 'Create a cloud strategy to start your online workspace', ); } @@ -78,6 +90,9 @@ class FolderContent extends ConsumerWidget { localStrategies: _filterLocalStrategies(ref, strategies), cloudStrategies: const [], isCloud: false, + emptyStateTitle: 'No strategies available', + emptyStateSubtitle: + 'Create a new strategy or drop strategies, folders, or .zip archives', ); }, ); @@ -111,8 +126,8 @@ class FolderContent extends ConsumerWidget { } Comparator comparator = switch (filter.sortBy) { - SortBy.alphabetical => - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), + SortBy.alphabetical => (a, b) => + a.name.toLowerCase().compareTo(b.name.toLowerCase()), SortBy.dateCreated => (a, b) => a.createdAt.compareTo(b.createdAt), SortBy.dateUpdated => (a, b) => a.lastEdited.compareTo(b.lastEdited), }; @@ -136,8 +151,8 @@ class FolderContent extends ConsumerWidget { } Comparator comparator = switch (filter.sortBy) { - SortBy.alphabetical => - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), + SortBy.alphabetical => (a, b) => + a.name.toLowerCase().compareTo(b.name.toLowerCase()), SortBy.dateCreated => (a, b) => a.createdAt.compareTo(b.createdAt), SortBy.dateUpdated => (a, b) => a.updatedAt.compareTo(b.updatedAt), }; @@ -154,18 +169,17 @@ class FolderContent extends ConsumerWidget { required List localStrategies, required List cloudStrategies, required bool isCloud, + required String emptyStateTitle, + required String emptyStateSubtitle, }) { - final hasStrategies = localStrategies.isNotEmpty || cloudStrategies.isNotEmpty; + final hasStrategies = + localStrategies.isNotEmpty || cloudStrategies.isNotEmpty; final Widget emptyState = Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text(isCloud ? 'No cloud strategies yet' : 'No strategies available'), - Text( - isCloud - ? 'Create a cloud strategy to start your online workspace' - : 'Create a new strategy or drop strategies, folders, or .zip archives', - ), + Text(emptyStateTitle), + Text(emptyStateSubtitle), ], ), ); @@ -174,9 +188,9 @@ class FolderContent extends ConsumerWidget { const double minTileWidth = 250; const double spacing = 20; const double padding = 32; - int crossAxisCount = - ((constraints.maxWidth - padding + spacing) / (minTileWidth + spacing)) - .floor(); + int crossAxisCount = ((constraints.maxWidth - padding + spacing) / + (minTileWidth + spacing)) + .floor(); crossAxisCount = crossAxisCount.clamp(1, double.infinity).toInt(); return CustomScrollView( @@ -243,8 +257,7 @@ class FolderContent extends ConsumerWidget { ); }, ); - final wrappedContent = - isCloud ? content : IcaDropTarget(child: content); + final wrappedContent = isCloud ? content : IcaDropTarget(child: content); return Stack( children: [ @@ -300,9 +313,7 @@ class FolderContent extends ConsumerWidget { ), Expanded( child: (folders.isEmpty && !hasStrategies) - ? (isCloud - ? emptyState - : IcaDropTarget(child: emptyState)) + ? (isCloud ? emptyState : IcaDropTarget(child: emptyState)) : wrappedContent, ), ], @@ -335,6 +346,57 @@ class FolderContent extends ConsumerWidget { ), ); } + + Widget _buildCommunityPlaceholder(BuildContext context, WidgetRef ref) { + return Stack( + children: [ + const Positioned.fill( + child: Padding( + padding: EdgeInsets.all(4.0), + child: DotGrid(), + ), + ), + Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.public, + size: 38, + color: Settings.tacticalVioletTheme.primary, + ), + const SizedBox(height: 16), + const Text( + 'Community strats are coming soon', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 8), + Text( + 'This space is reserved for public lineups, team executes, and discoverable strategy packs.', + textAlign: TextAlign.center, + style: TextStyle( + color: Settings.tacticalVioletTheme.mutedForeground, + ), + ), + const SizedBox(height: 18), + ShadButton.secondary( + onPressed: () { + ref + .read(libraryWorkspaceProvider.notifier) + .select(LibraryWorkspace.local); + }, + child: const Text('Back to Local'), + ), + ], + ), + ), + ), + ], + ); + } } class _SortSelect extends StatelessWidget { diff --git a/lib/widgets/folder_navigator.dart b/lib/widgets/folder_navigator.dart index 201d3cd0..16036217 100644 --- a/lib/widgets/folder_navigator.dart +++ b/lib/widgets/folder_navigator.dart @@ -1,8 +1,8 @@ import 'dart:async'; -import 'dart:io'; import 'package:desktop_updater/desktop_updater.dart'; -import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/foundation.dart' + show TargetPlatform, defaultTargetPlatform, kIsWeb; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/coordinate_system.dart'; @@ -10,7 +10,9 @@ import 'package:icarus/const/settings.dart'; import 'package:icarus/const/update_checker.dart'; import 'package:icarus/main.dart'; import 'package:icarus/providers/auth_provider.dart'; +import 'package:icarus/providers/collab/remote_library_provider.dart'; import 'package:icarus/providers/folder_provider.dart'; +import 'package:icarus/providers/library_rail_hover_provider.dart'; import 'package:icarus/providers/library_workspace_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/strategy/strategy_import_export.dart'; @@ -47,6 +49,9 @@ class _FolderNavigatorState extends ConsumerState { final ShadPopoverController _importExportPopoverController = ShadPopoverController(); + bool get _isWindowsDesktop => + !kIsWeb && defaultTargetPlatform == TargetPlatform.windows; + @override void dispose() { _importExportPopoverController.dispose(); @@ -72,7 +77,7 @@ class _FolderNavigatorState extends ConsumerState { void _warnWebView() async { if (kIsWeb) return; - if (!Platform.isWindows) return; + if (!_isWindowsDesktop) return; await warmUpWebViewEnvironment(); if (!mounted) return; if (isWebViewInitialized) return; @@ -194,7 +199,7 @@ class _FolderNavigatorState extends ConsumerState { } final bool isDirectWindowsInstall = - !kIsWeb && Platform.isWindows && !result.isSupported; + _isWindowsDesktop && !result.isSupported; if (isDirectWindowsInstall && _desktopUpdaterController == null) { _desktopUpdaterController = WindowsDesktopUpdateController( appArchiveUrl: Settings.desktopUpdaterArchiveUrl, @@ -233,12 +238,18 @@ class _FolderNavigatorState extends ConsumerState { CoordinateSystem(playAreaSize: playAreaSize); final workspace = ref.watch(libraryWorkspaceProvider); final isCloudWorkspace = workspace == LibraryWorkspace.cloud; - final cloudAvailable = ref.watch(isCloudWorkspaceAvailableProvider); + final isCommunityWorkspace = workspace == LibraryWorkspace.community; final currentFolderId = ref.watch(folderProvider); final currentFolder = currentFolderId != null - ? ref.read(folderProvider.notifier).findLocalFolderByID(currentFolderId) + ? isCloudWorkspace + ? ref.read(folderProvider.notifier).findCloudFolderByID( + currentFolderId, + ref.watch(cloudAllFoldersProvider).valueOrNull ?? const [], + ) + : ref + .read(folderProvider.notifier) + .findLocalFolderByID(currentFolderId) : null; - final authState = ref.watch(authProvider); Future navigateWithLoading( BuildContext context, String strategyId) async { // Show loading overlay @@ -307,19 +318,24 @@ class _FolderNavigatorState extends ConsumerState { ), ); }, - ), - ); + ), + ); } else { await navigateWithLoading(context, strategyId); } } } + const double railReservedWidth = 64; + return Stack( children: [ Scaffold( appBar: AppBar( - title: const CurrentPathBar(), + title: const Padding( + padding: EdgeInsets.only(left: railReservedWidth), + child: CurrentPathBar(), + ), toolbarHeight: 70, actionsPadding: const EdgeInsets.only(right: 24), @@ -332,51 +348,6 @@ class _FolderNavigatorState extends ConsumerState { Row( spacing: 15, children: [ - if (cloudAvailable) - ShadSelect( - initialValue: workspace, - selectedOptionBuilder: (context, value) { - return Text( - value == LibraryWorkspace.cloud ? 'Cloud' : 'Local', - ); - }, - options: const [ - ShadOption( - value: LibraryWorkspace.local, - child: Text('Local'), - ), - ShadOption( - value: LibraryWorkspace.cloud, - child: Text('Cloud'), - ), - ], - onChanged: (value) { - if (value == null) return; - ref.read(libraryWorkspaceProvider.notifier).select(value); - }, - ), - ShadButton.secondary( - onPressed: authState.isLoading - ? null - : () { - if (authState.isAuthenticated) { - unawaited(ref.read(authProvider.notifier).signOut()); - } else { - showDialog( - context: context, - builder: (_) => const AuthDialog(), - ); - } - }, - leading: Icon( - authState.isAuthenticated ? Icons.logout : Icons.login, - ), - child: Text( - authState.isLoading - ? 'Please wait...' - : (authState.isAuthenticated ? 'Sign Out' : 'Log In'), - ), - ), ShadPopover( controller: _importExportPopoverController, padding: const EdgeInsets.all(8), @@ -427,7 +398,9 @@ class _FolderNavigatorState extends ConsumerState { }, child: ShadButton.secondary( key: _importExportButtonKey, - onPressed: isCloudWorkspace ? null : _toggleImportExportPopover, + onPressed: isCloudWorkspace || isCommunityWorkspace + ? null + : _toggleImportExportPopover, leading: const Icon(Icons.import_export), trailing: const Icon(Icons.keyboard_arrow_down), child: const Text('Import / Export'), @@ -435,21 +408,25 @@ class _FolderNavigatorState extends ConsumerState { ), ShadButton.secondary( leading: const Icon(LucideIcons.folderPlus), + onPressed: isCommunityWorkspace + ? null + : () async { + await showDialog( + context: context, + builder: (context) { + return const FolderEditDialog(); + }, + ); + }, child: const Text('Add Folder'), - onPressed: () async { - await showDialog( - context: context, - builder: (context) { - return const FolderEditDialog(); - }, - ); - }, ), ShadButton( - onPressed: showCreateDialog, + onPressed: isCommunityWorkspace ? null : showCreateDialog, leading: const Icon(Icons.add), child: Text( - isCloudWorkspace ? 'Create Cloud Strategy' : 'Create Strategy', + isCloudWorkspace + ? 'Create Cloud Strategy' + : 'Create Strategy', ), ), ], @@ -457,7 +434,16 @@ class _FolderNavigatorState extends ConsumerState { ], // ... your existing actions ), - body: FolderContent(folder: currentFolder), + body: Padding( + padding: const EdgeInsets.only(left: railReservedWidth), + child: FolderContent(folder: currentFolder), + ), + ), + const Positioned( + left: 0, + top: 0, + bottom: 0, + child: LibraryNavigationRail(), ), if (_desktopUpdaterController != null) DesktopUpdateDialogListener( @@ -480,8 +466,524 @@ class StrategyItem extends GridItem { final String strategyId; final StrategyData? strategy; - StrategyItem.local(this.strategy) - : strategyId = strategy!.id; + StrategyItem.local(this.strategy) : strategyId = strategy!.id; StrategyItem.cloud(this.strategyId) : strategy = null; } + +class LibraryNavigationRail extends ConsumerStatefulWidget { + const LibraryNavigationRail({super.key}); + + @override + ConsumerState createState() => + _LibraryNavigationRailState(); +} + +class _LibraryNavigationRailState extends ConsumerState { + static const _closeDelay = Duration(milliseconds: 120); + static const _detailsDelay = Duration(milliseconds: 190); + static const _routeArrivalHoverDelay = Duration(seconds: 2); + + bool _expanded = false; + bool _showExpandedContent = false; + Timer? _closeTimer; + Timer? _routeArrivalHoverTimer; + + @override + void dispose() { + _closeTimer?.cancel(); + _routeArrivalHoverTimer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final workspace = ref.watch(libraryWorkspaceProvider); + final cloudSection = ref.watch(cloudLibrarySectionProvider); + final cloudAvailable = ref.watch(isCloudWorkspaceAvailableProvider); + final authState = ref.watch(authProvider); + + final items = [ + _LibraryRailItemData( + icon: LucideIcons.monitor, + label: 'This Computer', + description: 'Local strategies and imports', + selected: workspace == LibraryWorkspace.local, + onTap: () => _selectLocal(), + ), + _LibraryRailItemData( + icon: LucideIcons.cloud, + label: 'Cloud', + description: cloudAvailable + ? 'Your online strategies' + : 'Log in to sync strategies', + selected: workspace == LibraryWorkspace.cloud && + cloudSection == CloudLibrarySection.home, + onTap: cloudAvailable ? () => _selectCloudHome() : null, + ), + _LibraryRailItemData( + icon: LucideIcons.users, + label: 'Shared', + description: cloudAvailable + ? 'Strategies shared with you' + : 'Log in to view shared strats', + selected: workspace == LibraryWorkspace.cloud && + cloudSection == CloudLibrarySection.sharedWithMe, + onTap: cloudAvailable ? () => _selectShared() : null, + ), + _LibraryRailItemData( + icon: Icons.public, + label: 'Community', + description: 'Public strategy library', + selected: workspace == LibraryWorkspace.community, + onTap: () => _selectCommunity(), + ), + ]; + + return MouseRegion( + onEnter: (_) { + if (ref.read(suppressLibraryRailHoverProvider)) { + _routeArrivalHoverTimer?.cancel(); + _routeArrivalHoverTimer = Timer(_routeArrivalHoverDelay, () { + if (!mounted) { + return; + } + ref.read(suppressLibraryRailHoverProvider.notifier).state = false; + }); + return; + } + _closeTimer?.cancel(); + setState(() => _expanded = true); + Future.delayed(_detailsDelay, () { + if (!mounted || !_expanded) { + return; + } + setState(() => _showExpandedContent = true); + }); + }, + onExit: (_) { + _routeArrivalHoverTimer?.cancel(); + if (ref.read(suppressLibraryRailHoverProvider)) { + ref.read(suppressLibraryRailHoverProvider.notifier).state = false; + } + _closeTimer?.cancel(); + _closeTimer = Timer(_closeDelay, () { + if (!mounted) { + return; + } + setState(() { + _showExpandedContent = false; + _expanded = false; + }); + }); + }, + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + width: _expanded ? 226 : 64, + margin: EdgeInsets.zero, + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.card.withValues(alpha: 0.96), + borderRadius: const BorderRadius.only( + // topRight: Radius.circular(14), + // bottomRight: Radius.circular(14), + ), + border: Border.all(color: Settings.tacticalVioletTheme.border), + boxShadow: const [Settings.cardForegroundBackdrop], + ), + child: ClipRRect( + borderRadius: const BorderRadius.only( + // topRight: Radius.circular(14), + // bottomRight: Radius.circular(14), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(8, 12, 8, 8), + child: _RailHeader( + expanded: _expanded, + showDetails: _showExpandedContent, + ), + ), + Divider(height: 1, color: Settings.tacticalVioletTheme.border), + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(8, 10, 8, 10), + child: Column( + children: [ + for (final item in items) ...[ + _LibraryRailItem( + data: item, + expanded: _expanded, + showDetails: _showExpandedContent, + ), + const SizedBox(height: 8), + ], + const Spacer(), + _AccountRailItem( + expanded: _expanded, + showDetails: _showExpandedContent, + isLoading: authState.isLoading, + isAuthenticated: authState.isAuthenticated, + avatarUrl: authState.avatarUrl, + label: authState.isAuthenticated + ? authState.displayName + : 'Log In', + onAuthAction: authState.isLoading + ? null + : () { + if (authState.isAuthenticated) { + unawaited( + ref.read(authProvider.notifier).signOut(), + ); + } else { + showDialog( + context: context, + builder: (_) => const AuthDialog(), + ); + } + }, + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } + + void _selectLocal() { + ref.read(libraryWorkspaceProvider.notifier).select(LibraryWorkspace.local); + ref.read(folderProvider.notifier).updateID(null); + } + + void _selectCloudHome() { + ref.read(libraryWorkspaceProvider.notifier).select(LibraryWorkspace.cloud); + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.home); + ref.read(folderProvider.notifier).updateID(null); + } + + void _selectShared() { + ref.read(libraryWorkspaceProvider.notifier).select(LibraryWorkspace.cloud); + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.sharedWithMe); + ref.read(folderProvider.notifier).updateID(null); + } + + void _selectCommunity() { + ref + .read(libraryWorkspaceProvider.notifier) + .select(LibraryWorkspace.community); + ref.read(folderProvider.notifier).updateID(null); + } +} + +class _RailHeader extends StatelessWidget { + const _RailHeader({ + required this.expanded, + required this.showDetails, + }); + + final bool expanded; + final bool showDetails; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 42, + child: LayoutBuilder( + builder: (context, constraints) { + final showLabel = showDetails && constraints.maxWidth >= 96; + return Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + left: 0, + top: 0, + bottom: 0, + width: 48, + child: Center( + child: SizedBox( + width: 32, + height: 32, + child: Image.asset( + 'assets/icarus-icon.webp', + fit: BoxFit.contain, + ), + ), + ), + ), + Positioned.fill( + left: 50, + child: IgnorePointer( + ignoring: !showLabel, + child: AnimatedOpacity( + duration: const Duration(milliseconds: 120), + opacity: expanded && showLabel ? 1 : 0, + child: const Align( + alignment: Alignment.centerLeft, + child: Text( + 'Icarus', + overflow: TextOverflow.ellipsis, + style: TextStyle(fontWeight: FontWeight.w800), + ), + ), + ), + ), + ), + ], + ); + }, + ), + ); + } +} + +class _LibraryRailItemData { + const _LibraryRailItemData({ + required this.icon, + required this.label, + required this.description, + required this.selected, + required this.onTap, + }); + + final IconData icon; + final String label; + final String description; + final bool selected; + final VoidCallback? onTap; +} + +class _LibraryRailItem extends StatelessWidget { + const _LibraryRailItem({ + required this.data, + required this.expanded, + required this.showDetails, + }); + + final _LibraryRailItemData data; + final bool expanded; + final bool showDetails; + + @override + Widget build(BuildContext context) { + final selectedColor = + Settings.tacticalVioletTheme.primary.withValues(alpha: 0.18); + return Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(10), + mouseCursor: data.onTap == null + ? SystemMouseCursors.basic + : SystemMouseCursors.click, + onTap: data.onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 140), + height: 48, + padding: const EdgeInsets.symmetric(horizontal: 9), + decoration: BoxDecoration( + color: data.selected ? selectedColor : Colors.transparent, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: data.selected + ? Settings.tacticalVioletTheme.primary + : Colors.transparent, + ), + ), + child: LayoutBuilder( + builder: (context, constraints) { + final showLabel = showDetails && constraints.maxWidth >= 96; + return Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + left: 0, + top: 0, + bottom: 0, + width: 26, + child: Align( + alignment: Alignment.center, + child: Icon( + data.icon, + size: 21, + color: data.onTap == null + ? Settings.tacticalVioletTheme.mutedForeground + : null, + ), + ), + ), + Positioned.fill( + left: 33, + child: IgnorePointer( + ignoring: !showLabel, + child: AnimatedOpacity( + duration: const Duration(milliseconds: 120), + opacity: expanded && showLabel ? 1 : 0, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + data.label, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 1), + Text( + data.description, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: Settings + .tacticalVioletTheme.mutedForeground, + fontSize: 10, + ), + ), + ], + ), + ), + ), + ), + ], + ); + }, + ), + ), + ), + ); + } +} + +class _AccountRailItem extends StatelessWidget { + const _AccountRailItem({ + required this.expanded, + required this.showDetails, + required this.isLoading, + required this.isAuthenticated, + required this.avatarUrl, + required this.label, + required this.onAuthAction, + }); + + final bool expanded; + final bool showDetails; + final bool isLoading; + final bool isAuthenticated; + final String? avatarUrl; + final String label; + final VoidCallback? onAuthAction; + + @override + Widget build(BuildContext context) { + return Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(10), + mouseCursor: onAuthAction == null + ? SystemMouseCursors.basic + : SystemMouseCursors.click, + onTap: onAuthAction, + child: AnimatedContainer( + duration: const Duration(milliseconds: 140), + curve: Curves.easeOutCubic, + height: 48, + padding: const EdgeInsets.symmetric(horizontal: 9), + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.secondary.withValues( + alpha: 0.5, + ), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Settings.tacticalVioletTheme.border), + ), + child: LayoutBuilder( + builder: (context, constraints) { + final showLabel = showDetails && constraints.maxWidth >= 96; + return Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + left: 0, + top: 0, + bottom: 0, + width: 28, + child: Align( + alignment: Alignment.center, + child: _AccountAvatar( + avatarUrl: avatarUrl, + isAuthenticated: isAuthenticated, + ), + ), + ), + Positioned.fill( + left: 38, + child: IgnorePointer( + ignoring: !showLabel, + child: AnimatedOpacity( + duration: const Duration(milliseconds: 120), + curve: Curves.easeOutCubic, + opacity: expanded && showLabel ? 1 : 0, + child: showLabel + ? Row( + children: [ + Expanded( + child: Text( + isLoading ? 'Please wait...' : label, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ) + : const SizedBox.shrink(), + ), + ), + ), + ], + ); + }, + ), + ), + ), + ); + } +} + +class _AccountAvatar extends StatelessWidget { + const _AccountAvatar({ + required this.avatarUrl, + required this.isAuthenticated, + }); + + final String? avatarUrl; + final bool isAuthenticated; + + @override + Widget build(BuildContext context) { + if (isAuthenticated && avatarUrl != null) { + return CircleAvatar( + radius: 14, + backgroundImage: NetworkImage(avatarUrl!), + ); + } + + return CircleAvatar( + radius: 14, + backgroundColor: Settings.tacticalVioletTheme.card, + child: Icon( + isAuthenticated ? Icons.person : LucideIcons.userRound, + size: 15, + ), + ); + } +} diff --git a/lib/widgets/folder_navigator_sidebar.dart b/lib/widgets/folder_navigator_sidebar.dart new file mode 100644 index 00000000..f4b418dd --- /dev/null +++ b/lib/widgets/folder_navigator_sidebar.dart @@ -0,0 +1,852 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:hive_ce_flutter/adapters.dart'; +import 'package:icarus/const/hive_boxes.dart'; +import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/collab/remote_library_provider.dart'; +import 'package:icarus/providers/folder_provider.dart'; +import 'package:icarus/providers/library_workspace_provider.dart'; +import 'package:icarus/providers/strategy_filter_provider.dart'; +import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/strategy/strategy_import_export.dart'; +import 'package:icarus/strategy/strategy_page_models.dart'; +import 'package:icarus/widgets/custom_search_field.dart'; +import 'package:icarus/widgets/dialogs/confirm_alert_dialog.dart'; +import 'package:icarus/widgets/dialogs/share_links_dialog.dart'; +import 'package:icarus/widgets/folder_edit_dialog.dart'; +import 'package:icarus/widgets/folder_navigator.dart'; +import 'package:shadcn_ui/shadcn_ui.dart'; + +class FolderNavigatorSidebar extends ConsumerWidget { + const FolderNavigatorSidebar({ + super.key, + required this.onCreateStrategy, + required this.onAddFolder, + required this.onImportIca, + required this.onImportBackup, + required this.onExportLibrary, + }); + + final VoidCallback onCreateStrategy; + final Future Function() onAddFolder; + final Future Function() onImportIca; + final Future Function() onImportBackup; + final Future Function() onExportLibrary; + + static final foldersListenable = + Provider>>((ref) { + return Hive.box(HiveBoxNames.foldersBox).listenable(); + }); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final workspace = ref.watch(libraryWorkspaceProvider); + final isCloud = workspace == LibraryWorkspace.cloud; + + if (isCloud) { + final cloudFolders = + (ref.watch(cloudAllFoldersProvider).valueOrNull ?? const []) + .map(FolderProvider.cloudSummaryToFolder) + .toList(growable: false); + return _SidebarShell( + folders: cloudFolders, + isCloud: true, + onCreateStrategy: onCreateStrategy, + onAddFolder: onAddFolder, + onImportIca: onImportIca, + onImportBackup: onImportBackup, + onExportLibrary: onExportLibrary, + ); + } + + final localFoldersListenable = ref.watch( + FolderNavigatorSidebar.foldersListenable, + ); + return ValueListenableBuilder>( + valueListenable: localFoldersListenable, + builder: (context, folderBox, _) { + return _SidebarShell( + folders: folderBox.values.toList(growable: false), + isCloud: false, + onCreateStrategy: onCreateStrategy, + onAddFolder: onAddFolder, + onImportIca: onImportIca, + onImportBackup: onImportBackup, + onExportLibrary: onExportLibrary, + ); + }, + ); + } +} + +class _SidebarShell extends ConsumerWidget { + const _SidebarShell({ + required this.folders, + required this.isCloud, + required this.onCreateStrategy, + required this.onAddFolder, + required this.onImportIca, + required this.onImportBackup, + required this.onExportLibrary, + }); + + final List folders; + final bool isCloud; + final VoidCallback onCreateStrategy; + final Future Function() onAddFolder; + final Future Function() onImportIca; + final Future Function() onImportBackup; + final Future Function() onExportLibrary; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final currentFolderId = ref.watch(folderProvider); + final cloudSection = ref.watch(cloudLibrarySectionProvider); + final canMutateCloudLibrary = + !isCloud || cloudSection == CloudLibrarySection.home; + final filterState = ref.watch(strategyFilterProvider); + final searchQuery = + ref.watch(strategySearchQueryProvider).trim().toLowerCase(); + final visibleRoots = _buildVisibleTree(folders, searchQuery); + + return Container( + width: 288, + margin: const EdgeInsets.fromLTRB(12, 12, 0, 12), + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.card, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: Settings.tacticalVioletTheme.border), + boxShadow: const [Settings.cardForegroundBackdrop], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(14, 14, 14, 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ShadButton( + onPressed: canMutateCloudLibrary ? onCreateStrategy : null, + leading: const Icon(Icons.add), + child: Text( + isCloud ? 'Create Cloud Strategy' : 'Create Strategy', + ), + ), + const SizedBox(height: 8), + ShadButton.secondary( + onPressed: canMutateCloudLibrary ? onAddFolder : null, + leading: const Icon(LucideIcons.folderPlus), + child: const Text('Add Folder'), + ), + if (isCloud) ...[ + const SizedBox(height: 8), + ShadButton.secondary( + onPressed: () async { + await showShadDialog( + context: context, + builder: (_) => const JoinShareLinkDialog(), + ); + }, + leading: const Icon(LucideIcons.link), + child: const Text('Join Share Link'), + ), + ], + const SizedBox(height: 12), + const SizedBox( + height: 40, + child: SearchTextField( + collapsedWidth: double.infinity, + expandedWidth: double.infinity, + compact: true, + hintText: 'Search strategies and folders', + ), + ), + const SizedBox(height: 12), + _SidebarSelect( + currentValue: filterState.sortBy, + values: SortBy.values, + labels: StrategyFilterProvider.sortByLabels, + onChanged: (value) { + ref.read(strategyFilterProvider.notifier).setSortBy(value); + }, + ), + const SizedBox(height: 8), + _SidebarSelect( + currentValue: filterState.sortOrder, + values: SortOrder.values, + labels: StrategyFilterProvider.sortOrderLabels, + onChanged: (value) { + ref + .read(strategyFilterProvider.notifier) + .setSortOrder(value); + }, + ), + const SizedBox(height: 12), + _SidebarSectionLabel( + label: isCloud ? 'Cloud Tools' : 'Library Tools', + ), + const SizedBox(height: 8), + _SidebarActionButton( + icon: Icons.file_download_outlined, + label: 'Import .ica', + onPressed: isCloud ? null : onImportIca, + ), + const SizedBox(height: 6), + _SidebarActionButton( + icon: Icons.archive_outlined, + label: 'Import Backup', + onPressed: isCloud ? null : onImportBackup, + ), + const SizedBox(height: 6), + _SidebarActionButton( + icon: Icons.backup_outlined, + label: 'Export Library', + onPressed: isCloud ? null : onExportLibrary, + ), + ], + ), + ), + Divider( + height: 1, + color: Settings.tacticalVioletTheme.border, + ), + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 12, 10, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (isCloud) ...[ + const Padding( + padding: EdgeInsets.symmetric(horizontal: 6), + child: _SidebarSectionLabel(label: 'Views'), + ), + const SizedBox(height: 8), + _SidebarSpecialItem( + icon: Icons.home_outlined, + label: 'Home', + isSelected: cloudSection == CloudLibrarySection.home && + currentFolderId == null, + onTap: () { + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.home); + ref.read(folderProvider.notifier).updateID(null); + }, + ), + const SizedBox(height: 4), + _SidebarSpecialItem( + icon: Icons.people_outline, + label: 'Shared with Me', + isSelected: + cloudSection == CloudLibrarySection.sharedWithMe, + onTap: () { + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.sharedWithMe); + ref.read(folderProvider.notifier).updateID(null); + }, + ), + const SizedBox(height: 12), + ], + const Padding( + padding: EdgeInsets.symmetric(horizontal: 6), + child: _SidebarSectionLabel(label: 'Folders'), + ), + const SizedBox(height: 8), + Expanded( + child: ListView( + children: [ + _SidebarRootItem( + isSelected: currentFolderId == null && + (!isCloud || + cloudSection == CloudLibrarySection.home), + ), + const SizedBox(height: 4), + if (visibleRoots.isEmpty) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 12, + ), + child: Text( + searchQuery.isEmpty + ? 'No folders yet' + : 'No folders match your search', + style: TextStyle( + color: Settings + .tacticalVioletTheme.mutedForeground, + fontSize: 13, + ), + ), + ) + else + ...visibleRoots.map( + (node) => _FolderSidebarItem( + node: node, + depth: 0, + selectedFolderId: currentFolderId, + folderLookup: { + for (final folder in folders) folder.id: folder, + }, + ), + ), + ], + ), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +class _SidebarRootItem extends ConsumerWidget { + const _SidebarRootItem({required this.isSelected}); + + final bool isSelected; + + @override + Widget build(BuildContext context, WidgetRef ref) { + return DragTarget( + onAcceptWithDetails: (details) { + final item = details.data; + if (item is StrategyItem) { + ref.read(strategyProvider.notifier).moveToFolder( + strategyID: item.strategyId, + parentID: null, + source: item.strategy == null + ? StrategySource.cloud + : StrategySource.local, + ); + } else if (item is FolderItem) { + ref.read(folderProvider.notifier).moveToFolder( + folderID: item.folder.id, + parentID: null, + workspace: ref.read(libraryWorkspaceProvider), + ); + } + }, + builder: (context, candidateData, rejectedData) { + final isDropTarget = candidateData.isNotEmpty; + return _SidebarRowShell( + selected: isSelected, + isDropTarget: isDropTarget, + onTap: () { + if (ref.read(libraryWorkspaceProvider) == LibraryWorkspace.cloud) { + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.home); + } + ref.read(folderProvider.notifier).updateID(null); + }, + child: const Row( + children: [ + Icon(Icons.home_outlined, size: 18), + SizedBox(width: 12), + Expanded( + child: Text( + 'Home', + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ); + }, + ); + } +} + +class _SidebarSpecialItem extends StatelessWidget { + const _SidebarSpecialItem({ + required this.icon, + required this.label, + required this.isSelected, + required this.onTap, + }); + + final IconData icon; + final String label; + final bool isSelected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return _SidebarRowShell( + selected: isSelected, + isDropTarget: false, + onTap: onTap, + child: Row( + children: [ + Icon(icon, size: 18), + const SizedBox(width: 12), + Expanded( + child: Text( + label, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ); + } +} + +class _FolderSidebarItem extends ConsumerStatefulWidget { + const _FolderSidebarItem({ + required this.node, + required this.depth, + required this.selectedFolderId, + required this.folderLookup, + }); + + final _FolderTreeNode node; + final int depth; + final String? selectedFolderId; + final Map folderLookup; + + @override + ConsumerState<_FolderSidebarItem> createState() => _FolderSidebarItemState(); +} + +class _FolderSidebarItemState extends ConsumerState<_FolderSidebarItem> { + static const _hoverExitDelay = Duration(milliseconds: 500); + + final ShadContextMenuController _menuButtonController = + ShadContextMenuController(); + final ShadContextMenuController _rightClickMenuController = + ShadContextMenuController(); + bool _hovered = false; + Timer? _hoverExitTimer; + + Folder get folder => widget.node.folder; + + @override + void dispose() { + _hoverExitTimer?.cancel(); + _menuButtonController.dispose(); + _rightClickMenuController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final color = folder.customColor ?? + Folder.folderColorMap[folder.color] ?? + Colors.white; + final selected = widget.selectedFolderId == folder.id; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + DragTarget( + onWillAcceptWithDetails: (details) { + final item = details.data; + if (item is FolderItem) { + return item.folder.id != folder.id && + !_isAncestor( + targetFolder: folder, draggedFolderId: item.folder.id); + } + return true; + }, + onAcceptWithDetails: (details) { + final item = details.data; + if (item is StrategyItem) { + ref.read(strategyProvider.notifier).moveToFolder( + strategyID: item.strategyId, + parentID: folder.id, + source: item.strategy == null + ? StrategySource.cloud + : StrategySource.local, + ); + } else if (item is FolderItem) { + ref.read(folderProvider.notifier).moveToFolder( + folderID: item.folder.id, + parentID: folder.id, + workspace: ref.read(libraryWorkspaceProvider), + ); + } + }, + builder: (context, candidateData, rejectedData) { + return Padding( + padding: EdgeInsets.only(left: widget.depth * 16.0), + child: MouseRegion( + onEnter: (_) { + _hoverExitTimer?.cancel(); + setState(() => _hovered = true); + }, + onExit: (_) { + _hoverExitTimer?.cancel(); + _hoverExitTimer = Timer(_hoverExitDelay, () { + if (!mounted) { + return; + } + setState(() => _hovered = false); + }); + }, + child: ShadContextMenuRegion( + controller: _rightClickMenuController, + items: _buildMenuItems(), + child: Draggable( + data: FolderItem(folder), + feedback: _FolderDragPreview(folder: folder), + dragAnchorStrategy: pointerDragAnchorStrategy, + child: _SidebarRowShell( + selected: selected, + isDropTarget: candidateData.isNotEmpty, + onTap: () { + if (ref.read(libraryWorkspaceProvider) == + LibraryWorkspace.cloud) { + ref + .read(cloudLibrarySectionProvider.notifier) + .select(CloudLibrarySection.home); + } + ref.read(folderProvider.notifier).updateID(folder.id); + }, + child: Row( + children: [ + Icon(folder.icon, size: 18, color: color), + const SizedBox(width: 12), + Expanded( + child: Text( + folder.name, + overflow: TextOverflow.ellipsis, + style: + const TextStyle(fontWeight: FontWeight.w500), + ), + ), + if (_hovered || selected) + ShadContextMenuRegion( + controller: _menuButtonController, + items: _buildMenuItems(), + child: ShadIconButton.ghost( + width: 26, + height: 26, + onPressed: _menuButtonController.toggle, + icon: const Icon(Icons.more_horiz, size: 16), + ), + ), + ], + ), + ), + ), + ), + ), + ); + }, + ), + if (widget.node.children.isNotEmpty) + ...widget.node.children.map( + (child) => _FolderSidebarItem( + node: child, + depth: widget.depth + 1, + selectedFolderId: widget.selectedFolderId, + folderLookup: widget.folderLookup, + ), + ), + ], + ); + } + + List _buildMenuItems() { + final isCloud = + ref.read(libraryWorkspaceProvider) == LibraryWorkspace.cloud; + final allFolders = + ref.read(cloudAllFoldersProvider).valueOrNull ?? const []; + final cloudRole = allFolders + .where((item) => item.publicId == folder.id) + .map((item) => item.role) + .firstOrNull; + final canManage = !isCloud || cloudRole == 'owner'; + + return [ + ShadContextMenuItem( + leading: const Icon(Icons.text_fields), + child: const Text('Edit'), + onPressed: !canManage + ? null + : () async { + await showDialog( + context: context, + builder: (context) => FolderEditDialog(folder: folder), + ); + }, + ), + if (isCloud && cloudRole == 'owner') + ShadContextMenuItem( + leading: const Icon(LucideIcons.link2), + child: const Text('Share'), + onPressed: () async { + await showShadDialog( + context: context, + builder: (_) => ShareLinksDialog( + targetType: 'folder', + targetPublicId: folder.id, + title: folder.name, + ), + ); + }, + ), + ShadContextMenuItem( + leading: const Icon(Icons.file_upload_outlined), + child: const Text('Export'), + onPressed: () async { + await StrategyImportExportService(ref).exportFolder(folder.id); + }, + ), + ShadContextMenuItem( + leading: const Icon(Icons.delete_outline, color: Colors.redAccent), + child: const Text( + 'Delete', + style: TextStyle(color: Colors.redAccent), + ), + onPressed: !canManage + ? null + : () async { + final confirmed = await ConfirmAlertDialog.show( + context: context, + title: "Delete '${folder.name}'?", + content: + 'This also removes every strategy and subfolder inside it.', + confirmText: 'Delete', + isDestructive: true, + ); + if (!confirmed) { + return; + } + ref.read(folderProvider.notifier).deleteFolder( + folder.id, + workspace: ref.read(libraryWorkspaceProvider), + ); + }, + ), + ]; + } + + bool _isAncestor({ + required Folder targetFolder, + required String draggedFolderId, + }) { + String? currentParentId = targetFolder.parentID; + while (currentParentId != null) { + if (currentParentId == draggedFolderId) { + return true; + } + currentParentId = widget.folderLookup[currentParentId]?.parentID; + } + return false; + } +} + +class _SidebarRowShell extends StatelessWidget { + const _SidebarRowShell({ + required this.child, + required this.onTap, + required this.selected, + required this.isDropTarget, + }); + + final Widget child; + final VoidCallback onTap; + final bool selected; + final bool isDropTarget; + + @override + Widget build(BuildContext context) { + final borderColor = isDropTarget + ? Settings.tacticalVioletTheme.ring + : (selected + ? Settings.tacticalVioletTheme.primary + : Colors.transparent); + final backgroundColor = selected + ? Settings.tacticalVioletTheme.primary.withValues(alpha: 0.18) + : (isDropTarget + ? Settings.tacticalVioletTheme.primary.withValues(alpha: 0.10) + : Colors.transparent); + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 1), + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 120), + height: 38, + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: borderColor), + ), + child: child, + ), + ), + ), + ); + } +} + +extension on Iterable { + String? get firstOrNull => isEmpty ? null : first; +} + +class _SidebarSectionLabel extends StatelessWidget { + const _SidebarSectionLabel({required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + return Text( + label, + style: TextStyle( + color: Settings.tacticalVioletTheme.mutedForeground, + fontSize: 11, + fontWeight: FontWeight.w700, + letterSpacing: 0.4, + ), + ); + } +} + +class _SidebarActionButton extends StatelessWidget { + const _SidebarActionButton({ + required this.icon, + required this.label, + required this.onPressed, + }); + + final IconData icon; + final String label; + final Future Function()? onPressed; + + @override + Widget build(BuildContext context) { + return ShadButton.ghost( + onPressed: onPressed, + mainAxisAlignment: MainAxisAlignment.start, + leading: Icon(icon, size: 18), + child: Text(label), + ); + } +} + +class _SidebarSelect extends StatelessWidget { + const _SidebarSelect({ + required this.currentValue, + required this.values, + required this.labels, + required this.onChanged, + }); + + final T currentValue; + final Iterable values; + final Map labels; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + return ShadSelect( + initialValue: currentValue, + selectedOptionBuilder: (context, value) => Text(labels[value]!), + options: [ + for (final value in values) + ShadOption( + value: value, + child: Text(labels[value]!), + ), + ], + onChanged: (value) { + if (value != null) { + onChanged(value); + } + }, + ); + } +} + +class _FolderDragPreview extends StatelessWidget { + const _FolderDragPreview({required this.folder}); + + final Folder folder; + + @override + Widget build(BuildContext context) { + final color = folder.customColor ?? + Folder.folderColorMap[folder.color] ?? + Colors.white; + return Material( + color: Colors.transparent, + child: Container( + height: 40, + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.card, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Settings.tacticalVioletTheme.ring), + boxShadow: const [Settings.cardForegroundBackdrop], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(folder.icon, size: 18, color: color), + const SizedBox(width: 10), + Text( + folder.name, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ], + ), + ), + ); + } +} + +class _FolderTreeNode { + const _FolderTreeNode({ + required this.folder, + required this.children, + }); + + final Folder folder; + final List<_FolderTreeNode> children; +} + +List<_FolderTreeNode> _buildVisibleTree( + List folders, + String searchQuery, +) { + final byParent = >{}; + for (final folder in folders) { + byParent.putIfAbsent(folder.parentID, () => []).add(folder); + } + + for (final entry in byParent.entries) { + entry.value.sort((a, b) => a.dateCreated.compareTo(b.dateCreated)); + } + + List<_FolderTreeNode> walk(String? parentId) { + final children = byParent[parentId] ?? const []; + final nodes = <_FolderTreeNode>[]; + for (final folder in children) { + final nested = walk(folder.id); + final matchesSearch = searchQuery.isEmpty || + folder.name.toLowerCase().contains(searchQuery); + if (matchesSearch || nested.isNotEmpty) { + nodes.add(_FolderTreeNode(folder: folder, children: nested)); + } + } + return nodes; + } + + return walk(null); +} diff --git a/lib/widgets/folder_pill.dart b/lib/widgets/folder_pill.dart index edba8321..c621286c 100644 --- a/lib/widgets/folder_pill.dart +++ b/lib/widgets/folder_pill.dart @@ -7,6 +7,7 @@ import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/strategy/strategy_import_export.dart'; import 'package:icarus/strategy/strategy_page_models.dart'; import 'package:icarus/widgets/dialogs/confirm_alert_dialog.dart'; +import 'package:icarus/widgets/dialogs/share_links_dialog.dart'; import 'package:icarus/widgets/folder_edit_dialog.dart'; import 'package:icarus/widgets/folder_navigator.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; @@ -62,6 +63,23 @@ class _FolderPillState extends ConsumerState Folder.folderColorMap[widget.folder.color] ?? Colors.grey; + bool get _isCloudWorkspace => + ref.read(libraryWorkspaceProvider) == LibraryWorkspace.cloud; + + String? get _cloudRole { + if (!_isCloudWorkspace) { + return null; + } + final allFolders = + ref.read(cloudAllFoldersProvider).valueOrNull ?? const []; + return allFolders + .where((folder) => folder.publicId == widget.folder.id) + .map((folder) => folder.role) + .firstOrNull; + } + + bool get _canManageCloudFolder => !_isCloudWorkspace || _cloudRole == 'owner'; + @override Widget build(BuildContext context) { return Draggable( @@ -72,6 +90,7 @@ class _FolderPillState extends ConsumerState onWillAcceptWithDetails: (details) { final item = details.data; if (widget.isDemo) return false; + if (!_canManageCloudFolder) return false; if (item is FolderItem) { return item.folder.id != widget.folder.id && !_isParentFolder(item.folder.id); @@ -83,18 +102,18 @@ class _FolderPillState extends ConsumerState final item = details.data; if (item is StrategyItem) { ref.read(strategyProvider.notifier).moveToFolder( - strategyID: item.strategyId, - parentID: widget.folder.id, - source: item.strategy == null - ? StrategySource.cloud - : StrategySource.local, - ); + strategyID: item.strategyId, + parentID: widget.folder.id, + source: item.strategy == null + ? StrategySource.cloud + : StrategySource.local, + ); } else if (item is FolderItem) { ref.read(folderProvider.notifier).moveToFolder( - folderID: item.folder.id, - parentID: widget.folder.id, - workspace: ref.read(libraryWorkspaceProvider), - ); + folderID: item.folder.id, + parentID: widget.folder.id, + workspace: ref.read(libraryWorkspaceProvider), + ); } }, builder: (context, candidateData, rejectedData) { @@ -207,16 +226,33 @@ class _FolderPillState extends ConsumerState ShadContextMenuItem( leading: const Icon(Icons.text_fields), child: const Text('Edit'), - onPressed: () async { - if (widget.isDemo) return; - await showDialog( - context: context, - builder: (context) { - return FolderEditDialog(folder: widget.folder); - }, - ); - }, + onPressed: !_canManageCloudFolder + ? null + : () async { + if (widget.isDemo) return; + await showDialog( + context: context, + builder: (context) { + return FolderEditDialog(folder: widget.folder); + }, + ); + }, ), + if (_isCloudWorkspace && _cloudRole == 'owner') + ShadContextMenuItem( + leading: const Icon(LucideIcons.link2), + child: const Text('Share'), + onPressed: () async { + await showShadDialog( + context: context, + builder: (_) => ShareLinksDialog( + targetType: 'folder', + targetPublicId: widget.folder.id, + title: widget.folder.name, + ), + ); + }, + ), ShadContextMenuItem( leading: const Icon(Icons.file_upload), child: const Text('Export'), @@ -227,25 +263,27 @@ class _FolderPillState extends ConsumerState ShadContextMenuItem( leading: const Icon(Icons.delete, color: Colors.redAccent), child: const Text('Delete', style: TextStyle(color: Colors.redAccent)), - onPressed: () async { - ConfirmAlertDialog.show( - context: context, - title: - "Are you sure you want to delete '${widget.folder.name}' folder?", - content: - "This will also delete all strategies and subfolders within it.", - confirmText: "Delete", - isDestructive: true, - ).then((confirmed) { - if (confirmed) { - if (widget.isDemo) return; - ref.read(folderProvider.notifier).deleteFolder( - widget.folder.id, - workspace: ref.read(libraryWorkspaceProvider), - ); - } - }); - }, + onPressed: !_canManageCloudFolder + ? null + : () async { + ConfirmAlertDialog.show( + context: context, + title: + "Are you sure you want to delete '${widget.folder.name}' folder?", + content: + "This will also delete all strategies and subfolders within it.", + confirmText: "Delete", + isDestructive: true, + ).then((confirmed) { + if (confirmed) { + if (widget.isDemo) return; + ref.read(folderProvider.notifier).deleteFolder( + widget.folder.id, + workspace: ref.read(libraryWorkspaceProvider), + ); + } + }); + }, ), ]; } @@ -293,7 +331,9 @@ class _FolderPillState extends ConsumerState while (currentParentId != null) { if (currentParentId == folderId) return true; final parentFolder = workspace == LibraryWorkspace.local - ? ref.read(folderProvider.notifier).findLocalFolderByID(currentParentId) + ? ref + .read(folderProvider.notifier) + .findLocalFolderByID(currentParentId) : ref.read(folderProvider.notifier).findCloudFolderByID( currentParentId, ref.read(cloudAllFoldersProvider).valueOrNull ?? const [], @@ -303,3 +343,7 @@ class _FolderPillState extends ConsumerState return false; } } + +extension on Iterable { + String? get firstOrNull => isEmpty ? null : first; +} diff --git a/lib/widgets/image_drop_target.dart b/lib/widgets/image_drop_target.dart index d0bb8344..f68aeeac 100644 --- a/lib/widgets/image_drop_target.dart +++ b/lib/widgets/image_drop_target.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/providers/image_provider.dart'; +import 'package:icarus/providers/strategy_provider.dart'; class ImageDropTarget extends ConsumerStatefulWidget { const ImageDropTarget({super.key, required this.child}); @@ -47,9 +48,13 @@ class _ImageDropTargetState extends ConsumerState { if (['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp'] .contains(rawExtension)) { final fileExtension = '.$rawExtension'; + final strategyState = ref.read(strategyProvider); await ref.read(placedImageProvider.notifier).addImage( - imageBytes: await file.readAsBytes(), - fileExtension: fileExtension); + imageBytes: await file.readAsBytes(), + strategyId: strategyState.strategyId, + strategySource: strategyState.source, + fileExtension: fileExtension, + ); } } }, diff --git a/lib/widgets/line_up_media_carousel.dart b/lib/widgets/line_up_media_carousel.dart index 3ce8ecbb..31326eff 100644 --- a/lib/widgets/line_up_media_carousel.dart +++ b/lib/widgets/line_up_media_carousel.dart @@ -7,6 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/line_provider.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/providers/image_provider.dart'; +import 'package:icarus/providers/collab/remote_strategy_snapshot_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/widgets/dialogs/create_lineup_dialog.dart'; @@ -71,7 +72,6 @@ class _ImageCarouselState extends ConsumerState @override Widget build(BuildContext context) { super.build(context); - // log(widget.youtubeLink ?? 'No youtube link'); if (imageFolderPath == null) { return const Center(child: CircularProgressIndicator()); } @@ -111,19 +111,29 @@ class _ImageCarouselState extends ConsumerState final fullPath = path.join( imageFolderPath!.path, image.id + image.fileExtension); final file = File(fullPath); + final snapshot = + ref.watch(remoteStrategySnapshotProvider).valueOrNull; + final remoteUrl = snapshot?.assetsById[image.id]?.url; - if (!file.existsSync()) { + if (!file.existsSync() && + (remoteUrl == null || remoteUrl.isEmpty)) { return const Center( - child: Icon(Icons.broken_image, color: Colors.white)); + child: Icon(Icons.broken_image, color: Colors.white), + ); } return InteractiveViewer( minScale: 0.5, maxScale: 4.0, - child: Image.file( - file, - fit: BoxFit.contain, - ), + child: file.existsSync() + ? Image.file( + file, + fit: BoxFit.contain, + ) + : Image.network( + remoteUrl!, + fit: BoxFit.contain, + ), ); }, ), diff --git a/lib/widgets/settings_tab.dart b/lib/widgets/settings_tab.dart index 94397581..8957ea39 100644 --- a/lib/widgets/settings_tab.dart +++ b/lib/widgets/settings_tab.dart @@ -11,7 +11,6 @@ import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/providers/strategy_page_session_provider.dart'; import 'package:icarus/providers/strategy_settings_provider.dart'; import 'package:icarus/strategy/strategy_models.dart'; -import 'package:icarus/widgets/dialogs/auth/auth_dialog.dart'; import 'package:icarus/widgets/map_theme_settings_section.dart'; import 'package:icarus/widgets/settings_scope_card.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; @@ -94,47 +93,6 @@ class SettingsTab extends ConsumerWidget { ), ], ), - const SizedBox(height: 10), - SizedBox( - width: double.infinity, - child: authState.isAuthenticated - ? ShadButton.secondary( - onPressed: authState.isLoading - ? null - : () => ref - .read(authProvider.notifier) - .signOut(), - child: authState.isLoading - ? const SizedBox( - width: 16, - height: 16, - child: CircularProgressIndicator( - strokeWidth: 2, - ), - ) - : const Text('Sign out'), - ) - : ShadButton( - onPressed: authState.isLoading - ? null - : () { - showDialog( - context: context, - builder: (_) => - const AuthDialog(), - ); - }, - child: authState.isLoading - ? const SizedBox( - width: 16, - height: 16, - child: CircularProgressIndicator( - strokeWidth: 2, - ), - ) - : const Text('Sign in / sign up'), - ), - ), if (authState.errorMessage != null) ...[ const SizedBox(height: 8), Text( diff --git a/lib/widgets/sidebar_widgets/tool_grid.dart b/lib/widgets/sidebar_widgets/tool_grid.dart index d858e486..ef70dbb2 100644 --- a/lib/widgets/sidebar_widgets/tool_grid.dart +++ b/lib/widgets/sidebar_widgets/tool_grid.dart @@ -12,6 +12,7 @@ import 'package:icarus/providers/interaction_state_provider.dart'; import 'package:icarus/providers/pen_provider.dart'; import 'package:icarus/providers/placement_center_provider.dart'; import 'package:icarus/providers/screen_zoom_provider.dart'; +import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/providers/utility_provider.dart'; import 'package:icarus/widgets/dialogs/upload_image_dialog.dart'; import 'package:icarus/widgets/draggable_widgets/zoom_transform.dart'; @@ -220,6 +221,7 @@ class ToolGrid extends ConsumerWidget { final aspectRatio = await ref .read(placedImageProvider.notifier) .getImageAspectRatio(imageBytes); + final strategyState = ref.read(strategyProvider); final placementCenter = ref.read(placementCenterProvider); final imageHeight = _defaultImageSpawnWidth / aspectRatio; final centeredTopLeft = @@ -231,6 +233,8 @@ class ToolGrid extends ConsumerWidget { ref.read(placedImageProvider.notifier).addImage( imageBytes: imageBytes, + strategyId: strategyState.strategyId, + strategySource: strategyState.source, fileExtension: fileExtension, aspectRatio: aspectRatio, position: centeredTopLeft, diff --git a/lib/widgets/strategy_quick_switcher.dart b/lib/widgets/strategy_quick_switcher.dart index f14387e0..3f60d3c0 100644 --- a/lib/widgets/strategy_quick_switcher.dart +++ b/lib/widgets/strategy_quick_switcher.dart @@ -245,6 +245,10 @@ class _StrategyQuickSwitcherState extends ConsumerState { @override Widget build(BuildContext context) { final currentStrategy = ref.watch(strategyProvider); + final currentStrategyId = currentStrategy.strategyId; + if (currentStrategyId == null) { + return const SizedBox.shrink(); + } final strategyName = currentStrategy.strategyName ?? 'Untitled Strategy'; final strategiesBox = Hive.box(HiveBoxNames.strategiesBox); @@ -257,7 +261,7 @@ class _StrategyQuickSwitcherState extends ConsumerState { builder: (context, box, _) { final recents = _recentStrategies( box: box, - currentStrategyId: currentStrategy.strategyId!, + currentStrategyId: currentStrategyId, ); return OverlayPortal( diff --git a/lib/widgets/strategy_save_icon_button.dart b/lib/widgets/strategy_save_icon_button.dart index 26f8ff3f..1f53ae4b 100644 --- a/lib/widgets/strategy_save_icon_button.dart +++ b/lib/widgets/strategy_save_icon_button.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/providers/auto_save_notifier.dart'; +import 'package:icarus/providers/strategy_save_state_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; import 'package:toastification/toastification.dart'; @@ -120,12 +121,20 @@ class _AutoSaveButtonState extends ConsumerState foregroundColor: Colors.white, icon: icon, onPressed: () async { - // manual save path shows a SnackBar await ref .read(strategyProvider.notifier) .forceSaveNow(ref.read(strategyProvider).strategyId!); if (!context.mounted) return; + final latestSaveState = ref.read(strategySaveStateProvider); + final hasIncompleteMediaSync = latestSaveState.hasPendingMediaSync || + latestSaveState.mediaSyncErrorCount > 0; + final toastMessage = hasIncompleteMediaSync + ? latestSaveState.mediaSyncErrorCount > 0 + ? 'Local save complete. Media sync needs retry.' + : 'Local save complete. Media still syncing.' + : 'Save Complete'; + toastification.showCustom( context: context, autoCloseDuration: const Duration(seconds: 3), @@ -143,7 +152,7 @@ class _AutoSaveButtonState extends ConsumerState ), ), child: Text( - 'Save Complete', + toastMessage, style: ShadTheme.of(context) .textTheme .small @@ -152,20 +161,6 @@ class _AutoSaveButtonState extends ConsumerState ); }, ); - // ScaffoldMessenger.of(context).showSnackBar( - // const SnackBar( - // content: Center( - // child: Text( - // "File Saved", - // style: TextStyle(color: Colors.white), - // ), - // ), - // duration: Duration(seconds: 2), - // backgroundColor: Settings.sideBarColor, - // behavior: SnackBarBehavior.floating, - // width: 200, - // ), - // ); }, ), ); diff --git a/lib/widgets/strategy_tile/strategy_tile.dart b/lib/widgets/strategy_tile/strategy_tile.dart index 2da72e8b..c552909d 100644 --- a/lib/widgets/strategy_tile/strategy_tile.dart +++ b/lib/widgets/strategy_tile/strategy_tile.dart @@ -12,6 +12,7 @@ import 'package:icarus/strategy/strategy_page_models.dart'; import 'package:icarus/strategy_view.dart'; import 'package:icarus/widgets/dialogs/strategy/delete_strategy_alert_dialog.dart'; import 'package:icarus/widgets/dialogs/strategy/rename_strategy_dialog.dart'; +import 'package:icarus/widgets/dialogs/share_links_dialog.dart'; import 'package:icarus/widgets/folder_navigator.dart'; import 'package:icarus/widgets/strategy_tile/strategy_tile_sections.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; @@ -56,6 +57,7 @@ class _StrategyTileState extends ConsumerState { ShadContextMenuController(); bool get _isCloud => widget.cloudStrategy != null; + bool get _canShare => _isCloud && widget.cloudStrategy?.role == 'owner'; String get _strategyId => widget.strategyData?.id ?? widget.cloudStrategy!.publicId; String get _strategyName => @@ -167,6 +169,12 @@ class _StrategyTileState extends ConsumerState { onPressed: () => _exportStrategy(), child: const Text('Export'), ), + if (_canShare) + ShadContextMenuItem( + leading: const Icon(LucideIcons.link2), + onPressed: _showShareDialog, + child: const Text('Share'), + ), ShadContextMenuItem( leading: const Icon(LucideIcons.trash2, color: Colors.redAccent), onPressed: widget.canDelete ? () => _showDeleteDialog() : null, @@ -185,7 +193,9 @@ class _StrategyTileState extends ConsumerState { try { if (_isCloud) { - await ref.read(strategyProvider.notifier).openCloudStrategy(_strategyId); + await ref + .read(strategyProvider.notifier) + .openCloudStrategy(_strategyId); } else { await ref.read(strategyProvider.notifier).loadFromHive(_strategyId); } @@ -266,6 +276,17 @@ class _StrategyTileState extends ConsumerState { ); } + Future _showShareDialog() async { + await showShadDialog( + context: context, + builder: (_) => ShareLinksDialog( + targetType: 'strategy', + targetPublicId: _strategyId, + title: _strategyName, + ), + ); + } + void _showDeleteDialog() { showDialog( context: context, diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..9e610db2 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,597 @@ +{ + "name": "icarus", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "icarus", + "dependencies": { + "convex": "^1.32.0" + }, + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.0.tgz", + "integrity": "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.0.tgz", + "integrity": "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.0.tgz", + "integrity": "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.0.tgz", + "integrity": "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.0.tgz", + "integrity": "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.0.tgz", + "integrity": "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.0.tgz", + "integrity": "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.0.tgz", + "integrity": "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.0.tgz", + "integrity": "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.0.tgz", + "integrity": "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.0.tgz", + "integrity": "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.0.tgz", + "integrity": "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.0.tgz", + "integrity": "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.0.tgz", + "integrity": "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.0.tgz", + "integrity": "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.0.tgz", + "integrity": "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.0.tgz", + "integrity": "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.0.tgz", + "integrity": "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.0.tgz", + "integrity": "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.0.tgz", + "integrity": "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.0.tgz", + "integrity": "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.0.tgz", + "integrity": "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.0.tgz", + "integrity": "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.0.tgz", + "integrity": "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.0.tgz", + "integrity": "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.0.tgz", + "integrity": "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/bun": { + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.3.11.tgz", + "integrity": "sha512-5vPne5QvtpjGpsGYXiFyycfpDF2ECyPcTSsFBMa0fraoxiQyMJ3SmuQIGhzPg2WJuWxVBoxWJ2kClYTcw/4fAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "bun-types": "1.3.11" + } + }, + "node_modules/@types/node": { + "version": "25.5.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.2.tgz", + "integrity": "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/bun-types": { + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.3.11.tgz", + "integrity": "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/convex": { + "version": "1.34.1", + "resolved": "https://registry.npmjs.org/convex/-/convex-1.34.1.tgz", + "integrity": "sha512-ooyFnZVVq0u6b5zt0Ptq8QB2ixhf/2vXe+PIcUtdtrs0lq/TwpkmmruHdqkFmWgMd6N+Tmfy8AGkz6QnZUYZBA==", + "license": "Apache-2.0", + "dependencies": { + "esbuild": "0.27.0", + "prettier": "^3.0.0", + "ws": "8.18.0" + }, + "bin": { + "convex": "bin/main.js" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=7.0.0" + }, + "peerDependencies": { + "@auth0/auth0-react": "^2.0.1", + "@clerk/clerk-react": "^4.12.8 || ^5.0.0", + "react": "^18.0.0 || ^19.0.0-0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@auth0/auth0-react": { + "optional": true + }, + "@clerk/clerk-react": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/esbuild": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.0.tgz", + "integrity": "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.0", + "@esbuild/android-arm": "0.27.0", + "@esbuild/android-arm64": "0.27.0", + "@esbuild/android-x64": "0.27.0", + "@esbuild/darwin-arm64": "0.27.0", + "@esbuild/darwin-x64": "0.27.0", + "@esbuild/freebsd-arm64": "0.27.0", + "@esbuild/freebsd-x64": "0.27.0", + "@esbuild/linux-arm": "0.27.0", + "@esbuild/linux-arm64": "0.27.0", + "@esbuild/linux-ia32": "0.27.0", + "@esbuild/linux-loong64": "0.27.0", + "@esbuild/linux-mips64el": "0.27.0", + "@esbuild/linux-ppc64": "0.27.0", + "@esbuild/linux-riscv64": "0.27.0", + "@esbuild/linux-s390x": "0.27.0", + "@esbuild/linux-x64": "0.27.0", + "@esbuild/netbsd-arm64": "0.27.0", + "@esbuild/netbsd-x64": "0.27.0", + "@esbuild/openbsd-arm64": "0.27.0", + "@esbuild/openbsd-x64": "0.27.0", + "@esbuild/openharmony-arm64": "0.27.0", + "@esbuild/sunos-x64": "0.27.0", + "@esbuild/win32-arm64": "0.27.0", + "@esbuild/win32-ia32": "0.27.0", + "@esbuild/win32-x64": "0.27.0" + } + }, + "node_modules/prettier": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz", + "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/pubspec.lock b/pubspec.lock index 93be18dd..8d762ad5 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -189,10 +189,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" checked_yaml: dependency: transitive description: @@ -833,18 +833,18 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.18" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: @@ -1318,10 +1318,10 @@ packages: dependency: transitive description: name: test_api - sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636" url: "https://pub.dev" source: hosted - version: "0.7.7" + version: "0.7.9" theme_extensions_builder_annotation: dependency: transitive description: diff --git a/skills-lock.json b/skills-lock.json index 1c45028c..b8f0e2f1 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -1,30 +1,41 @@ { "version": 1, "skills": { + "convex": { + "source": "get-convex/agent-skills", + "sourceType": "github", + "skillPath": "skills/convex/SKILL.md", + "computedHash": "1515307c00539d299b2b2ac7084d39a12d6abbc86f665eec585f7de04220328e" + }, "convex-create-component": { "source": "get-convex/agent-skills", "sourceType": "github", - "computedHash": "84897925dd765dd58847b3b05b22ad706e65609f93a962345b48a97ff93a760f" + "skillPath": "skills/convex-create-component/SKILL.md", + "computedHash": "d46d3f80f9701612651a087c4cd37b03ec2bba7f53ac2e661efb2838b0c18f29" }, "convex-migration-helper": { "source": "get-convex/agent-skills", "sourceType": "github", - "computedHash": "b99262360eb6fba714155b630537861da2d4c890365f629c75d607c8a1405c7b" + "skillPath": "skills/convex-migration-helper/SKILL.md", + "computedHash": "8e839a8a51ac6fa5c341bf1bb57d8e5af229395467f1e606c51a8ddde42136d6" }, "convex-performance-audit": { "source": "get-convex/agent-skills", "sourceType": "github", - "computedHash": "1a41a616f9615b9229928653fa22c752e86487f415c73082dd17f1073e059127" + "skillPath": "skills/convex-performance-audit/SKILL.md", + "computedHash": "c150925d80d8b003b25dd80a52da016bce2451ebb9da5b4adc75cbf6b6ff37c9" }, "convex-quickstart": { "source": "get-convex/agent-skills", "sourceType": "github", - "computedHash": "51322b7e70b0f47ec67650b2db721eb91043cba99bf8c864366b7b250d8a313f" + "skillPath": "skills/convex-quickstart/SKILL.md", + "computedHash": "60bb7707dc0a87a51f17cfeb004e3fd403346e56694076f30a746ad285a5a7cc" }, "convex-setup-auth": { "source": "get-convex/agent-skills", "sourceType": "github", - "computedHash": "7cc29991c446d2ea574dc9abb5fb85c0c9a7f3ef3af4c94454eef45017bda794" + "skillPath": "skills/convex-setup-auth/SKILL.md", + "computedHash": "152289aa8150432c2c843e5861b554a46aa5992eb44a67041c333a8679d6c5f8" } } } diff --git a/skills/convex-create-component/SKILL.md b/skills/convex-create-component/SKILL.md index a79c18e0..64bd42f9 100644 --- a/skills/convex-create-component/SKILL.md +++ b/skills/convex-create-component/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-create-component -description: Designs and builds Convex components with isolated tables, clear boundaries, and app-facing wrappers. Use this skill when creating a new Convex component, extracting reusable backend logic into a component, building a third-party integration that owns its own tables, packaging Convex functionality for reuse, or when the user mentions defineComponent, app.use, ComponentApi, ctx.runQuery/runMutation across component boundaries, or wants to separate concerns into isolated Convex modules. +description: Builds reusable Convex components with isolated tables and app-facing APIs. Use for new components, reusable backend modules, integrations, or component boundary work. --- # Convex Create Component @@ -42,12 +42,12 @@ Create reusable Convex components with clear boundaries and a small app-facing A Ask the user, then pick one path: -| Goal | Shape | Reference | -|------|-------|-----------| -| Component for this app only | Local | `references/local-components.md` | -| Publish or share across apps | Packaged | `references/packaged-components.md` | -| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | -| Not sure | Default to local | `references/local-components.md` | +| Goal | Shape | Reference | +| ------------------------------------------------- | ---------------- | ----------------------------------- | +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | Read exactly one reference file before proceeding. @@ -111,7 +111,7 @@ export const listUnread = query({ userId: v.string(), message: v.string(), read: v.boolean(), - }) + }), ), handler: async (ctx, args) => { return await ctx.db @@ -234,12 +234,16 @@ export const sendNotification = mutation({ ```ts // Bad: parent app table IDs are not valid component validators -args: { userId: v.id("users") } +args: { + userId: v.id("users"); +} ``` ```ts // Good: treat parent-owned IDs as strings at the boundary -args: { userId: v.string() } +args: { + userId: v.string(); +} ``` ### Advanced Patterns diff --git a/skills/convex-migration-helper/SKILL.md b/skills/convex-migration-helper/SKILL.md index 97f64c1a..4a4ed167 100644 --- a/skills/convex-migration-helper/SKILL.md +++ b/skills/convex-migration-helper/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-migration-helper -description: Plans and executes safe Convex schema and data migrations using the widen-migrate-narrow workflow and the @convex-dev/migrations component. Use this skill when a deployment fails schema validation, existing documents need backfilling, fields need adding or removing or changing type, tables need splitting or merging, or a zero-downtime migration strategy is needed. Also use when the user mentions breaking schema changes, multi-deploy rollouts, or data transformations on existing Convex tables. +description: Plans Convex schema and data migrations with widen-migrate-narrow and @convex-dev/migrations. Use for breaking schema changes, backfills, table reshaping, or zero-downtime rollouts. --- # Convex Migration Helper @@ -55,13 +55,13 @@ Unless you are certain, prefer deprecating fields over deleting them. Mark the f // Before users: defineTable({ name: v.string(), -}) +}); // After - safe, new field is optional users: defineTable({ name: v.string(), bio: v.optional(v.string()), -}) +}); ``` ### Adding New Table @@ -70,7 +70,7 @@ users: defineTable({ posts: defineTable({ userId: v.id("users"), title: v.string(), -}).index("by_user", ["userId"]) +}).index("by_user", ["userId"]); ``` ### Adding Index @@ -79,8 +79,7 @@ posts: defineTable({ users: defineTable({ name: v.string(), email: v.string(), -}) - .index("by_email", ["email"]) +}).index("by_email", ["email"]); ``` ## Breaking Changes: The Deployment Workflow diff --git a/skills/convex-migration-helper/references/migration-patterns.md b/skills/convex-migration-helper/references/migration-patterns.md index 219583e0..53b4946f 100644 --- a/skills/convex-migration-helper/references/migration-patterns.md +++ b/skills/convex-migration-helper/references/migration-patterns.md @@ -9,7 +9,7 @@ Common migration patterns, zero-downtime strategies, and verification techniques users: defineTable({ name: v.string(), role: v.optional(v.union(v.literal("user"), v.literal("admin"))), -}) +}); // Migration: backfill the field export const addDefaultRole = migrations.define({ @@ -25,7 +25,7 @@ export const addDefaultRole = migrations.define({ users: defineTable({ name: v.string(), role: v.union(v.literal("user"), v.literal("admin")), -}) +}); ``` ## Deleting a Field diff --git a/skills/convex-migration-helper/references/migrations-component.md b/skills/convex-migration-helper/references/migrations-component.md index c80522f2..95ec2921 100644 --- a/skills/convex-migration-helper/references/migrations-component.md +++ b/skills/convex-migration-helper/references/migrations-component.md @@ -151,8 +151,7 @@ Process only matching documents instead of the full table: ```typescript export const fixEmptyNames = migrations.define({ table: "users", - customRange: (query) => - query.withIndex("by_name", (q) => q.eq("name", "")), + customRange: (query) => query.withIndex("by_name", (q) => q.eq("name", "")), migrateOne: () => ({ name: "" }), }); ``` diff --git a/skills/convex-performance-audit/SKILL.md b/skills/convex-performance-audit/SKILL.md index 9d92b33c..f2554dca 100644 --- a/skills/convex-performance-audit/SKILL.md +++ b/skills/convex-performance-audit/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-performance-audit -description: Audits and optimizes Convex application performance across hot-path reads, write contention, subscription cost, and function limits. Use this skill when a Convex feature is slow or expensive, npx convex insights shows high bytes or documents read, OCC conflict errors or mutation retries appear, subscriptions or UI updates are costly, functions hit execution or transaction limits, or the user mentions performance, latency, read amplification, or invalidation problems in a Convex app. +description: Audits Convex performance for reads, subscriptions, write contention, and function limits. Use for slow features, insights findings, OCC conflicts, or read amplification. --- # Convex Performance Audit @@ -43,13 +43,13 @@ Start with the strongest signal available: After gathering signals, identify the problem class and read the matching reference file. -| Signal | Reference | -|---|---| -| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | -| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | -| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | -| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | -| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | +| Signal | Reference | +| -------------------------------------------------------------- | ----------------------------------------- | +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. @@ -107,7 +107,7 @@ After finding one problem, inspect both sibling readers and sibling writers for Examples: - If one list query switches from full docs to a digest table, inspect the other list queries for that table -- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one mutation isolates a frequently-updated field or splits a hot document, inspect the other writers to the same table - If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. @@ -119,7 +119,7 @@ Confirm all of these: 1. Results are the same as before, no dropped records 2. Eliminated reads or writes are no longer in the path where expected 3. Fallback behavior works when denormalized or indexed fields are missing -4. New writes avoid unnecessary invalidation when data is unchanged +4. Frequently-updated fields are isolated from widely-read documents where needed 5. Every relevant sibling reader and writer was inspected, not just the original function ## Reference Files diff --git a/skills/convex-performance-audit/references/function-budget.md b/skills/convex-performance-audit/references/function-budget.md index c71d14cb..d4d4aa5a 100644 --- a/skills/convex-performance-audit/references/function-budget.md +++ b/skills/convex-performance-audit/references/function-budget.md @@ -10,17 +10,17 @@ Convex functions run inside transactions with budgets for time, reads, and write These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. -| Resource | Limit | -|---|---| -| Query/mutation execution time | 1 second (user code only, excludes DB operations) | -| Action execution time | 10 minutes | -| Data read per transaction | 16 MiB | -| Data written per transaction | 16 MiB | +| Resource | Limit | +| --------------------------------- | ----------------------------------------------------- | +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | | Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | -| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | -| Documents written per transaction | 16,000 | -| Individual document size | 1 MiB | -| Function return value size | 16 MiB | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | ## Symptoms diff --git a/skills/convex-performance-audit/references/hot-path-rules.md b/skills/convex-performance-audit/references/hot-path-rules.md index e3e44b15..e003e052 100644 --- a/skills/convex-performance-audit/references/hot-path-rules.md +++ b/skills/convex-performance-audit/references/hot-path-rules.md @@ -121,13 +121,15 @@ Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need // Bad: two indexes where one would do defineTable({ team: v.id("teams"), user: v.id("users") }) .index("by_team", ["team"]) - .index("by_team_and_user", ["team", "user"]) + .index("by_team_and_user", ["team", "user"]); ``` ```ts // Good: single compound index serves both query patterns -defineTable({ team: v.id("teams"), user: v.id("users") }) - .index("by_team_and_user", ["team", "user"]) +defineTable({ team: v.id("teams"), user: v.id("users") }).index( + "by_team_and_user", + ["team", "user"], +); ``` Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. @@ -170,9 +172,7 @@ const ownerName = project.ownerName ?? "Unknown owner"; ```ts // Good: denormalized data is an optimization, not the only source of truth const ownerName = - project.ownerName ?? - (await ctx.db.get(project.ownerId))?.name ?? - null; + project.ownerName ?? (await ctx.db.get(project.ownerId))?.name ?? null; ``` Bad lookup map pattern: @@ -241,35 +241,33 @@ const projects = await ctx.db .take(20); ``` -## 4. Skip No-Op Writes - -No-op writes still cost work in Convex: +## 4. Isolate Frequently-Updated Fields -- invalidation -- replication -- trigger execution -- downstream sync +Convex already no-ops unchanged writes. The invalidation problem here is real writes hitting documents that many queries subscribe to. -Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. +Move high-churn fields like `lastSeen`, counters, presence, or ephemeral status off widely-read documents when most readers do not need them. -Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. +Apply this across sibling writers too. Splitting one write path does not help much if three other mutations still update the same widely-read document. ```ts -// Bad: patching unchanged values still triggers invalidation and downstream work -await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, +// Bad: every presence heartbeat invalidates subscribers to the whole profile +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, + lastSeen: Date.now(), }); ``` ```ts -// Good: only write when something actually changed -if (settings.theme !== args.theme || settings.locale !== args.locale) { - await ctx.db.patch(settings._id, { - theme: args.theme, - locale: args.locale, - }); -} +// Good: keep profile reads stable, move heartbeat updates to a separate document +await ctx.db.patch(user._id, { + name: args.name, + avatarUrl: args.avatarUrl, +}); + +await ctx.db.patch(presence._id, { + lastSeen: Date.now(), +}); ``` ## 5. Match Consistency To Read Patterns diff --git a/skills/convex-performance-audit/references/occ-conflicts.md b/skills/convex-performance-audit/references/occ-conflicts.md index a96d0466..1da43801 100644 --- a/skills/convex-performance-audit/references/occ-conflicts.md +++ b/skills/convex-performance-audit/references/occ-conflicts.md @@ -73,42 +73,30 @@ await ctx.db.patch(shardId, { count: shard!.count + 1 }); Aggregate the shards in a query or scheduled job when you need the total. -### 3. Skip no-op writes +### 3. Move non-critical work to scheduled functions -Writes that do not change data still participate in conflict detection and trigger invalidation. +If a mutation does primary work plus secondary bookkeeping (analytics, non-critical notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. ```ts -// Bad: patches even when nothing changed -await ctx.db.patch(doc._id, { status: args.status }); -``` - -```ts -// Good: only write when the value actually differs -if (doc.status !== args.status) { - await ctx.db.patch(doc._id, { status: args.status }); -} -``` - -### 4. Move non-critical work to scheduled functions - -If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. - -```ts -// Bad: analytics update in the same transaction as the user action -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +// Bad: canonical write and derived work happen in the same transaction +await ctx.db.patch(userId, { name: args.name }); +await ctx.db.insert("userUpdateAnalytics", { + userId, + kind: "name_changed", + name: args.name, +}); ``` ```ts -// Good: schedule the bookkeeping so the primary transaction is smaller -await ctx.db.patch(userId, { lastActiveAt: Date.now() }); -await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { - event: "action", +// Good: keep the primary write small, defer the analytics work +await ctx.db.patch(userId, { name: args.name }); +await ctx.scheduler.runAfter(0, internal.users.recordNameChangeAnalytics, { userId, + name: args.name, }); ``` -### 5. Combine competing writes +### 4. Combine competing writes If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. diff --git a/skills/convex-quickstart/SKILL.md b/skills/convex-quickstart/SKILL.md index 792bba3d..f506b3e4 100644 --- a/skills/convex-quickstart/SKILL.md +++ b/skills/convex-quickstart/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-quickstart -description: Initializes a new Convex project from scratch or adds Convex to an existing app. Use this skill when starting a new project with Convex, scaffolding with npm create convex@latest, adding Convex to an existing React, Next.js, Vue, Svelte, or other frontend, wiring up ConvexProvider, configuring environment variables for the deployment URL, or running npx convex dev for the first time, even if the user just says "set up Convex" or "add a backend." +description: Creates or adds Convex to an app. Use for new Convex projects, npm create convex@latest, frontend setup, env vars, or the first npx convex dev run. --- # Convex Quickstart @@ -32,15 +32,15 @@ Use the official scaffolding tool. It creates a complete project with the fronte ### Pick a template -| Template | Stack | -|----------|-------| -| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | -| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | -| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | -| `nextjs-clerk` | Next.js + Clerk auth | -| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | -| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | -| `bare` | Convex backend only, no frontend | +| Template | Stack | +| -------------------------- | ----------------------------------------- | +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. @@ -77,6 +77,7 @@ npm install **Ask the user to run this themselves:** Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: + - Create a Convex project and dev deployment - Write the deployment URL to `.env.local` - Create the `convex/` directory with generated types @@ -111,6 +112,7 @@ my-app/ ``` The template already has: + - `ConvexProvider` wired into the app root - Correct env var names for the framework - Tailwind and shadcn/ui ready (for shadcn templates) @@ -141,7 +143,9 @@ Create the `ConvexReactClient` at module scope, not inside a component: ```tsx // Bad: re-creates the client on every render function App() { - const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + const convex = new ConvexReactClient( + import.meta.env.VITE_CONVEX_URL as string, + ); return ...; } @@ -192,7 +196,11 @@ export function ConvexClientProvider({ children }: { children: ReactNode }) { // app/layout.tsx import { ConvexClientProvider } from "./ConvexClientProvider"; -export default function RootLayout({ children }: { children: React.ReactNode }) { +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { return ( @@ -218,11 +226,11 @@ For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the mat The env var name depends on the framework: -| Framework | Variable | -|-----------|----------| -| Vite | `VITE_CONVEX_URL` | -| Next.js | `NEXT_PUBLIC_CONVEX_URL` | -| Remix | `CONVEX_URL` | +| Framework | Variable | +| ------------ | ------------------------ | +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | | React Native | `EXPO_PUBLIC_CONVEX_URL` | `npx convex dev` writes the correct variable to `.env.local` automatically. @@ -299,7 +307,9 @@ function Tasks() { return (
- {tasks?.map((t) =>
{t.text}
)} + {tasks?.map((t) => ( +
{t.text}
+ ))}
); } diff --git a/skills/convex-setup-auth/SKILL.md b/skills/convex-setup-auth/SKILL.md index 0fa00e2f..59a92285 100644 --- a/skills/convex-setup-auth/SKILL.md +++ b/skills/convex-setup-auth/SKILL.md @@ -1,6 +1,6 @@ --- name: convex-setup-auth -description: Sets up Convex authentication with user management, identity mapping, and access control. Use this skill when adding login or signup to a Convex app, configuring Convex Auth, Clerk, WorkOS AuthKit, Auth0, or custom JWT providers, wiring auth.config.ts, protecting queries and mutations with ctx.auth.getUserIdentity(), creating a users table with identity mapping, or setting up role-based access control, even if the user just says "add auth" or "make it require login." +description: Sets up Convex auth, identity mapping, and access control. Use for login, auth providers, users tables, protected functions, or roles in a Convex app. --- # Convex Authentication Setup @@ -102,7 +102,7 @@ export const getMyProfile = query({ return await ctx.db .query("users") .withIndex("by_tokenIdentifier", (q) => - q.eq("tokenIdentifier", identity.tokenIdentifier) + q.eq("tokenIdentifier", identity.tokenIdentifier), ) .unique(); }, diff --git a/skills/convex/SKILL.md b/skills/convex/SKILL.md new file mode 100644 index 00000000..9e8ebbd8 --- /dev/null +++ b/skills/convex/SKILL.md @@ -0,0 +1,47 @@ +--- +name: convex +description: Routes general Convex requests to the right project skill. Use when the user asks which Convex skill to use or gives an underspecified Convex app task. +--- + +# Convex + +Use this as the routing skill for Convex work in this repo. + +If a more specific Convex skill clearly matches the request, use that instead. + +## Start Here + +If the project does not already have Convex AI guidance installed, or the existing guidance looks stale, strongly recommend installing it first. + +Preferred: + +```bash +npx convex ai-files install +``` + +This installs or refreshes the managed Convex AI files. It is the recommended starting point for getting the official Convex guidelines in place and following the current Convex AI setup described in the docs: + +- [Convex AI docs](https://docs.convex.dev/ai) + +Simple fallback: + +- [convex_rules.txt](https://convex.link/convex_rules.txt) + +Prefer `npx convex ai-files install` over copying rules by hand when possible. + +## Route to the Right Skill + +After that, use the most specific Convex skill for the task: + +- New project or adding Convex to an app: `convex-quickstart` +- Authentication setup: `convex-setup-auth` +- Building a reusable Convex component: `convex-create-component` +- Planning or running a migration: `convex-migration-helper` +- Investigating performance issues: `convex-performance-audit` + +If one of those clearly matches the user's goal, switch to it instead of staying in this skill. + +## When Not to Use + +- The user has already named a more specific Convex workflow +- Another Convex skill obviously fits the request better diff --git a/test/action_history_hydration_test.dart b/test/action_history_hydration_test.dart index a7c0107d..deed01b3 100644 --- a/test/action_history_hydration_test.dart +++ b/test/action_history_hydration_test.dart @@ -3,7 +3,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:icarus/const/coordinate_system.dart'; import 'package:icarus/const/drawing_element.dart'; -import 'package:icarus/const/maps.dart'; import 'package:icarus/const/placed_classes.dart'; import 'package:icarus/providers/action_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; @@ -16,7 +15,7 @@ import 'package:icarus/strategy/strategy_page_models.dart'; class _NoopStrategyProvider extends StrategyProvider { @override StrategyState build() { - return StrategyState( + return const StrategyState( strategyId: 'test-strategy', strategyName: 'Test Strategy', source: StrategySource.local, @@ -56,7 +55,8 @@ void main() { CoordinateSystem(playAreaSize: const Size(1920, 1080)); }); - test('preserveHistory keeps text undo/redo working across hydration', () async { + test('preserveHistory keeps text undo/redo working across hydration', + () async { final container = _createContainer(); final notifier = container.read(textProvider.notifier); @@ -139,4 +139,22 @@ void main() { expect(flippedDeleted.lineStart, _flipPoint(const Offset(10, 20))); expect(flippedDeleted.lineEnd, _flipPoint(const Offset(40, 50))); }); + + test('switchSide mirrors text width when measurement is missing', () { + final container = _createContainer(); + final text = PlacedText( + id: 'text-1', + position: const Offset(10, 20), + size: 100, + fontSize: 20, + sizeVersion: worldSizedMediaVersion, + )..text = 'One line'; + + container.read(textProvider.notifier).fromHive([text]); + container.read(mapProvider.notifier).switchSide(); + + final flipped = container.read(textProvider).single.position; + + expect(flipped.dx, lessThan(_flipPoint(text.position).dx)); + }); } diff --git a/test/action_provider_bulk_clear_test.dart b/test/action_provider_bulk_clear_test.dart index 968e2986..6c7e8fac 100644 --- a/test/action_provider_bulk_clear_test.dart +++ b/test/action_provider_bulk_clear_test.dart @@ -13,10 +13,8 @@ import 'package:icarus/providers/action_provider.dart'; import 'package:icarus/providers/agent_provider.dart'; import 'package:icarus/providers/drawing_provider.dart'; import 'package:icarus/providers/image_provider.dart'; -import 'package:icarus/providers/image_widget_size_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/providers/text_provider.dart'; -import 'package:icarus/providers/text_widget_height_provider.dart'; import 'package:icarus/providers/utility_provider.dart'; import 'package:icarus/strategy/strategy_models.dart'; import 'package:icarus/strategy/strategy_page_models.dart'; @@ -239,13 +237,6 @@ void main() { .read(lineUpProvider.notifier) .fromHive([_buildLineUp('lineup-all')]); - container - .read(imageWidgetSizeProvider.notifier) - .updateSize('image-all', const Offset(80, 60)); - container - .read(textWidgetHeightProvider.notifier) - .updateHeight('text-all', const Offset(120, 44)); - container.read(actionProvider.notifier).clearAllAsAction(); expect(container.read(agentProvider), isEmpty); @@ -255,14 +246,6 @@ void main() { expect(container.read(placedImageProvider).images, isEmpty); expect(container.read(utilityProvider), isEmpty); expect(container.read(lineUpProvider).lineUps, isEmpty); - expect( - container.read(imageWidgetSizeProvider.notifier).getSize('image-all'), - Offset.zero, - ); - expect( - container.read(textWidgetHeightProvider.notifier).getOffset('text-all'), - Offset.zero, - ); expect(container.read(actionProvider), hasLength(1)); expect( container.read(actionProvider).single.type, ActionType.bulkDeletion); @@ -276,14 +259,6 @@ void main() { expect(container.read(placedImageProvider).images, hasLength(1)); expect(container.read(utilityProvider), hasLength(1)); expect(container.read(lineUpProvider).lineUps, hasLength(1)); - expect( - container.read(imageWidgetSizeProvider.notifier).getSize('image-all'), - const Offset(80, 60), - ); - expect( - container.read(textWidgetHeightProvider.notifier).getOffset('text-all'), - const Offset(120, 44), - ); expect(container.read(actionProvider), isEmpty); }); diff --git a/test/collab_sync_models_test.dart b/test/collab_sync_models_test.dart index 678045a6..c1b0f5ca 100644 --- a/test/collab_sync_models_test.dart +++ b/test/collab_sync_models_test.dart @@ -110,4 +110,114 @@ void main() { expect(remote.decodedPayload(), isEmpty); }); }); + + group('RemoteStrategySnapshot helpers', () { + final header = RemoteStrategyHeader( + publicId: 'strat-1', + name: 'Original', + mapData: '{}', + sequence: 1, + createdAt: DateTime.fromMillisecondsSinceEpoch(1), + updatedAt: DateTime.fromMillisecondsSinceEpoch(2), + ); + const page1 = RemotePage( + publicId: 'page-1', + strategyPublicId: 'strat-1', + name: 'Page 1', + sortIndex: 0, + isAttack: true, + revision: 1, + ); + const page2 = RemotePage( + publicId: 'page-2', + strategyPublicId: 'strat-1', + name: 'Page 2', + sortIndex: 1, + isAttack: false, + revision: 1, + ); + const element = RemoteElement( + publicId: 'el-1', + strategyPublicId: 'strat-1', + pagePublicId: 'page-1', + elementType: 'text', + payload: '{}', + sortIndex: 1, + revision: 1, + deleted: false, + ); + const deletedElement = RemoteElement( + publicId: 'el-2', + strategyPublicId: 'strat-1', + pagePublicId: 'page-1', + elementType: 'text', + payload: '{}', + sortIndex: 0, + revision: 2, + deleted: true, + ); + const lineup = RemoteLineup( + publicId: 'lineup-1', + strategyPublicId: 'strat-1', + pagePublicId: 'page-2', + payload: '{}', + sortIndex: 0, + revision: 1, + deleted: false, + ); + + RemoteStrategySnapshot snapshot() => RemoteStrategySnapshot( + header: header, + pages: const [page1, page2], + elementsByPage: const { + 'page-1': [element], + }, + lineupsByPage: const { + 'page-2': [lineup], + }, + assetsById: const {}, + ); + + test('header update preserves pages assets elements and lineups', () { + final updated = snapshot().replaceHeader( + RemoteStrategyHeader( + publicId: 'strat-1', + name: 'Updated', + mapData: '{}', + sequence: 2, + createdAt: DateTime.fromMillisecondsSinceEpoch(1), + updatedAt: DateTime.fromMillisecondsSinceEpoch(3), + ), + ); + + expect(updated.header.name, 'Updated'); + expect(updated.pages, const [page1, page2]); + expect(updated.elementsByPage['page-1'], const [element]); + expect(updated.lineupsByPage['page-2'], const [lineup]); + }); + + test('pages update preserves unchanged page maps and prunes removed pages', + () { + final updated = snapshot().replacePages(const [page1]); + + expect(updated.pages, const [page1]); + expect(updated.elementsByPage.containsKey('page-1'), isTrue); + expect(updated.lineupsByPage.containsKey('page-2'), isFalse); + }); + + test('strategy-level elements are grouped by page and retain deletes', () { + final grouped = RemoteStrategySnapshot.groupElementsByPage( + const [element, deletedElement], + ); + + expect(grouped['page-1'], const [deletedElement, element]); + expect(grouped['page-1']!.first.deleted, isTrue); + }); + + test('strategy-level lineups are grouped by page', () { + final grouped = RemoteStrategySnapshot.groupLineupsByPage(const [lineup]); + + expect(grouped['page-2'], const [lineup]); + }); + }); } diff --git a/test/placed_media_dimensions_test.dart b/test/placed_media_dimensions_test.dart new file mode 100644 index 00000000..cc9b482a --- /dev/null +++ b/test/placed_media_dimensions_test.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:icarus/const/coordinate_system.dart'; +import 'package:icarus/const/image_scale_policy.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + CoordinateSystem(playAreaSize: const Size(1920, 1080)); + }); + + test('image helper returns expected width and height', () { + final size = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: ImageScalePolicy.defaultWidth, + aspectRatio: 2.0, + ); + + final expectedWidth = CoordinateSystem.instance + .worldWidthToScreen(ImageScalePolicy.defaultWidth); + final cardWidth = expectedWidth - + PlacedImageDimensions.tagWidth - + PlacedImageDimensions.tagGap; + final contentWidth = cardWidth - (PlacedImageDimensions.imagePadding * 2); + final expectedHeight = + (contentWidth / 2.0) + (PlacedImageDimensions.imagePadding * 2); + + expect(size.width, expectedWidth); + expect(size.height, expectedHeight); + }); + + test('image helper clamps scale', () { + final size = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: ImageScalePolicy.maxWidth * 10, + aspectRatio: 1.0, + ); + + expect( + size.width, + CoordinateSystem.instance.worldWidthToScreen(ImageScalePolicy.maxWidth), + ); + }); + + test('image helper falls back to square aspect ratio', () { + final zeroAspect = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: ImageScalePolicy.defaultWidth, + aspectRatio: 0, + ); + final squareAspect = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: ImageScalePolicy.defaultWidth, + aspectRatio: 1, + ); + + expect(zeroAspect, squareAspect); + }); + + test('text helper returns deterministic screen width', () { + final size = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: 220, + fontSizeWorld: 16, + text: 'one line', + ); + + expect(size.width, CoordinateSystem.instance.worldWidthToScreen(220)); + }); + + test('text helper uses one-line height for empty text', () { + final empty = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: 220, + fontSizeWorld: 16, + text: '', + ); + final singleLine = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: 220, + fontSizeWorld: 16, + text: 'one line', + ); + + expect(empty.height, singleLine.height); + expect(empty.height, lessThan(64)); + }); + + test('text helper height increases for wrapped text', () { + final singleLine = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: 220, + fontSizeWorld: 16, + text: 'short text', + ); + final wrapped = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: 80, + fontSizeWorld: 16, + text: 'this is a long annotation that should wrap across several lines', + ); + + expect(wrapped.height, greaterThan(singleLine.height)); + }); +} diff --git a/test/side_switch_media_test.dart b/test/side_switch_media_test.dart new file mode 100644 index 00000000..79c720ee --- /dev/null +++ b/test/side_switch_media_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:icarus/const/coordinate_system.dart'; +import 'package:icarus/const/image_scale_policy.dart'; +import 'package:icarus/const/placed_classes.dart'; +import 'package:icarus/const/placed_media_dimensions.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + CoordinateSystem(playAreaSize: const Size(1920, 1080)); + }); + + group('PlacedText side switch', () { + test('double switch returns empty text to original position', () { + final text = _placedText(text: ''); + + _switchText(text); + _switchText(text); + + _expectClose(text.position, const Offset(100, 120)); + }); + + test('double switch returns single-line text to original position', () { + final text = _placedText(text: 'one line'); + + _switchText(text); + _switchText(text); + + _expectClose(text.position, const Offset(100, 120)); + }); + + test('double switch returns wrapped text to original position', () { + final text = _placedText( + text: 'this text is long enough to wrap across multiple lines', + size: 90, + ); + + _switchText(text); + _switchText(text); + + _expectClose(text.position, const Offset(100, 120)); + }); + }); + + test( + 'PlacedImage double switch returns non-square image to original position', + () { + final image = PlacedImage( + id: 'image-1', + position: const Offset(200, 220), + aspectRatio: 16 / 9, + scale: ImageScalePolicy.defaultWidth, + fileExtension: '.png', + sizeVersion: worldSizedMediaVersion, + ); + + _switchImage(image); + _switchImage(image); + + _expectClose(image.position, const Offset(200, 220)); + }); +} + +PlacedText _placedText({ + required String text, + double size = 220, +}) { + return PlacedText( + id: 'text-1', + position: const Offset(100, 120), + size: size, + fontSize: 16, + sizeVersion: worldSizedMediaVersion, + )..text = text; +} + +void _switchText(PlacedText text) { + final size = PlacedTextDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + widthWorld: text.size, + fontSizeWorld: text.fontSize, + text: text.text, + ); + + text.switchSides(Offset(size.width, size.height)); +} + +void _switchImage(PlacedImage image) { + final size = PlacedImageDimensions.screenSize( + coordinateSystem: CoordinateSystem.instance, + scale: image.scale, + aspectRatio: image.aspectRatio, + ); + + image.switchSides(Offset(size.width, size.height)); +} + +void _expectClose(Offset actual, Offset expected) { + expect(actual.dx, closeTo(expected.dx, 1e-9)); + expect(actual.dy, closeTo(expected.dy, 1e-9)); +} diff --git a/test/strategy_op_queue_provider_test.dart b/test/strategy_op_queue_provider_test.dart index 02312712..b036aabb 100644 --- a/test/strategy_op_queue_provider_test.dart +++ b/test/strategy_op_queue_provider_test.dart @@ -1,9 +1,25 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/providers/collab/active_page_live_sync_models.dart'; import 'package:icarus/providers/collab/strategy_op_queue_provider.dart'; void main() { + group('Entity sync keys', () { + test('round trips page ids that contain delimiters', () { + final pageId = 'strategy-1:page:1'; + final elementId = 'element-1'; + final lineupId = 'lineup-1'; + + expect(pageIdForEntityKey(pageSettingsEntityKey(pageId)), pageId); + expect(pageIdForEntityKey(elementEntityKey(pageId, elementId)), pageId); + expect( + entityIdForEntityKey(elementEntityKey(pageId, elementId)), elementId); + expect(pageIdForEntityKey(lineupEntityKey(pageId, lineupId)), pageId); + expect(entityIdForEntityKey(lineupEntityKey(pageId, lineupId)), lineupId); + }); + }); + group('StrategyOpQueueNotifier coalescing', () { late ProviderContainer container; late StrategyOpQueueNotifier notifier; diff --git a/test/strategy_page_session_provider_test.dart b/test/strategy_page_session_provider_test.dart index 3a933805..e62e1cd6 100644 --- a/test/strategy_page_session_provider_test.dart +++ b/test/strategy_page_session_provider_test.dart @@ -6,8 +6,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive_ce/hive.dart'; import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/const/agents.dart'; import 'package:icarus/const/coordinate_system.dart'; import 'package:icarus/const/hive_boxes.dart'; +import 'package:icarus/const/line_provider.dart'; import 'package:icarus/const/maps.dart'; import 'package:icarus/const/placed_classes.dart'; import 'package:icarus/const/transition_data.dart'; @@ -16,6 +18,8 @@ import 'package:icarus/providers/collab/active_page_live_sync_provider.dart'; import 'package:icarus/providers/collab/active_page_live_sync_models.dart'; import 'package:icarus/providers/collab/remote_strategy_snapshot_provider.dart'; import 'package:icarus/providers/collab/strategy_op_queue_provider.dart'; +import 'package:icarus/providers/agent_provider.dart'; +import 'package:icarus/providers/map_provider.dart'; import 'package:icarus/providers/strategy_page.dart'; import 'package:icarus/providers/strategy_page_session_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; @@ -170,6 +174,7 @@ RemoteStrategySnapshot _cloudSnapshot({ required int sequence, required List pages, Map> elementsByPage = const {}, + Map> lineupsByPage = const {}, }) { final now = DateTime.utc(2026, 1, 1); return RemoteStrategySnapshot( @@ -183,7 +188,8 @@ RemoteStrategySnapshot _cloudSnapshot({ ), pages: pages, elementsByPage: elementsByPage, - lineupsByPage: const {}, + lineupsByPage: lineupsByPage, + assetsById: const {}, ); } @@ -227,6 +233,40 @@ RemoteElement _remoteText({ ); } +RemoteLineup _remoteLineup({ + required String strategyId, + required String pageId, + required String lineupId, + required String notes, + int sortIndex = 0, +}) { + final lineup = LineUp( + id: lineupId, + agent: PlacedAgent( + id: '$lineupId-agent', + type: AgentType.jett, + position: const Offset(10, 20), + ), + ability: PlacedAbility( + id: '$lineupId-ability', + data: AgentData.agents[AgentType.jett]!.abilities.first, + position: const Offset(30, 40), + ), + youtubeLink: '', + images: const [], + notes: notes, + ); + return RemoteLineup( + publicId: lineupId, + strategyPublicId: strategyId, + pagePublicId: pageId, + payload: jsonEncode(lineup.toJson()), + sortIndex: sortIndex, + revision: 1, + deleted: false, + ); +} + StrategyData _localStrategy({ required String strategyId, required String firstText, @@ -375,6 +415,537 @@ void main() { expect(container.read(textProvider).single.text, 'after'); }); + test('late active-page elements rehydrate after header sequence advance', + () async { + const strategyId = 'cloud-strategy'; + final pageOne = + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); + final beforeSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'before', + ), + ], + }, + ); + final headerFirstSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'before', + ), + ], + }, + ); + final elementsArrivedSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'after', + ), + ], + }, + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(beforeSnapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + remoteNotifier.setSnapshot(headerFirstSnapshot); + await _settle(); + expect(container.read(textProvider).single.text, 'before'); + + remoteNotifier.setSnapshot(elementsArrivedSnapshot); + await _settle(); + + expect(container.read(textProvider).single.text, 'after'); + expect(queueNotifier.enqueueAllCount, 0); + expect(queueNotifier.flushNowCount, 0); + }); + + test('late active-page lineups rehydrate after header sequence advance', + () async { + const strategyId = 'cloud-strategy'; + final pageOne = + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); + final beforeSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [pageOne], + lineupsByPage: { + 'page-1': [ + _remoteLineup( + strategyId: strategyId, + pageId: 'page-1', + lineupId: 'lineup-1', + notes: 'before', + ), + ], + }, + ); + final headerFirstSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + lineupsByPage: { + 'page-1': [ + _remoteLineup( + strategyId: strategyId, + pageId: 'page-1', + lineupId: 'lineup-1', + notes: 'before', + ), + ], + }, + ); + final lineupsArrivedSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + lineupsByPage: { + 'page-1': [ + _remoteLineup( + strategyId: strategyId, + pageId: 'page-1', + lineupId: 'lineup-1', + notes: 'after', + ), + ], + }, + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(beforeSnapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + remoteNotifier.setSnapshot(headerFirstSnapshot); + await _settle(); + expect(container.read(lineUpProvider).lineUps.single.notes, 'before'); + + remoteNotifier.setSnapshot(lineupsArrivedSnapshot); + await _settle(); + + expect(container.read(lineUpProvider).lineUps.single.notes, 'after'); + expect(queueNotifier.enqueueAllCount, 0); + expect(queueNotifier.flushNowCount, 0); + }); + + test('active-page elements wait for header sequence before rehydrate', + () async { + const strategyId = 'cloud-strategy'; + final pageOne = + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); + final beforeSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'before', + ), + ], + }, + ); + final elementsFirstSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'after', + ), + ], + }, + ); + final headerArrivedSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + elementsByPage: elementsFirstSnapshot.elementsByPage, + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(beforeSnapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + remoteNotifier.setSnapshot(elementsFirstSnapshot); + await _settle(); + expect(container.read(textProvider).single.text, 'before'); + + remoteNotifier.setSnapshot(headerArrivedSnapshot); + await _settle(); + + expect(container.read(textProvider).single.text, 'after'); + expect(queueNotifier.enqueueAllCount, 0); + expect(queueNotifier.flushNowCount, 0); + }); + + test('unchanged same-sequence section payload does not rehydrate', () async { + const strategyId = 'cloud-strategy'; + final pageOne = + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); + final beforeSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'before', + ), + ], + }, + ); + final updatedSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'after', + ), + ], + }, + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(beforeSnapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + remoteNotifier.setSnapshot(updatedSnapshot); + await _settle(); + expect(container.read(textProvider).single.text, 'after'); + + container.read(textProvider.notifier).fromHive([ + PlacedText(id: 'local-text', position: const Offset(50, 60)) + ..text = 'local-only', + ]); + remoteNotifier.setSnapshot(updatedSnapshot); + await _settle(); + + expect(container.read(textProvider).single.text, 'local-only'); + expect(queueNotifier.flushNowCount, 0); + }); + + test('late same-sequence section rehydrate preserves local overlay', + () async { + const strategyId = 'cloud-strategy'; + final pageOne = + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); + final beforeSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'remote-a', + sortIndex: 0, + ), + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-2', + text: 'remote-b', + sortIndex: 1, + ), + ], + }, + ); + final headerFirstSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + elementsByPage: beforeSnapshot.elementsByPage, + ); + final elementsArrivedSnapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 2, + pages: [pageOne], + elementsByPage: { + 'page-1': [ + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-1', + text: 'remote-a-server', + sortIndex: 0, + ), + _remoteText( + strategyId: strategyId, + pageId: 'page-1', + elementId: 'text-2', + text: 'remote-b-updated', + sortIndex: 1, + ), + ], + }, + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(beforeSnapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + final localTextPayload = Map.from( + (PlacedText(id: 'text-1', position: const Offset(10, 20)) + ..text = 'local-a') + .toJson(), + )..putIfAbsent('elementType', () => 'text'); + container.read(activePageLiveSyncProvider.notifier).setStateForTest( + ActivePageLiveSyncState( + strategyPublicId: strategyId, + activePageId: 'page-1', + overlayByEntityKey: { + elementEntityKey('page-1', 'text-1'): ActivePageOverlayEntry( + entityKey: elementEntityKey('page-1', 'text-1'), + entityType: ActivePageOverlayEntityType.element, + desiredPayload: jsonEncode(localTextPayload), + desiredSortIndex: 0, + deletion: false, + baseRevision: 1, + dirtyAt: DateTime.now(), + ), + }, + ), + ); + + remoteNotifier.setSnapshot(headerFirstSnapshot); + await _settle(); + remoteNotifier.setSnapshot(elementsArrivedSnapshot); + await _settle(); + + final textsById = { + for (final text in container.read(textProvider)) text.id: text.text, + }; + expect(textsById['text-1'], 'local-a'); + expect(textsById['text-2'], 'remote-b-updated'); + expect(queueNotifier.flushNowCount, 0); + }); + + test('cloud agent addition queues an add op immediately', () async { + const strategyId = 'cloud-strategy'; + final snapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [ + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0), + ], + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(snapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + container.read(agentProvider.notifier).addAgent( + PlacedAgent( + id: 'agent-1', + type: AgentType.jett, + position: const Offset(120, 160), + ), + ); + await _settle(); + + final pending = container.read(strategyOpQueueProvider).pending; + expect( + pending.any( + (entry) => + entry.op.kind == StrategyOpKind.add && + entry.op.entityType == StrategyOpEntityType.element && + entry.op.entityPublicId == 'agent-1' && + entry.op.pagePublicId == 'page-1', + ), + isTrue, + ); + }); + + test('cloud map change queues a strategy patch op', () async { + const strategyId = 'cloud-strategy'; + final snapshot = _cloudSnapshot( + strategyId: strategyId, + sequence: 1, + pages: [ + _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0), + ], + ); + + final remoteNotifier = _FakeRemoteStrategySnapshotNotifier(snapshot); + final queueNotifier = _FakeStrategyOpQueueNotifier(strategyId); + final container = await _cloudContainer( + strategyState: const StrategyState( + strategyId: strategyId, + strategyName: 'Cloud Strategy', + source: StrategySource.cloud, + storageDirectory: null, + isOpen: true, + ), + remoteNotifier: remoteNotifier, + queueNotifier: queueNotifier, + ); + await container + .read(strategyPageSessionProvider.notifier) + .initializeForStrategy( + strategyId: strategyId, + source: StrategySource.cloud, + selectFirstPageIfNeeded: true, + ); + + container.read(mapProvider.notifier).updateMap(MapValue.bind); + await _settle(); + + final pending = container.read(strategyOpQueueProvider).pending; + final strategyPatch = pending + .map((entry) => entry.op) + .where( + (op) => + op.entityType == StrategyOpEntityType.strategy && + op.kind == StrategyOpKind.patch, + ) + .single; + expect( + jsonDecode(strategyPatch.payload!) as Map, + containsPair('mapData', Maps.mapNames[MapValue.bind]), + ); + }); + test('projected active-page merge prefers local overlay for touched entities', () async { const strategyId = 'cloud-strategy'; @@ -427,7 +998,8 @@ void main() { await container.read(remoteStrategySnapshotProvider.future); final localTextPayload = Map.from( - (PlacedText(id: 'text-1', position: const Offset(10, 20))..text = 'local-a') + (PlacedText(id: 'text-1', position: const Offset(10, 20)) + ..text = 'local-a') .toJson(), )..putIfAbsent('elementType', () => 'text'); container.read(activePageLiveSyncProvider.notifier).setStateForTest( @@ -462,7 +1034,8 @@ void main() { expect(textsById['text-2'], 'remote-b-updated'); }); - test('reject refresh preserves local state and queues follow-up sync', () async { + test('reject refresh preserves local state and queues follow-up sync', + () async { const strategyId = 'cloud-strategy'; final pageOne = _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); @@ -777,7 +1350,8 @@ void main() { expect(container.read(textProvider).single.text, 'before'); }); - test('pending cloud sync does not block projected active-page rehydrate', () async { + test('pending cloud sync does not block projected active-page rehydrate', + () async { const strategyId = 'cloud-strategy'; final pageOne = _remotePage(strategyId: strategyId, pageId: 'page-1', sortIndex: 0); diff --git a/test/text_widget_resilience_test.dart b/test/text_widget_resilience_test.dart index b8f9f6e7..d4c924d2 100644 --- a/test/text_widget_resilience_test.dart +++ b/test/text_widget_resilience_test.dart @@ -311,6 +311,15 @@ void main() { expect(container.read(textDraftProvider), {'text-1': 'before edited'}); expect(savedStrategy, isNotNull); expect(savedStrategy!.pages.single.textData.single.text, 'before edited'); + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const MaterialApp(home: SizedBox.shrink()), + ), + ); + await tester.pump(); + container.read(strategyProvider.notifier).cancelPendingSave(); }); testWidgets('feedback widget matches editable widget size', (tester) async { @@ -323,4 +332,104 @@ void main() { expect(feedbackSize.width, editableSize.width); expect(feedbackSize.height, editableSize.height); }); + + testWidgets('text widget starts single-line and grows instead of scrolling', + (tester) async { + final container = createContainer(); + container.read(textProvider.notifier).fromHive([ + PlacedText( + id: 'text-1', + position: const Offset(10, 20), + size: 80, + fontSize: 16, + sizeVersion: worldSizedMediaVersion, + )..text = 'ew', + ]); + + await tester.pumpWidget(buildTextHarness(container)); + await tester.pump(); + + final initialSize = tester.getSize(find.byType(TextWidget)); + expect(initialSize.height, lessThan(64)); + + await tester.enterText( + find.byType(TextField), + 'this text is long enough to wrap across several lines in the editor', + ); + await tester.pump(); + + final wrappedSize = tester.getSize(find.byType(TextWidget)); + expect(wrappedSize.height, greaterThan(initialSize.height)); + + final scrollableFinder = find.descendant( + of: find.byType(TextField), + matching: find.byType(Scrollable), + ); + final scrollableState = + tester.state(scrollableFinder.first); + final scrollable = tester.widget(scrollableFinder.first); + expect(scrollable.axisDirection, AxisDirection.down); + expect( + scrollableState.position.maxScrollExtent, + 0, + reason: 'wrappedSize=$wrappedSize', + ); + }); + + testWidgets('side switch mirrors text with deterministic widget bounds', + (tester) async { + final container = createContainer(); + final placedText = PlacedText( + id: 'text-1', + position: const Offset(10, 20), + size: 220, + fontSize: 16, + sizeVersion: worldSizedMediaVersion, + )..text = 'same text\nsecond line'; + + container.read(textProvider.notifier).fromHive([placedText]); + await tester.pumpWidget(buildTextHarness(container)); + await tester.pump(); + + final renderedSize = tester.getSize(find.byType(TextWidget)); + + container.read(textProvider.notifier).switchSides(); + + expect( + container.read(textProvider).single.position, + getFlippedPosition( + position: placedText.position, + scaledSize: Offset(renderedSize.width, renderedSize.height), + ), + ); + }); + + testWidgets( + 'side switch uses deterministic rendered text height for vertical placement', + (tester) async { + final container = createContainer(); + final placedText = PlacedText( + id: 'text-1', + position: const Offset(10, 20), + size: 220, + fontSize: 16, + sizeVersion: worldSizedMediaVersion, + )..text = 'one line'; + + container.read(textProvider.notifier).fromHive([placedText]); + await tester.pumpWidget(buildTextHarness(container)); + await tester.pump(); + + final renderedSize = tester.getSize(find.byType(TextWidget)); + + container.read(textProvider.notifier).switchSides(); + + expect( + container.read(textProvider).single.position, + getFlippedPosition( + position: placedText.position, + scaledSize: Offset(renderedSize.width, renderedSize.height), + ), + ); + }); }