Compare commits
3 Commits
a09538a3c9
...
d95afbbc72
| Author | SHA1 | Date | |
|---|---|---|---|
| d95afbbc72 | |||
| 66d811aeaf | |||
| a960055532 |
+2
-2
@@ -38,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) {
|
||||||
@@ -64,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);
|
||||||
|
|||||||
@@ -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}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export default function MainScreen({ onOpenEditor }: MainScreenProps) {
|
|||||||
const handleImportFile = () => {
|
const handleImportFile = () => {
|
||||||
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) {
|
||||||
@@ -101,7 +101,7 @@ export default function MainScreen({ onOpenEditor }: MainScreenProps) {
|
|||||||
<FileText className="w-6 h-6 text-neutral-400 group-hover:text-blue-400" />
|
<FileText className="w-6 h-6 text-neutral-400 group-hover:text-blue-400" />
|
||||||
</div>
|
</div>
|
||||||
<h3 className="font-medium mb-1">Import File</h3>
|
<h3 className="font-medium mb-1">Import File</h3>
|
||||||
<p className="text-sm text-neutral-500">Open an existing .json project file</p>
|
<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" />
|
<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>
|
</button>
|
||||||
|
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef, onGoHome }) => {
|
|||||||
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);
|
||||||
@@ -101,7 +101,7 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef, onGoHome }) => {
|
|||||||
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) {
|
||||||
@@ -324,7 +324,7 @@ const TopBar: React.FC<TopBarProps> = ({ stageRef, onGoHome }) => {
|
|||||||
</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>
|
||||||
|
|||||||
@@ -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> </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;
|
||||||
@@ -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>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user