4 Commits

Author SHA1 Message Date
yveskalume d95afbbc72 feat: implement pan and zoom functionality with wheel gestures in Canvas component 2026-01-08 10:14:15 +02:00
yveskalume 66d811aeaf feat: integrate CodeEditor component for enhanced code editing experience 2026-01-08 10:03:29 +02:00
yveskalume a960055532 feat: update file import/export to use .yvsnap extension instead of .json 2026-01-08 09:51:41 +02:00
yveskalume a09538a3c9 Add initial templates for code snippets and explanations
- Introduced a variety of templates including "Code Snippet", "Code with Title", "Before & After", "Code Explanation", "Social Tip Card", "Code Flow", and "LinkedIn Carousel".
- Each template includes detailed properties such as background styles, elements, and code examples.
- Enhanced user experience with visually appealing gradients and structured layouts for better presentation of code.
2026-01-08 09:42:28 +02:00
9 changed files with 2089 additions and 86 deletions
+24 -4
View File
@@ -1,4 +1,4 @@
import { useRef, useEffect, useCallback } from 'react'; import { useRef, useEffect, useCallback, useState } from 'react';
import type Konva from 'konva'; import type Konva from 'konva';
import Canvas from './components/Canvas'; import Canvas from './components/Canvas';
import TopBar from './components/TopBar'; import TopBar from './components/TopBar';
@@ -6,10 +6,12 @@ import Toolbar from './components/Toolbar';
import Inspector from './components/Inspector'; import Inspector from './components/Inspector';
import LayersPanel from './components/LayersPanel'; import LayersPanel from './components/LayersPanel';
import FontLoader from './components/FontLoader'; import FontLoader from './components/FontLoader';
import MainScreen from './components/MainScreen';
import { useCanvasStore } from './store/canvasStore'; import { useCanvasStore } from './store/canvasStore';
import { useRecentSnapsStore } from './store/recentSnapsStore'; import { useRecentSnapsStore } from './store/recentSnapsStore';
function App() { function App() {
const [showMainScreen, setShowMainScreen] = useState(true);
const stageRef = useRef<Konva.Stage>(null); const stageRef = useRef<Konva.Stage>(null);
const { const {
snap, snap,
@@ -36,7 +38,7 @@ function App() {
const handleImportFile = useCallback(() => { const handleImportFile = useCallback(() => {
const input = document.createElement('input'); const input = document.createElement('input');
input.type = 'file'; input.type = 'file';
input.accept = '.json'; input.accept = '.yvsnap';
input.onchange = (e) => { input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0]; const file = (e.target as HTMLInputElement).files?.[0];
if (file) { if (file) {
@@ -62,7 +64,7 @@ function App() {
const blob = new Blob([json], { type: 'application/json' }); const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const link = document.createElement('a'); const link = document.createElement('a');
link.download = `${snap.meta.title || 'canvas'}.json`; link.download = `${snap.meta.title || 'canvas'}.yvsnap`;
link.href = url; link.href = url;
link.click(); link.click();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
@@ -79,6 +81,14 @@ function App() {
} }
}, [snap, addRecentSnap, newSnap]); }, [snap, addRecentSnap, newSnap]);
// Handle going back to main screen
const handleGoToMainScreen = useCallback(() => {
if (snap.elements.length > 0) {
addRecentSnap(snap);
}
setShowMainScreen(true);
}, [snap, addRecentSnap]);
// Keyboard shortcuts // Keyboard shortcuts
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { const handleKeyDown = (e: KeyboardEvent) => {
@@ -178,10 +188,20 @@ function App() {
return () => window.removeEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectedElementId, deleteElement, duplicateElement, undo, redo, zoom, setZoom, showGrid, setShowGrid, setTool, selectElement, handleNewSnap, handleImportFile, handleExportFile]); }, [selectedElementId, deleteElement, duplicateElement, undo, redo, zoom, setZoom, showGrid, setShowGrid, setTool, selectElement, handleNewSnap, handleImportFile, handleExportFile]);
// Show main screen
if (showMainScreen) {
return (
<>
<FontLoader />
<MainScreen onOpenEditor={() => setShowMainScreen(false)} />
</>
);
}
return ( return (
<div className="h-screen flex flex-col bg-neutral-900 text-white"> <div className="h-screen flex flex-col bg-neutral-900 text-white">
<FontLoader /> <FontLoader />
<TopBar stageRef={stageRef} /> <TopBar stageRef={stageRef} onGoHome={handleGoToMainScreen} />
<div className="flex-1 flex overflow-hidden"> <div className="flex-1 flex overflow-hidden">
<LayersPanel /> <LayersPanel />
<Toolbar /> <Toolbar />
+65 -3
View File
@@ -15,6 +15,7 @@ interface CanvasProps {
const Canvas: React.FC<CanvasProps> = ({ stageRef }) => { const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: window.innerWidth, height: window.innerHeight - 120 }); const [dimensions, setDimensions] = useState({ width: window.innerWidth, height: window.innerHeight - 120 });
const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
const { const {
snap, snap,
zoom, zoom,
@@ -24,6 +25,7 @@ const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
selectElement, selectElement,
addElement, addElement,
updateElement, updateElement,
setZoom,
} = useCanvasStore(); } = useCanvasStore();
const { width, height } = snap.meta; const { width, height } = snap.meta;
@@ -70,10 +72,15 @@ const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
const scaledWidth = width * zoom; const scaledWidth = width * zoom;
const scaledHeight = height * zoom; const scaledHeight = height * zoom;
return { return {
x: Math.max(20, (dimensions.width - scaledWidth) / 2), x: Math.max(20, (dimensions.width - scaledWidth) / 2) + panOffset.x,
y: Math.max(20, (dimensions.height - scaledHeight) / 2), y: Math.max(20, (dimensions.height - scaledHeight) / 2) + panOffset.y,
}; };
}, [width, height, zoom, dimensions]); }, [width, height, zoom, dimensions, panOffset]);
// Reset pan offset when zoom changes significantly or canvas is re-centered
const resetPan = useCallback(() => {
setPanOffset({ x: 0, y: 0 });
}, []);
const handleStageClick = (e: Konva.KonvaEventObject<MouseEvent>) => { const handleStageClick = (e: Konva.KonvaEventObject<MouseEvent>) => {
const clickedOnEmpty = e.target === e.target.getStage() || e.target.name() === 'background'; const clickedOnEmpty = e.target === e.target.getStage() || e.target.name() === 'background';
@@ -416,11 +423,66 @@ const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
const stagePosition = useMemo(() => getStagePosition(), [getStagePosition]); const stagePosition = useMemo(() => getStagePosition(), [getStagePosition]);
// Handle wheel/pinch zoom and pan on canvas
const handleWheel = useCallback((e: React.WheelEvent<HTMLDivElement>) => {
// Check if it's a pinch zoom gesture (ctrlKey is true for pinch-to-zoom)
if (e.ctrlKey || e.metaKey) {
e.preventDefault();
e.stopPropagation();
const scaleBy = 1.05;
const minZoom = 0.1;
const maxZoom = 3;
// Determine zoom direction
const direction = e.deltaY > 0 ? -1 : 1;
const newZoom = direction > 0 ? zoom * scaleBy : zoom / scaleBy;
// Clamp zoom between min and max
const clampedZoom = Math.min(Math.max(newZoom, minZoom), maxZoom);
setZoom(clampedZoom);
} else {
// Two-finger scroll for panning
e.preventDefault();
e.stopPropagation();
setPanOffset(prev => ({
x: prev.x - e.deltaX,
y: prev.y - e.deltaY,
}));
}
}, [zoom, setZoom]);
// Prevent default browser zoom behavior on the container
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const preventDefaultZoom = (e: WheelEvent) => {
// Prevent default for both zoom (ctrl/meta) and pan (regular scroll)
e.preventDefault();
};
// Use passive: false to allow preventDefault
container.addEventListener('wheel', preventDefaultZoom, { passive: false });
return () => {
container.removeEventListener('wheel', preventDefaultZoom);
};
}, []);
return ( return (
<div <div
ref={containerRef} ref={containerRef}
className="flex-1 bg-neutral-900 overflow-hidden relative" className="flex-1 bg-neutral-900 overflow-hidden relative"
style={{ cursor: tool !== 'select' ? 'crosshair' : 'default' }} style={{ cursor: tool !== 'select' ? 'crosshair' : 'default' }}
onWheel={handleWheel}
onDoubleClick={(e) => {
// Double-click on empty area to reset pan
if (e.target === containerRef.current) {
resetPan();
}
}}
> >
<Stage <Stage
ref={stageRef} ref={stageRef}
+277
View File
@@ -0,0 +1,277 @@
import { useState } from 'react';
import { Plus, FileText, Layout, Clock, Trash2, ChevronRight, Sparkles } from 'lucide-react';
import { useRecentSnapsStore, formatRelativeTime } from '../store/recentSnapsStore';
import { useCanvasStore } from '../store/canvasStore';
import { templates, type Template } from '../data/templates';
import SnapPreview from './SnapPreview';
import type { Snap } from '../types';
interface MainScreenProps {
onOpenEditor: () => void;
}
export default function MainScreen({ onOpenEditor }: MainScreenProps) {
const [activeTab, setActiveTab] = useState<'recent' | 'templates'>('recent');
const { recentSnaps, removeRecentSnap, clearRecentSnaps } = useRecentSnapsStore();
const { setSnap, newSnap } = useCanvasStore();
const handleNewSnap = () => {
newSnap({ title: 'Untitled', aspect: '16:9', width: 1920, height: 1080 });
onOpenEditor();
};
const handleOpenRecent = (snap: Snap) => {
setSnap(snap);
onOpenEditor();
};
const handleUseTemplate = (template: Template) => {
setSnap(template.snap);
onOpenEditor();
};
const handleImportFile = () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.yvsnap';
input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (evt) => {
try {
const json = evt.target?.result as string;
const snap = JSON.parse(json) as Snap;
setSnap(snap);
onOpenEditor();
} catch {
alert('Invalid file format');
}
};
reader.readAsText(file);
}
};
input.click();
};
return (
<div className="min-h-screen bg-neutral-900 text-white">
{/* Header */}
<header className="sticky top-0 z-50 bg-[#09090b]/95 backdrop-blur-xl border-b border-white/[0.08]">
<div className="max-w-6xl mx-auto px-6 py-6">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-gradient-to-br from-blue-600 to-blue-700 rounded-xl flex items-center justify-center shadow-lg shadow-blue-500/20">
<svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
</div>
<div>
<h1 className="text-xl font-semibold">YvCode</h1>
<p className="text-sm text-neutral-400">Create beautiful code screenshots</p>
</div>
</div>
</div>
</header>
{/* Main Content */}
<main className="max-w-6xl mx-auto px-6 py-8">
{/* Create New Section */}
<section className="mb-10">
<h2 className="text-lg font-medium mb-4">Create New</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{/* New Blank */}
<button
onClick={handleNewSnap}
className="group relative bg-neutral-900 border border-white/10 rounded-xl p-6 hover:border-blue-500/50 hover:bg-white/[0.03] transition-all duration-200 text-left"
>
<div className="w-12 h-12 bg-white/[0.05] group-hover:bg-blue-500/20 rounded-xl flex items-center justify-center mb-4 transition-colors">
<Plus className="w-6 h-6 text-neutral-400 group-hover:text-blue-400" />
</div>
<h3 className="font-medium mb-1">Blank Canvas</h3>
<p className="text-sm text-neutral-500">Start from scratch with a fresh canvas</p>
<ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-neutral-600 group-hover:text-blue-400 opacity-0 group-hover:opacity-100 transition-all" />
</button>
{/* Import File */}
<button
onClick={handleImportFile}
className="group relative bg-neutral-900 border border-white/10 rounded-xl p-6 hover:border-blue-500/50 hover:bg-white/[0.03] transition-all duration-200 text-left"
>
<div className="w-12 h-12 bg-white/[0.05] group-hover:bg-blue-500/20 rounded-xl flex items-center justify-center mb-4 transition-colors">
<FileText className="w-6 h-6 text-neutral-400 group-hover:text-blue-400" />
</div>
<h3 className="font-medium mb-1">Import File</h3>
<p className="text-sm text-neutral-500">Open an existing .yvsnap project file</p>
<ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-neutral-600 group-hover:text-blue-400 opacity-0 group-hover:opacity-100 transition-all" />
</button>
{/* Quick Template */}
<button
onClick={() => setActiveTab('templates')}
className="group relative bg-neutral-900 border border-white/10 rounded-xl p-6 hover:border-blue-500/50 hover:bg-white/[0.03] transition-all duration-200 text-left"
>
<div className="w-12 h-12 bg-white/[0.05] group-hover:bg-blue-500/20 rounded-xl flex items-center justify-center mb-4 transition-colors">
<Layout className="w-6 h-6 text-neutral-400 group-hover:text-blue-400" />
</div>
<h3 className="font-medium mb-1">Use Template</h3>
<p className="text-sm text-neutral-500">Start with a pre-designed template</p>
<ChevronRight className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-neutral-600 group-hover:text-blue-400 opacity-0 group-hover:opacity-100 transition-all" />
</button>
</div>
</section>
{/* Tabs */}
<div className="flex items-center gap-1 border-b border-white/[0.08] mb-6">
<button
onClick={() => setActiveTab('recent')}
className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
activeTab === 'recent'
? 'border-blue-500 text-white'
: 'border-transparent text-neutral-500 hover:text-neutral-300'
}`}
>
<Clock className="w-4 h-4 inline-block mr-2 -mt-0.5" />
Recent Work
</button>
<button
onClick={() => setActiveTab('templates')}
className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
activeTab === 'templates'
? 'border-blue-500 text-white'
: 'border-transparent text-neutral-500 hover:text-neutral-300'
}`}
>
<Sparkles className="w-4 h-4 inline-block mr-2 -mt-0.5" />
Templates
</button>
</div>
{/* Tab Content */}
{activeTab === 'recent' && (
<section>
{recentSnaps.length === 0 ? (
<div className="text-center py-16">
<div className="w-16 h-16 bg-neutral-900 rounded-full flex items-center justify-center mx-auto mb-4">
<Clock className="w-8 h-8 text-neutral-600" />
</div>
<h3 className="text-lg font-medium mb-2">No recent work</h3>
<p className="text-neutral-500 mb-6">Your recent projects will appear here</p>
<button
onClick={handleNewSnap}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg transition-colors"
>
<Plus className="w-4 h-4" />
Create your first snap
</button>
</div>
) : (
<>
<div className="flex items-center justify-between mb-4">
<p className="text-sm text-neutral-500">{recentSnaps.length} recent project{recentSnaps.length !== 1 ? 's' : ''}</p>
<button
onClick={() => {
if (confirm('Clear all recent projects?')) {
clearRecentSnaps();
}
}}
className="text-sm text-neutral-500 hover:text-red-400 transition-colors"
>
Clear all
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{recentSnaps.map((entry) => (
<div
key={entry.id}
className="group relative bg-neutral-900 border border-white/10 rounded-xl overflow-hidden hover:border-white/20 transition-colors"
>
{/* Preview */}
<button
onClick={() => handleOpenRecent(entry.snap)}
className="w-full aspect-video relative overflow-hidden"
>
<SnapPreview snap={entry.snap} />
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30">
<span className="px-3 py-1.5 bg-white/10 backdrop-blur-sm rounded-lg text-sm">Open</span>
</div>
</button>
{/* Info */}
<div className="p-4">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<h3 className="font-medium truncate">{entry.title}</h3>
<p className="text-sm text-neutral-500">{formatRelativeTime(entry.savedAt)}</p>
</div>
<button
onClick={(e) => {
e.stopPropagation();
removeRecentSnap(entry.id);
}}
className="p-1.5 text-neutral-600 hover:text-red-400 hover:bg-neutral-800 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="mt-2 flex items-center gap-2 text-xs text-neutral-600">
<span>{entry.snap.meta.width}×{entry.snap.meta.height}</span>
<span></span>
<span>{entry.snap.elements.length} element{entry.snap.elements.length !== 1 ? 's' : ''}</span>
</div>
</div>
</div>
))}
</div>
</>
)}
</section>
)}
{activeTab === 'templates' && (
<section>
<p className="text-sm text-neutral-500 mb-4">{templates.length} templates available</p>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{templates.map((template) => (
<div
key={template.id}
className="group relative bg-neutral-900 border border-white/10 rounded-xl overflow-hidden hover:border-white/20 transition-colors"
>
{/* Preview */}
<button
onClick={() => handleUseTemplate(template)}
className="w-full aspect-video relative overflow-hidden"
>
<SnapPreview snap={template.snap} />
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30">
<span className="px-3 py-1.5 bg-white/10 backdrop-blur-sm rounded-lg text-sm">Use Template</span>
</div>
</button>
{/* Info */}
<div className="p-4">
<h3 className="font-medium mb-1">{template.name}</h3>
<p className="text-sm text-neutral-500">{template.description}</p>
<div className="mt-2 flex items-center gap-2 text-xs text-neutral-600">
<span>{template.snap.meta.width}×{template.snap.meta.height}</span>
<span></span>
<span>{template.snap.elements.length} element{template.snap.elements.length !== 1 ? 's' : ''}</span>
</div>
</div>
</div>
))}
</div>
</section>
)}
</main>
{/* Footer */}
<footer className="border-t border-white/[0.08] mt-16">
<div className="max-w-6xl mx-auto px-6 py-6">
<p className="text-sm text-neutral-600 text-center">
YvCode Create beautiful code screenshots for social media
</p>
</div>
</footer>
</div>
);
}
+222
View File
@@ -0,0 +1,222 @@
import type { Snap, CanvasElement, CodeElement, TextElement, ArrowElement } from '../types';
interface SnapPreviewProps {
snap: Snap;
}
// Helper to get code theme background color
function getCodeThemeBg(theme: string): string {
const themes: Record<string, string> = {
'andromeeda': '#23262e',
'aurora-x': '#07090f',
'dark-plus': '#1e1e1e',
'dracula': '#282a36',
'dracula-soft': '#282a36',
'github-dark': '#0d1117',
'github-dark-dimmed': '#22272e',
'github-light': '#ffffff',
'light-plus': '#ffffff',
'material-theme-darker': '#212121',
'material-theme-ocean': '#0f111a',
'material-theme-palenight': '#292d3e',
'min-dark': '#1f1f1f',
'min-light': '#ffffff',
'monokai': '#272822',
'night-owl': '#011627',
'nord': '#2e3440',
'one-dark-pro': '#282c34',
'poimandres': '#1b1e28',
'rose-pine': '#191724',
'rose-pine-moon': '#232136',
'slack-dark': '#222222',
'solarized-dark': '#002b36',
'solarized-light': '#fdf6e3',
'tokyo-night': '#1a1b26',
'vesper': '#101010',
'vitesse-dark': '#121212',
'vitesse-light': '#ffffff',
};
return themes[theme] || '#1e1e1e';
}
// Helper to get highlight color for code lines
function getHighlightColor(lineNum: number, highlights: { from: number; to: number; style: string }[]): string | null {
for (const h of highlights) {
if (lineNum >= h.from && lineNum <= h.to) {
switch (h.style) {
case 'focus': return 'rgba(251, 191, 36, 0.4)';
case 'added': return 'rgba(34, 197, 94, 0.4)';
case 'removed': return 'rgba(239, 68, 68, 0.4)';
}
}
}
return null;
}
export default function SnapPreview({ snap }: SnapPreviewProps) {
const { meta, background, elements } = snap;
const scaleX = 1 / (meta.width / 400); // Scale to fit ~400px width
const scaleY = 1 / (meta.height / 225); // Scale to fit ~225px height (16:9 aspect)
const scale = Math.min(scaleX, scaleY);
const getBackground = () => {
if (background.type === 'gradient') {
return `linear-gradient(${background.gradient.angle}deg, ${background.gradient.from}, ${background.gradient.to})`;
}
return background.solid.color;
};
const renderElement = (element: CanvasElement) => {
if (!element.visible) return null;
switch (element.type) {
case 'code': {
const codeEl = element as CodeElement;
return (
<div
key={element.id}
style={{
position: 'absolute',
left: codeEl.x * scale,
top: codeEl.y * scale,
width: codeEl.width * scale,
height: codeEl.height * scale,
backgroundColor: getCodeThemeBg(codeEl.props.theme),
borderRadius: codeEl.props.cornerRadius * scale,
overflow: 'hidden',
boxShadow: codeEl.props.shadow.blur > 0
? `0 ${codeEl.props.shadow.blur * scale * 0.5}px ${codeEl.props.shadow.blur * scale}px ${codeEl.props.shadow.color}`
: undefined,
}}
>
{/* Code lines preview */}
<div style={{ padding: codeEl.props.padding * scale * 0.5 }}>
{codeEl.props.code.split('\n').slice(0, 8).map((line, i) => (
<div
key={i}
style={{
height: Math.max(2, codeEl.props.fontSize * scale * 0.8),
marginBottom: Math.max(1, codeEl.props.fontSize * scale * 0.3),
display: 'flex',
gap: 2,
}}
>
{codeEl.props.lineNumbers && (
<div
style={{
width: Math.max(8, 16 * scale),
backgroundColor: 'rgba(255,255,255,0.1)',
borderRadius: 1,
}}
/>
)}
<div
style={{
width: `${Math.min(100, Math.max(20, line.length * 3))}%`,
backgroundColor: getHighlightColor(i + 1, codeEl.props.highlights) || 'rgba(255,255,255,0.3)',
borderRadius: 1,
}}
/>
</div>
))}
</div>
</div>
);
}
case 'text': {
const textEl = element as TextElement;
const fontSize = Math.max(6, textEl.props.fontSize * scale);
return (
<div
key={element.id}
style={{
position: 'absolute',
left: textEl.x * scale,
top: textEl.y * scale,
fontSize,
fontFamily: textEl.props.fontFamily,
fontWeight: textEl.props.bold ? 'bold' : 'normal',
fontStyle: textEl.props.italic ? 'italic' : 'normal',
color: textEl.props.color,
whiteSpace: 'pre',
lineHeight: 1.2,
padding: textEl.props.background ? textEl.props.padding * scale : 0,
backgroundColor: textEl.props.background?.color,
borderRadius: textEl.props.cornerRadius * scale,
maxWidth: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{textEl.props.text.length > 50 ? textEl.props.text.slice(0, 50) + '...' : textEl.props.text}
</div>
);
}
case 'arrow': {
const arrowEl = element as ArrowElement;
if (arrowEl.points.length < 2) return null;
const start = arrowEl.points[0];
const end = arrowEl.points[arrowEl.points.length - 1];
// Calculate SVG bounds
const minX = Math.min(start.x, end.x) - 10;
const minY = Math.min(start.y, end.y) - 10;
const maxX = Math.max(start.x, end.x) + 10;
const maxY = Math.max(start.y, end.y) + 10;
return (
<svg
key={element.id}
style={{
position: 'absolute',
left: minX * scale,
top: minY * scale,
width: (maxX - minX) * scale,
height: (maxY - minY) * scale,
overflow: 'visible',
}}
>
<defs>
<marker
id={`arrowhead-${element.id}`}
markerWidth="10"
markerHeight="7"
refX="9"
refY="3.5"
orient="auto"
>
<polygon
points="0 0, 10 3.5, 0 7"
fill={arrowEl.props.color}
/>
</marker>
</defs>
<line
x1={(start.x - minX) * scale}
y1={(start.y - minY) * scale}
x2={(end.x - minX) * scale}
y2={(end.y - minY) * scale}
stroke={arrowEl.props.color}
strokeWidth={Math.max(1, arrowEl.props.thickness * scale)}
markerEnd={arrowEl.props.head !== 'none' ? `url(#arrowhead-${element.id})` : undefined}
/>
</svg>
);
}
default:
return null;
}
};
return (
<div
className="w-full h-full relative overflow-hidden"
style={{ background: getBackground() }}
>
{elements.map(renderElement)}
</div>
);
}
+11 -6
View File
@@ -7,9 +7,10 @@ import RecentSnapsDropdown from './RecentSnapsDropdown';
interface TopBarProps { interface TopBarProps {
stageRef: React.RefObject<Konva.Stage | null>; stageRef: React.RefObject<Konva.Stage | null>;
onGoHome?: () => void;
} }
const TopBar: React.FC<TopBarProps> = ({ stageRef }) => { const TopBar: React.FC<TopBarProps> = ({ stageRef, onGoHome }) => {
const [showRecentSnaps, setShowRecentSnaps] = useState(false); const [showRecentSnaps, setShowRecentSnaps] = useState(false);
const [showExportMenu, setShowExportMenu] = useState(false); const [showExportMenu, setShowExportMenu] = useState(false);
const recentButtonRef = useRef<HTMLButtonElement>(null); const recentButtonRef = useRef<HTMLButtonElement>(null);
@@ -87,7 +88,7 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef }) => {
const blob = new Blob([json], { type: 'application/json' }); const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const link = document.createElement('a'); const link = document.createElement('a');
link.download = `${snap.meta.title || 'canvas'}.json`; link.download = `${snap.meta.title || 'canvas'}.yvsnap`;
link.href = url; link.href = url;
link.click(); link.click();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
@@ -100,7 +101,7 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef }) => {
const handleImportJSON = useCallback(() => { const handleImportJSON = useCallback(() => {
const input = document.createElement('input'); const input = document.createElement('input');
input.type = 'file'; input.type = 'file';
input.accept = '.json'; input.accept = '.yvsnap';
input.onchange = (e) => { input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0]; const file = (e.target as HTMLInputElement).files?.[0];
if (file) { if (file) {
@@ -138,11 +139,15 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef }) => {
{/* Left section: Logo & Actions */} {/* Left section: Logo & Actions */}
<div className="flex items-center gap-5"> <div className="flex items-center gap-5">
<div className="flex items-center gap-3 pr-5 border-r border-white/[0.08]"> <div className="flex items-center gap-3 pr-5 border-r border-white/[0.08]">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-600 to-blue-700 shadow-lg shadow-blue-500/20 flex items-center justify-center"> <button
onClick={onGoHome}
className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-600 to-blue-700 shadow-lg shadow-blue-500/20 flex items-center justify-center hover:from-blue-500 hover:to-blue-600 transition-all"
title="Go to Home"
>
<svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M13 10V3L4 14h7v7l9-11h-7z" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg> </svg>
</div> </button>
<span className="font-bold text-base tracking-tight text-white"> <span className="font-bold text-base tracking-tight text-white">
YvCode YvCode
</span> </span>
@@ -319,7 +324,7 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef }) => {
</div> </div>
<div className="flex flex-col items-start gap-0.5"> <div className="flex flex-col items-start gap-0.5">
<span className="text-sm font-medium text-neutral-200 group-hover:text-white transition-colors">Save Project</span> <span className="text-sm font-medium text-neutral-200 group-hover:text-white transition-colors">Save Project</span>
<span className="text-[10px] text-neutral-500">Edit later (.json)</span> <span className="text-[10px] text-neutral-500">Edit later (.yvsnap)</span>
</div> </div>
</div> </div>
</button> </button>
+314
View File
@@ -0,0 +1,314 @@
import React, { useRef, useEffect, useState, useCallback } from 'react';
import { tokenizeCode, getThemeBackground, isLightTheme } from '../../utils/highlighter';
import type { CodeThemeId } from '../../types';
interface CodeEditorProps {
value: string;
onChange: (value: string) => void;
onBlur?: () => void;
language: string;
theme: CodeThemeId;
className?: string;
}
interface TokenInfo {
content: string;
color: string;
}
interface LineTokens {
tokens: TokenInfo[];
}
const CodeEditor: React.FC<CodeEditorProps> = ({
value,
onChange,
onBlur,
language,
theme,
className = '',
}) => {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const highlightRef = useRef<HTMLDivElement>(null);
const [tokens, setTokens] = useState<LineTokens[]>([]);
const [isLoading, setIsLoading] = useState(false);
// Sync scroll between textarea and highlight overlay
const syncScroll = useCallback(() => {
if (textareaRef.current && highlightRef.current) {
highlightRef.current.scrollTop = textareaRef.current.scrollTop;
highlightRef.current.scrollLeft = textareaRef.current.scrollLeft;
}
}, []);
// Tokenize code for syntax highlighting
useEffect(() => {
let cancelled = false;
tokenizeCode(value, language, theme)
.then((result) => {
if (!cancelled) {
setTokens(result);
setIsLoading(false);
}
})
.catch(() => {
if (!cancelled) {
setIsLoading(false);
}
});
return () => {
cancelled = true;
};
}, [value, language, theme]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
const textarea = e.currentTarget;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const currentValue = textarea.value;
// Handle Tab for indentation
if (e.key === 'Tab') {
e.preventDefault();
if (e.shiftKey) {
// Shift+Tab: Remove indentation
const beforeCursor = currentValue.substring(0, start);
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const linePrefix = currentValue.substring(lineStart, start);
if (linePrefix.startsWith(' ')) {
const newValue = currentValue.substring(0, lineStart) + currentValue.substring(lineStart + 2);
onChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = Math.max(lineStart, start - 2);
}, 0);
} else if (linePrefix.startsWith('\t')) {
const newValue = currentValue.substring(0, lineStart) + currentValue.substring(lineStart + 1);
onChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = Math.max(lineStart, start - 1);
}, 0);
}
} else {
// Tab: Add indentation (2 spaces)
const newValue = currentValue.substring(0, start) + ' ' + currentValue.substring(end);
onChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = start + 2;
}, 0);
}
return;
}
// Handle Enter for auto-indentation
if (e.key === 'Enter') {
e.preventDefault();
const beforeCursor = currentValue.substring(0, start);
const afterCursor = currentValue.substring(end);
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const currentLine = currentValue.substring(lineStart, start);
const indentMatch = currentLine.match(/^(\s*)/);
const indent = indentMatch ? indentMatch[1] : '';
const charBefore = currentValue[start - 1];
const charAfter = currentValue[end];
// Check if we're between matching brackets
const isBetweenBrackets =
(charBefore === '{' && charAfter === '}') ||
(charBefore === '(' && charAfter === ')') ||
(charBefore === '[' && charAfter === ']');
if (isBetweenBrackets) {
// Insert new line with extra indent, then closing bracket on same indent level
const newValue =
beforeCursor +
'\n' +
indent +
' ' +
'\n' +
indent +
afterCursor;
onChange(newValue);
// Position cursor on the middle line with extra indentation
const newCursorPos = start + 1 + indent.length + 2;
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = newCursorPos;
}, 0);
} else {
// Normal enter behavior with smart indentation
const trimmedLine = currentLine.trim();
const needsExtraIndent =
trimmedLine.endsWith('{') ||
trimmedLine.endsWith(':') ||
trimmedLine.endsWith('(') ||
trimmedLine.endsWith('[');
const extraIndent = needsExtraIndent ? ' ' : '';
const newValue = beforeCursor + '\n' + indent + extraIndent + afterCursor;
onChange(newValue);
const newCursorPos = start + 1 + indent.length + extraIndent.length;
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = newCursorPos;
}, 0);
}
return;
}
// Auto-close brackets
const bracketPairs: Record<string, string> = {
'{': '}',
'(': ')',
'[': ']',
'"': '"',
"'": "'",
'`': '`',
};
if (bracketPairs[e.key]) {
const closingChar = bracketPairs[e.key];
const charAfter = currentValue[end];
// Don't auto-close if the next character is alphanumeric
if (charAfter && /\w/.test(charAfter)) {
return;
}
// For quotes, check if we're already inside a quote
if (['"', "'", '`'].includes(e.key)) {
// If next char is the same quote, just move cursor forward
if (charAfter === e.key) {
e.preventDefault();
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = end + 1;
}, 0);
return;
}
}
e.preventDefault();
const newValue =
currentValue.substring(0, start) +
e.key +
closingChar +
currentValue.substring(end);
onChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = start + 1;
}, 0);
return;
}
// Handle closing bracket - skip if same char is next
const closingBrackets = ['}', ')', ']'];
if (closingBrackets.includes(e.key)) {
const charAfter = currentValue[end];
if (charAfter === e.key) {
e.preventDefault();
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = end + 1;
}, 0);
return;
}
}
// Handle Backspace - delete matching bracket pair
if (e.key === 'Backspace' && start === end && start > 0) {
const charBefore = currentValue[start - 1];
const charAfter = currentValue[start];
const pairMatch =
(charBefore === '{' && charAfter === '}') ||
(charBefore === '(' && charAfter === ')') ||
(charBefore === '[' && charAfter === ']') ||
(charBefore === '"' && charAfter === '"') ||
(charBefore === "'" && charAfter === "'") ||
(charBefore === '`' && charAfter === '`');
if (pairMatch) {
e.preventDefault();
const newValue = currentValue.substring(0, start - 1) + currentValue.substring(end + 1);
onChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = start - 1;
}, 0);
return;
}
}
};
const bgColor = getThemeBackground(theme);
const isLight = isLightTheme(theme);
const textColor = isLight ? '#1f2937' : '#e5e7eb';
const caretColor = isLight ? '#000000' : '#ffffff';
return (
<div
className={`relative font-mono text-sm rounded overflow-hidden ${className}`}
style={{ backgroundColor: bgColor }}
>
{/* Syntax highlighted overlay */}
<div
ref={highlightRef}
className="absolute inset-0 overflow-hidden pointer-events-none p-3 whitespace-pre"
style={{
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',
fontSize: '0.875rem',
lineHeight: '1.5',
tabSize: 2,
}}
aria-hidden="true"
>
{isLoading ? (
<span style={{ color: textColor, opacity: 0.5 }}>{value}</span>
) : (
tokens.map((line, lineIndex) => (
<div key={lineIndex} style={{ minHeight: '1.5em' }}>
{line.tokens.length === 0 ? (
<span>&nbsp;</span>
) : (
line.tokens.map((token, tokenIndex) => (
<span key={tokenIndex} style={{ color: token.color }}>
{token.content}
</span>
))
)}
</div>
))
)}
</div>
{/* Transparent textarea for input */}
<textarea
ref={textareaRef}
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={onBlur}
onScroll={syncScroll}
className="relative w-full h-32 bg-transparent resize-y p-3 outline-none"
style={{
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',
fontSize: '0.875rem',
lineHeight: '1.5',
tabSize: 2,
color: 'transparent',
caretColor: caretColor,
WebkitTextFillColor: 'transparent',
}}
spellCheck={false}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
/>
</div>
);
};
export default CodeEditor;
+5 -72
View File
@@ -4,6 +4,7 @@ import type { CodeElement, LineHighlight } from '../../types';
import { LANGUAGES, FONT_FAMILIES, CODE_THEMES } from '../../types'; import { LANGUAGES, FONT_FAMILIES, CODE_THEMES } from '../../types';
import { detectLanguage } from '../../utils/highlighter'; import { detectLanguage } from '../../utils/highlighter';
import { loadFont } from '../../utils/fontLoader'; import { loadFont } from '../../utils/fontLoader';
import CodeEditor from './CodeEditor';
interface CodeInspectorProps { interface CodeInspectorProps {
element: CodeElement; element: CodeElement;
@@ -53,85 +54,17 @@ const CodeInspector: React.FC<CodeInspectorProps> = ({ element }) => {
const totalLines = element.props.code.split('\n').length; const totalLines = element.props.code.split('\n').length;
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// Handle Tab for indentation
if (e.key === 'Tab') {
e.preventDefault();
const textarea = e.currentTarget;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const value = textarea.value;
if (e.shiftKey) {
// Shift+Tab: Remove indentation
const beforeCursor = value.substring(0, start);
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const linePrefix = value.substring(lineStart, start);
if (linePrefix.startsWith(' ')) {
const newValue = value.substring(0, lineStart) + value.substring(lineStart + 2);
handleCodeChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = Math.max(lineStart, start - 2);
}, 0);
} else if (linePrefix.startsWith('\t')) {
const newValue = value.substring(0, lineStart) + value.substring(lineStart + 1);
handleCodeChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = Math.max(lineStart, start - 1);
}, 0);
}
} else {
// Tab: Add indentation (2 spaces)
const newValue = value.substring(0, start) + ' ' + value.substring(end);
handleCodeChange(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = start + 2;
}, 0);
}
}
// Handle Enter for auto-indentation
if (e.key === 'Enter') {
e.preventDefault();
const textarea = e.currentTarget;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const value = textarea.value;
const beforeCursor = value.substring(0, start);
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const currentLine = value.substring(lineStart, start);
const indentMatch = currentLine.match(/^(\s*)/);
const indent = indentMatch ? indentMatch[1] : '';
const trimmedLine = currentLine.trim();
const needsExtraIndent = trimmedLine.endsWith('{') || trimmedLine.endsWith(':') || trimmedLine.endsWith('(');
const extraIndent = needsExtraIndent ? ' ' : '';
const newValue = value.substring(0, start) + '\n' + indent + extraIndent + value.substring(end);
handleCodeChange(newValue);
const newCursorPos = start + 1 + indent.length + extraIndent.length;
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = newCursorPos;
}, 0);
}
};
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{/* Code editor */} {/* Code editor */}
<div> <div>
<label className="block text-sm text-neutral-400 mb-2">Code</label> <label className="block text-sm text-neutral-400 mb-2">Code</label>
<textarea <CodeEditor
value={element.props.code} value={element.props.code}
onChange={(e) => handleCodeChange(e.target.value)} onChange={handleCodeChange}
onKeyDown={handleKeyDown}
onBlur={saveToHistory} onBlur={saveToHistory}
className="w-full h-32 bg-neutral-900 text-white text-sm font-mono p-3 rounded resize-y" language={element.props.language}
spellCheck={false} theme={element.props.theme}
style={{ tabSize: 2 }}
/> />
</div> </div>
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -6,7 +6,8 @@
html, body, #root { html, body, #root {
height: 100%; height: 100%;
width: 100%; width: 100%;
overflow: hidden; overflow-x: hidden;
overflow-y: auto;
} }
body { body {
@@ -37,6 +38,7 @@ body {
/* Color picker styling */ /* Color picker styling */
input[type="color"] { input[type="color"] {
-webkit-appearance: none; -webkit-appearance: none;
appearance: none;
border: none; border: none;
padding: 0; padding: 0;
} }