Skip to content

[Grida AI] System prompt playground - #307

Merged
softmarshmallow merged 7 commits into
mainfrom
ai
Apr 22, 2025
Merged

softmarshmallow merged 7 commits into
mainfrom
ai

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Apr 22, 2025 •

Copy link
Copy Markdown
Member
day-224-grida-ai-system-prompt-playground.mp4

Summary by CodeRabbit

  • New Features

    • Introduced an AI-powered design playground with a prompt-based canvas, model and preset selectors, parameter controls, and real-time response streaming.
    • Added UI components for model selection, parameter adjustment (temperature, max tokens, top-p), chat input, and preset management (select, save, share).
    • Provided hooks and APIs for fetching available AI models and streaming AI-generated content.
    • Added utility hooks for DOM mutation observation.
  • Enhancements

    • Made AI model selection configurable via environment variables.
    • Updated dependencies and migrated several internal utilities to dedicated packages for color, SVG, Figma, and vector network handling.
    • Improved color conversion logic across the app by introducing a new color utility namespace.
  • Documentation

    • Added README files for new packages and features, including pixel grid, timeline, and TailwindCSS integration.
  • Chores

    • Added and updated multiple package manifests and TypeScript configurations to support modularization and workspace management.
    • Refactored import paths to use external packages for shared utilities.

@codesandbox

codesandbox Bot commented Apr 22, 2025

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web Editor • VS Code • Insiders

Open Preview

@vercel

vercel Bot commented Apr 22, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
backgrounds ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2025 6:55am
grida ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2025 6:55am
legacy-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2025 6:55am
viewer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2025 6:55am
5 Skipped Deployments
Name Status Preview Comments Updated (UTC)
code ⬜️ Ignored (Inspect) Apr 22, 2025 6:55am
legacy ⬜️ Ignored (Inspect) Apr 22, 2025 6:55am
sites ⬜️ Ignored (Inspect) Apr 22, 2025 6:55am
blog ⬜️ Skipped (Inspect) Apr 22, 2025 6:55am
docs ⬜️ Skipped (Inspect) Apr 22, 2025 6:55am

@coderabbitai

coderabbitai Bot commented Apr 22, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces a comprehensive AI-powered design playground within the editor, focused on generating and rendering UI layouts using OpenAI models. It adds a suite of React components for model selection, parameter tuning, prompt input, and live canvas rendering of AI-generated HTML/Tailwind outputs. Supporting hooks, data modules, and streaming generation utilities are included. The backend is extended with an API route for listing available AI models. Several new packages are introduced or refactored for modular color, SVG, Figma, and vector network handling, with dependencies adjusted accordingly. Color utilities are centralized in the new cmath namespace, with related code updated to use these functions.

Changes

File(s) / Path(s) Change Summary
editor/app/(dev)/canvas/tools/ai/_components/*.tsx, editor/app/(dev)/canvas/tools/ai/_data/presets.ts, editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts, editor/app/(dev)/canvas/tools/ai/generate.ts, editor/app/(dev)/canvas/tools/ai/page.tsx Added a full-featured AI design playground: React components for chat input, model/preset selection, parameter controls, and live canvas rendering; data modules for presets; a hook for fetching models; utilities for streaming AI generation; and a new page integrating these features.
editor/app/(api)/private/ai/models/route.ts Added a new API route handler to list available OpenAI models via a GET request, returning model data as JSON.
editor/.env.example, editor/app/actions.ts Added a new environment variable for OpenAI model selection and updated code to use this variable for model configuration.
editor/package.json Updated dependencies: bumped versions for @ai-sdk/openai, ai, and openai; added @grida/io-figma, @grida/io-svg, @grida/vn; removed svgo, svgson, and inline-style-parser.
editor/grida/index.ts Changed vn import to package import; made CSS property type partial; removed several color utility exports.
editor/grida-react-canvas-starter-kit/starterkit-toolbar/brush-toolbar.tsx, editor/grida-react-canvas/reducers/event-target.reducer.ts, editor/grida-react-canvas/viewport/hotkeys.tsx, editor/scaffolds/sidecontrol/controls/color-picker.tsx, packages/grida-canvas-io-figma/lib.ts Updated color conversion utility usage from grida.program.cg to cmath.color functions.
editor/grida-react-canvas/nodes/path.tsx, editor/grida-react-canvas/reducers/document.reducer.ts, editor/grida-react-canvas/reducers/methods/transform.ts Changed vn import from local alias to default import from @grida/vn package.
editor/grida-react-canvas/provider.tsx, editor/app/(dev)/canvas/tools/io-svg/page.tsx, editor/scaffolds/playground-canvas/playground.tsx Changed iosvg and iofigma imports to use new package paths. Added "AI" tool menu item in the playground sidebar.
editor/hooks/use-mutation-observer.ts Added a new React hook for observing DOM mutations on a referenced element.
packages/grida-cmath/index.ts Introduced the cmath.color namespace with types and utility functions for color conversion and manipulation (HEX, RGBA, float/integer conversions, alpha multiplication).
packages/grida-canvas-io-figma/index.ts, packages/grida-canvas-io-svg/index.ts, packages/grida-canvas-vn/index.ts Added package entry points re-exporting main functionality (iofigma, iosvg, vn) as default exports.
packages/grida-canvas-io-figma/package.json, packages/grida-canvas-io-svg/package.json, packages/grida-canvas-vn/package.json, packages/grida-canvas-tailwind/package.json Added new package manifests for @grida/io-figma, @grida/io-svg, @grida/vn, and @grida/tailwindcss with descriptions and dependencies.
packages/grida-canvas-io-svg/lib.ts Switched color and named color handling from internal grida utilities to cmath.color and color-name package; updated types and comments.
packages/grida-canvas-tailwind/tailwindcss.ts Added Tailwind CSS utility configuration module: defines prefixes and allowed units/classes for margin, width, min/max width, cursor, and opacity utilities.
packages/grida-canvas-tailwind/README.md, packages/grida-canvas-pixelgrid/README.md, packages/grida-canvas-react-timeline/README.md Added brief README files for new/in-progress packages.
packages/grida-canvas-vn/__tests__/vn.test.ts Changed test import path for vn module to parent directory.
packages/grida-canvas-vn/tsconfig.json Added TypeScript configuration enabling esModuleInterop.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PlaygroundPage
    participant ModelSelector
    participant ModelParams
    participant PresetSelector
    participant ChatBox
    participant generate (utility)
    participant OpenAI API

    User->>PlaygroundPage: Loads page
    PlaygroundPage->>ModelSelector: Renders model selection UI
    PlaygroundPage->>ModelParams: Renders parameter controls
    PlaygroundPage->>PresetSelector: Renders preset selection
    User->>ChatBox: Enters prompt and submits
    ChatBox->>PlaygroundPage: onValueCommit(prompt)
    PlaygroundPage->>generate: Calls generate({system, prompt, ...params})
    generate->>OpenAI API: Streams AI response (HTML/Tailwind JSON)
    generate-->>PlaygroundPage: Streams partial/final output
    PlaygroundPage->>Canvas: Renders generated HTML in iframe
Loading

Poem

In the warren of code, a new playground appears,
Where AI and design hop close as peers.
Models to pick, sliders to slide,
Prompts and presets, all bunnyfied!
Colors now handled with cmath’s delight,
New packages assembled, dependencies light.
With a twitch of the nose, we render and cheer—
The future of canvas is hopping right here! 🐇✨
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 23

🔭 Outside diff range comments (1)
packages/grida-canvas-io-svg/lib.ts (1)

320-374: 🛠️ Refactor suggestion

Update return types to use the new namespace

While you've updated the import and type references, some function return types still use the old namespace (grida.program.cg.Paint). Consider updating these to use the new namespace for consistency.

-    ): grida.program.cg.Paint | undefined {
+    ): cmath.color.Paint | undefined {

Similarly for the fill function on line 330 and the paint function on line 341.

🧰 Tools
🪛 Biome (1.9.4)

[error] 350-352: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🧹 Nitpick comments (24)
packages/grida-canvas-pixelgrid/README.md (1)

1-1: Enhance the README title with package identifier

The title is clear, but conventionally the NPM scope and package name are included, e.g.:

# @grida/grida-canvas-pixelgrid

This makes it immediately obvious which package this doc refers to.

packages/grida-canvas-vn/tsconfig.json (1)

1-5: Minimal tsconfig: consider extending a base config and adding essential settings
Currently, this package-specific tsconfig.json only enables esModuleInterop. In a monorepo or multi-package setup, it’s often beneficial to:

  1. Extend a shared root/base tsconfig.json to keep compiler settings consistent across packages.
  2. Add key compiler options like strict, declaration, outDir, rootDir, skipLibCheck, etc., to ensure robust type safety and proper declaration output.

Example diff:

{
+ "extends": "../../tsconfig.base.json",
  "compilerOptions": {
+   "target": "ES2019",
+   "module": "ESNext",
    "esModuleInterop": true,
+   "allowSyntheticDefaultImports": true,
+   "strict": true,
+   "declaration": true,
+   "declarationMap": true,
+   "emitDeclarationOnly": true,
+   "outDir": "dist",
+   "rootDir": "src",
+   "skipLibCheck": true,
+   "forceConsistentCasingInFileNames": true
  }
}
packages/grida-canvas-react-timeline/README.md (1)

3-3: Improve grammar and expand documentation.
Capitalize the sentence and add punctuation. More importantly, flesh out the README with Installation, Usage, and Contributing sections to guide new users. For example:

This package is a work in progress.
packages/grida-canvas-tailwind/README.md (1)

1-3: Minimal placeholder README for WIP feature

While this README is very minimal, it appropriately indicates that TailwindCSS support is under development.

Consider expanding this README with:

  • Current state of implementation
  • Planned features
  • Usage examples (even if partial)
  • Integration instructions with the main Grida Canvas
editor/app/actions.ts (1)

9-10: Consider using a server-side environment variable.

Since this code runs on the server, using a client-side accessible environment variable (prefixed with NEXT_PUBLIC_) is unnecessary and could potentially expose configuration.

-const MODEL = process.env.NEXT_PUBLIC_OPENAI_BEST_MODEL_ID || "gpt-4o-mini";
+const MODEL = process.env.OPENAI_BEST_MODEL_ID || "gpt-4o-mini";
packages/grida-canvas-io-figma/package.json (1)

1-11: Package configuration requires additional metadata

The package.json file is missing several important fields that are typically required for packages:

  • Missing version field (required for publishing)
  • No main/types/exports fields to define entry points
  • No license, repository, or author information
  • Potential circular dependency with "editor" (editor depends on this package, but this package has editor as a devDependency)
 {
   "name": "@grida/io-figma",
   "description": "Figma I/O for Grida Canvas",
+  "version": "0.1.0",
+  "main": "lib/index.js",
+  "types": "lib/index.d.ts",
+  "license": "MIT",
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/gridaco/grida"
+  },
   "dependencies": {
     "@grida/cmath": "workspace:*"
   },
   "devDependencies": {
     "@figma/rest-api-spec": "^0.21.0",
     "editor": "workspace:*"
   }
 }
editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts (2)

1-15: Well-implemented hook with SWR for data fetching

This is a clean implementation of a hook for fetching OpenAI models. It uses SWR correctly for data fetching with built-in caching and revalidation.

Consider extracting the fetcher function for better reusability and testability:

 import useSWR from "swr";
 import type OpenAI from "openai";
 
+const fetchModels = async () => {
+  const res = await fetch("/private/ai/models");
+  if (!res.ok) {
+    throw new Error("Failed to fetch models");
+  }
+  return res.json();
+};
+
 export function useModels() {
   return useSWR<{ data: OpenAI.Models.Model[] }>(
     "/private/ai/models",
-    async () => {
-      const res = await fetch("/private/ai/models");
-      if (!res.ok) {
-        throw new Error("Failed to fetch models");
-      }
-      return res.json();
-    }
+    fetchModels
   );
 }

This makes the hook more concise and the fetcher function could be reused elsewhere if needed.


5-6: Consider adding error and loading states

The current implementation doesn't provide explicit handling of loading and error states from SWR.

Enhance the hook to provide more granular state information:

 export function useModels() {
-  return useSWR<{ data: OpenAI.Models.Model[] }>(
+  const { data, error, isLoading } = useSWR<{ data: OpenAI.Models.Model[] }>(
     "/private/ai/models",
     async () => {
       const res = await fetch("/private/ai/models");
       if (!res.ok) {
         throw new Error("Failed to fetch models");
       }
       return res.json();
     }
   );
+  
+  return { 
+    models: data?.data || [], 
+    isLoading, 
+    error 
+  };
 }

This makes it easier for consumers of this hook to handle loading and error states explicitly.

editor/scaffolds/sidecontrol/controls/color-picker.tsx (1)

18-108:

Details

❓ Verification inconclusive

Consider updating type definitions for consistency with new color utilities.

While the implementation now uses the centralized color utilities from @grida/cmath, the interface still references the old grida.program.cg.RGBA8888 type.

Consider updating the interface definitions to use the new type definitions if available:

interface IDColor {
  id: string;
-  color: grida.program.cg.RGBA8888;
+  color: cmath.color.RGBA8888; // Update if this type exists in the new package
}

export function ColorPicker({
  color,
  onColorChange,
  options,
}: {
-  color: grida.program.cg.RGBA8888;
-  onColorChange?: (color: grida.program.cg.RGBA8888) => void;
+  color: cmath.color.RGBA8888; // Update if this type exists in the new package
+  onColorChange?: (color: cmath.color.RGBA8888) => void; // Update if this type exists in the new package
  options?: IDColor[];
}) {
  // ...
}

🏁 Script executed:

#!/bin/bash
# Check if RGBA8888 type is defined in the cmath package
rg -t typescript "export (type|interface) RGBA8888" -A 3

Length of output: 93


Confirm and update the RGBA8888 type import from @grida/cmath

Please verify that the new RGBA8888 type is exported by the @grida/cmath package (and note its exact import path), then update your interface and component props accordingly:

• editor/scaffolds/sidecontrol/controls/color-picker.tsx
– Replace any reference to grida.program.cg.RGBA8888 with the correctly imported type from @grida/cmath.
– Update both the IDColor.color field and the ColorPicker props (color and onColorChange).

 interface IDColor {
   id: string;
-  color: grida.program.cg.RGBA8888;
+  color: cmath.color.RGBA8888; // ensure this type exists and is imported correctly
 }

 export function ColorPicker({
   color,
   onColorChange,
   options,
 }: {
-  color: grida.program.cg.RGBA8888;
-  onColorChange?: (color: grida.program.cg.RGBA8888) => void;
+  color: cmath.color.RGBA8888;
+  onColorChange?: (color: cmath.color.RGBA8888) => void;
   options?: IDColor[];
 }) {
   /* … */
 }
editor/app/(dev)/canvas/tools/ai/_components/model-params.tsx (1)

14-30: Add accessible labels to the popover for better a11y.

The current implementation is missing some a11y features in the popover component.

Add appropriate aria attributes to improve accessibility:

-    <Popover>
+    <Popover modal={true}>
      <PopoverTrigger>
        <Button
          variant="ghost"
          size="icon"
          role="combobox"
          aria-label="Load a preset..."
+          aria-expanded={open}
        >
          <Settings2 className="size-4" />
        </Button>
      </PopoverTrigger>
-      <PopoverContent>
+      <PopoverContent className="w-72" aria-label="Model Parameters">
+        <div className="flex items-center justify-between mb-4">
+          <h4 className="font-medium leading-none">Model Parameters</h4>
+        </div>
         <TemperatureSelector defaultValue={[0.56]} />
         <MaxTokensSelector defaultValue={[256]} />
         <TopPSelector defaultValue={[0.9]} />
      </PopoverContent>
editor/app/(dev)/canvas/tools/ai/_components/top-p-selector.tsx (1)

1-54: Well-implemented TopPSelector component with clear UX.

The TopPSelector component is well-structured with appropriate state management, accessible UI elements, and helpful tooltips explaining the Top P parameter to users. The HoverCard provides good context for users unfamiliar with nucleus sampling.

Consider adding an onChange callback prop to expose the selected value to parent components:

 interface TopPSelectorProps {
   defaultValue: SliderProps["defaultValue"];
+  onChange?: (value: number[]) => void;
 }

-export function TopPSelector({ defaultValue }: TopPSelectorProps) {
+export function TopPSelector({ defaultValue, onChange }: TopPSelectorProps) {
   const [value, setValue] = React.useState(defaultValue);
   
+  React.useEffect(() => {
+    if (onChange && Array.isArray(value)) {
+      onChange(value);
+    }
+  }, [value, onChange]);

   // ...
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (2)

41-43: Consider removing the empty div

The empty <div /> element appears to be used only for layout spacing. Consider replacing it with CSS margin/padding or using a more semantic approach if needed for layout.

-      <div className="flex items-center justify-between mt-2">
-        <div />
+      <div className="flex justify-end mt-2">

27-53: Add loading state indicator

The chat interface would benefit from a visual loading indicator when waiting for AI responses. This helps improve the user experience by providing feedback during potentially long operations.

 export function ChatBox({
   disabled,
   onValueCommit,
+  isLoading,
 }: {
   disabled?: boolean;
   onValueCommit?: (value: string) => void;
+  isLoading?: boolean;
 }) {
   const [txt, setTxt] = React.useState<string>("");
   
   // ...
   
       <Button
-        disabled={disabled}
+        disabled={disabled || isLoading}
         onClick={onSubmit}
         variant="default"
         size="icon"
         className="rounded-full"
       >
-        <ArrowUpIcon className="size-5" />
+        {isLoading ? <span className="size-5 animate-spin">↻</span> : <ArrowUpIcon className="size-5" />}
       </Button>
editor/app/(dev)/canvas/tools/ai/_components/maxtokens-selector.tsx (2)

14-16: Fix interface naming inconsistency

The interface name MaxLengthSelectorProps doesn't match the component name MaxTokensSelector. For consistency and clarity, rename the interface.

-interface MaxLengthSelectorProps {
+interface MaxTokensSelectorProps {
   defaultValue: SliderProps["defaultValue"];
 }

27-40: Align element IDs with label text

The id attribute "maxlength" doesn't match the label text "Max Tokens". For better accessibility and consistency, these should match.

-            <Label htmlFor="maxlength">Max Tokens</Label>
+            <Label htmlFor="maxtokens">Max Tokens</Label>
             <span className="w-12 rounded-md border border-transparent px-2 py-0.5 text-right text-sm text-muted-foreground hover:border-border">
               {value}
             </span>
           </div>
           <Slider
-            id="maxlength"
+            id="maxtokens"
             max={4000}
             defaultValue={value}
             step={10}
             onValueChange={setValue}
             className="[&_[role=slider]]:h-4 [&_[role=slider]]:w-4"
-            aria-label="Maximum Length"
+            aria-label="Maximum Tokens"
editor/app/(dev)/canvas/tools/ai/_components/model-selector.tsx (1)

27-31: Consider adding a default model selection.

The component initializes with no selected model, which may not provide the best user experience. Consider setting an initial default model based on an environment variable or the first available model.

export function ModelSelector({ ...props }: ModelSelectorProps) {
  const [open, setOpen] = React.useState(false);
  const [selectedModel, setSelectedModel] = React.useState<Model>();

  const { data: models } = useModels();
+ 
+ // Set default model when models are loaded
+ React.useEffect(() => {
+   if (models?.data?.length && !selectedModel) {
+     // Either use an environment variable or the first model
+     const defaultModelId = process.env.NEXT_PUBLIC_OPENAI_BEST_MODEL_ID;
+     const defaultModel = defaultModelId 
+       ? models.data.find(m => m.id === defaultModelId) 
+       : models.data[0];
+     
+     if (defaultModel) {
+       setSelectedModel(defaultModel);
+     }
+   }
+ }, [models, selectedModel]);
editor/app/(dev)/canvas/tools/ai/_components/preset-selector.tsx (2)

22-25: Add initial selection support.

The component doesn't support setting an initially selected preset. Add a prop to allow specifying a default preset.

interface PresetSelectorProps extends PopoverProps {
  presets: Preset[];
  onValueChange?: (preset: Preset) => void;
+ defaultPresetId?: string;
}

Then update the component to use it:

export function PresetSelector({
  presets,
  onValueChange,
+ defaultPresetId,
  ...props
}: PresetSelectorProps) {
  const [open, setOpen] = React.useState(false);
- const [selectedPreset, setSelectedPreset] = React.useState<Preset>();
+ const [selectedPreset, setSelectedPreset] = React.useState<Preset | undefined>(
+   defaultPresetId ? presets.find(p => p.id === defaultPresetId) : undefined
+ );

49-49: Fix inconsistent icon size properties.

In PresetSelector, you're using className="opacity-50" for the ChevronsUpDown icon, but in ModelSelector, you're using className="opacity-50 size-4". Ensure consistent styling across components.

- <ChevronsUpDown className="opacity-50" />
+ <ChevronsUpDown className="opacity-50 size-4" />
editor/app/(dev)/canvas/tools/ai/page.tsx (3)

19-20: Remove commented-out code.

There are commented-out state variables that are no longer used. Remove these to keep the codebase clean.

- // const [modelId, setModelId] = useState<string | undefined>(undefined);
- // const [modelConfig, setModelConfig] = useState<any>(undefined);

99-102: Add loading indicator for Canvas component.

When generation is in progress, there's no visual feedback in the Canvas area. Add a loading indicator to improve user experience.

<div className="flex-1 flex flex-col gap-2">
+ {streamBusy && (
+   <div className="absolute inset-0 flex items-center justify-center bg-background/50 z-10 rounded-xl">
+     <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
+   </div>
+ )}
  <Canvas
    node={response?.html}
-   className="flex-1 rounded-xl overflow-hidden border"
+   className="flex-1 rounded-xl overflow-hidden border relative"
  />
</div>

58-61: Add explanatory tooltips for disabled buttons.

The PresetSave and PresetShare components are disabled without any explanation to the user. Add tooltips to explain why these features are unavailable.

import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";

// Then update the buttons
- <PresetSave disabled />
+ <Tooltip>
+   <TooltipTrigger asChild>
+     <span>
+       <PresetSave disabled />
+     </span>
+   </TooltipTrigger>
+   <TooltipContent>
+     <p>Saving presets is coming soon</p>
+   </TooltipContent>
+ </Tooltip>

- <PresetShare disabled />
+ <Tooltip>
+   <TooltipTrigger asChild>
+     <span>
+       <PresetShare disabled />
+     </span>
+   </TooltipTrigger>
+   <TooltipContent>
+     <p>Sharing presets is coming soon</p>
+   </TooltipContent>
+ </Tooltip>
editor/app/(dev)/canvas/tools/ai/generate.ts (2)

27-65: Robust implementation of the generate function with streaming support.

The implementation properly handles:

  • Optional configuration parameters with sensible defaults
  • Streaming for progressive updates to the UI
  • Async processing using IIFE to avoid blocking
  • Error handling through the schema validation

The commented-out line 61 should be removed as it's not being used.

-    // const final = (stream.value as any)["curr"];

56-56: Type assertion could be improved.

The type assertion as any is a potential source of bugs. Consider defining a proper type for the partial object or using a more specific type assertion.

-      stream.update(partialObject as any);
+      stream.update(partialObject as z.infer<typeof schema>);
packages/grida-canvas-tailwind/tailwindcss.ts (1)

1-112: Consider exposing these configurations for external use.

The file defines several useful Tailwind configurations but doesn't export them. Consider adding exports to make these configurations available to other modules that might need to validate or process Tailwind classes.

+export { margin, width, minwidth, maxwidth, cursor, opacity };
+
+// Consider also exporting a combined configuration object
+export const tailwindConfig = {
+  margin,
+  width,
+  minwidth,
+  maxwidth,
+  cursor,
+  opacity,
+};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5572000 and ab0571e.

⛔ Files ignored due to path filters (2)
  • packages/grida-canvas-io-svg/test.svg is excluded by !**/*.svg
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (46)
  • editor/.env.example (1 hunks)
  • editor/app/(api)/private/ai/models/route.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/canvas.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/maxtokens-selector.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/model-params.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/model-selector.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/preset-save.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/preset-selector.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/preset-share.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/temperature-selector.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/top-p-selector.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_data/presets.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/generate.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/page.tsx (1 hunks)
  • editor/app/(dev)/canvas/tools/io-svg/page.tsx (1 hunks)
  • editor/app/actions.ts (1 hunks)
  • editor/grida-react-canvas-starter-kit/starterkit-toolbar/brush-toolbar.tsx (1 hunks)
  • editor/grida-react-canvas/nodes/path.tsx (1 hunks)
  • editor/grida-react-canvas/provider.tsx (1 hunks)
  • editor/grida-react-canvas/reducers/document.reducer.ts (1 hunks)
  • editor/grida-react-canvas/reducers/event-target.reducer.ts (2 hunks)
  • editor/grida-react-canvas/reducers/methods/transform.ts (1 hunks)
  • editor/grida-react-canvas/viewport/hotkeys.tsx (2 hunks)
  • editor/grida/index.ts (2 hunks)
  • editor/hooks/use-mutation-observer.ts (1 hunks)
  • editor/package.json (4 hunks)
  • editor/scaffolds/playground-canvas/playground.tsx (2 hunks)
  • editor/scaffolds/sidecontrol/controls/color-picker.tsx (3 hunks)
  • packages/grida-canvas-io-figma/index.ts (1 hunks)
  • packages/grida-canvas-io-figma/lib.ts (6 hunks)
  • packages/grida-canvas-io-figma/package.json (1 hunks)
  • packages/grida-canvas-io-svg/index.ts (1 hunks)
  • packages/grida-canvas-io-svg/lib.ts (4 hunks)
  • packages/grida-canvas-io-svg/package.json (1 hunks)
  • packages/grida-canvas-pixelgrid/README.md (1 hunks)
  • packages/grida-canvas-react-timeline/README.md (1 hunks)
  • packages/grida-canvas-tailwind/README.md (1 hunks)
  • packages/grida-canvas-tailwind/package.json (1 hunks)
  • packages/grida-canvas-tailwind/tailwindcss.ts (1 hunks)
  • packages/grida-canvas-vn/__tests__/vn.test.ts (1 hunks)
  • packages/grida-canvas-vn/index.ts (1 hunks)
  • packages/grida-canvas-vn/package.json (1 hunks)
  • packages/grida-canvas-vn/tsconfig.json (1 hunks)
  • packages/grida-cmath/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
editor/app/(dev)/canvas/tools/ai/_components/model-params.tsx (3)
editor/app/(dev)/canvas/tools/ai/_components/temperature-selector.tsx (1)
  • TemperatureSelector (18-57)
editor/app/(dev)/canvas/tools/ai/_components/maxtokens-selector.tsx (1)
  • MaxTokensSelector (18-55)
editor/app/(dev)/canvas/tools/ai/_components/top-p-selector.tsx (1)
  • TopPSelector (18-54)
packages/grida-canvas-io-figma/lib.ts (1)
packages/grida-canvas-io-svg/lib.ts (1)
  • paint (334-374)
packages/grida-canvas-io-svg/lib.ts (2)
editor/grida/index.ts (1)
  • RGBA8888 (2125-2142)
packages/grida-cmath/index.ts (1)
  • RGBA8888 (3260-3277)
editor/app/(dev)/canvas/tools/ai/_components/preset-selector.tsx (1)
editor/app/(dev)/canvas/tools/ai/_data/presets.ts (2)
  • Preset (1-5)
  • presets (147-153)
packages/grida-cmath/index.ts (1)
editor/grida/index.ts (3)
  • TRGBA (2091-2096)
  • RGBAf (2102-2119)
  • RGBA8888 (2125-2142)
🔇 Additional comments (45)
editor/hooks/use-mutation-observer.ts (1)

3-20: Well-implemented React hook for MutationObserver

This is a clean implementation of a React hook that wraps the MutationObserver Web API. The hook provides a good abstraction with sensible defaults and proper cleanup when components unmount.

packages/grida-cmath/index.ts (6)

3222-3249: Good type definitions for color representations

The RGBA type definitions are well structured with appropriate documentation for each representation. This provides a solid foundation for color handling in the application.


3250-3277: Well-documented RGBA8888 type with clear value ranges

The documentation clearly specifies the expected ranges for each color channel, which helps prevent incorrect usage.


3279-3313: Robust hex color parsing with error handling

The implementation handles both short (#RGB) and long (#RRGGBB) hex formats appropriately, with proper error handling for invalid inputs.


3315-3317: Utility for uint8 color conversion

This utility function is useful for converting RGBA8888 to a format suitable for raw memory operations or binary formats.


3319-3339: Consistent RGB normalization utility

Good implementation for converting between normalized and 8-bit RGB values while preserving alpha. The documentation with example is helpful.


3341-3348: Alpha multiplication utility

Simple utility for alpha channel multiplication that preserves the original RGB channels.

editor/app/(dev)/canvas/tools/ai/_data/presets.ts (3)

1-5: Clean interface definition for AI presets

The Preset interface is concise and well-structured with all necessary properties.


7-146: Comprehensive AI system prompt with clear guidelines

This system prompt is well-structured with multiple sections addressing:

  • AI role and capabilities
  • Required JSON output format
  • Design style guidelines
  • HTML/CSS constraints
  • Common pitfalls to avoid

The inclusion of a timestamp in the environment section is a good practice for providing temporal context to the AI.


147-153: Presets array with initial default configuration

The presets array is properly set up with a single initial configuration. This pattern allows for easy addition of more presets in the future.

packages/grida-canvas-vn/__tests__/vn.test.ts (1)

1-1: Import path updated to match new package structure.

The module import was changed from a relative path (./vn) to one that references the parent directory (../vn). This aligns with the package restructuring, making the code consistent with the new module organization.

editor/grida-react-canvas-starter-kit/starterkit-toolbar/brush-toolbar.tsx (1)

306-306: Function reference updated to use the new color utility namespace.

The color conversion function has been migrated from the internal grida.program.cg namespace to the centralized cmath.color namespace. This change is part of a broader refactoring effort to consolidate color utilities.

editor/grida-react-canvas/nodes/path.tsx (1)

4-5: Imports updated to use the new package structure.

Two changes have been made to the imports:

  1. The import order was changed to place queryattributes before vn
  2. The vn import was changed from a named import from a local path to a default import from the new @grida/vn package

This change aligns with the modularization of the codebase, where vector network utilities have been centralized in a dedicated package.

editor/.env.example (1)

27-27: Added configurable environment variable for OpenAI model.

A new environment variable NEXT_PUBLIC_OPENAI_BEST_MODEL_ID has been added with a default value of "gpt-4o-mini". This improves configurability by allowing the AI model to be set via environment variables rather than being hardcoded in the application.

packages/grida-canvas-io-figma/index.ts (1)

1-2: Looks good - clean module export pattern.

This straightforward export provides a clean entry point for the Figma I/O functionality, following standard module patterns and supporting the broader package modularization effort.

editor/grida-react-canvas/reducers/methods/transform.ts (1)

21-21: Import updated to use the new modular package.

The import has been updated from a named import (import { vn } from "@/grida/vn") to a default import from the new modular package. This is consistent with the broader refactoring of vector network handling across the codebase.

#!/bin/bash
# Verify that this import change is consistent across the codebase
rg "import.*vn.*from" --type ts
editor/grida-react-canvas/viewport/hotkeys.tsx (2)

11-11: New import for centralized math utilities.

Added import for the new centralized math utilities package that contains the color conversion functions previously found in grida.program.cg.


537-537: Updated color conversion function namespace.

Color conversion function call has been updated to use the new centralized cmath.color namespace instead of the previous grida.program.cg namespace, aligning with the broader refactoring of color utilities.

editor/grida-react-canvas/reducers/document.reducer.ts (1)

35-35: Import updated to use the new modular package.

The import has been updated from a named import (import { vn } from "@/grida/vn") to a default import from the newly created package. This maintains functionality while improving code organization and modularity.

#!/bin/bash
# Check the usages of VectorNetworkEditor to ensure consistent import pattern
rg "new vn\.VectorNetworkEditor" --type ts
packages/grida-canvas-vn/index.ts (1)

1-2: Clean module export structure.

This is a well-implemented module entry point that follows the standard pattern of re-exporting functionality via a default export.

editor/app/(dev)/canvas/tools/io-svg/page.tsx (1)

20-21: Import refactoring looks good.

The imports have been correctly updated to use the new package structure, importing iosvg as a default export from @grida/io-svg instead of a named import from a local path.

editor/grida-react-canvas/provider.tsx (1)

35-35: Consistent import refactoring.

The import has been correctly updated to use the new modular package structure, using the default export from @grida/io-svg. This aligns with the broader refactoring effort to modularize the codebase.

packages/grida-canvas-io-svg/index.ts (1)

1-2: Clean module export structure.

This entry point follows the standard pattern for exporting functionality as a default export, which aligns with the import changes seen in other files.

editor/grida-react-canvas/reducers/event-target.reducer.ts (2)

39-39: Import change looks good.

The change from named import to default import aligns with the new packaging structure.


1274-1276: Color utility function update is appropriate.

The change reflects the refactoring of color utilities to the new cmath.color namespace.

editor/app/actions.ts (1)

16-16: Model parameterization is a good improvement.

Making the model configurable through environment variables is good practice for flexibility.

editor/scaffolds/playground-canvas/playground.tsx (2)

122-123: Good refactoring to use the new modular packages

These import changes correctly reference the newly created scoped packages, which is better for maintainability and separation of concerns.


347-355: Good addition of AI tooling integration

The new AI menu item follows the existing pattern and provides access to the new AI playground. This is a clean way to expose the new functionality.

editor/package.json (2)

29-31: Good addition of new workspace dependencies

Adding the new scoped packages as workspace dependencies aligns with the modularization approach and ensures consistency with the import changes seen in other files.

Also applies to: 35-35


157-157:

Details

✅ Verification successful

Verify OpenAI SDK compatibility

The OpenAI SDK has been updated from ^4.29.1 to ^4.95.1, which is a significant jump in minor versions that could introduce new features or deprecate existing ones.

Let's check if there were any significant changes or deprecations between these versions:


🏁 Script executed:

#!/bin/bash
# Fetch the OpenAI changelog or release notes to check for significant changes
curl -s https://api.github.com/repos/openai/openai-node/releases | jq -r '.[] | select(.tag_name >= "v4.29.1" and .tag_name <= "v4.95.1") | .tag_name + "\n" + .body + "\n"' | head -n 100

Length of output: 5356


No breaking changes found in OpenAI SDK upgrade

We reviewed the changelog for versions v4.29.1→v4.95.1 and found only backwards‑compatible additions (new model IDs, minor features, bug fixes) with no deprecations or removals.

editor/scaffolds/sidecontrol/controls/color-picker.tsx (2)

1-1: Import refactoring for color utilities looks good.

The simplified React import and new imports for color utilities from @grida/cmath align with the broader refactoring effort to centralize color functions.

Also applies to: 15-16


53-53: Properly migrated to centralized color utilities.

The code correctly switches from the internal grida.program.cg.hex_to_rgba8888 to the new centralized cmath.color.hex_to_rgba8888 function.

packages/grida-canvas-io-figma/lib.ts (2)

14-14: Import path updated correctly.

The import path for the grida module has been updated from a relative alias @/grida to editor/grida, which aligns with the refactoring of the codebase.


111-112: Color utility functions migrated to cmath namespace.

Color conversion and alpha multiplication functions have been consistently moved from grida.program.cg namespace to the new cmath.color namespace across the file. This change is part of a broader refactoring where color utilities are now centralized in the cmath namespace, making them more modular and reusable.

Also applies to: 132-133, 319-320, 474-475, 550-551

editor/app/(dev)/canvas/tools/ai/_components/temperature-selector.tsx (1)

1-57: Well-implemented temperature selector component!

This component provides a user-friendly UI for controlling the temperature parameter in AI model generation with good accessibility features. The implementation uses React hooks correctly and provides helpful contextual information through the hover card.

editor/grida/index.ts (2)

2-2: Package import updated from local to absolute path.

The import of vn type has been changed from a relative local import "./vn" to an absolute package import "@grida/vn". This aligns with the introduction of the new @grida/vn package in this PR.


722-760: Type definition made more flexible with Partial wrapper.

The ExplicitlySupportedCSSProperties type has been changed from a required Pick to a Partial<Pick<...>>, making all selected CSS properties optional while keeping the same property list. This change provides more flexibility when defining CSS properties.

editor/app/(dev)/canvas/tools/ai/generate.ts (3)

1-9: Server-side AI generation setup with appropriate model defaults.

The module sets up server actions for AI generation with OpenAI model support, properly importing the necessary streaming utilities. The default model fallback to "gpt-4o-mini" is a good practice for when environment variables are not available.


10-25: Well-structured Zod schema for AI output validation.

The schema defines the expected structure for AI-generated content, including HTML elements and image data. This ensures type safety and consistent output structure for downstream components.


67-78: Clean implementation of image generation functionality.

The generateImage function is concise and follows best practices for async/await usage. It properly extracts and returns only the necessary data (MIME type and base64-encoded image).

packages/grida-canvas-tailwind/tailwindcss.ts (5)

1-6: Well-organized Tailwind constant definitions.

The numeric and fractional value arrays are properly defined and organized. Using separate constants for different scales (64, 100, and fractional values) makes the code maintainable and easy to update.


7-20: Comprehensive margin and width configurations.

The margin and width configurations properly cover Tailwind's utility prefixes and supported units. Including both positive and negative margin values is thorough.


22-59: Extensive width constraint configurations.

The min-width and max-width configurations are comprehensive, covering all viewport units, standard sizes, and special values. The shared constant __w_min_max reduces duplication.


61-104: Complete cursor utility mapping with documentation.

The cursor configuration includes all Tailwind cursor utilities with proper documentation link. This will be valuable for validation and code completion tools.


106-112: Opacity configuration with documentation.

The opacity configuration is straightforward and includes the standard percentage values with proper documentation reference.

@@ -0,0 +1,3 @@
# Grida Canvas Pixel Grid

Infinite pixel grid

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Provide a more detailed description and usage examples

A single line “Infinite pixel grid” is too minimal. Please expand this section to include:

  • A concise summary of what the pixel grid does and why users need it.
  • Installation instructions (e.g., npm install @grida/grida-canvas-pixelgrid).
  • A basic code snippet showing how to import and render the grid.
  • Any key configuration options or API links.

Expanding the README will significantly improve developer onboarding.

@@ -0,0 +1,3 @@
# WIP - React timeline renderer

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance the README title for clarity and consistency.
The current header is very minimal. Consider using the actual package name and a brief tagline. For example:

# @grida/canvas-react-timeline
**Work in Progress**: A React component for rendering interactive timelines

This will align it with other Grida packages and improve discoverability.

Comment on lines +1 to +4
{
"name": "@grida/tailwindcss",
"description": "TailwindCSS Integration for Grida Canvas"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Package.json file is missing essential fields.

This package.json is minimal and lacks important fields required for a proper npm package.

Consider enhancing it with the following fields:

{
  "name": "@grida/tailwindcss",
  "description": "TailwindCSS Integration for Grida Canvas"
+  "version": "0.1.0",
+  "main": "tailwindcss.ts",
+  "types": "tailwindcss.d.ts",
+  "dependencies": {
+    "tailwindcss": "^3.x"
+  },
+  "peerDependencies": {
+    "tailwindcss": "^3.x"
+  },
+  "keywords": ["grida", "tailwindcss", "canvas"],
+  "license": "MIT"
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +4 to +6
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Missing API key validation.

The code creates an OpenAI client without verifying if the API key exists, which could lead to runtime errors.

Add a check to validate the API key's presence:

const openai = new OpenAI({
-  apiKey: process.env.OPENAI_API_KEY,
+  apiKey: process.env.OPENAI_API_KEY || (() => {
+    throw new Error('OPENAI_API_KEY is not defined in environment variables');
+  })(),
});
📝 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.

Suggested change
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY || (() => {
throw new Error('OPENAI_API_KEY is not defined in environment variables');
})(),
});

Comment on lines +8 to +11
export async function GET() {
const result = await openai.models.list();

return NextResponse.json({ data: result.data });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Implement error handling and response caching.

The API endpoint lacks error handling and caching, which could lead to unexpected behavior and potential rate limiting issues.

Add error handling and consider implementing caching:

export async function GET() {
+  try {
    const result = await openai.models.list();
    return NextResponse.json({ data: result.data });
+  } catch (error) {
+    console.error('Error fetching OpenAI models:', error);
+    return NextResponse.json(
+      { error: 'Failed to fetch models from OpenAI' },
+      { status: 500 }
+    );
+  }
}

You might also want to implement caching using Response headers or a caching solution to avoid hitting rate limits:

export async function GET() {
  try {
    const result = await openai.models.list();
-    return NextResponse.json({ data: result.data });
+    const response = NextResponse.json({ data: result.data });
+    // Cache for 1 hour
+    response.headers.set('Cache-Control', 'max-age=3600, s-maxage=3600');
+    return response;
  } catch (error) {
    console.error('Error fetching OpenAI models:', error);
    return NextResponse.json(
      { error: 'Failed to fetch models from OpenAI' },
      { status: 500 }
    );
  }
}
📝 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.

Suggested change
export async function GET() {
const result = await openai.models.list();
return NextResponse.json({ data: result.data });
export async function GET() {
try {
const result = await openai.models.list();
const response = NextResponse.json({ data: result.data });
// Cache for 1 hour
response.headers.set('Cache-Control', 'max-age=3600, s-maxage=3600');
return response;
} catch (error) {
console.error('Error fetching OpenAI models:', error);
return NextResponse.json(
{ error: 'Failed to fetch models from OpenAI' },
{ status: 500 }
);
}
}

Comment on lines +61 to +76
function renderJSONToHTML(node: any): string {
if (typeof node === "string") {
return node;
}

const { tag, class: className, attributes = {}, children = [] } = node;

const classAttr = className ? `class="${className}"` : "";
const attrPairs = Object.entries(attributes).map(([k, v]) => `${k}="${v}"`);
if (classAttr) attrPairs.unshift(classAttr);
const attrString = attrPairs.join(" ");

const childrenHTML = children.map(renderJSONToHTML).join("");

return `<${tag}${attrString ? " " + attrString : ""}>${childrenHTML}</${tag}>`;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve the renderJSONToHTML function with stronger type safety.

The renderJSONToHTML function lacks proper type checking and validation. Add stronger type safety to prevent runtime errors.

- function renderJSONToHTML(node: any): string {
+ function renderJSONToHTML(node: NodeElement | string | null | undefined): string {
+   if (node === null || node === undefined) {
+     return "";
+   }
+   
    if (typeof node === "string") {
      return node;
    }

-   const { tag, class: className, attributes = {}, children = [] } = node;
+   // Ensure required properties exist
+   if (!node.tag) {
+     console.warn("Node is missing required 'tag' property:", node);
+     return "";
+   }
+   
+   const { tag, class: className, attributes = {}, children = [] } = node;

+   // Escape attribute values to prevent XSS
+   const escapedAttributes = Object.entries(attributes).reduce((acc, [k, v]) => {
+     acc[k] = String(v).replace(/"/g, '&quot;');
+     return acc;
+   }, {} as Record<string, string>);
+   
    const classAttr = className ? `class="${className}"` : "";
-   const attrPairs = Object.entries(attributes).map(([k, v]) => `${k}="${v}"`);
+   const attrPairs = Object.entries(escapedAttributes).map(([k, v]) => `${k}="${v}"`);
    if (classAttr) attrPairs.unshift(classAttr);
    const attrString = attrPairs.join(" ");

    const childrenHTML = children.map(renderJSONToHTML).join("");

    return `<${tag}${attrString ? " " + attrString : ""}>${childrenHTML}</${tag}>`;
  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +6 to +11
window.addEventListener("message", (event) => {
if (event.data?.type === "render") {
document.body.innerHTML = event.data.html;
}
});
</script>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add content sanitization before rendering HTML.

Directly setting innerHTML from external sources poses a security risk (XSS). Implement a sanitization step to prevent malicious code execution.

window.addEventListener("message", (event) => {
  if (event.data?.type === "render") {
-   document.body.innerHTML = event.data.html;
+   // Use DOMPurify to sanitize the HTML
+   const sanitizedHtml = DOMPurify.sanitize(event.data.html, {
+     USE_PROFILES: { html: true },
+     ADD_ATTR: ['target']
+   });
+   document.body.innerHTML = sanitizedHtml;
  }
});

Then add DOMPurify to the head:

<head>
  <script src="https://cdn.tailwindcss.com"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.5/purify.min.js"></script>
  <script>

Comment on lines +60 to +77
{presets.map((preset) => (
<CommandItem
key={preset.id}
onSelect={() => {
handlePresetChange(preset);
}}
>
{preset.name}
<Check
className={cn(
"ml-auto",
selectedPreset?.id === preset.id
? "opacity-100"
: "opacity-0"
)}
/>
</CommandItem>
))}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle empty presets array.

The component doesn't handle the case where the presets array is empty. Add a check to display a message when no presets are available.

<CommandList>
  <CommandEmpty>No presets found.</CommandEmpty>
+ {presets.length === 0 && (
+   <CommandItem disabled>No presets available</CommandItem>
+ )}
  {presets.map((preset) => (
    <CommandItem
      key={preset.id}
      onSelect={() => {
        handlePresetChange(preset);
      }}
    >
      {preset.name}
      <Check
        className={cn(
          "ml-auto",
          selectedPreset?.id === preset.id
            ? "opacity-100"
            : "opacity-0"
        )}
      />
    </CommandItem>
  ))}
</CommandList>

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +70 to +71
<ModelSelector />
<ModelParams />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Connect model selection to generation parameters.

The ModelSelector and ModelParams components are rendered but not connected to the generation logic. Update the code to pass the selected model and parameters to the generate function.

+ const [selectedModel, setSelectedModel] = useState<string | undefined>(undefined);
+ const [temperature, setTemperature] = useState<number>(1);
+ const [maxTokens, setMaxTokens] = useState<number>(16384);

// Then update the onPrompt function
const onPrompt = (system: string, prompt: string) => {
  setStreamBusy(true);
  generate({ 
    system, 
    prompt, 
-   maxTokens: 16384, 
-   temperature: 1 
+   maxTokens,
+   temperature,
+   modelId: selectedModel
  }).then(
    // ...
  );
};

// Then update the components
<ModelSelector 
+ onValueChange={(model) => setSelectedModel(model.id)} 
/>
<ModelParams 
+ onTemperatureChange={setTemperature}
+ onMaxTokensChange={setMaxTokens}
+ temperature={temperature}
+ maxTokens={maxTokens}
/>
📝 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.

Suggested change
<ModelSelector />
<ModelParams />
// --- inside your component, at the top: ---
const [selectedModel, setSelectedModel] = useState<string | undefined>(undefined);
const [temperature, setTemperature] = useState<number>(1);
const [maxTokens, setMaxTokens] = useState<number>(16384);
// --- update your onPrompt handler: ---
const onPrompt = (system: string, prompt: string) => {
setStreamBusy(true);
generate({
system,
prompt,
maxTokens,
temperature,
modelId: selectedModel,
}).then(
// ...
);
};
// --- in your JSX, replace the two lines around ModelSelector/ModelParams with: ---
<ModelSelector
onValueChange={(model) => setSelectedModel(model.id)}
/>
<ModelParams
onTemperatureChange={setTemperature}
onMaxTokensChange={setMaxTokens}
temperature={temperature}
maxTokens={maxTokens}
/>

Comment on lines +32 to +44
const onPrompt = (system: string, prompt: string) => {
setStreamBusy(true);
generate({ system, prompt, maxTokens: 16384, temperature: 1 }).then(
async ({ output }) => {
for await (const delta of readStreamableValue(output)) {
// setData(delta as JSONForm);
setResponse(delta as any);
}
generating.current = false;
setStreamBusy(false);
}
);
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for the generation process.

The component doesn't handle errors that might occur during the generation process. Add proper error handling to provide feedback to users.

const onPrompt = (system: string, prompt: string) => {
  setStreamBusy(true);
+ setResponse(null); // Reset previous response
+ 
  generate({ system, prompt, maxTokens: 16384, temperature: 1 }).then(
    async ({ output }) => {
-     for await (const delta of readStreamableValue(output)) {
-       // setData(delta as JSONForm);
-       setResponse(delta as any);
-     }
-     generating.current = false;
-     setStreamBusy(false);
+     try {
+       for await (const delta of readStreamableValue(output)) {
+         setResponse(delta as any);
+       }
+     } catch (error) {
+       console.error("Error during generation:", error);
+       setResponse({ html: `<div class="p-4 text-red-500">Error generating content: ${error.message}</div>` });
+     } finally {
+       generating.current = false;
+       setStreamBusy(false);
+     }
    }
+ ).catch(error => {
+   console.error("Failed to start generation:", error);
+   setResponse({ html: `<div class="p-4 text-red-500">Failed to start generation: ${error.message}</div>` });
+   generating.current = false;
+   setStreamBusy(false);
  );
};

Committable suggestion skipped: line range outside the PR's diff.

This branch was successfully deployed

4 active and 2 inactive deployments
Preview – backgrounds — ab0571e5 Deployed Apr 22, 2025 by vercel[bot]
Preview – legacy-www — ab0571e5 Deployed Apr 22, 2025 by vercel[bot]
Preview – viewer — ab0571e5 Deployed Apr 22, 2025 by vercel[bot]
Preview – grida — ab0571e5 Deployed Apr 22, 2025 by vercel[bot]
Preview – blog — ab0571e5 Deployed Apr 22, 2025 by vercel[bot]
Preview – docs — ab0571e5 Deployed Apr 22, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant