Repository navigation
[Grida Canvas] Image Playground Canvas - #276
Conversation
Review or Edit in CodeSandboxOpen the branch in Web Editor • VS Code • Insiders |
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
9 Skipped Deployments
|
WalkthroughThis update introduces edge and network graph support to the canvas editor, expands AI image generation capabilities with flexible sizing and aspect ratios, adds a comprehensive AI model catalog, and modularizes the chat box UI. New hooks, types, and components are added for session management, authentication flows, and improved document initialization. Numerous UI and infrastructure refinements are included. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CanvasEditor
participant AIImageAPI
participant RateLimiter
participant ImageModelResolver
User->>CanvasEditor: Request AI image (prompt, size, aspect_ratio)
CanvasEditor->>ImageModelResolver: Resolve model & metadata
CanvasEditor->>RateLimiter: Check credits (model.avg_credit)
RateLimiter-->>CanvasEditor: Allow/Reject
alt Allowed
CanvasEditor->>AIImageAPI: Generate image (with prompt, size/aspect)
AIImageAPI-->>CanvasEditor: Return image bytes
CanvasEditor->>CanvasEditor: Extract actual image dimensions
CanvasEditor-->>User: Insert image node with accurate metadata
else Rejected
CanvasEditor-->>User: Show rate limit/credit error
end
sequenceDiagram
participant User
participant CanvasEditor
participant NetworkOverlay
User->>CanvasEditor: Add nodes and connect with edge
CanvasEditor->>NetworkOverlay: Render edges between nodes
NetworkOverlay->>CanvasEditor: Compute anchor positions
NetworkOverlay-->>User: Display Bezier curves/arrows between nodes
Possibly related PRs
Suggested labels
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 15
🔭 Outside diff range comments (1)
editor/app/(api)/private/ai/generate/image/route.ts (1)
205-226: 🛠️ Refactor suggestionParameter mismatch across providers
OpenAI accepts a fixed
sizestring, Replicate models often require explicitwidth/heightoraspect_ratio. The current logic passes bothsize&aspectRatiounconditionally, which may be silently ignored or error depending on SDK implementation. It would be safer to branch bymodel.provider.- size: size, - aspectRatio: aspect_ratio, + ...(model.provider === "openai" && size ? { size } : {}), + ...(model.provider === "replicate" + ? { width, height, aspectRatio: aspect_ratio } + : {}),
🧹 Nitpick comments (34)
editor/app/(dev)/playground/image/_components/image-frame.tsx (1)
35-39: Re-enable exhaustive-deps or memoizepause: Suppressingreact-hooks/exhaustive-depshides missing dependency warnings, butpauseshould be either included in the dependency array or guaranteed stable. For example, addpauseto the deps:-useEffect(() => { if (image) { pause(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [image]); +useEffect(() => { if (image) { pause(); } }, [image, pause]);This prevents stale closures and maintains lint compliance.
editor/grida-react-canvas/api.md (2)
1-3: Consolidate document heading: The file declares# API - Working draftand then repeats the title in plain text. Retain a single level-1 heading and remove duplicate text for clarity:# API - Working Draft for Grida React CanvasThis streamlines the document structure.
5-5: Use heading syntax instead of emphasis: Replace**Insert custom node**with a proper markdown heading (e.g.,### Insert Custom Node) to improve semantics and accessibility.🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
5-5: Emphasis used instead of a heading
null(MD036, no-emphasis-as-heading)
editor/scaffolds/playground-canvas/playground.tsx (2)
898-908: TODO marked for API integrationThe TODO indicates a plan to refactor this function to use the Grida library API. This is a good practice to document future improvements.
Consider adding more specificity to the TODO comment, such as which API method to use and potentially a JIRA/GitHub issue reference for tracking.
910-930: TODO marked for API integrationSimilar to the previous TODO, this marks a function for future refactoring to use the Grida library API.
For better maintainability and to avoid duplication, consider moving both functions to a utility file that could be imported by this component until the refactoring is complete.
editor/app/(api)/private/ai/ratelimit.ts (2)
21-21: Good enhancement for variable cost rate limiting.The parameter addition to
ai_credit_limitand the implementation of therateoption allow for dynamic credit consumption based on the specific AI model's cost rather than treating all operations equally.This approach is more fair and efficient - it enables fine-grained control over resource allocation where expensive operations consume more credits than simple ones.
Also applies to: 30-31
7-7:Details
❓ Verification inconclusive
Significant rate limit increase.
The sliding window limit has been increased from 20 to 500 over a 30-day period. This is a 25x increase in allowed AI operations. Ensure this aligns with your infrastructure capacity and business model.
🏁 Script executed:
#!/bin/bash # Check for any related infrastructure capacity planning documentation fd -t f "capacity|planning|infrastructure" -e md -e txt | xargs cat | grep -i "rate limit\|ai credit\|usage projection"Length of output: 121
Evaluate Infrastructure Capacity for Increased AI Rate Limit
The sliding window limit was raised from 20 to 500 over a 30-day period (a 25× increase). Please confirm this aligns with your infrastructure throughput, cost model, and upstream API allowances:
- Coordinate with SRE/DevOps to validate queuing, database load, and network bandwidth under the new cap.
- Update or create internal capacity-planning documentation to reflect the change.
- Adjust monitoring and alerting thresholds for AI usage to catch unexpected spikes.
editor/services/new/index.ts (1)
15-15: Unused import added.The
GridFileStorageQueueProvideris imported but not used in this file. Either remove the unused import or document why it's needed.-import { GridFileStorageQueueProvider } from "@/scaffolds/grid/providers";editor/scaffolds/auth/continue-with-auth-dialog.tsx (1)
32-32: Add alt text to GridaLogo for better accessibility.The GridaLogo is missing an alt text attribute. While it appears to be decorative in this context, it's a good practice to add an alt attribute for screen readers.
- <GridaLogo className="h-8 w-8" /> + <GridaLogo className="h-8 w-8" aria-label="Grida logo" />editor/hooks/use-pending-callback.tsx (1)
58-64: Remove unnecessary catch clause.The catch clause that only rethrows the original error is redundant and can be removed.
try { setState((prev) => ({ ...prev, isExecuting: true })); await state.callback(); - } catch (error) { - // Let the error propagate up - throw error; } finally { setState({ callback: null, isExecuting: false }); }🧰 Tools
🪛 Biome (1.9.4)
[error] 63-63: The catch clause that only rethrows the original error is useless.
An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.(lint/complexity/noUselessCatch)
editor/lib/ai/hooks/use-generate-image.ts (1)
73-80: Consider adding error state to the returned object.The hook returns various states but doesn't include any error state that consumers could use to display error messages.
+ const [error, setError] = useState<Error | null>(null); // In the catch block of the generate function: + setError(error); return { key, loading, image, start, end, generate, + error, };editor/app/(www)/(ai)/ai/models/page.tsx (2)
108-124: Style-badge “+N more” does not convey full list accessThe “+N more” badge is not interactive, so users cannot discover the hidden styles.
Consider wrapping it in aHoverCard(or linking to a detail page) to preserve discoverability and accessibility.
163-170: Minor type-guard optimisationThe inline
filtercallback redundantly checks for!== undefined;Object.values<T>(models)already returnsT[], not(T | undefined)[], ifmodelsis typed as a record.
Ifmodelsreally can containundefined, prefer narrowing once and memoising, e.g. withuseMemo, to avoid filtering on every render.editor/scaffolds/auth/use-continue-with-auth.tsx (1)
70-81: Modal can leave unresolved PromisesIf the user closes the dialog without authenticating, the Promise returned by
withAuthneither resolves nor rejects, potentially hanging UI flows.
Provide a rejection path inonOpenChange={setIsOpen}whenopenbecomesfalseand!session.editor/scaffolds/auth/continue-with-google-button.tsx (1)
31-33: Accessibility: addaria-labelThe button has no accessible name beyond its text. Adding an
aria-label="Continue with Google"(or wrapping in<Button>from your design system) ensures assistive technologies recognise it if icon/text order changes.editor/grida-react-canvas/provider.tsx (1)
1431-1433: Add JSDoc comment for the createNodeId function.The implementation of
createNodeIdis straightforward, but it would benefit from JSDoc documentation explaining its purpose and usage. This is particularly important since it's being exposed as part of the public API.+ /** + * Creates a unique node ID for use when creating new nodes in the document. + * @returns A unique string ID + */ const createNodeId = useCallback(() => { return nid(); }, []);editor/grida-react-canvas/viewport/ui/network-curve.tsx (4)
1-6: Proper imports for network curve component.The component correctly imports the necessary dependencies, but there are commented-out imports that should either be implemented or removed to keep the codebase clean.
import { cmath } from "@grida/cmath"; -// import { color_connection_line } from "../theme"; -// import { get_direction } from "./math"; import { NetworkArrow } from "./network-arrow"; import { cn } from "@/utils";
7-54: Clean implementation of the BezierCurvedLine component.The component is well-structured for rendering a curved line between two points, with an arrow at the end. However, there are commented-out code lines (lines 20, 31, 41, 50) that should be cleaned up.
The component also uses hardcoded values for the arrow size (12) and direction ("e"), which could be made configurable via props for more flexibility.
export function BezierCurvedLine({ id, a, b, width = 2, className, + arrowSize = 12, + arrowDirection = "e", }: { id?: string; width?: number; className?: string; a: cmath.Vector2; b: cmath.Vector2; + arrowSize?: number; + arrowDirection?: "n" | "s" | "e" | "w"; }) { - // const direction = get_direction(a, b); return ( <svg id={id} fill="transparent" style={{ overflow: "visible", position: "absolute", pointerEvents: "none", - // transform: `translate(${a[0]}px, ${a[1]}px)`, zIndex: 10, }} className={cn("text-foreground", className)} > <path strokeWidth={width} d={make_bazier_curved_svg_path_data( a, b, "x" - // direction_to_axis_map[direction] )} className="stroke-current" /> <NetworkArrow - size={12} + size={arrowSize} b={b} width={width} - direction="e" + direction={arrowDirection} - // direction={direction} /> </svg> ); }
56-61: Unused direction to axis mapping.This mapping is currently unused as the related code is commented out. It should either be used or removed to avoid dead code.
-const direction_to_axis_map = { - n: "v", - s: "v", - e: "h", - w: "h", -} as const;
80-98: Fix typo in function name "bazier" → "bezier".The helper function has a typo in its name:
make_bazier_curved_svg_path_datashould bemake_bezier_curved_svg_path_data.-function make_bazier_curved_svg_path_data( +function make_bezier_curved_svg_path_data( a: cmath.Vector2, b: cmath.Vector2, axis: "x" | "y" = "x" ) { // function implementation... }And update the function call in the component:
d={make_bezier_curved_svg_path_data( a, b, "x" )}editor/lib/ai/hooks/use-image-model.ts (1)
30-87: Comprehensive size parsing and validation logic.The
setSizefunction handles multiple input formats flexibly and validates against the model's supported sizes. However, there's an unused variable declaration that should be cleaned up.In the
setSizefunction, you declare local variables_width,_height, and_aspect_ratiothat are used for parsing, but then you also declarewidth,height, andaspect_ratiofor validation. The latter set is correctly used in the final state update. You could simplify this by using only one set of variables:- let _width: number | null = null; - let _height: number | null = null; - let _aspect_ratio: ai.image.AspectRatioString | null = null; let width: number | null = null; let height: number | null = null; let aspect_ratio: ai.image.AspectRatioString | null = null; // parse size if (typeof size === "string") { if (size.includes("x")) { const [widthStr, heightStr] = size.split("x"); - _width = parseInt(widthStr); - _height = parseInt(heightStr); + width = parseInt(widthStr); + height = parseInt(heightStr); } else if (size.includes(":")) { - _aspect_ratio = size as ai.image.AspectRatioString; + aspect_ratio = size as ai.image.AspectRatioString; } } else if (typeof size === "object") { if ("width" in size && "height" in size) { - _width = size.width; - _height = size.height; + width = size.width; + height = size.height; } else if ("aspect_ratio" in size) { - _aspect_ratio = size.aspect_ratio as ai.image.AspectRatioString; + aspect_ratio = size.aspect_ratio as ai.image.AspectRatioString; } } // validate size if (card.sizes) { const _size = card.sizes?.find(([w, h, r]) => { - return (w === _width && h === _height) || r === _aspect_ratio; + return (w === width && h === height) || r === aspect_ratio; }); if (_size) { const [w, h, r] = _size; width = w; height = h; aspect_ratio = r; } }editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1)
52-70: Parameter naming can be misleading & path is left open
The helper receives
{ width, height }but internallyconst w = width / 2;– so width actually ends up as “full arrow width”, whilewis half of that.
A more explicit variable name (halfWidth) would make this clearer.Because the path is not closed (
Z), usingfillin CSS will produce an empty shape.
If arrows are ever meant to be filled, addZor usestrokeLinejoin="round"for aesthetics.Example diff:
-const w = width / 2; +const halfWidth = width / 2; ... - return `M${x - height},${y + w} L${x},${y} L${x - height},${y - w}`; + return `M${x - height},${y + halfWidth} L${x},${y} L${x - height},${y - halfWidth} Z`;editor/grida-react-canvas/viewport/surface.tsx (1)
332-339: Forced horizontal scroll reset may thrash layout
onScroll={(e) => (e.target as HTMLDivElement).scrollLeft = 0}is executed on every scroll tick, creating an immediate additionalscrollevent and potentially hurting performance.If horizontal scrolling should be disabled, prefer CSS:
overscroll-behavior-x: contain; /* already present */ overflow-x: hidden; /* instead of 'scroll' */or guard the assignment:
if (et.scrollLeft !== 0) et.scrollLeft = 0;editor/lib/ai/ai.ts (1)
82-87: Consider marking thedefaultsize asreadonlyThe
defaultsize tuple represents static metadata – making it immutable prevents accidental runtime mutation:- default: { + readonly default: {editor/grida/index.ts (4)
289-307: Edge schema lacks direction info & immutable guards
Edge2Dcurrently stores only two points. For future routing, you may need areadonly direction?: "undirected" | "directed"flag (or similar metadata) andreadonlyqualifiers on immutable fields (id,type). Adding them now avoids a breaking change later.export interface Edge2D { - id: string; - readonly type: "edge"; + readonly id: string; + readonly type: "edge"; + direction?: "undirected" | "directed";
454-458: Minor: allow callers to pre-seed edges
init_scenealways overridesedgeswith a new empty array, ignoring a providedinit.edges. Consider using the same pattern used forchildren:-edges: [], +edges: init.edges ?? [],
950-956: Prototype_ $idshould be namespaced or symbol-basedExposing
_$idin public typings risks accidental persistence when prototypes are serialised.
Using a brandedSymbol('prototypeId')avoids key-collision and keeps the field non-enumerable.
2056-2085:createContainerNodehelper – expose padding object support
paddingis initialised to0, but the interface allows an object form. Accepting{ paddingTop, ... }inpartialand normalising internally would improve ergonomics.editor/app/(api)/private/ai/generate/image/route.ts (1)
52-56: Race-condition: credit consumption before generation successCredits are decremented (
ai_credit_limit) before the generation call. If the generation fails (network error, model quota), the user still loses credits. Consider performing the credit deduction only after successful generation, or refund on failure.editor/components/chat/chatbox.tsx (2)
198-207: IME / composition input is not respected
Enteris intercepted unconditionally for submission. While!e.shiftKeyguards multi-line input, it still fires while the user is composing characters (e.g. Korean, Japanese) causing premature submission.- if (e.key === "Enter" && !e.shiftKey) { + if ( + e.key === "Enter" && + !e.shiftKey && + !e.nativeEvent.isComposing + ) {A tiny change, but it prevents a frustrating UX for CJK users.
248-261: Submit button ignores globaldisabledstate in UI
ChatBoxSubmitdisables the<Button>but the icon’s color/state remains unchanged, giving no visual cue. Consider using thevariant="secondary"or reducing opacity whendisabledis true so users instantly understand the form is busy.editor/app/(dev)/playground/image/_page.tsx (3)
24-26: Unused importGenerationImageFrame—will fail theno-unused-varslint rule
GenerationImageFrameisn’t referenced after the refactor. Remove the import to keep the build green.-import { GenerationImageFrame } from "./_components/image-frame";
131-132: Destructured valueskey,image,start,endare no longer used
const { generate, key, loading, image, start, end } = useGenerateImage();Only
generateandloadingare referenced later. Unused symbols will trigger TypeScript/ESLint errors and incur unnecessary re-renders.-const { generate, key, loading, image, start, end } = useGenerateImage(); +const { generate, loading } = useGenerateImage();
370-374: Spelling nit:Hotkyes→HotkeysSmall typo in component name; correcting improves readability and discoverability.
-function Hotkyes() { +function Hotkeys() {Remember to update the JSX
<Hotkyes />invocation above.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (45)
editor/app/(api)/private/ai/generate/image/route.ts(5 hunks)editor/app/(api)/private/ai/ratelimit.ts(3 hunks)editor/app/(dev)/canvas/examples/[example]/page.tsx(1 hunks)editor/app/(dev)/canvas/examples/network/page.tsx(1 hunks)editor/app/(dev)/canvas/minimal/page.tsx(2 hunks)editor/app/(dev)/canvas/tools/ai/page.tsx(2 hunks)editor/app/(dev)/canvas/tools/transparency-grid/page.tsx(1 hunks)editor/app/(dev)/playground/image/_components/image-frame.tsx(1 hunks)editor/app/(dev)/playground/image/_page.tsx(3 hunks)editor/app/(dev)/playground/image/page.tsx(2 hunks)editor/app/(workbench)/[org]/[proj]/[id]/canvas/page.tsx(0 hunks)editor/app/(www)/(ai)/ai/models/page.tsx(1 hunks)editor/app/sitemap.ts(2 hunks)editor/components/chat/chatbox.tsx(2 hunks)editor/components/chat/index.ts(1 hunks)editor/components/chat/minimal-chatbox.tsx(1 hunks)editor/grida-react-canvas/action.ts(1 hunks)editor/grida-react-canvas/api.md(1 hunks)editor/grida-react-canvas/provider.tsx(7 hunks)editor/grida-react-canvas/renderer.tsx(1 hunks)editor/grida-react-canvas/state.ts(2 hunks)editor/grida-react-canvas/viewport/surface.tsx(5 hunks)editor/grida-react-canvas/viewport/ui/network-arrow.tsx(1 hunks)editor/grida-react-canvas/viewport/ui/network-curve.tsx(1 hunks)editor/grida/index.ts(9 hunks)editor/grida/mixed/index.ts(1 hunks)editor/hooks/use-pending-callback.tsx(1 hunks)editor/lib/ai/ai.ts(5 hunks)editor/lib/ai/hooks/index.ts(1 hunks)editor/lib/ai/hooks/use-credits.ts(1 hunks)editor/lib/ai/hooks/use-generate-image.ts(1 hunks)editor/lib/ai/hooks/use-image-model.ts(1 hunks)editor/lib/supabase/use-session.ts(1 hunks)editor/package.json(2 hunks)editor/scaffolds/auth/continue-with-auth-dialog.tsx(1 hunks)editor/scaffolds/auth/continue-with-google-button.tsx(2 hunks)editor/scaffolds/auth/use-continue-with-auth.tsx(1 hunks)editor/scaffolds/playground-canvas/playground.tsx(2 hunks)editor/services/new/index.ts(2 hunks)editor/www/data/sitemap.ts(1 hunks)editor/www/footer.tsx(1 hunks)editor/www/header-cta.tsx(1 hunks)editor/www/header.tsx(4 hunks)packages/grida-canvas-io-figma/lib.ts(1 hunks)packages/grida-cmath/index.ts(1 hunks)
💤 Files with no reviewable changes (1)
- editor/app/(workbench)/[org]/[proj]/[id]/canvas/page.tsx
🧰 Additional context used
🧬 Code Graph Analysis (14)
editor/app/(dev)/playground/image/page.tsx (1)
editor/app/(dev)/playground/image/_page.tsx (1)
ImagePlayground(71-123)
editor/www/footer.tsx (2)
editor/kits/minimal-tiptap/extensions/link/link.ts (1)
Link(7-97)editor/app/sitemap.ts (1)
sitemap(3-116)
editor/app/(dev)/canvas/tools/ai/page.tsx (1)
editor/components/chat/minimal-chatbox.tsx (1)
MinimalChatBox(15-49)
editor/grida-react-canvas/renderer.tsx (2)
packages/grida-canvas-transparency-grid/component.tsx (1)
TransparencyGrid(14-49)packages/grida-cmath/index.ts (2)
transform(831-839)transform(1277-1313)
editor/lib/supabase/use-session.ts (1)
editor/lib/supabase/client.ts (1)
createBrowserClient(22-23)
editor/components/chat/minimal-chatbox.tsx (2)
editor/lib/file/index.ts (1)
BucketFileUploaderFn(51-51)editor/components/chat/chatbox.tsx (7)
ChatBox(266-266)ChatBoxHeader(267-267)ChatBoxAttachmentPreview(271-271)ChatBoxTextArea(269-269)ChatBoxFooter(268-268)ChatBoxAttachmentUploader(270-270)ChatBoxSubmit(272-272)
editor/scaffolds/auth/continue-with-auth-dialog.tsx (2)
desktop/src/components/grida-logo.tsx (1)
GridaLogo(3-30)editor/scaffolds/auth/continue-with-google-button.tsx (1)
ContinueWithGoogleButton(13-81)
editor/www/header.tsx (1)
editor/www/header-cta.tsx (1)
HeaderCTA(8-21)
editor/grida-react-canvas/viewport/ui/network-curve.tsx (2)
editor/grida/index.ts (1)
Vector2(2101-2101)editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1)
NetworkArrow(5-34)
editor/grida-react-canvas/state.ts (1)
editor/grida/index.ts (3)
Document(392-395)IBitmapsRepository(261-268)Scene(409-438)
editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1)
editor/grida/index.ts (1)
Vector2(2101-2101)
editor/app/(api)/private/ai/generate/image/route.ts (2)
editor/lib/ai/ai.ts (5)
AspectRatioString(60-60)ProviderModel(12-20)ImageModelId(58-58)ImageModelCard(66-87)SizeString(62-62)editor/app/(api)/private/ai/ratelimit.ts (1)
ai_credit_limit(21-47)
editor/components/chat/chatbox.tsx (1)
editor/lib/file/index.ts (1)
BucketFileUploaderFn(51-51)
editor/grida/index.ts (2)
editor/grida-react-canvas/document-query.ts (1)
nodes(586-588)packages/grida-canvas-io-figma/lib.ts (1)
document(178-244)
🪛 markdownlint-cli2 (0.17.2)
editor/grida-react-canvas/api.md
5-5: Emphasis used instead of a heading
null
(MD036, no-emphasis-as-heading)
🪛 Biome (1.9.4)
editor/hooks/use-pending-callback.tsx
[error] 63-63: The catch clause that only rethrows the original error is useless.
An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.
(lint/complexity/noUselessCatch)
[error] 6-6: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 6-6: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 16-16: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 16-16: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 40-40: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 40-40: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
🔇 Additional comments (58)
editor/package.json (2)
146-146: LGTM: Adding image-size dependency.The addition of the
image-sizepackage is appropriate for handling image dimension extraction functionality, which will be used for determining the width and height of generated images.
253-253: LGTM: Simplified pnpm configuration.The removal of the empty nested
"overrides": {}property simplifies the configuration while maintaining the same functionality.editor/lib/supabase/use-session.ts (1)
1-24: Well-structured authentication session hook implementation.This new hook effectively manages Supabase authentication sessions with proper React patterns:
- Memoized client creation prevents unnecessary re-renders
- Appropriate subscription cleanup in the effect's return function
- Correct dependency array for the useEffect
- Clean type safety with the Session type
The implementation follows best practices for React hooks working with external services.
editor/app/(dev)/canvas/examples/[example]/page.tsx (1)
4-4: LGTM: Import order adjustment.The repositioning of the import statement is a minor stylistic change that doesn't affect functionality. It simply aligns the import order with conventions used in other example pages.
editor/www/footer.tsx (1)
87-92: LGTM: New AI Models link added to Resources section.The addition of the AI Models link follows the existing pattern for footer links, with consistent styling and proper navigation path. This link provides users with direct access to the new AI Models catalog page.
editor/www/data/sitemap.ts (1)
10-10: Newai_modelssitemap link added: The new entryai_models: "/ai/models"correctly reflects the AI Models catalog route. Verify this link is utilized in the footer and any other navigation components to ensure discoverability of the AI Models page.editor/app/(dev)/canvas/tools/ai/page.tsx (2)
13-13: ImportMinimalChatBoxinstead ofChatBox: Updating this import toMinimalChatBoxaligns with the modular chat UI refactor. Ensure no unusedChatBoximports remain in this or related files.
190-195: Replace<ChatBox>with<MinimalChatBox>: The usage ofMinimalChatBoxmaintains prop compatibility while leveraging the slimmed-down chat interface. Confirm thatonValueCommit,uploader, andacceptbehavior match expectations and update any associated styles if needed.editor/components/chat/index.ts (1)
2-2: Re-exportMinimalChatBox: ExposingMinimalChatBoxvia the chat index streamlines imports across the app. Confirm the public API surface is documented and update any references in the docs or code samples accordingly.editor/lib/ai/hooks/index.ts (1)
1-3: Module export organization looks good.The index file provides a clean central point for importing AI-related hooks throughout the application.
editor/grida-react-canvas/renderer.tsx (1)
117-122: Always rendering TransparencyGrid improves visual consistency.This modification ensures the transparency grid is always visible, which enhances visual clarity for complex scenes with nodes and edges, aligning with the network graph visualization objectives of this PR.
editor/grida-react-canvas/action.ts (1)
553-556: Adding optional ID support for node prototypes enables better graph management.The optional
idparameter allows for explicit node identification during insertion, which is essential for managing edges and references between nodes in network graphs.editor/app/(dev)/canvas/tools/transparency-grid/page.tsx (1)
40-57: Nice UI enhancements for transparency grid controls.The addition of a control panel with a Reset button and display of current zoom/offset values improves usability of the demo. The panel is well-positioned and provides useful feedback to users.
editor/grida/mixed/index.ts (1)
98-99: Good defensive programming!Adding the nullish coalescing operator (
??) to handle potential null or undefined values in the objects array prevents runtime errors when callingObject.keys(). This makes the code more robust against unexpected input.packages/grida-canvas-io-figma/lib.ts (1)
235-236: Added edges support for network graphsAdding the empty
edgesarray property to the scene document structure is a good first step for supporting network graph rendering between nodes as mentioned in the PR objectives.editor/app/(dev)/playground/image/page.tsx (2)
3-4: Added necessary UI providersAdding imports for sidebar and tooltip providers is essential for the enhanced UI functionality in the image playground.
13-19: Improved component structure with context providersWrapping the
ImagePlaygroundcomponent withTooltipProviderandSidebarProviderproperly establishes the UI context hierarchy, ensuring tooltip and sidebar functionality is available throughout the component tree.editor/app/sitemap.ts (2)
90-94: Added new AI models section to sitemap.This addition aligns with the expanded AI image generation capabilities mentioned in the PR summary, providing SEO discoverability for the new AI model catalog.
18-18:Details
❓ Verification inconclusive
Reduced crawl frequency for several sections.
The change frequency for multiple site sections has been reduced (e.g., blog from weekly to monthly, tools from daily to yearly). This could reduce your site's search engine freshness if these sections are actually updated more frequently than the new settings indicate.
Also applies to: 97-97, 102-102, 107-107, 112-112
🏁 Script executed:
#!/bin/bash # Check update frequency of these sections by looking at commit history echo "Checking update frequency for blog content:" git log --since="3 months ago" --name-only --pretty=format: | grep -i "blog" | sort | uniq -c | sort -nr | head -5 echo -e "\nChecking update frequency for tools content:" git log --since="6 months ago" --name-only --pretty=format: | grep -i "tools" | sort | uniq -c | sort -nr | head -5Length of output: 201
Confirm content update cadence before finalizing crawl settings
Commit history shows no changes to “blog” files in the last 3 months or “tools” files in the last 6 months, so the reduced
changeFrequencyvalues (monthly for blog, yearly for tools) match the repo’s activity. However, if these sections are updated via an external CMS or other processes not captured in Git, please verify their true update cadence before shipping.• Files to review:
- editor/app/sitemap.ts (lines 18, 97, 102, 107, 112)
editor/services/new/index.ts (1)
254-261: Improved scene initialization approach.Simplified the scene initialization by removing explicit properties and relying on the
init_scenefunction to provide defaults. This follows the principle of having a single source of truth for initialization logic.This change supports the PR objective of introducing edge and network graph support to the canvas editor by centralizing initialization logic that may now include edge-related defaults.
editor/app/(dev)/canvas/examples/network/page.tsx (3)
1-5: Good imports and module organization.Clean imports and proper organization of modules. You're correctly importing both the editor component and the necessary utilities from
gridaandcmathlibraries.
6-46: Well-structured document initialization with edge support.The document structure is well-defined, demonstrating the new edge/network graph functionality. The nodes and their connection are clearly specified.
Note that you've included commented-out code on lines 25-26 that shows an alternative way to define edge connections using absolute positions instead of anchors. Consider either removing these comments if they're not needed or adding a brief explanation comment about why both approaches are shown.
48-54: Clean component implementation.The page component follows React best practices and properly renders the full-screen editor with the demo network graph.
packages/grida-cmath/index.ts (1)
3296-3320: Enhanced support for RGBA colors in hex format.Your implementation now correctly handles 8-character hex strings (#RRGGBBAA) for colors with alpha channel. The alpha value is properly normalized from 0-255 to a 0-1 range.
The error message has been appropriately updated to include the new supported format. This enhancement improves color handling for the canvas by supporting transparency, which is essential for the network graph feature.
editor/www/header-cta.tsx (2)
1-21: Well-structured authentication-aware header component.The
HeaderCTAcomponent cleanly handles user authentication state using theuseSessionhook. The conditional rendering for showing the "Sign in" button only for unauthenticated users is implemented well, and I like the responsive design consideration with thehidden md:blockclass.
23-37: Clear conditional CTA rendering based on auth state.The internal
CTAcomponent follows a clean pattern for conditional rendering based on authentication state. It directs users to either the dashboard (if signed in) or the general CTA page (if not signed in).editor/components/chat/minimal-chatbox.tsx (3)
1-14: Good component imports and organization.The imports are well-organized, bringing in all necessary chat box subcomponents. This demonstrates good modularity and component composition approach.
15-29: Well-typed props interface with reasonable defaults.The component has a clear props interface with appropriate TypeScript types. The default placeholder text is sensible, and optional props are correctly marked with question marks.
30-49: Clean component composition pattern.The component follows an excellent composition pattern, assembling smaller focused components into a cohesive UI. The structure with header, text area, and footer is logical and makes the code easy to understand and maintain.
This approach of composing specialized components rather than a monolithic implementation enhances maintainability and reusability. It allows for more flexibility in how the chat UI can be customized in different contexts.
editor/scaffolds/auth/continue-with-auth-dialog.tsx (3)
14-18: Great interface design for auth props.The interface is well-defined with optional properties that allow for flexible authentication configurations.
20-26: Well-implemented dialog component with proper prop handling.The component properly extends Dialog props and handles authentication-specific parameters in a clean way. The usage of skipBrowserRedirect with the Google login button enables a popup-based auth flow that doesn't navigate away from the current page, which improves user experience.
Also applies to: 28-48
4-4:Details
❌ Incorrect review comment
Check default import path for GridaLogo component.
The import for
GridaLogouses a path alias@/components/grida-logo, but based on the relevant code snippets provided, this component seems to be located indesktop/src/components/grida-logo.tsx. Ensure the path alias is correctly configured in your project to resolve to the right location.
🏁 Script executed:
#!/bin/bash # Verify if GridaLogo component is accessible from the imported path find . -name "grida-logo.tsx" | grep -v "node_modules"Length of output: 172
🏁 Script executed:
#!/bin/bash # Locate and inspect path aliases in TypeScript/JS configs echo "=== editor/tsconfig.json ===" if [ -f editor/tsconfig.json ]; then grep -R -n '"paths"\|"baseUrl"' -C3 editor/tsconfig.json || echo " (no alias config found)" else echo " editor/tsconfig.json not found" fi echo echo "=== tsconfig.json (root) ===" if [ -f tsconfig.json ]; then grep -R -n '"paths"\|"baseUrl"' -C3 tsconfig.json || echo " (no alias config found)" else echo " tsconfig.json not found" fiLength of output: 428
Import path for GridaLogo is correctly configured
The editor’stsconfig.jsonmaps@/*→./*, soimport { GridaLogo } from "@/components/grida-logo";resolves toeditor/components/grida-logo.tsx, which exists. No changes needed.Likely an incorrect or invalid review comment.
editor/app/(dev)/canvas/minimal/page.tsx (4)
41-41: Component name improvement.The component has been renamed from
CanvasPlaygroundtoMinimalCanvasDemo, which better reflects its purpose as a minimal demonstration of canvas functionality.
75-81: Clean sidebar implementation.The sidebars are now implemented as floating elements that are siblings of the main canvas container rather than being nested inside. This simplifies the DOM hierarchy while maintaining the same functionality.
Also applies to: 101-122
82-82: Improved layout structure.The container div now uses fixed positioning covering the entire viewport, which simplifies the layout structure while maintaining the full-screen canvas experience.
83-99: Well-structured editor surface composition.The editor surface composition maintains a logical hierarchy of components with proper nesting of clipboard sync, dropzone, context menu, viewport root, and other UI elements.
editor/hooks/use-pending-callback.tsx (2)
23-39: Great example documentation.The JSDoc comment includes a clear example that demonstrates how to use the hook, which is very helpful for developers.
49-67: Well-implemented state management.The hook properly maintains state for the callback and execution status, preventing concurrent executions of the same callback.
🧰 Tools
🪛 Biome (1.9.4)
[error] 63-63: The catch clause that only rethrows the original error is useless.
An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.(lint/complexity/noUselessCatch)
editor/lib/ai/hooks/use-generate-image.ts (1)
16-21: Well-structured state management.The hook uses separate state variables for different aspects of the image generation process, making the code easier to understand and maintain.
editor/scaffolds/auth/use-continue-with-auth.tsx (1)
55-67: Effect cleanup resetshasHandledSessionevery renderBecause the cleanup function sets
hasHandledSession.current = false, togglingsessionfrom truthy → truthy (token refresh) will re-runhandleAuthSuccesseven though no user action occurred.
Consider tying the flag to a specificpendingState.idor removing the reset unless a new pending callback is queued.editor/scaffolds/auth/continue-with-google-button.tsx (1)
6-12:redirect_urivsredirectTomismatchSupabase expects
options.redirectTo; the additionalredirect_urisearch param may be redundant or conflict with backend handling.
Verify that/auth/callbackpropagates the intended redirect and remove unused query keys to avoid open-redirect risks.editor/grida-react-canvas/provider.tsx (4)
39-39: Clean import of node ID generator utility.The import of the
nidutility is appropriately placed at the top of the file with other imports.
2005-2005: API extension to expose node ID creation functionality.Exposing the
createNodeIdfunction in the hook's return value enables consumers to generate consistent node IDs, which is necessary for the new edge connection functionality.
2391-2391: Including edges from scene in useEventTarget hook.Properly destructuring the
edgesproperty from the scene object to make it available within the hook.
2835-2835: Exposing edges through the useEventTarget hook return value.This change appropriately exposes the
edgesproperty to consumers of theuseEventTargethook, enabling integration with the network graph rendering system.editor/www/header.tsx (3)
1-22: Clean up imports and refactor session management.Good refactoring to separate concerns by importing the dedicated
HeaderCTAcomponent instead of managing session state directly in the header component.
51-53: Improved header container layout.The layout adjustments simplify the markup structure while maintaining the same visual presentation.
123-123: Delegate call-to-action rendering to specialized component.Using the
HeaderCTAcomponent here improves separation of concerns and makes the header component more focused on its primary responsibility of navigation.editor/lib/ai/hooks/use-image-model.ts (3)
1-9: Well-defined default image size configuration.The default size configuration is appropriately defined with type safety for the aspect ratio string.
11-29: Clean implementation of model selection and state management.The hook follows React patterns for state management and provides a clean
selectcallback for model switching. The state initialization with the default model is well-implemented.
89-98: Clean and comprehensive hook return API.The hook returns a complete set of values and functions needed for image model configuration, with appropriate naming conventions.
editor/grida-react-canvas/state.ts (2)
886-889:IDocumentEditorInit.document.scenestyping looks good but may break existing callers
scenesis now strongly typed asRecord<string, IDocumentSceneInit>.
Any caller that previously passed an array or a plain object withoutid | name | constraintswill now fail to compile.
Please make sure every place that builds anIDocumentEditorInitvalue is adjusted accordingly (tests, storybook fixtures, etc.).
949-952: Silent behavioural change – defaultwhen_not_removableswitched to"deactivate"Changing the default from
"ignore"➜"deactivate"means that previously-ignored remove actions will now flipactive=falseon the node.
Before this lands, double-check:
- Hotkeys / menu flows that rely on “nothing happens” still behave acceptably.
- Any consumer that inspects the
activeflag (export, rendering, etc.) won’t regress.If this was intentional – great, but please call it out explicitly in the PR description / changelog so downstreams are aware.
editor/lib/ai/ai.ts (2)
219-254: Validate aspect-ratio math on the new “Flux Schnell” modelA few listed dimensions do not exactly match the declared ratio (e.g.
1536×640vs21:9→ 2.40 vs 2.33).
If this metadata feeds UI filters or server-side validation, the mismatch can cause false rejections. Double-check the manufacturer’s spec or round the ratio string to the nearest integer pair.-[1536, 640, "21:9"], +[1536, 640, "12:5"], # ratio 2.40
64-66:Details
✅ Verification successful
Check for dangling references to removed
SizeWithAspectRatiotype
SizeSpecreplaces the oldSizeWithAspectRatio, but other files may still import / reference the previous alias. To avoid type-errors at build time, run a quick grep across the repo:and update any remaining usages.
🏁 Script executed:
#!/bin/bash rg --line-number --fixed-strings "SizeWithAspectRatio" || trueLength of output: 61
All references to
SizeWithAspectRatiohave been removed
Verified via a repository-wide grep—no occurrences of the old alias remain. The newSizeSpecfully replaces it, so no further updates are needed.editor/grida/index.ts (2)
410-412: Scene now extendsIEdges– update initialisers & migrationsAny code that manually spreads a Scene object (tests, fixtures, migrations) must now include an
edges: []field or rely oninit_scene. Failing to do so will break JSON-schema validation.
1944-1946: 🛠️ Refactor suggestionInconsistent default size for basic nodes (0 vs 100)
createNodeDataFromPrototypeWithoutChildrenassignswidth/height = 100for most nodes, but rectangles still receive0. This inconsistency complicates hit-testing logic that assumes non-zero dimensions.-width: 0, -height: 0, +width: 100, +height: 100,Likely an incorrect or invalid review comment.
editor/app/(dev)/playground/image/_page.tsx (1)
133-157: Callback type mismatch: attachments are silently discarded
ChatBoxinvokesonValueCommitwith{ text, attachments }, butonCommitis declared to accept only{ text }. In strict function-type mode this is not assignable and will break the build; at runtime attachments are always ignored.Either handle the attachments or widen the parameter type:
-const onCommit = (value: { text: string }) => { +const onCommit = (value: { text: string; attachments: Attachment[] }) => { const id = editor.createNodeId(); ...(and propagate the generic
Attachmenttype import).This also enables future use cases such as generating images based on a reference picture.
| export function useCredits() { | ||
| const [remaining, setRemaining] = useState(0); | ||
| const [reset, setReset] = useState(0); | ||
|
|
||
| const refresh = useCallback(async () => { | ||
| const r = await fetch(`/private/ai/credits`, { | ||
| method: "GET", | ||
| }).then((res) => res.json()); | ||
| setRemaining(r.data.remaining); | ||
| setReset(r.data.reset); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| refresh(); | ||
| }, [refresh]); | ||
|
|
||
| return { | ||
| remaining, | ||
| reset, | ||
| refresh, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Well-implemented React hook for credit management.
This credit tracking hook follows React best practices with proper state management, memoization via useCallback, and cleanup. The API exposed is clean and intuitive.
However, there's no error handling for the fetch request. Consider adding error handling to gracefully manage API failures.
const refresh = useCallback(async () => {
- const r = await fetch(`/private/ai/credits`, {
- method: "GET",
- }).then((res) => res.json());
- setRemaining(r.data.remaining);
- setReset(r.data.reset);
+ try {
+ const response = await fetch(`/private/ai/credits`, {
+ method: "GET",
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to fetch credits: ${response.status}`);
+ }
+ const r = await response.json();
+ setRemaining(r.data.remaining);
+ setReset(r.data.reset);
+ } catch (error) {
+ console.error("Error fetching credits:", error);
+ // Optionally set an error state here to show in the UI
+ }
}, []);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function useCredits() { | |
| const [remaining, setRemaining] = useState(0); | |
| const [reset, setReset] = useState(0); | |
| const refresh = useCallback(async () => { | |
| const r = await fetch(`/private/ai/credits`, { | |
| method: "GET", | |
| }).then((res) => res.json()); | |
| setRemaining(r.data.remaining); | |
| setReset(r.data.reset); | |
| }, []); | |
| useEffect(() => { | |
| refresh(); | |
| }, [refresh]); | |
| return { | |
| remaining, | |
| reset, | |
| refresh, | |
| }; | |
| } | |
| export function useCredits() { | |
| const [remaining, setRemaining] = useState(0); | |
| const [reset, setReset] = useState(0); | |
| const refresh = useCallback(async () => { | |
| try { | |
| const response = await fetch(`/private/ai/credits`, { | |
| method: "GET", | |
| }); | |
| if (!response.ok) { | |
| throw new Error(`Failed to fetch credits: ${response.status}`); | |
| } | |
| const r = await response.json(); | |
| setRemaining(r.data.remaining); | |
| setReset(r.data.reset); | |
| } catch (error) { | |
| console.error("Error fetching credits:", error); | |
| // Optionally set an error state here to show in the UI | |
| } | |
| }, []); | |
| useEffect(() => { | |
| refresh(); | |
| }, [refresh]); | |
| return { | |
| remaining, | |
| reset, | |
| refresh, | |
| }; | |
| } |
🤖 Prompt for AI Agents (early access)
In editor/lib/ai/hooks/use-credits.ts around lines 3 to 24, the fetch request
inside the refresh function lacks error handling, which can cause unhandled
promise rejections or silent failures. Wrap the fetch call in a try-catch block
to catch any errors during the API request, and handle them gracefully by
logging the error or updating state to reflect the failure. This ensures the
hook remains robust and does not break the component using it when the API call
fails.
| const r: GenerateImageApiResponse = await fetch( | ||
| `/private/ai/generate/image`, | ||
| { | ||
| body: JSON.stringify({ | ||
| model, | ||
| width, | ||
| height, | ||
| aspect_ratio, | ||
| prompt, | ||
| } satisfies GenerateImageApiRequestBody), | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| }, | ||
| } | ||
| ).then((res) => res.json()); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add error handling for API requests.
The fetch request doesn't include any error handling. If the API call fails or returns a non-JSON response, it could result in unhandled exceptions.
- const r: GenerateImageApiResponse = await fetch(
- `/private/ai/generate/image`,
- {
- body: JSON.stringify({
- model,
- width,
- height,
- aspect_ratio,
- prompt,
- } satisfies GenerateImageApiRequestBody),
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- }
- ).then((res) => res.json());
+ try {
+ const response = await fetch(
+ `/private/ai/generate/image`,
+ {
+ body: JSON.stringify({
+ model,
+ width,
+ height,
+ aspect_ratio,
+ prompt,
+ } satisfies GenerateImageApiRequestBody),
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error(`Image generation failed: ${response.status} ${response.statusText}`);
+ }
+
+ const r: GenerateImageApiResponse = await response.json();Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents (early access)
In editor/lib/ai/hooks/use-generate-image.ts around lines 41 to 56, the fetch
request lacks error handling, which can cause unhandled exceptions if the API
call fails or returns invalid JSON. Wrap the fetch call in a try-catch block to
catch network or parsing errors, check the response status before parsing JSON,
and handle non-OK responses gracefully by throwing or returning an appropriate
error.
| const n = getNodeById(p.target); | ||
| const cx = (n as any).left + (n as any).width / 2; | ||
| const cy = (n as any).top + (n as any).height / 2; | ||
| return vector2ToSurfaceSpace([cx, cy], transform); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Node center calculation assumes left/top props exist
The centre is derived via (n as any).left + width / 2, but many node definitions use x / y (or position) instead of left / top.
Consider normalising through a helper already used elsewhere (e.g. getNodeBoundingRect) to avoid undefined maths:
- const cx = n.left + n.width / 2;
- const cy = n.top + n.height / 2;
+ const rect = getNodeBoundingRect(n); // ← shared util
+ const cx = rect.x + rect.width / 2;
+ const cy = rect.y + rect.height / 2;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const n = getNodeById(p.target); | |
| const cx = (n as any).left + (n as any).width / 2; | |
| const cy = (n as any).top + (n as any).height / 2; | |
| return vector2ToSurfaceSpace([cx, cy], transform); | |
| const n = getNodeById(p.target); | |
| const rect = getNodeBoundingRect(n); // ← shared util | |
| const cx = rect.x + rect.width / 2; | |
| const cy = rect.y + rect.height / 2; | |
| return vector2ToSurfaceSpace([cx, cy], transform); |
🤖 Prompt for AI Agents (early access)
In editor/grida-react-canvas/viewport/surface.tsx around lines 1063 to 1066, the
code calculates the node center using left and top properties which may not
exist on all node types, causing incorrect or undefined values. Replace this
calculation by using a helper function like getNodeBoundingRect that normalizes
node position and size, then compute the center from the bounding rectangle's x,
y, width, and height to ensure consistent and correct center coordinates.
| const get_pos = (p: grida.program.document.EdgePoint) => { | ||
| switch (p.type) { | ||
| case "position": | ||
| return vector2ToSurfaceSpace([p.x, p.y], transform); | ||
| case "anchor": | ||
| try { | ||
| const n = getNodeById(p.target); | ||
| const cx = (n as any).left + (n as any).width / 2; | ||
| const cy = (n as any).top + (n as any).height / 2; | ||
| return vector2ToSurfaceSpace([cx, cy], transform); | ||
| } catch (e) {} | ||
| } | ||
| }; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Swallowing errors hides edge-resolution problems
get_pos catches any exception from getNodeById but silently continues, returning undefined.
This makes debugging broken edges hard.
- try {
- const n = getNodeById(p.target);
- ...
- } catch (e) {}
+ const n = getNodeById(p.target);
+ if (!n) {
+ console.warn(`[Edge] target node '${p.target}' not found for edge '${id}'.`);
+ return;
+ }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents (early access)
In editor/grida-react-canvas/viewport/surface.tsx around lines 1057 to 1069, the
get_pos function catches errors from getNodeById but silently ignores them,
causing it to return undefined and making debugging difficult. Modify the catch
block to log the error or rethrow it so that edge-resolution problems are
visible during debugging instead of being swallowed silently.
| speed_label: "fastest" | "fast" | "medium" | "slow" | "slowest"; | ||
| speed_max: string; | ||
| min_width: number; | ||
| max_width: number; | ||
| min_height: number; | ||
| max_height: number; | ||
| sizes: SizeWithAspectRatio[] | null; | ||
| sizes: SizeSpec[] | null; | ||
| avg_ppi: number; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
New "fastest" speed label may break existing enum switches
Down-stream UI components or logic that use a finite switch / mapping on speed_label will now receive an unexpected value. Please audit those call-sites (e.g. badge colour mapping, rate-limit calculator) to ensure they include "fastest" and fall back gracefully.
-case "fast":
+case "fast":
+case "fastest":Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents (early access)
In editor/lib/ai/ai.ts around lines 73 to 80, the addition of the "fastest"
value to the speed_label union type may cause downstream switch statements or
mappings to break if they do not handle this new case. Review all usages of
speed_label in the codebase, especially UI components like badge color mappings
and rate-limit calculators, and update their switch or conditional logic to
include a case for "fastest". Also, ensure that all switches have a default or
fallback case to handle unexpected values gracefully.
| import imageSize from "image-size"; | ||
| import ai from "@/lib/ai"; |
There was a problem hiding this comment.
image-size may throw – wrap in try/catch
If the generated bytes are corrupt or an unsupported format, imageSize throws, resulting in a 500. Guard it to return a 422 validation error instead.
-const { width, height } = imageSize(generation.image.uint8Array);
+let width = body.width, height = body.height;
+try {
+ ({ width, height } = imageSize(generation.image.uint8Array));
+} catch (e) {
+ return NextResponse.json(
+ { message: "Failed to read dimensions", error: (e as Error).message },
+ { status: 422 }
+ );
+}🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/generate/image/route.ts around lines 13 to 14,
the import of image-size is fine but when calling imageSize on generated bytes,
it may throw an error if the image is corrupt or unsupported. Wrap the call to
imageSize in a try/catch block and in the catch, return a 422 validation error
response instead of letting the error propagate and cause a 500 server error.
| useEffect(() => { | ||
| if (plainFiles.length === 1) { | ||
| const file = plainFiles[0]; | ||
| const task = uploader?.(file).then((result) => { | ||
| setAttachment({ | ||
| type: "image", | ||
| filename: file.name, | ||
| mimeType: file.type, | ||
| url: result.publicUrl, | ||
| }); | ||
| }); | ||
|
|
||
| if (task) { | ||
| toast.promise(task, { | ||
| loading: "Uploading...", | ||
| success: "Uploaded", | ||
| error: "Failed to upload", | ||
| }); | ||
| } | ||
| if (task) { | ||
| toast.promise(task, { |
There was a problem hiding this comment.
Broken optional–chain triggers a runtime TypeError when uploader is undefined
uploader?.(file) may legitimately return undefined, but the chained .then(...) is still executed, dereferencing undefined and crashing the component the moment a user picks a file without an uploader prop.
Refactor to guard the promise creation explicitly:
- const task = uploader?.(file).then((result) => {
+ let task: Promise<UploadResult> | undefined;
+ if (uploader) {
+ task = uploader(file).then((result) => {
setAttachment({
type: "image",
filename: file.name,
mimeType: file.type,
url: result.publicUrl,
});
});
+ }- if (task) {
+ if (task) {
toast.promise(task, {
loading: "Uploading...",
success: "Uploaded",
error: "Failed to upload",
});
}Without this fix, file-picking silently breaks in any context where uploader is omitted.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| useEffect(() => { | |
| if (plainFiles.length === 1) { | |
| const file = plainFiles[0]; | |
| const task = uploader?.(file).then((result) => { | |
| setAttachment({ | |
| type: "image", | |
| filename: file.name, | |
| mimeType: file.type, | |
| url: result.publicUrl, | |
| }); | |
| }); | |
| if (task) { | |
| toast.promise(task, { | |
| loading: "Uploading...", | |
| success: "Uploaded", | |
| error: "Failed to upload", | |
| }); | |
| } | |
| if (task) { | |
| toast.promise(task, { | |
| useEffect(() => { | |
| if (plainFiles.length === 1) { | |
| const file = plainFiles[0]; | |
| let task: Promise<UploadResult> | undefined; | |
| if (uploader) { | |
| task = uploader(file).then((result) => { | |
| setAttachment({ | |
| type: "image", | |
| filename: file.name, | |
| mimeType: file.type, | |
| url: result.publicUrl, | |
| }); | |
| }); | |
| } | |
| if (task) { | |
| toast.promise(task, { | |
| loading: "Uploading...", | |
| success: "Uploaded", | |
| error: "Failed to upload", | |
| }); | |
| } | |
| } | |
| }, [plainFiles, uploader]); |
🤖 Prompt for AI Agents (early access)
In editor/components/chat/chatbox.tsx around lines 91 to 104, the optional
chaining on uploader followed by .then causes a runtime TypeError when uploader
is undefined because .then is called on undefined. To fix this, explicitly check
if uploader is defined before calling it and chaining .then. Only create the
promise and call .then if uploader exists; otherwise, skip this logic to prevent
the error.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
editor/hooks/use-pending-callback.tsx (2)
60-68: Consider removing the unnecessary catch clauseThe catch clause only rethrows the error without additional processing, making it redundant.
try { setState((prev) => ({ ...prev, isExecuting: true })); await state.callback(); -} catch (error) { - // Let the error propagate up - throw error; } finally { setState({ callback: null, isExecuting: false }); }🧰 Tools
🪛 Biome (1.9.4)
[error] 65-65: The catch clause that only rethrows the original error is useless.
An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.(lint/complexity/noUselessCatch)
32-40: Minor improvement to example codeSince
executeCallbackreturns a Promise, theawaitkeyword in the example isn't necessary unless you specifically want to wait for its completion before proceeding.// Set a callback to be executed later handlers.setCallback(() => () => console.log('Hello')); // Execute the callback when ready -await handlers.executeCallback(); +handlers.executeCallback();Alternatively, if waiting for completion is intended, add a comment explaining why:
// Wait for callback to complete before proceeding await handlers.executeCallback();
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
editor/hooks/use-pending-callback.tsx(1 hunks)editor/scaffolds/auth/use-continue-with-auth.tsx(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- editor/scaffolds/auth/use-continue-with-auth.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
editor/hooks/use-pending-callback.tsx
[error] 65-65: The catch clause that only rethrows the original error is useless.
An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.
(lint/complexity/noUselessCatch)
🔇 Additional comments (4)
editor/hooks/use-pending-callback.tsx (4)
3-4: Good choice defining a custom function typeUsing a custom type
Fninstead of the genericFunctiontype addresses the issues flagged in previous reviews. This approach provides better type safety while maintaining flexibility.
8-13: Well-structured interface with proper JSDocThe
PendingCallbackStateinterface is properly typed with the customFntype and includes helpful documentation comments explaining each property.
18-23: Clear handler interface with descriptive commentsThe
PendingCallbackHandlersinterface is well-defined and includes descriptive JSDoc comments that clearly explain the purpose of each method.
25-41: Excellent documentation with examplesThe hook includes comprehensive JSDoc comments explaining its purpose, usage scenario, and even provides a code example, which significantly improves developer experience.
Image Playground Canvas
👉 https://grida.co/playground/image
This PR introduces,
edges- tool for rendering network graphs between nodes. (WIP)day-231-grida-canvas-image-playground.mp4
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Documentation
Chores