CodeEditor
An editor for code and settings files, with line numbers, search and errors on their lines. It is a controlled field: value and onValueChange. diagnostics marks lines ({ line, message }, 1-based) and marks each with an error line, a gutter mark and a visible list under the editor (“Line 2: message”; a diagnostic whose line is not in the text shows in the list without a mark, and without “Line” when the line is not a whole number of 1 or more); validate in your own code, the editor does not. language is yaml (default) or text. readOnly keeps focus, selection, search and copy. label names the editor for screen readers, and minLines sets its least height. The code is always left to right; the error list and the hint follow the page direction. Tab indents, so to leave the editor with the keyboard press Escape, then Tab (with text selected, press Escape twice); an editable editor shows this hint while it has focus, and screen readers read it as its description. CodeMirror makes it heavy, so it has its own entry, @percentsa/ui/code-editor: the root entry does not load it. Its words (search, errors) come from the provider strings. errorList={false} keeps the line marks and the gutter marks but draws no list under the editor, for a page that shows its own list (make that list a polite live region, as the built-in list is).
import { CodeEditor } from "@percentsa/ui/code-editor";Examples
Press Escape, then Tab, to leave the editor.
Change an image version to “latest” to see an error on its line.
Code
export function CodeEditorExample() {
const t = useT();
const [value, setValue] = useState(CONFIG);
return (
<div className="w-full max-w-xl">
<CodeEditor value={value} onValueChange={setValue} diagnostics={checkConfig(value, t("Name a version, not latest", "حدّد إصدارًا بدل latest"))} label={t("Service settings", "إعدادات الخدمات")} minLines={10} />
<p className="mt-2 text-sm text-fg-3">{t("Change an image version to “latest” to see an error on its line.", "غيّر إصدار صورة إلى «latest» لترى الخطأ على سطرها.")}</p>
</div>
);
}Press Escape, then Tab, to leave the editor.
Code
export function CodeEditorOwnListExample() {
const t = useT();
const [value, setValue] = useState(CONFIG);
const found = checkConfig(value, t("Name a version, not latest", "حدّد إصدارًا بدل latest"));
return (
<div className="w-full max-w-xl">
<ul aria-live="polite" className="mb-2 list-none text-sm text-danger">
{found.map((d, i) => (
<li key={i}>{t(`Line ${d.line}: ${d.message}`, `السطر ${d.line}: ${d.message}`)}</li>
))}
</ul>
<CodeEditor value={value} onValueChange={setValue} diagnostics={found} errorList={false} label={t("Service settings", "إعدادات الخدمات")} minLines={8} />
</div>
);
}Code
export function CodeEditorReadOnlyExample() {
const t = useT();
return <CodeEditor value={CONFIG} readOnly label={t("Service settings, read only", "إعدادات الخدمات، للقراءة فقط")} minLines={4} className="w-full max-w-xl" />;
}