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