|
| 1 | +// based on vanilla https://css-tricks.com/creating-an-editable-textarea-that-supports-syntax-highlighted-code/ |
| 2 | + |
| 3 | +import React, { useEffect, useRef, useState } from "react" |
| 4 | + |
| 5 | +import "../styles/highlight-theme-light.css" |
| 6 | +import { tst } from "../utils/overrides.js" |
| 7 | +import { escapeHtml } from "../../worker/common.js" |
| 8 | +import { usePrism } from "../utils/HighlightLoader.js" |
| 9 | +import { Autocomplete, AutocompleteItem, Input, Select, SelectItem } from "@heroui/react" |
| 10 | + |
| 11 | +import "../styles/highlight-theme-light.css" |
| 12 | +import "../styles/highlight-theme-dark.css" |
| 13 | + |
| 14 | +// TODO: |
| 15 | +// - line number |
| 16 | +// - clear button |
| 17 | +interface CodeInputProps extends React.HTMLProps<HTMLDivElement> { |
| 18 | + content: string |
| 19 | + setContent: (code: string) => void |
| 20 | + lang?: string |
| 21 | + setLang: (lang?: string) => void |
| 22 | + filename?: string |
| 23 | + setFilename: (filename?: string) => void |
| 24 | + placeholder?: string |
| 25 | + disabled?: boolean |
| 26 | +} |
| 27 | + |
| 28 | +interface TabSetting { |
| 29 | + char: "tab" | "space" |
| 30 | + width: 2 | 4 |
| 31 | +} |
| 32 | + |
| 33 | +function formatTabSetting(s: TabSetting) { |
| 34 | + return `${s.char} ${s.width}` |
| 35 | +} |
| 36 | + |
| 37 | +function parseTabSetting(s: string): TabSetting | undefined { |
| 38 | + const match = s.match(/^(tab|space) ([24])$/) |
| 39 | + if (match) { |
| 40 | + return { char: match[1] as TabSetting["char"], width: parseInt(match[2]) as TabSetting["width"] } |
| 41 | + } else { |
| 42 | + return undefined |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const tabSettings: TabSetting[] = [ |
| 47 | + { char: "tab", width: 2 }, |
| 48 | + { char: "tab", width: 4 }, |
| 49 | + { char: "space", width: 2 }, |
| 50 | + { char: "space", width: 4 }, |
| 51 | +] |
| 52 | + |
| 53 | +function handleNewLines(str: string): string { |
| 54 | + if (str.at(-1) === "\n") { |
| 55 | + str += " " |
| 56 | + } |
| 57 | + return str |
| 58 | +} |
| 59 | + |
| 60 | +export function CodeInput({ |
| 61 | + content, |
| 62 | + setContent, |
| 63 | + lang, |
| 64 | + setLang, |
| 65 | + filename, |
| 66 | + setFilename, |
| 67 | + placeholder, |
| 68 | + disabled, |
| 69 | + className, |
| 70 | + ...rest |
| 71 | +}: CodeInputProps) { |
| 72 | + const refHighlighting = useRef<HTMLPreElement | null>(null) |
| 73 | + const refTextarea = useRef<HTMLTextAreaElement | null>(null) |
| 74 | + |
| 75 | + const [heightPx, setHeightPx] = useState<number>(0) |
| 76 | + const prism = usePrism() |
| 77 | + const [tabSetting, setTabSettings] = useState<TabSetting>({ char: "space", width: 2 }) |
| 78 | + |
| 79 | + function syncScroll() { |
| 80 | + refHighlighting.current!.scrollLeft = refTextarea.current!.scrollLeft |
| 81 | + refHighlighting.current!.scrollTop = refTextarea.current!.scrollTop |
| 82 | + } |
| 83 | + |
| 84 | + function handleInput(_: React.FormEvent<HTMLTextAreaElement>) { |
| 85 | + const editing = refTextarea.current! |
| 86 | + setContent(editing.value) |
| 87 | + syncScroll() |
| 88 | + } |
| 89 | + |
| 90 | + function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) { |
| 91 | + const element = refTextarea.current! |
| 92 | + if (event.key === "Tab") { |
| 93 | + event.preventDefault() // stop normal |
| 94 | + const beforeTab = content.slice(0, element.selectionStart) |
| 95 | + const afterTab = content.slice(element.selectionEnd, element.value.length) |
| 96 | + const insertedString = tabSetting.char === "tab" ? "\t" : " ".repeat(tabSetting.width) |
| 97 | + const curPos = element.selectionStart + insertedString.length |
| 98 | + setContent(beforeTab + insertedString + afterTab) |
| 99 | + // move cursor |
| 100 | + element.selectionStart = curPos |
| 101 | + element.selectionEnd = curPos |
| 102 | + } else if (event.key === "Escape") { |
| 103 | + element.blur() |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + useEffect(() => { |
| 108 | + setHeightPx(refTextarea.current!.clientHeight) |
| 109 | + const observer = new ResizeObserver((entries) => { |
| 110 | + for (const entry of entries) { |
| 111 | + if (entry.contentRect) { |
| 112 | + setHeightPx(entry.contentRect.height) |
| 113 | + } |
| 114 | + } |
| 115 | + }) |
| 116 | + |
| 117 | + observer.observe(refTextarea.current!) |
| 118 | + |
| 119 | + return () => { |
| 120 | + observer.disconnect() |
| 121 | + } |
| 122 | + }, []) |
| 123 | + |
| 124 | + function highlightedHTML() { |
| 125 | + if (prism && lang && prism.listLanguages().includes(lang) && lang !== "plaintext") { |
| 126 | + const highlighted = prism.highlight(handleNewLines(content), { language: lang }) |
| 127 | + return highlighted.value |
| 128 | + } else { |
| 129 | + return escapeHtml(content) |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + return ( |
| 134 | + <div className={className} {...rest}> |
| 135 | + <div className={"mb-2 gap-4 flex flex-row" + " "}> |
| 136 | + <Input type={"text"} label={"File name"} size={"sm"} key={filename} onValueChange={setFilename} /> |
| 137 | + <Autocomplete |
| 138 | + className={"max-w-[10em]"} |
| 139 | + label={"Language"} |
| 140 | + size={"sm"} |
| 141 | + defaultItems={prism ? prism.listLanguages().map((lang) => ({ key: lang })) : []} |
| 142 | + selectedKey={lang} |
| 143 | + onSelectionChange={(key) => { |
| 144 | + setLang((key as string | null) || undefined) |
| 145 | + }} |
| 146 | + > |
| 147 | + {(language) => <AutocompleteItem key={language.key}>{language.key}</AutocompleteItem>} |
| 148 | + </Autocomplete> |
| 149 | + <Select |
| 150 | + size={"sm"} |
| 151 | + label={"Tabs"} |
| 152 | + className={"max-w-[10em]"} |
| 153 | + selectedKeys={[formatTabSetting(tabSetting)]} |
| 154 | + onSelectionChange={(s) => { |
| 155 | + setTabSettings(parseTabSetting(s.currentKey as string)!) |
| 156 | + }} |
| 157 | + > |
| 158 | + {tabSettings.map((s) => ( |
| 159 | + <SelectItem key={formatTabSetting(s)}>{formatTabSetting(s)}</SelectItem> |
| 160 | + ))} |
| 161 | + </Select> |
| 162 | + </div> |
| 163 | + <div className={`w-full bg-default-100 ${tst} rounded-xl p-2`}> |
| 164 | + <div className={"relative w-full"}> |
| 165 | + <pre |
| 166 | + className={"w-full font-mono overflow-auto text-foreground top-0 left-0 absolute"} |
| 167 | + ref={refHighlighting} |
| 168 | + dangerouslySetInnerHTML={{ __html: highlightedHTML() }} |
| 169 | + style={{ height: `${heightPx}px` }} |
| 170 | + ></pre> |
| 171 | + <textarea |
| 172 | + className={`w-full font-mono min-h-[20em] text-[transparent] placeholder-default-400 ${tst} caret-foreground bg-transparent outline-none relative`} |
| 173 | + ref={refTextarea} |
| 174 | + readOnly={disabled} |
| 175 | + placeholder={placeholder} |
| 176 | + onScroll={syncScroll} |
| 177 | + onInput={handleInput} |
| 178 | + onKeyDown={handleKeyDown} |
| 179 | + value={content} |
| 180 | + spellCheck={false} |
| 181 | + aria-label={"Paste editor"} |
| 182 | + ></textarea> |
| 183 | + </div> |
| 184 | + </div> |
| 185 | + </div> |
| 186 | + ) |
| 187 | +} |
0 commit comments