modscode EN

modscode / 図鑑 / now-playing

now-playing

Now Playing pane, status line and model tool for Apple Music and Spotify on macOS

確かめやすいコードターミナル+デスクトップペインステータスライントーストBoxButtonText

何をするか

  • 欄・トーストを描く
  • /music を足す
  • mcp__now-playing__music の呼び出しを見張る(止めることがある)
  • session.start・ui.closeにフックする
  • ターンをまたいで自分の状態を持つ

良いところ

  • ネットワークに出ない
  • TypeScript で書かれている
  • デスクトップ専用の分岐がある
  • エラーを扱う

作り始めるためのコード

2 種類あります。上のデザインから modscode が書いた雛形と、その Mod 自身のコードのうち描いている部分です。

雛形(register.tsx)

register.tsx
import type { Register } from 'claude-code'

// Drawn like now-playing by Jimmy Hsiao (pane, status, toast), as modscode read it from the mod's code:
// https://modscode.com/gallery/fatmylin-now-playing/
// Written by modscode from that reading, not copied from the mod: use it as you like.
// Each value below stands for one the mod works out at run time; put in your own.
export const register: Register = on => {
  // the pane: open it with $.ui.open({ id: 'my-pane', title: "Now Playing" })
  on('ui.render', { component: 'Pane', requestId: 'my-pane' }, async ($, e) => {
    const { Box, Button, Text } = $.ui.resolve(e)
    const label = '…'
    const i = '…'
    const formatTime = '…'
    const formatTime2 = '…'
    const repeat = '…'
    const volume = '…'
    return (
      <Box flexDirection="column">
        <Box flexDirection="row" justifyContent="center">
          <Box flexDirection="row" columnGap={3}>
            <Button label={`${label} ♪`} hotkey={`${i}`} plain />
            <Button label={`${label} ♪`} hotkey={`${i}`} plain />
            <Button label={`${label} ♪`} hotkey={`${i}`} plain />
          </Box>
        </Box>
        <Box height={1} />
        <Box flexDirection="row" justifyContent="center" />
        <Box height={1} />
        <Box flexDirection="row" justifyContent="center">
          <Text bold />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text bold />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text bold />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text dimColor />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text dimColor />
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text dimColor />
        </Box>
        <Box height={1} />
        <Box flexDirection="row" justifyContent="center">
          <Text dimColor wrap="truncate-end">
            {" "}
          </Text>
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text bold wrap="truncate-end">
            {" "}
          </Text>
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text dimColor wrap="truncate-end">
            {" "}
          </Text>
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Text dimColor>
            No synced lyrics
          </Text>
        </Box>
        <Box height={1} />
        <Box flexDirection="row">
          <Text>
            ━━━━━━━━
          </Text>
          <Text bold>
            ╸
          </Text>
          <Text dimColor>
            ────────
          </Text>
        </Box>
        <Box flexDirection="row" justifyContent="space-between">
          <Text dimColor>
            {formatTime}
          </Text>
          <Text dimColor>
            {formatTime2}
          </Text>
        </Box>
        <Box height={1} />
        <Box flexDirection="row" justifyContent="center">
          <Box flexDirection="row" columnGap={4}>
            <Button label="⏮" hotkey="b" plain />
            <Button label="⏸" hotkey="k" plain />
            <Button label="⏭" hotkey="n" plain />
            <Button label="♥" hotkey="f" plain />
          </Box>
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Box flexDirection="row" columnGap={3}>
            <Box flexDirection="row" columnGap={1}>
              <Text>
                ●
              </Text>
              <Button label="⇄ Shuffle on" hotkey="s" plain />
              <Text>
                {" "}
              </Text>
            </Box>
            <Box flexDirection="row" columnGap={1}>
              <Text>
                ●
              </Text>
              <Button label={`↻ Repeat ${repeat}`} hotkey="r" plain />
            </Box>
          </Box>
        </Box>
        <Box flexDirection="row" justifyContent="center">
          <Box flexDirection="row" columnGap={1}>
            <Button label="−" hotkey="d" plain dimColor />
            <Text dimColor>
              {"vol "}
              {volume}
            </Text>
            <Button label="+" hotkey="u" plain dimColor />
            <Button label="lyrics off" hotkey="l" plain dimColor />
          </Box>
        </Box>
      </Box>
    )
  })

  on('session.start', async ($, e, next) => {
    const app = '…'
    const stderr = '…'
    const what = '…'
    const error = '…'
    await $.ui.toast(`Could not open ${app}: ${stderr}`)
    await $.ui.toast(`${what} failed: ${error}`)
    return next(e)
  })
}

Mod 自身のコード

Mod のライセンス(MIT)に従って載せています。全文は下にあります。写すときは著作権表示を残してください。

plugins/now-playing/hooks/register.tsx 508〜631 行 · ペイン
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
    const players = await read($, playersAtom)
    const active = await read($, trackAtom)
    const picked = await read($, sourceAtom)
    const covers = await read($, coversAtom)
    const artMode = await read($, artModeAtom)
    await read($, tickAtom) // subscribes the pane to the 1 s redraw
    const lyricsOn = await read($, lyricsOnAtom)
    await read($, lyricsRevAtom) // redraws when a lyrics fetch lands
    const now = await $.clock.now()
    const width = Math.max(1, e.props.bodyColumns)

    // An empty list means no poll has answered yet, which is not the same as
    // a poll that found nothing installed.
    const installed = players.filter(p => p.isInstalled)
    const shown: PlayerApp = picked ?? active?.app ?? installed[0]?.app ?? 'Music'
    const player = players.find(p => p.app === shown)
    const track = player?.track ?? null

    // The pane redraws on success; a control that failed says so in a toast.
    const press = (action: Action, value?: number) => async () => {
      try {
        const result = await control($, action, shown, value)
        if (!result.startsWith(`${shown} is playing`) && !result.startsWith(`${shown} is paused`)) $.ui.toast(result)
      } catch (error) {
        $.ui.toast(`${action} failed: ${String(error)}`)
      }
    }

    const cover = covers[shown]
    const hasCover = track !== null && cover !== undefined && cover.trackId === track.id
    const accent = readable(hasCover && cover.accent !== undefined ? cover.accent : NEUTRAL)
    const layout = layoutFor(width)

    const state: PaneView['state'] =
      players.length > 0 && installed.length === 0 ? 'none-installed' : player === undefined || !player.isRunning ? 'closed' : track === null ? 'stopped' : 'track'

    const position = track === null ? 0 : positionNow(track, polledAt[track.app] ?? now, now)
    let lyrics: PaneView['lyrics'] = { status: 'off' }
    if (track !== null && state === 'track' && lyricsOn) {
      const entry = lyricsCache.get(track.id)
      lyrics =
        entry === undefined
          ? { status: 'loading' }
          : entry.status === 'none'
            ? { status: 'none' }
            : { status: 'found', ...lyricWindow(entry.lines, position) }
    }
    isTicking = state === 'track' && track?.state === 'playing'
    isPaneOpen = true

    // The sleeve: the cover, with the record peeking out from behind it.
    // Image and Raster are the terminal's alone; the engine draws an Image
    // only where it detects kitty graphics, so half-block cells are the default.
    record = null
    let sleeve = null
    if (track !== null && state === 'track' && e.surface === 'terminal' && layout.art !== 0) {
      const { Box, Image, Raster } = $.ui.resolve(e)
      const size = layout.art
      const artRows = size / 2
      const cells = hasCover ? cover.cells[`${size}`] : undefined
      const art =
        hasCover && (artMode === 'image' || cells === undefined) ? (
          <Image
            key="cover"
            source={{ file: cover.file, format: 'png', generation: cover.generation }}
            columns={size}
            rows={artRows}
            alt={`${track.album} cover (try /music art blocks)`}
          />
        ) : cells !== undefined ? (
          <Raster key="cover" columns={size} rows={artRows} cells={cells} />
        ) : null
      if (art !== null) {
        record = layout.peek > 0 ? { columns: layout.peek, rows: artRows, label: accent, isPlaying: track.state === 'playing' } : null
        sleeve = (
          <Box flexDirection="row">
            {art}
            {record !== null && (
              <Raster key="record" columns={record.columns} rows={record.rows} cells={recordCells(record.columns, record.rows, theta, accent)} />
            )}
          </Box>
        )
      }
    }

    const view: PaneView = {
      width,
      tabs: installed.map(({ app }) => ({
        app,
        label: LABELS[app],
        isShown: app === shown,
        isPlaying: players.find(p => p.app === app)?.track?.state === 'playing',
      })),
      shown,
      shownLabel: LABELS[shown],
      canFavorite: shown === 'Music' && track?.favorited !== undefined,
      state,
      track,
      position,
      lyrics,
      accent,
      layout,
      sleeve,
      handlers: {
        toggleLyrics: () => void setLyricsOn($, !lyricsOn),
        pickTab: app => void update($, sourceAtom, () => app),
        open: () => void openApp($, shown),
        press,
        toggleShuffle: () => playModeBusy.shuffle || void notify($, setPlayMode($, 'shuffle', undefined, shown), 'Shuffle'),
        cycleRepeat: () => playModeBusy.repeat || void notify($, setPlayMode($, 'repeat', undefined, shown), 'Repeat'),
        toggleFavorite: () =>
          void (async () => {
            try {
              const result = await setFavorite($, !(track?.favorited ?? false))
              if (!result.startsWith('Added') && !result.startsWith('Removed')) $.ui.toast(result)
            } catch (error) {
              $.ui.toast(`Favorite failed: ${String(error)}`)
            }
          })(),
      },
    }
    return paneTree($.ui.resolve(e), view)
  })
plugins/now-playing/hooks/pane.tsx 39〜169 行 · ペイン
export function paneTree(ui: Pick<Elements['desktop'], 'Box' | 'Text' | 'Button'>, view: PaneView) {
  const { Box, Text, Button } = ui
  const row = (key: string, ...children: RenderChildren[]) => (
    <Box key={key} flexDirection="row" justifyContent="center" width={view.width}>
      {children}
    </Box>
  )
  const tabs =
    view.tabs.length > 1
      ? row(
          'row-tabs',
          <Box flexDirection="row" columnGap={3}>
            {view.tabs.map((t, i) => (
              <Button
                key={`tab-${t.app}`}
                label={t.isPlaying ? `${t.label} ♪` : t.label}
                hotkey={String(i + 1)}
                plain
                dimColor={!t.isShown}
                onPress={() => view.handlers.pickTab(t.app)}
              />
            ))}
          </Box>,
        )
      : null
  const label = view.shownLabel

  if (view.state === 'none-installed') {
    return (
      <Box flexDirection="column">
        {row('row-message', <Text dimColor>Install Apple Music or Spotify to use this player.</Text>)}
      </Box>
    )
  }
  if (view.state === 'closed') {
    return (
      <Box flexDirection="column" rowGap={1}>
        {tabs}
        {row('row-message', <Text dimColor>{label} is closed.</Text>)}
        {row('row-action', <Button key="open" label={`Open ${label}`} hotkey="o" plain onPress={view.handlers.open} />)}
      </Box>
    )
  }
  if (view.state === 'stopped' || view.track === null) {
    return (
      <Box flexDirection="column" rowGap={1}>
        {tabs}
        {row('row-message', <Text dimColor>{label} is stopped.</Text>)}
        {row(
          'row-action',
          <Button
            key="toggle"
            label="▶ Play"
            hotkey="k"
            plain
            onPress={view.handlers.press('play')}
          />,
        )}
      </Box>
    )
  }

  const track = view.track
  const isPlaying = track.state === 'playing'
  const isShuffle = track.shuffle === true
  const isRepeat = track.repeat === 'all' || track.repeat === 'one'
  const played = track.duration > 0 ? Math.min(view.width - 1, Math.floor((view.position / track.duration) * view.width)) : 0
  return (
    <Box flexDirection="column">
      {tabs}
      <Box height={1} />
      {view.sleeve !== null && row('row-sleeve', view.sleeve as RenderChildren)}
      <Box height={1} />
      {wrapLines(track.name, view.width).map((line, i) => row(`row-title-${i}`, <Text bold>{line}</Text>))}
      {wrapLines(track.artist, view.width).map((line, i) => row(`row-artist-${i}`, <Text>{line}</Text>))}
      {wrapLines(track.album, view.width).map((line, i) => row(`row-album-${i}`, <Text dimColor>{line}</Text>))}
      {view.lyrics.status !== 'off' && <Box height={1} />}
      {view.lyrics.status === 'found' && row('row-lyric-prev', <Text dimColor wrap="truncate-end">{view.lyrics.prev || ' '}</Text>)}
      {view.lyrics.status === 'found' && row('row-lyric-current', <Text bold color={hex(view.accent)} wrap="truncate-end">{view.lyrics.current || ' '}</Text>)}
      {view.lyrics.status === 'found' && row('row-lyric-next', <Text dimColor wrap="truncate-end">{view.lyrics.next || ' '}</Text>)}
      {(view.lyrics.status === 'none' || view.lyrics.status === 'loading') &&
        row('row-lyric-none', <Text dimColor>{view.lyrics.status === 'none' ? 'No synced lyrics' : 'Looking for lyrics…'}</Text>)}
      <Box height={1} />
      <Box key="row-bar" flexDirection="row" width={view.width}>
        <Text color={hex(view.accent)}>{'━'.repeat(played)}</Text>
        <Text color={hex(view.accent)} bold>╸</Text>
        <Text dimColor>{'─'.repeat(Math.max(0, view.width - played - 1))}</Text>
      </Box>
      <Box key="row-times" flexDirection="row" justifyContent="space-between" width={view.width}>
        <Text dimColor>{formatTime(view.position)}</Text>
        <Text dimColor>{formatTime(track.duration)}</Text>
      </Box>
      <Box height={1} />
      {row(
        'row-transport',
        <Box flexDirection="row" columnGap={4}>
          <Button key="prev" label="⏮" hotkey="b" plain onPress={view.handlers.press('previous')} />
          <Button key="toggle" label={isPlaying ? '⏸' : '▶'} hotkey="k" plain onPress={view.handlers.press('toggle')} />
          <Button key="next" label="⏭" hotkey="n" plain onPress={view.handlers.press('next')} />
          {view.canFavorite && (
            <Button key="fav" label={track.favorited === true ? '♥' : '♡'} hotkey="f" plain onPress={view.handlers.toggleFavorite} />
          )}
        </Box>,
      )}
      {row(
        'row-playmode',
        <Box flexDirection="row" columnGap={3}>
          <Box flexDirection="row" columnGap={1}>
            {isShuffle ? <Text color={hex(view.accent)}>●</Text> : <Text> </Text>}
            <Button key="shuffle" label={`⇄ Shuffle ${isShuffle ? 'on' : 'off'}`} hotkey="s" plain dimColor={!isShuffle} onPress={view.handlers.toggleShuffle} />
            {/* "on" is one column narrower than "off"; keep the row's width fixed */}
            {isShuffle && <Text> </Text>}
          </Box>
          <Box flexDirection="row" columnGap={1}>
            {isRepeat ? <Text color={hex(view.accent)}>●</Text> : <Text> </Text>}
            <Button key="repeat" label={`↻ Repeat ${track.repeat ?? 'off'}`} hotkey="r" plain dimColor={!isRepeat} onPress={view.handlers.cycleRepeat} />
          </Box>
        </Box>,
      )}
      {row(
        'row-volume',
        <Box flexDirection="row" columnGap={1}>
          <Button key="vol-down" label="−" hotkey="d" plain dimColor onPress={view.handlers.press('volume', track.volume - 10)} />
          <Text dimColor>vol {track.volume}</Text>
          <Button key="vol-up" label="+" hotkey="u" plain dimColor onPress={view.handlers.press('volume', track.volume + 10)} />
          <Button key="lyrics" label={view.lyrics.status === 'off' ? 'lyrics off' : 'lyrics on'} hotkey="l" plain dimColor onPress={view.handlers.toggleLyrics} />
        </Box>,
      )}
    </Box>
  )
}
ライセンスの全文(MIT)
MIT License

Copyright (c) 2026 Jimmy Hsiao

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

コードが呼ぶもの

プログラム起動環境変数ツール呼び出し保存

コードから読み取ったデザイン

読み取ったコミットのソースから描いたもので、動かした結果ではありません。一覧は 3 回描き、条件はデスクトップアプリで描く最初の分岐を取り、動かしたときにだけ決まる値は仮の例(点線の下線)にするか省きます。色と書体はこのサイトのものです。

コードから読めること

2026-10-06 に読んだコミット 89d6e13a9fa8 のソースから。最初のまとまりが載せる条件で、残りは自分で判断するための材料です。後のコミットは、次に読むまで見ていません。

載せる条件: 確かめやすいコード
入口を読んだhooks/hooks.json が名指すモジュールをすべて読んだ。plugins/now-playing/hooks/register.tsx
解析できるすべてのファイルが TypeScript か JavaScript として解析できる。6 ファイルを解析
コードが Mod の中で完結import は Mod 自身のファイルかエンジンのモジュールだけ。パッケージも require もない。コードはすべて Mod の中
読める圧縮した行・eval・new Function・計算した道の import()・符号化した塊がない。圧縮・eval・符号化した塊なし
呼び出しが見える通信とプログラム起動はその場で $.http.fetch・$.process.run と書き、他へ渡さない。外への呼び出しはすべてその場の $ で
入れる前に自分で判断する材料
描く場所コードから読んだ、描く先。ターミナル・デスクトップアプリ・両方・何も描かない(フックだけ: 見張りやプロンプトの書き換え)のどれか。出すだけで、外す理由にはしない。ターミナルとデスクトップアプリに同じように描く
入れる手順リポジトリ自身の .claude-plugin/marketplace.json にこの Mod が載っていて、ページに書いた手順でそのマーケットプレイスから入れられるか。リポジトリの .claude-plugin/marketplace.json に載っており、そこから入れられる
Windows のプログラム$.process で起動するプログラムが Windows にあるか(tail・date・open・osascript・/usr/… などは無い)。plugins/now-playing/hooks/register.tsx:164 mkdir(Windows にない); plugins/now-playing/hooks/register.tsx:316 open(Windows にない)
通信fetch の送り先(https のホスト)がコードに書いてあるか。通信なし
プログラム起動するプログラムの名前がコードに書いてあり、シェル・インタプリタ・通信用の道具でないか。plugins/now-playing/hooks/register.tsx:76 osascript(シェル・インタプリタ); plugins/now-playing/hooks/register.tsx:80 curl(通信する)
読んで送るファイルや環境変数を読み、かつ通信するか。読んだうえで通信する
ソースの鍵ソースに API キーや秘密鍵らしきものがあるか。ソースに鍵なし
ライセンスオープンなライセンス(MIT・Apache-2.0・BSD・ISC・Unlicense・0BSD・CC0)で全文があれば、modscode にコードを載せる。違えばリンクだけ。MIT

コードの文面を読んだだけで、安全の審査ではありません。動かしてはおらず、起動するプログラムの中で何が起きるかも見えません。入れる前の確認はあなたの役目です。 載せる条件

入れる

入れる前に、必ず自分で確かめてください。Mod はサンドボックスなしで、あなたの権限で動きます。modscode はこのコードの安全を保証しません。下のコードを読み(またはフォルダーで claude plugin validate .)、触るものを見て、読んだコミットを入れてください。

リポジトリがそのままマーケットプレイスです。このマーケットプレイスを足し(ターミナルでは次のコマンド、デスクトップアプリではプラグインの設定)、そこから Mod を入れます。

/plugin marketplace add Fatmylin/now-playing
/plugin install now-playing@now-playing

入るのはマーケットプレイスの最新のコミットで、ここで読んだもの(89d6e13a9fa8)と違うことがあります。入れる前に見比べてください。

Claude に聞く

modscode のコネクタを入れると、Claude がこのデザイン・コードが触るもの・コードを読んで、それをもとに作れます。たとえば:

modscode のデザイン「fatmylin-now-playing」をコードごと読んで、同じようなペインを作って

Claude から探す: MCP コネクタ

似たデザイン