| 保存先 | 保持される期間 | 用途 |
|---|---|---|
| モジュール変数 | リロードすると消える | 描画に使わない一時的な値 |
$.state | セッション中(リロードしても保持される) | 描画に使う値。値を書き込むと、その値を読んでいる描画箇所だけが再描画される(invalidate は不要) |
$.store | セッションをまたいで保持される | 設定や累計など。JSON ファイルとして保存される |
型定義ファイル
$.state に保存する値は、型定義ファイルで宣言します。plugin と key はソースコード上でリテラルとして書く必要があります(StateFamily の id だけは計算した値を使えます)。
// types/index.d.ts(plugin.json に "types": "./types/index.d.ts" を書く)
export type Turn = { seconds: number; tools: number }
declare module 'claude-code' {
interface PluginState {
'turn-band': { last: Turn | null; isHidden: boolean }
}
}
状態管理の関数(import { … } from 'claude-code')
| 関数 | 説明 |
|---|---|
atom(ref, initial) | 初期値を持つ名前付きの値を定義する。値がまだ書き込まれていなければ read は初期値を返すため、undefined にはならない。 |
read($, source) | atom、derive、参照の値を読む。描画中に呼ぶと、その描画箇所が値の変更を購読する。 |
update($, atom, fn) | 値を読み、fn を適用し、ifVersion を付けて書き込む。他の書き込みと競合した場合はやり直す。ハンドラからはこの関数を使う。ボタンが素早く2回押されても、両方の更新が反映される。 |
derive(sources, fn) | 他の値から計算される値を定義する。元の値のバージョンをもとに結果をキャッシュする。 |
memberOf(family, e) | StateFamily<T> のうち、描画中のインスタンス(e.requestId)に対応する値を返す。 |
import { atom, read, update } from 'claude-code'
const count = atom({ plugin: 'counter', key: 'count' } as const, 0)
on('ui.render', { component: 'Pane', requestId: 'counter' }, async ($, e) => {
const { Box, Text, Button } = $.ui.resolve(e)
const n = await read($, count) // 描画中に読むと変更を購読する
return (
<Box gap={1}>
<Text>{n}</Text>
<Button key="inc" label="+1" onPress={() => update($, count, v => v + 1)} />
</Box>
)
})
絞り込みの条件に一致する行がありません。