CodeEditor
コードを書く欄。色分け、括弧の対応、折り畳み、候補、書き間違いの下線を持ち、スマホでも動く。中身は CodeMirror 6。CodeMirror を使う画面でだけ読み込むように、knowidea-ui/editor から読み込む。
import { CodeEditor, editorLanguageOfPath } from "knowidea-ui/editor";カテゴリ: Data display。同じカテゴリ: Avatar、Badge、Chip、Status、Stat、Table、List、Timeline、Tooltip、Popover、CodeBlock、Kbd、Quote、Display、Jacket、Conversation、DiffView
Demos
Basic
language は editorLanguageOfPath でパスから決められる。スマホの幅(600px 未満)では長い行を折り返す。
107 字
Show code
import { lazy, Suspense, useState } from "react";import { Skeleton, editorLanguageOfPath } from "knowidea-ui";import type { CodeEditorProps } from "knowidea-ui/editor";const LazyEditor = lazy(() => import("knowidea-ui/editor").then((m) => ({ default: m.CodeEditor })));function CodeEditor(props: CodeEditorProps) { // CodeMirror は大きいので、エディタを出す時にだけ読み込む return <Suspense fallback={<Skeleton shape="block" />}><LazyEditor {...props} /></Suspense>;}const source = `export function total(items: number[]) { let sum = 0; for (const n of items) sum += n; return sum;}`;function Basic() { const [value, setValue] = useState(source); return ( <div style={{ width: "100%", display: "grid", gap: "var(--space-2)" }}> <CodeEditor label="src/total.ts" language={editorLanguageOfPath("src/total.ts")} value={value} onChange={setValue} /> <p className="ki-editor-demo__count" style={{ margin: 0, color: "var(--color-text-muted)", fontSize: "var(--font-size-2)" }}>{value.length} 字</p> </div> );}export function total(items: number[]) {
let sum = 0;
for (const n of items) sum += n;
return sum;
}
Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。Languages
TypeScript、JavaScript(JSX も)、CSS、Markdown、JSON を色分けする。ほかは text。
Show code
import { lazy, Suspense, useState } from "react";import { Skeleton } from "knowidea-ui";import type { CodeEditorProps } from "knowidea-ui/editor";const LazyEditor = lazy(() => import("knowidea-ui/editor").then((m) => ({ default: m.CodeEditor })));function CodeEditor(props: CodeEditorProps) { // CodeMirror は大きいので、エディタを出す時にだけ読み込む return <Suspense fallback={<Skeleton shape="block" />}><LazyEditor {...props} /></Suspense>;}function Languages() { const [css, setCss] = useState(".card {\n padding: var(--space-3);\n color: var(--color-text);\n}\n"); const [md, setMd] = useState("# 使い方\n\n合計を返す。**負**になる時は `RangeError` を投げる。\n"); return ( <div style={{ width: "100%", display: "grid", gap: "var(--space-3)" }}> <CodeEditor label="card.css" language="css" value={css} onChange={setCss} /> <CodeEditor label="README.md" language="markdown" value={md} onChange={setMd} /> </div> );}.card {
padding: var(--space-3);
color: var(--color-text);
}
Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。# 使い方 合計を返す。**負**になる時は `RangeError` を投げる。Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。
Diagnostics
diagnostics に行と列を渡すと、その場所に波の下線が付く。合わせるか、中に入って Ctrl+Shift+M(Mac は Cmd+Shift+M)で中身が出る。
書き間違いが 2 件
Show code
import { lazy, Suspense, useState } from "react";import { Skeleton } from "knowidea-ui";import type { CodeEditorProps, EditorDiagnostic } from "knowidea-ui/editor";const LazyEditor = lazy(() => import("knowidea-ui/editor").then((m) => ({ default: m.CodeEditor })));function CodeEditor(props: CodeEditorProps) { // CodeMirror は大きいので、エディタを出す時にだけ読み込む return <Suspense fallback={<Skeleton shape="block" />}><LazyEditor {...props} /></Suspense>;}function Diagnostics() { const [value, setValue] = useState(`const count: number = "3";\nconsole.log(cuont);\n`); const found: EditorDiagnostic[] = []; if (value.includes(`= "3"`)) found.push({ line: 1, column: 23, endColumn: 26, severity: "error", message: "文字列は number に入らない" }); const at = value.split("\n")[1]?.indexOf("cuont") ?? -1; if (at >= 0) found.push({ line: 2, column: at + 1, endColumn: at + 6, severity: "error", message: "cuont が見つからない。count ではないか" }); return ( <div style={{ width: "100%", display: "grid", gap: "var(--space-2)" }}> <CodeEditor label="src/count.ts" language="typescript" value={value} onChange={setValue} diagnostics={found} /> <p role="status" style={{ margin: 0, fontSize: "var(--font-size-2)" }}>{found.length ? `書き間違いが ${found.length} 件` : "書き間違いは無い"}</p> </div> );}const count: number = "3"; console.log(cuont);Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。
Completion and hover
complete が返した候補は、言語が元から持つ候補に足される。Ctrl+Space でも開く。hover は、合わせた所の説明を返す。キーでは Ctrl+Shift+Space(Mac は Cmd+Shift+Space)で、カーソルの所の説明が出る。
Show code
import { lazy, Suspense, useState } from "react";import { Skeleton } from "knowidea-ui";import type { CodeEditorProps } from "knowidea-ui/editor";const LazyEditor = lazy(() => import("knowidea-ui/editor").then((m) => ({ default: m.CodeEditor })));function CodeEditor(props: CodeEditorProps) { // CodeMirror は大きいので、エディタを出す時にだけ読み込む return <Suspense fallback={<Skeleton shape="block" />}><LazyEditor {...props} /></Suspense>;}const parts = [ { label: "Breadcrumbs", detail: "今いる場所", type: "class" }, { label: "Badge", detail: "短い印", type: "class" }, { label: "BottomNavigation", detail: "下の切り替え", type: "class" }, { label: "DiffView", detail: "変更の表示", type: "class" },];function Completion() { const [value, setValue] = useState("import { } from \"knowidea-ui\";\n"); return ( <div style={{ width: "100%" }}> <CodeEditor label="src/App.tsx" language="tsx" value={value} onChange={setValue} complete={({ word }) => parts.filter((p) => p.label.toLowerCase().startsWith(word.toLowerCase()))} hover={({ text, offset }) => { const hit = parts.find((p) => { const i = text.indexOf(p.label); return i >= 0 && offset >= i && offset <= i + p.label.length; }); return hit ? `${hit.label}: ${hit.detail}` : null; }} /> </div> );}import { } from "knowidea-ui";
Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。Switching files
value、label、language を外から替えると、同じエディタのまま別のファイルになる。この時 onChange は呼ばれず、元に戻す履歴は空になる。
書き換えていない
Show code
import { lazy, Suspense, useState } from "react";import { Button, Skeleton, editorLanguageOfPath } from "knowidea-ui";import type { CodeEditorProps } from "knowidea-ui/editor";const LazyEditor = lazy(() => import("knowidea-ui/editor").then((m) => ({ default: m.CodeEditor })));function CodeEditor(props: CodeEditorProps) { // CodeMirror は大きいので、エディタを出す時にだけ読み込む return <Suspense fallback={<Skeleton shape="block" />}><LazyEditor {...props} /></Suspense>;}const source = `export function total(items: number[]) { let sum = 0; for (const n of items) sum += n; return sum;}`;const files = [ { path: "src/total.ts", text: source }, { path: "README.md", text: "# total\n\n合計を返す。\n" },];function Files() { const [at, setAt] = useState(0); const [texts, setTexts] = useState(files.map((f) => f.text)); const dirty = texts.some((t, i) => t !== files[i]!.text); return ( <div style={{ width: "100%", display: "grid", gap: "var(--space-2)" }}> <div style={{ display: "flex", gap: "var(--space-2)", flexWrap: "wrap" }}> {files.map((f, i) => <Button key={f.path} variant={i === at ? "primary" : "secondary"} aria-pressed={i === at} onClick={() => setAt(i)}>{f.path}</Button>)} </div> <CodeEditor label={files[at]!.path} language={editorLanguageOfPath(files[at]!.path)} value={texts[at]!} onChange={(v) => setTexts((t) => t.map((x, i) => (i === at ? v : x)))} /> <p role="status" style={{ margin: 0, fontSize: "var(--font-size-2)" }}>{dirty ? "書き換えた" : "書き換えていない"}</p> </div> );}export function total(items: number[]) {
let sum = 0;
for (const n of items) sum += n;
return sum;
}
Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。Read only
readOnly で読むだけにする。height を渡すと高さが決まり、中で送る。
Show code
import { lazy, Suspense } from "react";import { Skeleton } from "knowidea-ui";import type { CodeEditorProps } from "knowidea-ui/editor";const LazyEditor = lazy(() => import("knowidea-ui/editor").then((m) => ({ default: m.CodeEditor })));function CodeEditor(props: CodeEditorProps) { // CodeMirror は大きいので、エディタを出す時にだけ読み込む return <Suspense fallback={<Skeleton shape="block" />}><LazyEditor {...props} /></Suspense>;}const source = `export function total(items: number[]) { let sum = 0; for (const n of items) sum += n; return sum;}`;function ReadOnly() { return <div style={{ width: "100%" }}><CodeEditor label="src/total.ts(読むだけ)" language="typescript" value={source} readOnly height="8rem" /></div>;}export function total(items: number[]) {
let sum = 0;
for (const n of items) sum += n;
return sum;
}
Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。States
すべてのコンポーネントが、Empty、Loading、Error、Disabled、Focus の 5 つの状態を備える。Hover と Active は、確認用に固定して表示している。そのコンポーネントにあてはまらない状態は「対象外」とし、理由を添える。
| State | Appearance |
|---|---|
| Empty | 中身が無い時も 6 行ぶんの高さを保つ |
| Loading | ファイルを取っている間は Skeleton で場所を取る |
| Error | ファイルを開けなかった もう一度開き直す。 エラー状態を持たない。開けない時は Alert に切り替える。中身の書き間違いは diagnostics で下線にする |
| Disabled | 無効でなく readOnly にする。選ぶ、写す、キーで動くはできる |
| Focus | エディタの中に入ると、枠の外に 2px のリングが出る。Tab は字下げに使い、Esc を押してから Tab で外へ移る |
const a = 1;Tab は字下げ。Esc を押してから Tab を押すと、エディタの外へ移る。
API
| Name | Type | Default | Description |
|---|---|---|---|
value | string | - | 中身 |
onChange | (value) => void | - | 打って中身が変わった時 |
label | string | - | 読み上げの名前。ファイルの名前など(必須) |
language | "typescript" | "tsx" | "javascript" | "jsx" | "css" | "markdown" | "json" | "text" | "text" | 言語 |
readOnly | boolean | false | 読むだけにする |
wrap | boolean | - | 長い行を折り返す。既定は 600px 未満の時だけ |
diagnostics | EditorDiagnostic[] | - | { line, column, endLine?, endColumn?, severity, message }。行と列は 1 から |
complete | (place) => EditorCompletion[] | null | - | 候補を返す。Promise でもよい。place は { line, column, offset, text, word, explicit } |
hover | (place) => string | null | - | 合わせた所の説明を返す。Promise でもよい |
onDefinition | (place) => void | - | F12 か、Ctrl か Cmd を押しながら押した時 |
onSave | (value) => void | - | Ctrl+S か Cmd+S |
height | string | - | 高さ(CSS の長さ)。無ければ中身に合わせて伸びる |
extensions | Extension[] | - | CodeMirror の拡張を足す |
cspNonce | string | - | CSP の nonce。CodeMirror は見た目を <style> で差し込むので、style-src を nonce で許す画面で渡す。作った時の値だけを使う |
CSS
Classes and data attributes
| Name | Description |
|---|---|
.ki-editor | 本体。data-readonly、data-fixed(height を渡した時) |
.ki-editor__hover | 合わせた所の説明 |
.tok-keyword、.tok-string、.tok-comment など | 色分け(@lezer/highlight のクラス) |
CSS variables
コンポーネントが参照するのは、役割を表す名前の変数だけで、素の値は参照しない。オーバーライドの方法は Overriding を参照。
| Variable | Usage |
|---|---|
| --ki-editor-height | 高さ(height で入る) |
| --color-primary、--color-success、--color-warn、--color-info | 色分け。どれも面の上で 4.5:1 以上 |
| --font-mono | 中身のフォント |
Accessibility
- label が欄の名前になる。行の番号と折り畳みの印は読み上げない
- Tab は字下げに使う。Esc を押してから Tab を押すと、エディタの外へ移る(読み上げにも同じ説明が付く)
- 書き間違いは色だけでなく、波の下線と、合わせた時の文字で示す。キーでは F8 で次の書き間違いへ移る
- 合わせた所の説明は、キーでは Ctrl+Shift+Space で出て、Esc で消える
- 折り畳みの印は 44px に届かないので、指で触る端末では出さない
- 指で触る端末では字が 16px になる(iOS が小さい字の欄を拡大するのを避ける)