Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThemeCssEditor.tsx

124 lines4.7 KB

1import { useId, useState, type KeyboardEvent } from "react";
2​
3import { Button } from "../ui/button";
4​
5export function ThemeCssEditor({
6 value,
7 onChange,
8}: {
9 value: string;
10 onChange: (value: string) => void;
11}) {
12 const hintId = useId();
13 const [position, setPosition] = useState({ line: 1, column: 1 });
14 const [tabIndents, setTabIndents] = useState(true);
15​
16 function updatePosition(editor: HTMLTextAreaElement) {
17 const preceding = editor.value.slice(0, editor.selectionStart).split("\n");
18 setPosition({ line: preceding.length, column: (preceding.at(-1)?.length ?? 0) + 1 });
19 }
20​
21 function replaceSelection(editor: HTMLTextAreaElement, replacement: string) {
22 // Native insertion preserves undo history for indentation as well as typing.
23 if (!document.execCommand("insertText", false, replacement)) {
24 editor.setRangeText(replacement, editor.selectionStart, editor.selectionEnd, "end");
25 }
26 onChange(editor.value);
27 updatePosition(editor);
28 }
29​
30 function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
31 if (event.nativeEvent.isComposing || event.ctrlKey || event.metaKey || event.altKey) return;
32 const editor = event.currentTarget;
33 if (event.key === "Escape") {
34 event.preventDefault();
35 event.stopPropagation();
36 setTabIndents(false);
37 return;
38 }
39 if (event.key === "Tab" && tabIndents) {
40 event.preventDefault();
41 const start = editor.selectionStart;
42 const end = editor.selectionEnd;
43 const lineStart = start === 0 ? 0 : editor.value.lastIndexOf("\n", start - 1) + 1;
44 if (start === end && !event.shiftKey) {
45 replaceSelection(editor, " ");
46 } else if (start === end) {
47 const indent = editor.value.slice(lineStart).match(/^(?: {1,2}|\t)/)?.[0] ?? "";
48 if (!indent) return;
49 editor.setSelectionRange(lineStart, lineStart + indent.length);
50 replaceSelection(editor, "");
51 editor.setSelectionRange(
52 Math.max(lineStart, start - indent.length),
53 Math.max(lineStart, end - indent.length),
54 );
55 } else {
56 // A selection ending at a line's start leaves that next line untouched.
57 const blockEnd = end > start && editor.value[end - 1] === "\n" ? end - 1 : end;
58 const selected = editor.value.slice(lineStart, blockEnd);
59 const replacement = selected
60 .split("\n")
61 .map((line) => (event.shiftKey ? line.replace(/^(?: {1,2}|\t)/, "") : ` ${line}`))
62 .join("\n");
63 editor.setSelectionRange(lineStart, blockEnd);
64 replaceSelection(editor, replacement);
65 editor.setSelectionRange(lineStart, lineStart + replacement.length);
66 }
67 updatePosition(editor);
68 } else if (event.key === "Enter" && editor.selectionStart === editor.selectionEnd) {
69 const precedingLine = editor.value.slice(0, editor.selectionStart).split("\n").at(-1) ?? "";
70 const indent = precedingLine.match(/^[\t ]*/)?.[0] ?? "";
71 event.preventDefault();
72 replaceSelection(editor, `\n${indent}${precedingLine.trimEnd().endsWith("{") ? " " : ""}`);
73 }
74 }
75​
76 return (
77 <div className="space-y-2">
78 <div className="overflow-hidden rounded-lg border border-input bg-code text-foreground focus-within:border-ring focus-within:ring-3 focus-within:ring-inset focus-within:ring-ring/24">
79 <textarea
80 aria-label="Custom CSS"
81 aria-describedby={hintId}
82 autoCapitalize="off"
83 autoComplete="off"
84 autoCorrect="off"
85 spellCheck={false}
86 wrap="off"
87 className="block h-52 w-full resize-none bg-transparent p-3 font-mono text-xs leading-5 outline-none"
88 value={value}
89 onFocus={() => setTabIndents(true)}
90 onChange={(event) => {
91 onChange(event.currentTarget.value);
92 updatePosition(event.currentTarget);
93 }}
94 onSelect={(event) => updatePosition(event.currentTarget)}
95 onKeyDown={handleKeyDown}
96 />
97 <div className="flex items-center justify-between border-t border-input px-3 py-1 font-mono text-xs">
98 <span>CSS</span>
99 <span>
100 Ln {position.line}, Col {position.column}
101 </span>
102 </div>
103 </div>
104 <div className="flex items-start justify-between gap-2">
105 <p id={hintId} className="text-xs text-muted-foreground">
106 {tabIndents
107 ? "Tab indents. Shift+Tab unindents. Press Escape, then Tab to leave."
108 : "Tab moves to the next control."}
109 </p>
110 <Button
111 size="xs"
112 variant="ghost"
113 disabled={!value}
114 onClick={() => {
115 onChange("");
116 setPosition({ line: 1, column: 1 });
117 }}
118 >
119 Clear CSS
120 </Button>
121 </div>
122 </div>
123 );