feat: add background panel for solid and gradient backgrounds

feat: implement code inspector with language detection and theme selection

feat: create text inspector for text properties and styling

style: add global styles and custom scrollbar for better UI

chore: initialize main entry point for the application

feat: set up Zustand store for canvas state management

feat: define types for canvas elements and background options

feat: implement code highlighting utility with language detection

chore: configure TypeScript settings for the project

chore: set up Vite configuration for React and Tailwind CSS
This commit is contained in:
2026-01-07 16:07:30 +02:00
commit bb5a9e0715
30 changed files with 6844 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+188
View File
@@ -0,0 +1,188 @@
# Spec: Lightweight Code Canvas for Social Media Images
## 1. Vision & Scope
- Purpose: A simple, fast web canvas to compose export-ready images featuring code blocks, text, and arrows with customizable backgrounds.
- Success Criteria: Create and export high-quality visuals in under 2 minutes, without complex design steps.
- Out of Scope (initial): Slides, animations/video, multi-user collaboration, online sharing/embedding, AI features.
## 2. Target Users & Jobs
- Developer/content creator: Creates quick, branded code images for X/LinkedIn/Instagram.
- Educator: Highlights parts of code with arrows and captions.
- OSS maintainer: Shares release notes with styled code examples.
## 3. Core User Flows
1) Start a new canvas → pick aspect ratio → set background → add code block → add text → add arrows → export PNG/JPEG.
2) Highlight lines in code to focus attention.
## 4. Functional Requirements
### 4.1 Canvas & Layout
- Create canvas with selectable aspect ratios: 1080x1080 (Square), 1920x1080 (16:9), 1600x900 (16:9), 1200x627 (LinkedIn), 1080x1350 (Portrait), 1080x1920 (Story), custom.
- Safe area guides & snapping lines for alignment.
- Grid overlay toggle and configurable spacing.
- Zoom in/out (25%400%) and pan.
### 4.2 Backgrounds
- Solid color (picker + hex), gradient presets, custom gradient.
- Optional brand strip (top/bottom) with color.
### 4.3 Elements
- Element types: Code Block, Text, Arrow.
- Common element actions: add, select, move, resize, rotate, duplicate, delete, bring to front/back, lock, hide.
- Layers panel: reorder, lock, visibility toggles.
#### 4.3.1 Code Block
- Paste/edit code inline.
- Syntax highlighting with selectable themes (e.g., light/dark). Supported languages: Kotlin, Java, extensible.
- Font family selection (e.g., Fira Code, JetBrains Mono), size, line height.
- Optional line numbers.
- Highlight line ranges and single lines; mark as “added” or “removed” styling.
- Indentation width and tab/space display.
- Padding, corner radius, drop shadow.
#### 4.3.2 Text
- Rich text minimal: bold/italic/underline, color, size, line spacing, alignment.
- Font family selection (brand fonts if available).
- Background fill, padding, corner radius, drop shadow.
#### 4.3.3 Arrow
- Styles: straight, curved.
- Properties: color, thickness, arrowhead style (filled/outline), start/end caps.
- Waypoints for curved arrows (23 control points).
- Optional text label attached to arrow.
### 4.4 Selection & Snapping
- Smart guides for center/edge alignment and spacing.
- Magnetic snapping to guides and grid.
- Nudge via arrow keys; modifiers for 1px/10px increments.
### 4.5 Export
- Formats: PNG and JPEG.
- Resolution: scale factor 1x/2x/3x; max 4096px on longest edge.
- Export metadata: remember last export settings.
### 4.6 Persistence
- Local storage autosave per snap.
- Import/export snap as JSON file.
- Open recent snaps list.
### 4.7 Shortcuts
- New snap: Cmd+N; Duplicate: Cmd+D; Delete: Backspace.
- Undo/Redo: Cmd+Z / Shift+Cmd+Z.
- Copy/Paste: Cmd+C / Cmd+V.
- Group/Ungroup: Cmd+G / Shift+Cmd+G.
- Toggle grid: Cmd+; Zoom: Cmd+Plus / Cmd+Minus.
### 4.8 Settings
- Global defaults: theme, default fonts, line numbers on/off, grid spacing.
- Language detection (best-effort) for code block from pasted content.
## 6. Data Model (JSON Schema indicative)
```json
{
"version": "1.0.0",
"meta": {"title": "My Snap", "aspect": "16:9", "width": 1920, "height": 1080},
"background": {
"type": "solid|gradient|image",
"solid": {"color": "#101022"},
"gradient": {"from": "#101022", "to": "#1f1f3a", "angle": 45},
"image": {"src": "data:url|path", "scale": 1, "x": 0, "y": 0, "blur": 0, "opacity": 1}
},
"elements": [
{
"id": "el_1",
"type": "code",
"x": 200, "y": 180, "width": 800, "height": 420, "rotation": 0,
"props": {
"code": "console.log('Hello');",
"language": "javascript",
"theme": "dark",
"fontFamily": "JetBrains Mono",
"fontSize": 16,
"lineHeight": 1.4,
"lineNumbers": true,
"highlights": [{"from": 2, "to": 3, "style": "focus"}],
"padding": 24,
"cornerRadius": 12,
"shadow": {"blur": 24, "spread": 0, "color": "#00000066"}
}
},
{
"id": "el_2",
"type": "text",
"x": 1040, "y": 180, "rotation": 0,
"props": {
"text": "How it works",
"fontFamily": "Inter",
"fontSize": 24,
"color": "#ffffff",
"bold": true,
"align": "left",
"background": {"color": "#00000033"},
"padding": 8,
"cornerRadius": 8
}
},
{
"id": "el_3",
"type": "arrow",
"points": [{"x": 980, "y": 220}, {"x": 880, "y": 260}],
"props": {
"style": "straight",
"color": "#60a5fa",
"thickness": 3,
"head": "filled"
}
}
]
}
```
## 7. UI Layout
- Top Bar: New/Open, aspect ratio, background settings, export button.
- Left Toolbar: element add (Code/Text/Arrow), move/rotate tools, grid toggle.
- Right Inspector: context panel showing properties for selected element; canvas settings when none selected.
- Bottom Bar: zoom, canvas size, snap guides toggle.
- Canvas: center stage with safe area and grid.
## 8. Tech Stack Assumptions (modifiable)
- Frontend: React + TypeScript, Vite.
- Canvas: React Konva (Konva.js) for performant transforms and export to image.
- Syntax highlighting: Shiki (serverless, on-the-fly) or Prism.js; pre-bundled themes.
- State: Zustand (simple, fast) + Immer.
- Persistence: LocalStorage for autosave; file import/export for JSON.
- Export: Konva stage to `toDataURL()`; optional `html-to-image` for mixed DOM.
- Styling: Tailwind CSS or minimal CSS modules.
## 9. Milestones
- M1 (MVP, 12 weeks): Canvas, add/move/resize elements; backgrounds; basic code highlighting; text; arrows; PNG/JPEG export; local autosave.
- M2: Grid/safe guides, snapping, line numbers & highlights; themes; shortcuts.
- M3: Layers panel, curved arrows, brand strip, custom fonts.
- M4: Import/export JSON; recent snaps; performance polish.
## 10. Acceptance Criteria (samples)
- Export: Given a 1920x1080 canvas with 3 elements, exporting PNG at 2x produces a 3840x2160 image in < 1s with correct positioning and anti-aliased edges.
- Code Block: Pasting TypeScript auto-detects TS and renders highlighting; toggling line numbers updates instantly; highlighting lines 35 changes their background.
- Arrow: Changing thickness updates rendering at 60fps while dragging; arrowhead style persists to export.
- Persistence: Closing and reopening restores last snap state within 1s.
## 11. Accessibility & Internationalization
- Keyboard operations for select/move/resize; screen-reader labels on buttons.
- Localizable UI strings; default English.
## 12. Risks & Open Questions
- Font licensing for bundled fonts (JetBrains Mono, Inter).
- Shiki bundle size vs Prism performance and theme parity.
- Very large exports (>4096px) may be slow; consider worker-based rasterization.
- How many languages/themes to ship in MVP?
## 13. Future Enhancements (post-MVP)
- Templates, brand profiles, watermark/avatars.
- Line diff (add/remove styles), blur/opacity regions.
- Drag-to-connect anchors for arrows.
- SVG export, batch export.
- VS Code extension to send selection → canvas.
---
Owner assumptions are placeholders. Please mark any sections to adjust (features, stack, constraints), and well refine before implementation.
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🖼️</text></svg>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Code Canvas - Create Beautiful Code Images</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+3964
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
{
"name": "yvcode",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tailwindcss/vite": "^4.1.18",
"@types/uuid": "^10.0.0",
"immer": "^11.1.3",
"konva": "^10.0.12",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-konva": "^19.2.1",
"shiki": "^3.21.0",
"tailwindcss": "^4.1.18",
"uuid": "^13.0.0",
"zustand": "^5.0.9"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
"vite": "npm:rolldown-vite@7.2.5"
},
"overrides": {
"vite": "npm:rolldown-vite@7.2.5"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+118
View File
@@ -0,0 +1,118 @@
import { useRef, useEffect } from 'react';
import type Konva from 'konva';
import Canvas from './components/Canvas';
import TopBar from './components/TopBar';
import Toolbar from './components/Toolbar';
import Inspector from './components/Inspector';
import { useCanvasStore } from './store/canvasStore';
function App() {
const stageRef = useRef<Konva.Stage>(null);
const {
deleteElement,
duplicateElement,
selectedElementId,
undo,
redo,
setZoom,
zoom,
setShowGrid,
showGrid,
setTool,
selectElement,
} = useCanvasStore();
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const isMeta = e.metaKey || e.ctrlKey;
// Delete
if (e.key === 'Backspace' || e.key === 'Delete') {
if (selectedElementId && !isInputFocused()) {
e.preventDefault();
deleteElement(selectedElementId);
}
}
// Duplicate
if (isMeta && e.key === 'd') {
if (selectedElementId) {
e.preventDefault();
duplicateElement(selectedElementId);
}
}
// Undo
if (isMeta && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
undo();
}
// Redo
if (isMeta && e.key === 'z' && e.shiftKey) {
e.preventDefault();
redo();
}
// Zoom in
if (isMeta && (e.key === '=' || e.key === '+')) {
e.preventDefault();
setZoom(zoom + 0.1);
}
// Zoom out
if (isMeta && e.key === '-') {
e.preventDefault();
setZoom(zoom - 0.1);
}
// Toggle grid
if (isMeta && e.key === ';') {
e.preventDefault();
setShowGrid(!showGrid);
}
// Tool shortcuts (only when not in input)
if (!isInputFocused()) {
if (e.key === 'v' || e.key === 'V') {
setTool('select');
}
if (e.key === 'c' && !isMeta) {
setTool('code');
}
if (e.key === 't' || e.key === 'T') {
setTool('text');
}
if (e.key === 'a' && !isMeta) {
setTool('arrow');
}
if (e.key === 'Escape') {
selectElement(null);
setTool('select');
}
}
};
const isInputFocused = () => {
const active = document.activeElement;
return active?.tagName === 'INPUT' || active?.tagName === 'TEXTAREA' || active?.tagName === 'SELECT';
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectedElementId, deleteElement, duplicateElement, undo, redo, zoom, setZoom, showGrid, setShowGrid, setTool, selectElement]);
return (
<div className="h-screen flex flex-col bg-neutral-900 text-white">
<TopBar stageRef={stageRef} />
<div className="flex-1 flex overflow-hidden">
<Toolbar />
<Canvas stageRef={stageRef} />
<Inspector />
</div>
</div>
);
}
export default App;
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+214
View File
@@ -0,0 +1,214 @@
import React, { useRef, useState, useEffect, useCallback } from 'react';
import { Stage, Layer, Rect, Line } from 'react-konva';
import type Konva from 'konva';
import { useCanvasStore, createCodeElement, createTextElement, createArrowElement } from '../store/canvasStore';
import CodeBlock from './elements/CodeBlock';
import TextBlock from './elements/TextBlock';
import Arrow from './elements/Arrow';
import type { CodeElement, TextElement, ArrowElement } from '../types';
interface CanvasProps {
stageRef: React.RefObject<Konva.Stage | null>;
}
const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: window.innerWidth, height: window.innerHeight - 120 });
const {
snap,
zoom,
showGrid,
tool,
selectedElementId,
selectElement,
addElement,
updateElement,
} = useCanvasStore();
const { width, height } = snap.meta;
const { background } = snap;
// Handle resize
useEffect(() => {
const updateDimensions = () => {
if (containerRef.current) {
setDimensions({
width: containerRef.current.offsetWidth,
height: containerRef.current.offsetHeight,
});
}
};
updateDimensions();
window.addEventListener('resize', updateDimensions);
return () => window.removeEventListener('resize', updateDimensions);
}, []);
// Calculate stage position to center the canvas
const getStagePosition = useCallback(() => {
const scaledWidth = width * zoom;
const scaledHeight = height * zoom;
return {
x: Math.max(20, (dimensions.width - scaledWidth) / 2),
y: Math.max(20, (dimensions.height - scaledHeight) / 2),
};
}, [width, height, zoom, dimensions]);
const handleStageClick = (e: Konva.KonvaEventObject<MouseEvent>) => {
const clickedOnEmpty = e.target === e.target.getStage() || e.target.name() === 'background';
if (clickedOnEmpty) {
const stage = e.target.getStage();
if (!stage) return;
const pos = stage.getPointerPosition();
if (!pos) return;
// Convert screen position to canvas position
const stagePos = getStagePosition();
const canvasX = (pos.x - stagePos.x) / zoom;
const canvasY = (pos.y - stagePos.y) / zoom;
if (tool === 'code') {
addElement(createCodeElement(canvasX - 300, canvasY - 150));
} else if (tool === 'text') {
addElement(createTextElement(canvasX, canvasY));
} else if (tool === 'arrow') {
addElement(createArrowElement(canvasX, canvasY));
} else {
selectElement(null);
}
}
};
// Background gradient
const renderBackground = () => {
if (background.type === 'gradient') {
return (
<Rect
name="background"
x={0}
y={0}
width={width}
height={height}
fillLinearGradientStartPoint={{ x: 0, y: 0 }}
fillLinearGradientEndPoint={{
x: width * Math.cos((background.gradient.angle * Math.PI) / 180),
y: height * Math.sin((background.gradient.angle * Math.PI) / 180)
}}
fillLinearGradientColorStops={[0, background.gradient.from, 1, background.gradient.to]}
/>
);
}
return (
<Rect
name="background"
x={0}
y={0}
width={width}
height={height}
fill={background.solid.color}
/>
);
};
// Grid overlay
const renderGrid = () => {
if (!showGrid) return null;
const gridSize = 50;
const lines = [];
// Vertical lines
for (let i = 0; i <= width; i += gridSize) {
lines.push(
<Line
key={`v-${i}`}
points={[i, 0, i, height]}
stroke="rgba(255,255,255,0.1)"
strokeWidth={1}
/>
);
}
// Horizontal lines
for (let i = 0; i <= height; i += gridSize) {
lines.push(
<Line
key={`h-${i}`}
points={[0, i, width, i]}
stroke="rgba(255,255,255,0.1)"
strokeWidth={1}
/>
);
}
return <>{lines}</>;
};
const stagePosition = getStagePosition();
return (
<div
ref={containerRef}
className="flex-1 bg-neutral-900 overflow-hidden relative"
style={{ cursor: tool !== 'select' ? 'crosshair' : 'default' }}
>
<Stage
ref={stageRef}
width={dimensions.width}
height={dimensions.height}
onClick={handleStageClick}
x={stagePosition.x}
y={stagePosition.y}
scaleX={zoom}
scaleY={zoom}
>
<Layer>
{renderBackground()}
{renderGrid()}
{snap.elements.map((element) => {
if (!element.visible) return null;
switch (element.type) {
case 'code':
return (
<CodeBlock
key={element.id}
element={element as CodeElement}
isSelected={selectedElementId === element.id}
onSelect={() => selectElement(element.id)}
onChange={(updates: Partial<CodeElement>) => updateElement(element.id, updates)}
/>
);
case 'text':
return (
<TextBlock
key={element.id}
element={element as TextElement}
isSelected={selectedElementId === element.id}
onSelect={() => selectElement(element.id)}
onChange={(updates: Partial<TextElement>) => updateElement(element.id, updates)}
/>
);
case 'arrow':
return (
<Arrow
key={element.id}
element={element as ArrowElement}
isSelected={selectedElementId === element.id}
onSelect={() => selectElement(element.id)}
onChange={(updates: Partial<ArrowElement>) => updateElement(element.id, updates)}
/>
);
default:
return null;
}
})}
</Layer>
</Stage>
</div>
);
};
export default Canvas;
+93
View File
@@ -0,0 +1,93 @@
import React from 'react';
import { useCanvasStore } from '../store/canvasStore';
import type { CodeElement, TextElement, ArrowElement } from '../types';
import BackgroundPanel from './inspector/BackgroundPanel';
import CodeInspector from './inspector/CodeInspector';
import TextInspector from './inspector/TextInspector';
import ArrowInspector from './inspector/ArrowInspector';
const Inspector: React.FC = () => {
const {
snap,
selectedElementId,
deleteElement,
duplicateElement,
moveElementUp,
moveElementDown,
} = useCanvasStore();
const selectedElement = snap.elements.find(el => el.id === selectedElementId);
return (
<div className="w-72 bg-neutral-800 border-l border-neutral-700 overflow-y-auto">
<div className="p-4">
{selectedElement ? (
<>
{/* Element header */}
<div className="flex items-center justify-between mb-4">
<h3 className="text-white font-medium capitalize">
{selectedElement.type} Element
</h3>
<div className="flex gap-1">
<button
onClick={() => moveElementDown(selectedElement.id)}
className="p-1.5 hover:bg-neutral-700 rounded text-neutral-400 hover:text-white"
title="Move Back"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 14l-7 7m0 0l-7-7m7 7V3" />
</svg>
</button>
<button
onClick={() => moveElementUp(selectedElement.id)}
className="p-1.5 hover:bg-neutral-700 rounded text-neutral-400 hover:text-white"
title="Move Front"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l7-7m0 0l7 7m-7-7v18" />
</svg>
</button>
<button
onClick={() => duplicateElement(selectedElement.id)}
className="p-1.5 hover:bg-neutral-700 rounded text-neutral-400 hover:text-white"
title="Duplicate (⌘D)"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</button>
<button
onClick={() => deleteElement(selectedElement.id)}
className="p-1.5 hover:bg-red-600 rounded text-neutral-400 hover:text-white"
title="Delete (⌫)"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
{/* Element-specific inspector */}
{selectedElement.type === 'code' && (
<CodeInspector element={selectedElement as CodeElement} />
)}
{selectedElement.type === 'text' && (
<TextInspector element={selectedElement as TextElement} />
)}
{selectedElement.type === 'arrow' && (
<ArrowInspector element={selectedElement as ArrowElement} />
)}
</>
) : (
<>
<h3 className="text-white font-medium mb-4">Canvas Settings</h3>
<BackgroundPanel />
</>
)}
</div>
</div>
);
};
export default Inspector;
+82
View File
@@ -0,0 +1,82 @@
import React from 'react';
import { useCanvasStore } from '../store/canvasStore';
const Toolbar: React.FC = () => {
const { tool, setTool, showGrid, setShowGrid, zoom, setZoom } = useCanvasStore();
const tools = [
{ id: 'select', icon: '↖', label: 'Select (V)' },
{ id: 'code', icon: '{ }', label: 'Code Block (C)' },
{ id: 'text', icon: 'T', label: 'Text (T)' },
{ id: 'arrow', icon: '→', label: 'Arrow (A)' },
] as const;
return (
<div className="w-14 bg-neutral-800 border-r border-neutral-700 flex flex-col items-center py-4 gap-2">
{/* Tools */}
<div className="flex flex-col gap-1">
{tools.map(({ id, icon, label }) => (
<button
key={id}
onClick={() => setTool(id)}
className={`w-10 h-10 rounded flex items-center justify-center text-lg transition-colors ${
tool === id
? 'bg-blue-600 text-white'
: 'text-neutral-400 hover:bg-neutral-700 hover:text-white'
}`}
title={label}
>
{icon}
</button>
))}
</div>
<div className="h-px w-8 bg-neutral-600 my-2" />
{/* Grid toggle */}
<button
onClick={() => setShowGrid(!showGrid)}
className={`w-10 h-10 rounded flex items-center justify-center transition-colors ${
showGrid
? 'bg-neutral-600 text-white'
: 'text-neutral-400 hover:bg-neutral-700 hover:text-white'
}`}
title="Toggle Grid (⌘;)"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM9 4v16M15 4v16M4 9h16M4 15h16" />
</svg>
</button>
{/* Spacer */}
<div className="flex-1" />
{/* Zoom controls */}
<div className="flex flex-col gap-1">
<button
onClick={() => setZoom(zoom + 0.1)}
className="w-10 h-10 rounded flex items-center justify-center text-neutral-400 hover:bg-neutral-700 hover:text-white transition-colors"
title="Zoom In (⌘+)"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v6m3-3H7" />
</svg>
</button>
<div className="text-xs text-neutral-400 text-center py-1">
{Math.round(zoom * 100)}%
</div>
<button
onClick={() => setZoom(zoom - 0.1)}
className="w-10 h-10 rounded flex items-center justify-center text-neutral-400 hover:bg-neutral-700 hover:text-white transition-colors"
title="Zoom Out (⌘-)"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM13 10H7" />
</svg>
</button>
</div>
</div>
);
};
export default Toolbar;
+219
View File
@@ -0,0 +1,219 @@
import React from 'react';
import { useCanvasStore } from '../store/canvasStore';
import { ASPECT_RATIOS } from '../types';
import type Konva from 'konva';
interface TopBarProps {
stageRef: React.RefObject<Konva.Stage | null>;
}
const TopBar: React.FC<TopBarProps> = ({ stageRef }) => {
const {
snap,
updateMeta,
newSnap,
exportSnap,
importSnap,
undo,
redo,
history,
} = useCanvasStore();
const handleNewSnap = () => {
if (confirm('Create a new canvas? Unsaved changes will be lost.')) {
newSnap({ title: 'Untitled', aspect: '16:9', width: 1920, height: 1080 });
}
};
const handleAspectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const ratio = ASPECT_RATIOS.find(r => r.name === e.target.value);
if (ratio) {
updateMeta({
aspect: ratio.name,
width: ratio.width,
height: ratio.height,
});
}
};
const handleExportImage = async (format: 'png' | 'jpeg', scale: number = 2) => {
const stage = stageRef.current;
if (!stage) return;
// Temporarily set scale for export
const oldScale = stage.scaleX();
const oldPosition = { x: stage.x(), y: stage.y() };
stage.scale({ x: scale, y: scale });
stage.position({ x: 0, y: 0 });
const dataUrl = stage.toDataURL({
pixelRatio: 1,
mimeType: format === 'png' ? 'image/png' : 'image/jpeg',
quality: 0.95,
width: snap.meta.width * scale,
height: snap.meta.height * scale,
});
// Restore scale
stage.scale({ x: oldScale, y: oldScale });
stage.position(oldPosition);
// Download
const link = document.createElement('a');
link.download = `${snap.meta.title || 'canvas'}.${format}`;
link.href = dataUrl;
link.click();
};
const handleExportJSON = () => {
const json = exportSnap();
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = `${snap.meta.title || 'canvas'}.json`;
link.href = url;
link.click();
URL.revokeObjectURL(url);
};
const handleImportJSON = () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const json = e.target?.result as string;
importSnap(json);
};
reader.readAsText(file);
}
};
input.click();
};
return (
<div className="h-14 bg-neutral-800 border-b border-neutral-700 flex items-center justify-between px-4">
{/* Left section */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<button
onClick={handleNewSnap}
className="p-2 hover:bg-neutral-700 rounded text-neutral-300 hover:text-white transition-colors"
title="New (⌘N)"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
</button>
<button
onClick={handleImportJSON}
className="p-2 hover:bg-neutral-700 rounded text-neutral-300 hover:text-white transition-colors"
title="Open"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z" />
</svg>
</button>
</div>
<div className="h-6 w-px bg-neutral-600" />
<div className="flex items-center gap-2">
<button
onClick={undo}
disabled={history.past.length === 0}
className="p-2 hover:bg-neutral-700 rounded text-neutral-300 hover:text-white transition-colors disabled:opacity-30"
title="Undo (⌘Z)"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
</svg>
</button>
<button
onClick={redo}
disabled={history.future.length === 0}
className="p-2 hover:bg-neutral-700 rounded text-neutral-300 hover:text-white transition-colors disabled:opacity-30"
title="Redo (⇧⌘Z)"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 10h-10a8 8 0 00-8 8v2M21 10l-6 6m6-6l-6-6" />
</svg>
</button>
</div>
</div>
{/* Center section */}
<div className="flex items-center gap-4">
<input
type="text"
value={snap.meta.title}
onChange={(e) => updateMeta({ title: e.target.value })}
className="bg-transparent text-white text-center px-2 py-1 border-b border-transparent hover:border-neutral-600 focus:border-blue-500 outline-none"
/>
<select
value={snap.meta.aspect}
onChange={handleAspectChange}
className="bg-neutral-700 text-white px-3 py-1.5 rounded text-sm"
>
{ASPECT_RATIOS.map((ratio) => (
<option key={ratio.name} value={ratio.name}>
{ratio.name}
</option>
))}
</select>
</div>
{/* Right section */}
<div className="flex items-center gap-2">
<button
onClick={handleExportJSON}
className="px-3 py-1.5 text-sm bg-neutral-700 hover:bg-neutral-600 rounded text-white transition-colors"
>
Save JSON
</button>
<div className="relative group">
<button
className="px-4 py-1.5 text-sm bg-blue-600 hover:bg-blue-500 rounded text-white font-medium transition-colors"
>
Export
</button>
<div className="absolute right-0 top-full mt-1 bg-neutral-800 border border-neutral-700 rounded shadow-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50">
<button
onClick={() => handleExportImage('png', 1)}
className="block w-full px-4 py-2 text-sm text-left text-white hover:bg-neutral-700"
>
PNG (1x)
</button>
<button
onClick={() => handleExportImage('png', 2)}
className="block w-full px-4 py-2 text-sm text-left text-white hover:bg-neutral-700"
>
PNG (2x)
</button>
<button
onClick={() => handleExportImage('png', 3)}
className="block w-full px-4 py-2 text-sm text-left text-white hover:bg-neutral-700"
>
PNG (3x)
</button>
<div className="border-t border-neutral-700" />
<button
onClick={() => handleExportImage('jpeg', 2)}
className="block w-full px-4 py-2 text-sm text-left text-white hover:bg-neutral-700"
>
JPEG (2x)
</button>
</div>
</div>
</div>
</div>
);
};
export default TopBar;
+70
View File
@@ -0,0 +1,70 @@
import React, { useRef } from 'react';
import { Group, Arrow as KonvaArrow, Circle } from 'react-konva';
import type Konva from 'konva';
import type { ArrowElement } from '../../types';
interface ArrowProps {
element: ArrowElement;
isSelected: boolean;
onSelect: () => void;
onChange: (updates: Partial<ArrowElement>) => void;
}
const Arrow: React.FC<ArrowProps> = ({ element, isSelected, onSelect, onChange }) => {
const arrowRef = useRef<Konva.Arrow>(null);
const { points, props } = element;
// Flatten points for Konva
const flatPoints = points.flatMap(p => [p.x, p.y]);
const handlePointDrag = (index: number, e: Konva.KonvaEventObject<DragEvent>) => {
const newPoints = [...points];
newPoints[index] = {
x: e.target.x(),
y: e.target.y(),
};
onChange({ points: newPoints });
};
// Arrow head pointer
const pointerLength = props.head === 'none' ? 0 : props.thickness * 4;
const pointerWidth = props.head === 'none' ? 0 : props.thickness * 3;
return (
<Group>
<KonvaArrow
ref={arrowRef}
points={flatPoints}
stroke={props.color}
strokeWidth={props.thickness}
fill={props.head === 'filled' ? props.color : 'transparent'}
pointerLength={pointerLength}
pointerWidth={pointerWidth}
tension={props.style === 'curved' ? 0.5 : 0}
lineCap="round"
lineJoin="round"
onClick={onSelect}
onTap={onSelect}
hitStrokeWidth={20}
/>
{/* Control points when selected */}
{isSelected && points.map((point, index) => (
<Circle
key={index}
x={point.x}
y={point.y}
radius={8}
fill="#3b82f6"
stroke="#ffffff"
strokeWidth={2}
draggable={!element.locked}
onDragMove={(e) => handlePointDrag(index, e)}
onDragEnd={(e) => handlePointDrag(index, e)}
/>
))}
</Group>
);
};
export default Arrow;
+184
View File
@@ -0,0 +1,184 @@
import React, { useRef, useEffect } from 'react';
import { Group, Rect, Text, Transformer } from 'react-konva';
import type Konva from 'konva';
import type { CodeElement } from '../../types';
interface CodeBlockProps {
element: CodeElement;
isSelected: boolean;
onSelect: () => void;
onChange: (updates: Partial<CodeElement>) => void;
}
const CodeBlock: React.FC<CodeBlockProps> = ({ element, isSelected, onSelect, onChange }) => {
const groupRef = useRef<Konva.Group>(null);
const trRef = useRef<Konva.Transformer>(null);
const { x, y, width, height, rotation, props } = element;
useEffect(() => {
if (isSelected && trRef.current && groupRef.current) {
trRef.current.nodes([groupRef.current]);
trRef.current.getLayer()?.batchDraw();
}
}, [isSelected]);
// Simple code rendering with line numbers
const renderCode = () => {
const lines = props.code.split('\n');
const lineHeight = props.fontSize * props.lineHeight;
const startY = props.padding;
const lineNumberWidth = props.lineNumbers ? 40 : 0;
const elements: React.ReactNode[] = [];
lines.forEach((line, index) => {
const yPos = startY + index * lineHeight;
const lineNum = index + 1;
// Check if this line is highlighted
const highlight = props.highlights.find(
h => lineNum >= h.from && lineNum <= h.to
);
// Line highlight background
if (highlight) {
let bgColor = 'rgba(255, 255, 0, 0.15)'; // focus
if (highlight.style === 'added') bgColor = 'rgba(0, 255, 0, 0.15)';
if (highlight.style === 'removed') bgColor = 'rgba(255, 0, 0, 0.15)';
elements.push(
<Rect
key={`highlight-${index}`}
x={0}
y={yPos - 2}
width={width}
height={lineHeight}
fill={bgColor}
/>
);
}
// Line number
if (props.lineNumbers) {
elements.push(
<Text
key={`linenum-${index}`}
x={props.padding}
y={yPos}
text={String(lineNum)}
fontSize={props.fontSize}
fontFamily={props.fontFamily}
fill={props.theme === 'dark' ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.4)'}
width={30}
align="right"
/>
);
}
// Code text
elements.push(
<Text
key={`code-${index}`}
x={props.padding + lineNumberWidth + 10}
y={yPos}
text={line || ' '}
fontSize={props.fontSize}
fontFamily={props.fontFamily}
fill={props.theme === 'dark' ? '#e5e5e5' : '#1f1f1f'}
/>
);
});
return elements;
};
const handleDragEnd = (e: Konva.KonvaEventObject<DragEvent>) => {
onChange({
x: e.target.x(),
y: e.target.y(),
});
};
const handleTransformEnd = () => {
const node = groupRef.current;
if (!node) return;
const scaleX = node.scaleX();
const scaleY = node.scaleY();
node.scaleX(1);
node.scaleY(1);
onChange({
x: node.x(),
y: node.y(),
width: Math.max(200, node.width() * scaleX),
height: Math.max(100, node.height() * scaleY),
rotation: node.rotation(),
});
};
const bgColor = props.theme === 'dark' ? '#1e1e2e' : '#f8f8f8';
return (
<>
<Group
ref={groupRef}
x={x}
y={y}
width={width}
height={height}
rotation={rotation}
draggable={!element.locked}
onClick={onSelect}
onTap={onSelect}
onDragEnd={handleDragEnd}
onTransformEnd={handleTransformEnd}
>
{/* Shadow */}
<Rect
x={props.shadow.spread}
y={props.shadow.spread}
width={width}
height={height}
cornerRadius={props.cornerRadius}
fill={props.shadow.color}
shadowBlur={props.shadow.blur}
shadowColor={props.shadow.color}
/>
{/* Background */}
<Rect
width={width}
height={height}
fill={bgColor}
cornerRadius={props.cornerRadius}
/>
{/* Code content */}
<Group clipFunc={(ctx) => {
ctx.beginPath();
ctx.roundRect(0, 0, width, height, props.cornerRadius);
ctx.closePath();
}}>
{renderCode()}
</Group>
</Group>
{isSelected && (
<Transformer
ref={trRef}
flipEnabled={false}
boundBoxFunc={(oldBox, newBox) => {
if (Math.abs(newBox.width) < 200 || Math.abs(newBox.height) < 100) {
return oldBox;
}
return newBox;
}}
/>
)}
</>
);
};
export default CodeBlock;
+120
View File
@@ -0,0 +1,120 @@
import React, { useRef, useEffect, useState } from 'react';
import { Group, Rect, Text, Transformer } from 'react-konva';
import type Konva from 'konva';
import type { TextElement } from '../../types';
interface TextBlockProps {
element: TextElement;
isSelected: boolean;
onSelect: () => void;
onChange: (updates: Partial<TextElement>) => void;
}
const TextBlock: React.FC<TextBlockProps> = ({ element, isSelected, onSelect, onChange }) => {
const groupRef = useRef<Konva.Group>(null);
const textRef = useRef<Konva.Text>(null);
const trRef = useRef<Konva.Transformer>(null);
const [textDimensions, setTextDimensions] = useState({ width: 200, height: 30 });
const { x, y, rotation, props } = element;
useEffect(() => {
if (isSelected && trRef.current && groupRef.current) {
trRef.current.nodes([groupRef.current]);
trRef.current.getLayer()?.batchDraw();
}
}, [isSelected]);
useEffect(() => {
if (textRef.current) {
setTextDimensions({
width: textRef.current.width(),
height: textRef.current.height(),
});
}
}, [props.text, props.fontSize, props.fontFamily, props.bold, props.italic]);
const handleDragEnd = (e: Konva.KonvaEventObject<DragEvent>) => {
onChange({
x: e.target.x(),
y: e.target.y(),
});
};
const handleTransformEnd = () => {
const node = groupRef.current;
if (!node) return;
node.scaleX(1);
node.scaleY(1);
onChange({
x: node.x(),
y: node.y(),
rotation: node.rotation(),
});
};
const totalWidth = textDimensions.width + props.padding * 2;
const totalHeight = textDimensions.height + props.padding * 2;
const fontStyle = [
props.bold ? 'bold' : '',
props.italic ? 'italic' : '',
].filter(Boolean).join(' ') || 'normal';
return (
<>
<Group
ref={groupRef}
x={x}
y={y}
rotation={rotation}
draggable={!element.locked}
onClick={onSelect}
onTap={onSelect}
onDragEnd={handleDragEnd}
onTransformEnd={handleTransformEnd}
>
{/* Background */}
{props.background && (
<Rect
x={-props.padding}
y={-props.padding}
width={totalWidth}
height={totalHeight}
fill={props.background.color}
cornerRadius={props.cornerRadius}
/>
)}
{/* Text */}
<Text
ref={textRef}
text={props.text}
fontSize={props.fontSize}
fontFamily={props.fontFamily}
fontStyle={fontStyle}
fill={props.color}
align={props.align}
textDecoration={props.underline ? 'underline' : ''}
/>
</Group>
{isSelected && (
<Transformer
ref={trRef}
flipEnabled={false}
enabledAnchors={['middle-left', 'middle-right']}
boundBoxFunc={(oldBox, newBox) => {
if (Math.abs(newBox.width) < 50) {
return oldBox;
}
return newBox;
}}
/>
)}
</>
);
};
export default TextBlock;
+131
View File
@@ -0,0 +1,131 @@
import React from 'react';
import { useCanvasStore } from '../../store/canvasStore';
import type { ArrowElement } from '../../types';
interface ArrowInspectorProps {
element: ArrowElement;
}
const ArrowInspector: React.FC<ArrowInspectorProps> = ({ element }) => {
const { updateElement } = useCanvasStore();
const update = (updates: Partial<ArrowElement>) => {
updateElement(element.id, updates);
};
const updateProps = (props: Partial<ArrowElement['props']>) => {
update({ props: { ...element.props, ...props } });
};
return (
<div className="space-y-4">
{/* Style */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Style</label>
<div className="flex gap-2">
<button
onClick={() => updateProps({ style: 'straight' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.style === 'straight'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Straight
</button>
<button
onClick={() => updateProps({ style: 'curved' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.style === 'curved'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Curved
</button>
</div>
</div>
{/* Color */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Color</label>
<div className="flex gap-2 items-center">
<input
type="color"
value={element.props.color}
onChange={(e) => updateProps({ color: e.target.value })}
className="w-10 h-10 rounded cursor-pointer bg-transparent"
/>
<input
type="text"
value={element.props.color}
onChange={(e) => updateProps({ color: e.target.value })}
className="flex-1 bg-neutral-700 text-white px-3 py-2 rounded text-sm"
/>
</div>
</div>
{/* Thickness */}
<div>
<label className="block text-sm text-neutral-400 mb-2">
Thickness: {element.props.thickness}px
</label>
<input
type="range"
value={element.props.thickness}
onChange={(e) => updateProps({ thickness: parseInt(e.target.value) })}
className="w-full"
min={1}
max={12}
/>
</div>
{/* Arrow head */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Arrow Head</label>
<div className="flex gap-2">
<button
onClick={() => updateProps({ head: 'filled' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.head === 'filled'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Filled
</button>
<button
onClick={() => updateProps({ head: 'outline' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.head === 'outline'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Outline
</button>
<button
onClick={() => updateProps({ head: 'none' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.head === 'none'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
None
</button>
</div>
</div>
{/* Points info */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Points</label>
<p className="text-xs text-neutral-500">
Drag the blue handles on the canvas to adjust arrow points.
</p>
</div>
</div>
);
};
export default ArrowInspector;
@@ -0,0 +1,155 @@
import React from 'react';
import { useCanvasStore } from '../../store/canvasStore';
const GRADIENT_PRESETS = [
{ from: '#101022', to: '#1f1f3a', name: 'Midnight' },
{ from: '#0f172a', to: '#1e3a5f', name: 'Ocean' },
{ from: '#1a1a2e', to: '#16213e', name: 'Deep Blue' },
{ from: '#0f0f0f', to: '#232323', name: 'Charcoal' },
{ from: '#1a1a1a', to: '#2d2d2d', name: 'Dark' },
{ from: '#2d1b4e', to: '#1a1a2e', name: 'Purple' },
{ from: '#1e3c72', to: '#2a5298', name: 'Royal' },
{ from: '#134e5e', to: '#71b280', name: 'Teal' },
{ from: '#f5f5f5', to: '#e0e0e0', name: 'Light' },
{ from: '#ffffff', to: '#f0f0f0', name: 'White' },
];
const BackgroundPanel: React.FC = () => {
const { snap, setBackground } = useCanvasStore();
const { background } = snap;
return (
<div className="space-y-4">
{/* Background type */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Type</label>
<div className="flex gap-2">
<button
onClick={() => setBackground({ type: 'solid' })}
className={`flex-1 py-2 rounded text-sm ${
background.type === 'solid'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300 hover:bg-neutral-600'
}`}
>
Solid
</button>
<button
onClick={() => setBackground({ type: 'gradient' })}
className={`flex-1 py-2 rounded text-sm ${
background.type === 'gradient'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300 hover:bg-neutral-600'
}`}
>
Gradient
</button>
</div>
</div>
{background.type === 'solid' ? (
<div>
<label className="block text-sm text-neutral-400 mb-2">Color</label>
<div className="flex gap-2 items-center">
<input
type="color"
value={background.solid.color}
onChange={(e) => setBackground({ solid: { color: e.target.value } })}
className="w-10 h-10 rounded cursor-pointer bg-transparent"
/>
<input
type="text"
value={background.solid.color}
onChange={(e) => setBackground({ solid: { color: e.target.value } })}
className="flex-1 bg-neutral-700 text-white px-3 py-2 rounded text-sm"
/>
</div>
</div>
) : (
<>
<div>
<label className="block text-sm text-neutral-400 mb-2">Presets</label>
<div className="grid grid-cols-5 gap-2">
{GRADIENT_PRESETS.map((preset, i) => (
<button
key={i}
onClick={() => setBackground({
gradient: { ...background.gradient, from: preset.from, to: preset.to }
})}
className="w-10 h-10 rounded border border-neutral-600 hover:border-blue-500 transition-colors"
style={{
background: `linear-gradient(135deg, ${preset.from}, ${preset.to})`
}}
title={preset.name}
/>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm text-neutral-400 mb-2">From</label>
<div className="flex gap-2 items-center">
<input
type="color"
value={background.gradient.from}
onChange={(e) => setBackground({
gradient: { ...background.gradient, from: e.target.value }
})}
className="w-8 h-8 rounded cursor-pointer bg-transparent"
/>
<input
type="text"
value={background.gradient.from}
onChange={(e) => setBackground({
gradient: { ...background.gradient, from: e.target.value }
})}
className="flex-1 bg-neutral-700 text-white px-2 py-1.5 rounded text-xs"
/>
</div>
</div>
<div>
<label className="block text-sm text-neutral-400 mb-2">To</label>
<div className="flex gap-2 items-center">
<input
type="color"
value={background.gradient.to}
onChange={(e) => setBackground({
gradient: { ...background.gradient, to: e.target.value }
})}
className="w-8 h-8 rounded cursor-pointer bg-transparent"
/>
<input
type="text"
value={background.gradient.to}
onChange={(e) => setBackground({
gradient: { ...background.gradient, to: e.target.value }
})}
className="flex-1 bg-neutral-700 text-white px-2 py-1.5 rounded text-xs"
/>
</div>
</div>
</div>
<div>
<label className="block text-sm text-neutral-400 mb-2">
Angle: {background.gradient.angle}°
</label>
<input
type="range"
min="0"
max="360"
value={background.gradient.angle}
onChange={(e) => setBackground({
gradient: { ...background.gradient, angle: parseInt(e.target.value) }
})}
className="w-full"
/>
</div>
</>
)}
</div>
);
};
export default BackgroundPanel;
+202
View File
@@ -0,0 +1,202 @@
import React from 'react';
import { useCanvasStore } from '../../store/canvasStore';
import type { CodeElement } from '../../types';
import { LANGUAGES, FONT_FAMILIES } from '../../types';
import { detectLanguage } from '../../utils/highlighter';
interface CodeInspectorProps {
element: CodeElement;
}
const CodeInspector: React.FC<CodeInspectorProps> = ({ element }) => {
const { updateElement, saveToHistory } = useCanvasStore();
const update = (updates: Partial<CodeElement>) => {
updateElement(element.id, updates);
};
const updateProps = (props: Partial<CodeElement['props']>) => {
update({ props: { ...element.props, ...props } });
};
const handleCodeChange = (code: string) => {
updateProps({ code });
};
const handleAutoDetect = () => {
const detected = detectLanguage(element.props.code);
updateProps({ language: detected });
};
return (
<div className="space-y-4">
{/* Code editor */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Code</label>
<textarea
value={element.props.code}
onChange={(e) => handleCodeChange(e.target.value)}
onBlur={saveToHistory}
className="w-full h-32 bg-neutral-900 text-white text-sm font-mono p-3 rounded resize-y"
spellCheck={false}
/>
</div>
{/* Language */}
<div>
<div className="flex items-center justify-between mb-2">
<label className="text-sm text-neutral-400">Language</label>
<button
onClick={handleAutoDetect}
className="text-xs text-blue-400 hover:text-blue-300"
>
Auto-detect
</button>
</div>
<select
value={element.props.language}
onChange={(e) => updateProps({ language: e.target.value })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
>
{LANGUAGES.map((lang) => (
<option key={lang} value={lang}>
{lang}
</option>
))}
</select>
</div>
{/* Theme */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Theme</label>
<div className="flex gap-2">
<button
onClick={() => updateProps({ theme: 'dark' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.theme === 'dark'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Dark
</button>
<button
onClick={() => updateProps({ theme: 'light' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.theme === 'light'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Light
</button>
</div>
</div>
{/* Font */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Font</label>
<select
value={element.props.fontFamily}
onChange={(e) => updateProps({ fontFamily: e.target.value })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
>
{FONT_FAMILIES.code.map((font) => (
<option key={font} value={font}>
{font}
</option>
))}
</select>
</div>
{/* Font size & Line height */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm text-neutral-400 mb-2">Size</label>
<input
type="number"
value={element.props.fontSize}
onChange={(e) => updateProps({ fontSize: parseInt(e.target.value) || 14 })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
min={10}
max={32}
/>
</div>
<div>
<label className="block text-sm text-neutral-400 mb-2">Line Height</label>
<input
type="number"
value={element.props.lineHeight}
onChange={(e) => updateProps({ lineHeight: parseFloat(e.target.value) || 1.5 })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
min={1}
max={3}
step={0.1}
/>
</div>
</div>
{/* Line numbers */}
<div className="flex items-center justify-between">
<label className="text-sm text-neutral-400">Line Numbers</label>
<button
onClick={() => updateProps({ lineNumbers: !element.props.lineNumbers })}
className={`w-12 h-6 rounded-full transition-colors ${
element.props.lineNumbers ? 'bg-blue-600' : 'bg-neutral-600'
}`}
>
<div
className={`w-5 h-5 bg-white rounded-full transition-transform ${
element.props.lineNumbers ? 'translate-x-6' : 'translate-x-0.5'
}`}
/>
</button>
</div>
{/* Padding & Corner radius */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm text-neutral-400 mb-2">Padding</label>
<input
type="number"
value={element.props.padding}
onChange={(e) => updateProps({ padding: parseInt(e.target.value) || 0 })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
min={0}
max={64}
/>
</div>
<div>
<label className="block text-sm text-neutral-400 mb-2">Radius</label>
<input
type="number"
value={element.props.cornerRadius}
onChange={(e) => updateProps({ cornerRadius: parseInt(e.target.value) || 0 })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
min={0}
max={32}
/>
</div>
</div>
{/* Shadow */}
<div>
<label className="block text-sm text-neutral-400 mb-2">
Shadow Blur: {element.props.shadow.blur}
</label>
<input
type="range"
value={element.props.shadow.blur}
onChange={(e) => updateProps({
shadow: { ...element.props.shadow, blur: parseInt(e.target.value) }
})}
className="w-full"
min={0}
max={64}
/>
</div>
</div>
);
};
export default CodeInspector;
+198
View File
@@ -0,0 +1,198 @@
import React from 'react';
import { useCanvasStore } from '../../store/canvasStore';
import type { TextElement } from '../../types';
import { FONT_FAMILIES } from '../../types';
interface TextInspectorProps {
element: TextElement;
}
const TextInspector: React.FC<TextInspectorProps> = ({ element }) => {
const { updateElement, saveToHistory } = useCanvasStore();
const update = (updates: Partial<TextElement>) => {
updateElement(element.id, updates);
};
const updateProps = (props: Partial<TextElement['props']>) => {
update({ props: { ...element.props, ...props } });
};
return (
<div className="space-y-4">
{/* Text */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Text</label>
<textarea
value={element.props.text}
onChange={(e) => updateProps({ text: e.target.value })}
onBlur={saveToHistory}
className="w-full h-24 bg-neutral-900 text-white text-sm p-3 rounded resize-y"
/>
</div>
{/* Font */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Font</label>
<select
value={element.props.fontFamily}
onChange={(e) => updateProps({ fontFamily: e.target.value })}
className="w-full bg-neutral-700 text-white px-3 py-2 rounded text-sm"
>
{FONT_FAMILIES.text.map((font) => (
<option key={font} value={font}>
{font}
</option>
))}
</select>
</div>
{/* Font size */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Size: {element.props.fontSize}</label>
<input
type="range"
value={element.props.fontSize}
onChange={(e) => updateProps({ fontSize: parseInt(e.target.value) })}
className="w-full"
min={12}
max={96}
/>
</div>
{/* Color */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Color</label>
<div className="flex gap-2 items-center">
<input
type="color"
value={element.props.color}
onChange={(e) => updateProps({ color: e.target.value })}
className="w-10 h-10 rounded cursor-pointer bg-transparent"
/>
<input
type="text"
value={element.props.color}
onChange={(e) => updateProps({ color: e.target.value })}
className="flex-1 bg-neutral-700 text-white px-3 py-2 rounded text-sm"
/>
</div>
</div>
{/* Style buttons */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Style</label>
<div className="flex gap-2">
<button
onClick={() => updateProps({ bold: !element.props.bold })}
className={`flex-1 py-2 rounded text-sm font-bold ${
element.props.bold
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
B
</button>
<button
onClick={() => updateProps({ italic: !element.props.italic })}
className={`flex-1 py-2 rounded text-sm italic ${
element.props.italic
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
I
</button>
<button
onClick={() => updateProps({ underline: !element.props.underline })}
className={`flex-1 py-2 rounded text-sm underline ${
element.props.underline
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
U
</button>
</div>
</div>
{/* Alignment */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Alignment</label>
<div className="flex gap-2">
<button
onClick={() => updateProps({ align: 'left' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.align === 'left'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Left
</button>
<button
onClick={() => updateProps({ align: 'center' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.align === 'center'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Center
</button>
<button
onClick={() => updateProps({ align: 'right' })}
className={`flex-1 py-2 rounded text-sm ${
element.props.align === 'right'
? 'bg-blue-600 text-white'
: 'bg-neutral-700 text-neutral-300'
}`}
>
Right
</button>
</div>
</div>
{/* Background */}
<div>
<div className="flex items-center justify-between mb-2">
<label className="text-sm text-neutral-400">Background</label>
<button
onClick={() => updateProps({
background: element.props.background
? null
: { color: 'rgba(0,0,0,0.5)' }
})}
className={`w-12 h-6 rounded-full transition-colors ${
element.props.background ? 'bg-blue-600' : 'bg-neutral-600'
}`}
>
<div
className={`w-5 h-5 bg-white rounded-full transition-transform ${
element.props.background ? 'translate-x-6' : 'translate-x-0.5'
}`}
/>
</button>
</div>
{element.props.background && (
<div className="flex gap-2 items-center">
<input
type="color"
value={element.props.background.color.substring(0, 7)}
onChange={(e) => updateProps({ background: { color: e.target.value } })}
className="w-10 h-10 rounded cursor-pointer bg-transparent"
/>
<input
type="text"
value={element.props.background.color}
onChange={(e) => updateProps({ background: { color: e.target.value } })}
className="flex-1 bg-neutral-700 text-white px-3 py-2 rounded text-sm"
/>
</div>
)}
</div>
</div>
);
};
export default TextInspector;
+106
View File
@@ -0,0 +1,106 @@
@import "tailwindcss";
@font-face {
font-family: 'JetBrains Mono';
src: url('https://fonts.gstatic.com/s/jetbrainsmono/v18/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPVmUsaaDhw.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'Inter';
src: url('https://fonts.gstatic.com/s/inter/v13/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuLyfAZ9hjp-Ek-_EeA.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: 'Inter', system-ui, -apple-system, sans-serif;
background-color: #171717;
color: #ffffff;
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #262626;
}
::-webkit-scrollbar-thumb {
background: #525252;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #737373;
}
/* Color picker styling */
input[type="color"] {
-webkit-appearance: none;
border: none;
padding: 0;
}
input[type="color"]::-webkit-color-swatch-wrapper {
padding: 0;
}
input[type="color"]::-webkit-color-swatch {
border: 1px solid #525252;
border-radius: 4px;
}
/* Range slider styling */
input[type="range"] {
-webkit-appearance: none;
appearance: none;
background: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-runnable-track {
background: #404040;
height: 6px;
border-radius: 3px;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
margin-top: -5px;
background-color: #3b82f6;
height: 16px;
width: 16px;
border-radius: 50%;
}
input[type="range"]:focus {
outline: none;
}
/* Select styling */
select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='white'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 8px center;
background-size: 16px;
padding-right: 32px;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+293
View File
@@ -0,0 +1,293 @@
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { persist } from 'zustand/middleware';
import { v4 as uuidv4 } from 'uuid';
import type {
Snap,
CanvasElement,
CodeElement,
TextElement,
ArrowElement,
Background,
CanvasMeta,
} from '../types';
interface HistoryState {
past: Snap[];
future: Snap[];
}
interface CanvasState {
snap: Snap;
selectedElementId: string | null;
zoom: number;
showGrid: boolean;
tool: 'select' | 'code' | 'text' | 'arrow';
history: HistoryState;
// Actions
setSnap: (snap: Snap) => void;
updateMeta: (meta: Partial<CanvasMeta>) => void;
setBackground: (background: Partial<Background>) => void;
addElement: (element: CanvasElement) => void;
updateElement: (id: string, updates: Partial<CanvasElement>) => void;
deleteElement: (id: string) => void;
duplicateElement: (id: string) => void;
selectElement: (id: string | null) => void;
setZoom: (zoom: number) => void;
setShowGrid: (show: boolean) => void;
setTool: (tool: 'select' | 'code' | 'text' | 'arrow') => void;
moveElementUp: (id: string) => void;
moveElementDown: (id: string) => void;
undo: () => void;
redo: () => void;
saveToHistory: () => void;
newSnap: (meta: CanvasMeta) => void;
exportSnap: () => string;
importSnap: (json: string) => void;
}
const defaultSnap: Snap = {
version: '1.0.0',
meta: {
title: 'Untitled',
aspect: '16:9',
width: 1920,
height: 1080,
},
background: {
type: 'gradient',
solid: { color: '#101022' },
gradient: { from: '#101022', to: '#1f1f3a', angle: 135 },
},
elements: [],
};
export const useCanvasStore = create<CanvasState>()(
persist(
immer((set, get) => ({
snap: defaultSnap,
selectedElementId: null,
zoom: 0.5,
showGrid: false,
tool: 'select',
history: { past: [], future: [] },
setSnap: (snap) => set((state) => {
state.snap = snap;
}),
updateMeta: (meta) => set((state) => {
state.snap.meta = { ...state.snap.meta, ...meta };
}),
setBackground: (background) => set((state) => {
state.snap.background = { ...state.snap.background, ...background };
}),
addElement: (element) => set((state) => {
get().saveToHistory();
state.snap.elements.push(element);
state.selectedElementId = element.id;
state.tool = 'select';
}),
updateElement: (id, updates) => set((state) => {
const index = state.snap.elements.findIndex((el) => el.id === id);
if (index !== -1) {
state.snap.elements[index] = { ...state.snap.elements[index], ...updates } as CanvasElement;
}
}),
deleteElement: (id) => set((state) => {
get().saveToHistory();
state.snap.elements = state.snap.elements.filter((el) => el.id !== id);
if (state.selectedElementId === id) {
state.selectedElementId = null;
}
}),
duplicateElement: (id) => set((state) => {
const element = state.snap.elements.find((el) => el.id === id);
if (element) {
get().saveToHistory();
const newElement = {
...JSON.parse(JSON.stringify(element)),
id: uuidv4(),
x: element.x + 20,
y: element.y + 20,
};
state.snap.elements.push(newElement);
state.selectedElementId = newElement.id;
}
}),
selectElement: (id) => set((state) => {
state.selectedElementId = id;
}),
setZoom: (zoom) => set((state) => {
state.zoom = Math.max(0.25, Math.min(4, zoom));
}),
setShowGrid: (show) => set((state) => {
state.showGrid = show;
}),
setTool: (tool) => set((state) => {
state.tool = tool;
if (tool !== 'select') {
state.selectedElementId = null;
}
}),
moveElementUp: (id) => set((state) => {
const index = state.snap.elements.findIndex((el) => el.id === id);
if (index < state.snap.elements.length - 1) {
const temp = state.snap.elements[index];
state.snap.elements[index] = state.snap.elements[index + 1];
state.snap.elements[index + 1] = temp;
}
}),
moveElementDown: (id) => set((state) => {
const index = state.snap.elements.findIndex((el) => el.id === id);
if (index > 0) {
const temp = state.snap.elements[index];
state.snap.elements[index] = state.snap.elements[index - 1];
state.snap.elements[index - 1] = temp;
}
}),
saveToHistory: () => set((state) => {
state.history.past.push(JSON.parse(JSON.stringify(state.snap)));
state.history.future = [];
if (state.history.past.length > 50) {
state.history.past.shift();
}
}),
undo: () => set((state) => {
if (state.history.past.length > 0) {
const previous = state.history.past.pop()!;
state.history.future.push(JSON.parse(JSON.stringify(state.snap)));
state.snap = previous;
state.selectedElementId = null;
}
}),
redo: () => set((state) => {
if (state.history.future.length > 0) {
const next = state.history.future.pop()!;
state.history.past.push(JSON.parse(JSON.stringify(state.snap)));
state.snap = next;
state.selectedElementId = null;
}
}),
newSnap: (meta) => set((state) => {
state.snap = {
...defaultSnap,
meta: { ...defaultSnap.meta, ...meta },
};
state.selectedElementId = null;
state.history = { past: [], future: [] };
}),
exportSnap: () => {
return JSON.stringify(get().snap, null, 2);
},
importSnap: (json) => {
try {
const snap = JSON.parse(json) as Snap;
set((state) => {
state.snap = snap;
state.selectedElementId = null;
state.history = { past: [], future: [] };
});
} catch (e) {
console.error('Failed to import snap:', e);
}
},
})),
{
name: 'code-canvas-storage',
partialize: (state) => ({ snap: state.snap }),
}
)
);
// Helper functions to create elements
export const createCodeElement = (x: number, y: number): CodeElement => ({
id: uuidv4(),
type: 'code',
x,
y,
width: 600,
height: 300,
rotation: 0,
locked: false,
visible: true,
props: {
code: '// Your code here\nconsole.log("Hello, World!");',
language: 'javascript',
theme: 'dark',
fontFamily: 'JetBrains Mono',
fontSize: 14,
lineHeight: 1.5,
lineNumbers: true,
highlights: [],
padding: 24,
cornerRadius: 12,
shadow: { blur: 24, spread: 0, color: 'rgba(0,0,0,0.4)' },
},
});
export const createTextElement = (x: number, y: number): TextElement => ({
id: uuidv4(),
type: 'text',
x,
y,
rotation: 0,
locked: false,
visible: true,
props: {
text: 'Your text here',
fontFamily: 'Inter',
fontSize: 24,
color: '#ffffff',
bold: false,
italic: false,
underline: false,
align: 'left',
background: null,
padding: 8,
cornerRadius: 4,
},
});
export const createArrowElement = (x: number, y: number): ArrowElement => ({
id: uuidv4(),
type: 'arrow',
x: 0,
y: 0,
rotation: 0,
locked: false,
visible: true,
points: [
{ x, y },
{ x: x + 150, y: y + 80 },
],
props: {
style: 'straight',
color: '#60a5fa',
thickness: 3,
head: 'filled',
},
});
+148
View File
@@ -0,0 +1,148 @@
export type BackgroundType = 'solid' | 'gradient';
export interface SolidBackground {
color: string;
}
export interface GradientBackground {
from: string;
to: string;
angle: number;
}
export interface Background {
type: BackgroundType;
solid: SolidBackground;
gradient: GradientBackground;
}
export interface Shadow {
blur: number;
spread: number;
color: string;
}
export interface LineHighlight {
from: number;
to: number;
style: 'focus' | 'added' | 'removed';
}
export interface CodeBlockProps {
code: string;
language: string;
theme: 'dark' | 'light';
fontFamily: string;
fontSize: number;
lineHeight: number;
lineNumbers: boolean;
highlights: LineHighlight[];
padding: number;
cornerRadius: number;
shadow: Shadow;
}
export interface TextProps {
text: string;
fontFamily: string;
fontSize: number;
color: string;
bold: boolean;
italic: boolean;
underline: boolean;
align: 'left' | 'center' | 'right';
background: { color: string } | null;
padding: number;
cornerRadius: number;
}
export interface ArrowProps {
style: 'straight' | 'curved';
color: string;
thickness: number;
head: 'filled' | 'outline' | 'none';
}
export type ElementType = 'code' | 'text' | 'arrow';
export interface BaseElement {
id: string;
type: ElementType;
x: number;
y: number;
rotation: number;
locked: boolean;
visible: boolean;
}
export interface CodeElement extends BaseElement {
type: 'code';
width: number;
height: number;
props: CodeBlockProps;
}
export interface TextElement extends BaseElement {
type: 'text';
props: TextProps;
}
export interface ArrowElement extends BaseElement {
type: 'arrow';
points: { x: number; y: number }[];
props: ArrowProps;
}
export type CanvasElement = CodeElement | TextElement | ArrowElement;
export interface AspectRatio {
name: string;
width: number;
height: number;
}
export interface CanvasMeta {
title: string;
aspect: string;
width: number;
height: number;
}
export interface Snap {
version: string;
meta: CanvasMeta;
background: Background;
elements: CanvasElement[];
}
export const ASPECT_RATIOS: AspectRatio[] = [
{ name: 'Square (1:1)', width: 1080, height: 1080 },
{ name: '16:9 (1920x1080)', width: 1920, height: 1080 },
{ name: '16:9 (1600x900)', width: 1600, height: 900 },
{ name: 'LinkedIn', width: 1200, height: 627 },
{ name: 'Portrait', width: 1080, height: 1350 },
{ name: 'Story', width: 1080, height: 1920 },
];
export const CODE_THEMES = ['dark', 'light'] as const;
export const LANGUAGES = [
'javascript',
'typescript',
'kotlin',
'java',
'python',
'rust',
'go',
'html',
'css',
'json',
'markdown',
'bash',
'sql',
] as const;
export const FONT_FAMILIES = {
code: ['JetBrains Mono', 'Fira Code', 'Source Code Pro', 'monospace'],
text: ['Inter', 'Roboto', 'Open Sans', 'sans-serif'],
};
+103
View File
@@ -0,0 +1,103 @@
import { codeToHtml } from 'shiki';
let highlighterReady = false;
export async function highlightCode(
code: string,
language: string,
theme: 'dark' | 'light'
): Promise<string> {
try {
const html = await codeToHtml(code, {
lang: language,
theme: theme === 'dark' ? 'github-dark' : 'github-light',
});
highlighterReady = true;
return html;
} catch (error) {
console.error('Highlighting error:', error);
return `<pre><code>${escapeHtml(code)}</code></pre>`;
}
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
export function isHighlighterReady(): boolean {
return highlighterReady;
}
// Language detection based on common patterns
export function detectLanguage(code: string): string {
// TypeScript/JavaScript patterns
if (/^import\s+.*from\s+['"]|^export\s+(default\s+)?|const\s+\w+:\s*\w+/m.test(code)) {
if (/:\s*(string|number|boolean|any|void|Promise|Array)\b/.test(code)) {
return 'typescript';
}
return 'javascript';
}
// Kotlin patterns
if (/^(fun|val|var|class|object|package|import)\s+/m.test(code) &&
/:\s*\w+(\s*=|\s*\{|\s*\))/.test(code)) {
return 'kotlin';
}
// Java patterns
if (/^(public|private|protected)\s+(static\s+)?(class|void|int|String)/m.test(code)) {
return 'java';
}
// Python patterns
if (/^(def|class|import|from|if __name__|print\()/m.test(code) && !/[{};]/.test(code)) {
return 'python';
}
// Rust patterns
if (/^(fn|let|mut|impl|struct|enum|use|pub)\s+/m.test(code) && /->/.test(code)) {
return 'rust';
}
// Go patterns
if (/^(func|package|import|type|var|const)\s+/m.test(code) && /:=/.test(code)) {
return 'go';
}
// HTML patterns
if (/^<!DOCTYPE|<html|<head|<body|<div/m.test(code)) {
return 'html';
}
// CSS patterns
if (/^[.#\w\-[\]]+\s*\{[^}]*\}/m.test(code)) {
return 'css';
}
// JSON patterns
if (/^\s*[{[]/.test(code) && /[}\]]\s*$/.test(code)) {
try {
JSON.parse(code);
return 'json';
} catch {
// Not valid JSON, continue checking
}
}
// SQL patterns
if (/^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)\s+/im.test(code)) {
return 'sql';
}
// Bash/Shell patterns
if (/^#!\/bin\/(bash|sh)|^\$\s+|^echo\s+|^export\s+/m.test(code)) {
return 'bash';
}
return 'javascript'; // Default
}
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
})