KNOW IDEA UIv0.18.0GitHub

CodeEditor

コードを書く欄。色分け、括弧の対応、折り畳み、候補、書き間違いの下線を持ち、スマホでも動く。中身は CodeMirror 6。CodeMirror を使う画面でだけ読み込むように、knowidea-ui/editor から読み込む。

tsx
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
tsx
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>  );}

Languages

TypeScript、JavaScript(JSX も)、CSS、Markdown、JSON を色分けする。ほかは text。

Show code
tsx
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>  );}

Diagnostics

diagnostics に行と列を渡すと、その場所に波の下線が付く。合わせるか、中に入って Ctrl+Shift+M(Mac は Cmd+Shift+M)で中身が出る。

書き間違いが 2 件

Show code
tsx
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>  );}

Completion and hover

complete が返した候補は、言語が元から持つ候補に足される。Ctrl+Space でも開く。hover は、合わせた所の説明を返す。キーでは Ctrl+Shift+Space(Mac は Cmd+Shift+Space)で、カーソルの所の説明が出る。

Show code
tsx
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>  );}

Switching files

value、label、language を外から替えると、同じエディタのまま別のファイルになる。この時 onChange は呼ばれず、元に戻す履歴は空になる。

書き換えていない

Show code
tsx
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>  );}

Read only

readOnly で読むだけにする。height を渡すと高さが決まり、中で送る。

Show code
tsx
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>;}

States

すべてのコンポーネントが、Empty、Loading、Error、Disabled、Focus の 5 つの状態を備える。Hover と Active は、確認用に固定して表示している。そのコンポーネントにあてはまらない状態は「対象外」とし、理由を添える。

StateAppearance
Empty

中身が無い時も 6 行ぶんの高さを保つ

Loading

ファイルを取っている間は Skeleton で場所を取る

Error

ファイルを開けなかった

もう一度開き直す。

エラー状態を持たない。開けない時は Alert に切り替える。中身の書き間違いは diagnostics で下線にする

Disabled

無効でなく readOnly にする。選ぶ、写す、キーで動くはできる

Focusエディタの中に入ると、枠の外に 2px のリングが出る。Tab は字下げに使い、Esc を押してから Tab で外へ移る

API

NameTypeDefaultDescription
valuestring-中身
onChange(value) => void-打って中身が変わった時
labelstring-読み上げの名前。ファイルの名前など(必須)
language"typescript" | "tsx" | "javascript" | "jsx" | "css" | "markdown" | "json" | "text""text"言語
readOnlybooleanfalse読むだけにする
wrapboolean-長い行を折り返す。既定は 600px 未満の時だけ
diagnosticsEditorDiagnostic[]-{ 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
heightstring-高さ(CSS の長さ)。無ければ中身に合わせて伸びる
extensionsExtension[]-CodeMirror の拡張を足す
cspNoncestring-CSP の nonce。CodeMirror は見た目を <style> で差し込むので、style-src を nonce で許す画面で渡す。作った時の値だけを使う

CSS

Classes and data attributes

NameDescription
.ki-editor本体。data-readonly、data-fixed(height を渡した時)
.ki-editor__hover合わせた所の説明
.tok-keyword、.tok-string、.tok-comment など色分け(@lezer/highlight のクラス)

CSS variables

コンポーネントが参照するのは、役割を表す名前の変数だけで、素の値は参照しない。オーバーライドの方法は Overriding を参照。

VariableUsage
--ki-editor-height高さ(height で入る)
--color-primary、--color-success、--color-warn、--color-info色分け。どれも面の上で 4.5:1 以上
--font-mono中身のフォント

Accessibility

KNOW IDEA UIv0.18.0

GitHub

ページと見出しを探す。/ か Ctrl K でどのページからも開く。

Code