3 Commits

6 changed files with 523 additions and 153 deletions
+1 -1
View File
@@ -199,7 +199,7 @@ function App() {
}
return (
<div className="h-screen flex flex-col bg-neutral-900 text-white">
<div className="h-screen flex flex-col bg-[#09090b] text-white">
<FontLoader />
<TopBar stageRef={stageRef} onGoHome={handleGoToMainScreen} />
<div className="flex-1 flex overflow-hidden">
+65 -3
View File
@@ -15,6 +15,7 @@ interface CanvasProps {
const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: window.innerWidth, height: window.innerHeight - 120 });
const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
const {
snap,
zoom,
@@ -24,6 +25,7 @@ const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
selectElement,
addElement,
updateElement,
setZoom,
} = useCanvasStore();
const { width, height } = snap.meta;
@@ -70,10 +72,15 @@ const Canvas: React.FC<CanvasProps> = ({ stageRef }) => {
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),
x: Math.max(20, (dimensions.width - scaledWidth) / 2) + panOffset.x,
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 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]);
// 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 (
<div
ref={containerRef}
className="flex-1 bg-neutral-900 overflow-hidden relative"
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
ref={stageRef}
+114 -77
View File
@@ -55,168 +55,203 @@ export default function MainScreen({ onOpenEditor }: MainScreenProps) {
};
return (
<div className="min-h-screen bg-neutral-900 text-white">
<div className="min-h-screen bg-[#09090b] text-white selection:bg-blue-500/30">
{/* 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">
<header className="sticky top-0 z-50 bg-[#09090b]/80 backdrop-blur-xl border-b border-white/[0.08]">
<div className="max-w-7xl mx-auto px-6 h-16 flex items-center justify-between">
<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">
<div className="w-8 h-8 bg-blue-600 rounded-lg 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>
<span className="font-bold text-lg tracking-tight">YvCode</span>
</div>
<div className="flex items-center gap-4">
{/* Add simplified user profile or links if needed later */}
</div>
</div>
</header>
{/* Main Content */}
<main className="max-w-6xl mx-auto px-6 py-8">
<main className="relative max-w-7xl mx-auto px-6 py-12">
{/* Welcome Section */}
<div className="mb-12 text-center">
<h1 className="text-4xl font-bold mb-3 bg-gradient-to-r from-white to-white/60 bg-clip-text text-transparent">
What will you create today?
</h1>
<p className="text-neutral-400">Create beautiful code snippets in seconds.</p>
</div>
{/* 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">
<section className="mb-16">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{/* 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"
className="group relative bg-white/[0.02] hover:bg-white/[0.04] border border-white/[0.08] hover:border-blue-500/30 rounded-2xl p-6 transition-all duration-300 text-left hover:shadow-2xl hover:shadow-blue-500/10 hover:-translate-y-1"
>
<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 className="w-12 h-12 bg-blue-500/10 text-blue-400 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300">
<Plus className="w-6 h-6" />
</div>
<h3 className="text-lg font-medium mb-2 text-white group-hover:text-blue-400 transition-colors">Blank Canvas</h3>
<p className="text-sm text-neutral-500 mb-4">Start from scratch with a fresh canvas</p>
<div className="flex items-center text-xs font-medium text-neutral-500 group-hover:text-blue-400 transition-colors">
<span>Create new</span>
<ChevronRight className="w-3 h-3 ml-1" />
</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"
className="group relative bg-white/[0.02] hover:bg-white/[0.04] border border-white/[0.08] hover:border-purple-500/30 rounded-2xl p-6 transition-all duration-300 text-left hover:shadow-2xl hover:shadow-purple-500/10 hover:-translate-y-1"
>
<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 className="w-12 h-12 bg-purple-500/10 text-purple-400 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300">
<FileText className="w-6 h-6" />
</div>
<h3 className="text-lg font-medium mb-2 text-white group-hover:text-purple-400 transition-colors">Import File</h3>
<p className="text-sm text-neutral-500 mb-4">Open an existing .yvsnap project file</p>
<div className="flex items-center text-xs font-medium text-neutral-500 group-hover:text-purple-400 transition-colors">
<span>Import</span>
<ChevronRight className="w-3 h-3 ml-1" />
</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"
className="group relative bg-white/[0.02] hover:bg-white/[0.04] border border-white/[0.08] hover:border-emerald-500/30 rounded-2xl p-6 transition-all duration-300 text-left hover:shadow-2xl hover:shadow-emerald-500/10 hover:-translate-y-1"
>
<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 className="w-12 h-12 bg-emerald-500/10 text-emerald-400 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300">
<Layout className="w-6 h-6" />
</div>
<h3 className="text-lg font-medium mb-2 text-white group-hover:text-emerald-400 transition-colors">Use Template</h3>
<p className="text-sm text-neutral-500 mb-4">Start with a pre-designed template</p>
<div className="flex items-center text-xs font-medium text-neutral-500 group-hover:text-emerald-400 transition-colors">
<span>Browse templates</span>
<ChevronRight className="w-3 h-3 ml-1" />
</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">
<div className="flex items-center gap-8 border-b border-white/[0.08] mb-8">
<button
onClick={() => setActiveTab('recent')}
className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
className={`pb-4 text-sm font-medium border-b-2 transition-colors relative ${
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
<div className="flex items-center gap-2">
<Clock className="w-4 h-4" />
<span>Recent Work</span>
</div>
{activeTab === 'recent' && (
<div className="absolute bottom-[-2px] left-0 w-full h-[2px] bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.5)]" />
)}
</button>
<button
onClick={() => setActiveTab('templates')}
className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
className={`pb-4 text-sm font-medium border-b-2 transition-colors relative ${
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
<div className="flex items-center gap-2">
<Sparkles className="w-4 h-4" />
<span>Templates</span>
</div>
{activeTab === 'templates' && (
<div className="absolute bottom-[-2px] left-0 w-full h-[2px] bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.5)]" />
)}
</button>
</div>
{/* Tab Content */}
{activeTab === 'recent' && (
<section>
<section className="animate-in fade-in duration-300 slide-in-from-bottom-4">
{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">
<div className="text-center py-24 bg-white/[0.02] border border-white/[0.08] rounded-2xl border-dashed">
<div className="w-16 h-16 bg-neutral-800/50 rounded-full flex items-center justify-center mx-auto mb-6">
<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>
<h3 className="text-xl font-medium mb-2">No recent work</h3>
<p className="text-neutral-500 mb-8 max-w-sm mx-auto">Projects you create or import will appear here for quick access.</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"
className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-500 rounded-xl transition-all hover:shadow-lg hover:shadow-blue-500/20 font-medium"
>
<Plus className="w-4 h-4" />
<Plus className="w-5 h-5" />
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>
<div className="flex items-center justify-between mb-6">
<p className="text-sm text-neutral-400 font-medium">{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"
className="text-sm text-neutral-500 hover:text-red-400 transition-colors px-3 py-1.5 hover:bg-red-400/10 rounded-lg"
>
Clear all
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
{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"
className="group relative bg-neutral-900 border border-white/[0.08] rounded-2xl overflow-hidden hover:border-blue-500/30 transition-all hover:shadow-xl hover:shadow-blue-500/5 hover:-translate-y-1 duration-300"
>
{/* Preview */}
<button
onClick={() => handleOpenRecent(entry.snap)}
className="w-full aspect-video relative overflow-hidden"
className="w-full aspect-video relative overflow-hidden bg-[#1e1e1e]"
>
<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 className="absolute inset-0 transition-transform duration-500 group-hover:scale-105">
<SnapPreview snap={entry.snap} />
</div>
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors duration-300" />
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 transform translate-y-2 group-hover:translate-y-0">
<span className="px-4 py-2 bg-white/10 backdrop-blur-md border border-white/20 rounded-xl text-sm font-medium shadow-xl">Open Project</span>
</div>
</button>
{/* Info */}
<div className="p-4">
<div className="flex items-start justify-between">
<div className="p-5">
<div className="flex items-start justify-between gap-4">
<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>
<h3 className="font-medium text-lg truncate mb-1 group-hover:text-blue-400 transition-colors">{entry.title}</h3>
<p className="text-xs text-neutral-500 font-medium uppercase tracking-wider">{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"
className="p-2 text-neutral-500 hover:text-red-400 hover:bg-red-400/10 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
title="Remove from recent"
>
<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 className="mt-4 pt-4 border-t border-white/[0.05] flex items-center gap-3 text-xs text-neutral-500 font-medium">
<span className="px-2 py-1 bg-white/5 rounded-md border border-white/5">{entry.snap.meta.width} × {entry.snap.meta.height}</span>
<span className="px-2 py-1 bg-white/5 rounded-md border border-white/5">{entry.snap.elements.length} element{entry.snap.elements.length !== 1 ? 's' : ''}</span>
</div>
</div>
</div>
@@ -228,33 +263,35 @@ export default function MainScreen({ onOpenEditor }: MainScreenProps) {
)}
{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">
<section className="animate-in fade-in duration-300 slide-in-from-bottom-4">
<p className="text-sm text-neutral-400 font-medium mb-6">{templates.length} templates available</p>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
{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"
className="group relative bg-neutral-900 border border-white/[0.08] rounded-2xl overflow-hidden hover:border-emerald-500/30 transition-all hover:shadow-xl hover:shadow-emerald-500/5 hover:-translate-y-1 duration-300"
>
{/* Preview */}
<button
onClick={() => handleUseTemplate(template)}
className="w-full aspect-video relative overflow-hidden"
className="w-full aspect-video relative overflow-hidden bg-[#1e1e1e]"
>
<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 className="absolute inset-0 transition-transform duration-500 group-hover:scale-105">
<SnapPreview snap={template.snap} />
</div>
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors duration-300" />
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 transform translate-y-2 group-hover:translate-y-0">
<span className="px-4 py-2 bg-emerald-500/90 backdrop-blur-md rounded-xl text-sm font-medium shadow-xl">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 className="p-5">
<h3 className="font-medium text-lg mb-2 group-hover:text-emerald-400 transition-colors">{template.name}</h3>
<p className="text-sm text-neutral-400 line-clamp-2">{template.description}</p>
<div className="mt-4 pt-4 border-t border-white/[0.05] flex items-center gap-3 text-xs text-neutral-500 font-medium">
<span className="px-2 py-1 bg-white/5 rounded-md border border-white/5">{template.snap.meta.width} × {template.snap.meta.height}</span>
<span className="px-2 py-1 bg-white/5 rounded-md border border-white/5">{template.snap.elements.length} element{template.snap.elements.length !== 1 ? 's' : ''}</span>
</div>
</div>
</div>
+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 { detectLanguage } from '../../utils/highlighter';
import { loadFont } from '../../utils/fontLoader';
import CodeEditor from './CodeEditor';
interface CodeInspectorProps {
element: CodeElement;
@@ -53,85 +54,17 @@ const CodeInspector: React.FC<CodeInspectorProps> = ({ element }) => {
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 (
<div className="space-y-4">
{/* Code editor */}
<div>
<label className="block text-sm text-neutral-400 mb-2">Code</label>
<textarea
<CodeEditor
value={element.props.code}
onChange={(e) => handleCodeChange(e.target.value)}
onKeyDown={handleKeyDown}
onChange={handleCodeChange}
onBlur={saveToHistory}
className="w-full h-32 bg-neutral-900 text-white text-sm font-mono p-3 rounded resize-y"
spellCheck={false}
style={{ tabSize: 2 }}
language={element.props.language}
theme={element.props.theme}
/>
</div>
+24
View File
@@ -89,3 +89,27 @@ select {
background-size: 16px;
padding-right: 32px;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideInFromBottom {
from { transform: translateY(1rem); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.animate-in {
animation-duration: 0.3s;
animation-fill-mode: both;
animation-timing-function: ease-out;
}
.fade-in {
animation-name: fadeIn;
}
.slide-in-from-bottom-4 {
animation-name: slideInFromBottom;
}