Compose Multiplatform Patterns logo

Compose Multiplatform Patterns

Community
mturac
compose-multiplatform-patterns

KMPプロジェクト向けのCompose MultiplatformおよびJetpack Composeパターン — 状態管理、ナビゲーション、テーマ設定、パフォーマンス、プラットフォーム固有のUI。

Overview

Publishermturac
Repositoryeverything-openai-codex
Skill namecompose-multiplatform-patterns
Stars
91
Forks
2
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by mturac on GitHub. Read the source before you install it.

Installation

Install the Compose Multiplatform Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/mturac/everything-openai-codex.git /tmp/everything-openai-codex
mkdir -p .claude/skills
cp -r /tmp/everything-openai-codex/docs/ja-JP/skills/compose-multiplatform-patterns .claude/skills/compose-multiplatform-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Compose Multiplatform Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Compose Multiplatform Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Compose Multiplatform Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Compose Multiplatformパターン

Compose MultiplatformとJetpack Composeを使用して、Android、iOS、デスクトップ、Web間で共有UIを構築するためのパターン。状態管理、ナビゲーション、テーマ設定、パフォーマンスをカバーします。

起動条件

  • Compose UIの構築(Jetpack ComposeまたはCompose Multiplatform)
  • ViewModelとCompose状態によるUI状態の管理
  • KMPまたはAndroidプロジェクトでのナビゲーション実装
  • 再利用可能なコンポーザブルとデザインシステムの設計
  • リコンポジションとレンダリングパフォーマンスの最適化

状態管理

ViewModel + 単一状態オブジェクト

画面状態には単一のデータクラスを使用します。StateFlowとして公開し、Composeで収集します:

kotlin
data class ItemListState(
    val items: List<Item> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
    val searchQuery: String = ""
)

class ItemListViewModel(
    private val getItems: GetItemsUseCase
) : ViewModel() {
    private val _state = MutableStateFlow(ItemListState())
    val state: StateFlow<ItemListState> = _state.asStateFlow()

    fun onSearch(query: String) {
        _state.update { it.copy(searchQuery = query) }
        loadItems(query)
    }

    private fun loadItems(query: String) {
        viewModelScope.launch {
            _state.update { it.copy(isLoading = true) }
            getItems(query).fold(
                onSuccess = { items -> _state.update { it.copy(items = items, isLoading = false) } },
                onFailure = { e -> _state.update { it.copy(error = e.message, isLoading = false) } }
            )
        }
    }
}

Composeでの状態収集

kotlin
@Composable
fun ItemListScreen(viewModel: ItemListViewModel = koinViewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    ItemListContent(
        state = state,
        onSearch = viewModel::onSearch
    )
}

@Composable
private fun ItemListContent(
    state: ItemListState,
    onSearch: (String) -> Unit
) {
    // ステートレスなコンポーザブル — プレビューとテストが容易
}

イベントシンクパターン

複雑な画面では、複数のコールバックラムダの代わりにイベント用のシールドインターフェースを使用します:

kotlin
sealed interface ItemListEvent {
    data class Search(val query: String) : ItemListEvent
    data class Delete(val itemId: String) : ItemListEvent
    data object Refresh : ItemListEvent
}

// ViewModelの中
fun onEvent(event: ItemListEvent) {
    when (event) {
        is ItemListEvent.Search -> onSearch(event.query)
        is ItemListEvent.Delete -> deleteItem(event.itemId)
        is ItemListEvent.Refresh -> loadItems(_state.value.searchQuery)
    }
}

// コンポーザブルの中 — 多数ではなく単一ラムダ
ItemListContent(
    state = state,
    onEvent = viewModel::onEvent
)

ナビゲーション

型安全なナビゲーション(Compose Navigation 2.8+)

ルートを@Serializableオブジェクトとして定義します:

kotlin
@Serializable data object HomeRoute
@Serializable data class DetailRoute(val id: String)
@Serializable data object SettingsRoute

@Composable
fun AppNavHost(navController: NavHostController = rememberNavController()) {
    NavHost(navController, startDestination = HomeRoute) {
        composable<HomeRoute> {
            HomeScreen(onNavigateToDetail = { id -> navController.navigate(DetailRoute(id)) })
        }
        composable<DetailRoute> { backStackEntry ->
            val route = backStackEntry.toRoute<DetailRoute>()
            DetailScreen(id = route.id)
        }
        composable<SettingsRoute> { SettingsScreen() }
    }
}

ダイアログとボトムシートナビゲーション

命令型のshow/hideの代わりにdialog()とオーバーレイパターンを使用します:

kotlin
NavHost(navController, startDestination = HomeRoute) {
    composable<HomeRoute> { /* ... */ }
    dialog<ConfirmDeleteRoute> { backStackEntry ->
        val route = backStackEntry.toRoute<ConfirmDeleteRoute>()
        ConfirmDeleteDialog(
            itemId = route.itemId,
            onConfirm = { navController.popBackStack() },
            onDismiss = { navController.popBackStack() }
        )
    }
}

コンポーザブル設計

スロットベースのAPI

柔軟性のためにスロットパラメータを持つコンポーザブルを設計します:

kotlin
@Composable
fun AppCard(
    modifier: Modifier = Modifier,
    header: @Composable () -> Unit = {},
    content: @Composable ColumnScope.() -> Unit,
    actions: @Composable RowScope.() -> Unit = {}
) {
    Card(modifier = modifier) {
        Column {
            header()
            Column(content = content)
            Row(horizontalArrangement = Arrangement.End, content = actions)
        }
    }
}

Modifier順序

Modifierの順序は重要です — 以下の順序で適用します:

kotlin
Text(
    text = "Hello",
    modifier = Modifier
        .padding(16.dp)          // 1. レイアウト(パディング、サイズ)
        .clip(RoundedCornerShape(8.dp))  // 2. 形状
        .background(Color.White) // 3. 描画(背景、ボーダー)
        .clickable { }           // 4. インタラクション
)

KMPプラットフォーム固有のUI

プラットフォームコンポーザブルのexpect/actual

kotlin
// commonMain
@Composable
expect fun PlatformStatusBar(darkIcons: Boolean)

// androidMain
@Composable
actual fun PlatformStatusBar(darkIcons: Boolean) {
    val systemUiController = rememberSystemUiController()
    SideEffect { systemUiController.setStatusBarColor(Color.Transparent, darkIcons) }
}

// iosMain
@Composable
actual fun PlatformStatusBar(darkIcons: Boolean) {
    // iOSはUIKitインターロップまたはInfo.plistで処理
}

パフォーマンス

スキップ可能なリコンポジションのための安定した型

すべてのプロパティが安定している場合、クラスを@Stableまたは@Immutableでマークします:

kotlin
@Immutable
data class ItemUiModel(
    val id: String,
    val title: String,
    val description: String,
    val progress: Float
)

key()と遅延リストの正しい使用

kotlin
LazyColumn {
    items(
        items = items,
        key = { it.id }  // 安定したキーによりアイテムの再利用とアニメーションが可能
    ) { item ->
        ItemRow(item = item)
    }
}

derivedStateOfで読み取りを遅延

kotlin
val listState = rememberLazyListState()
val showScrollToTop by remember {
    derivedStateOf { listState.firstVisibleItemIndex > 5 }
}

リコンポジションでのアロケーションを避ける

kotlin
// 悪い例 — リコンポジションのたびに新しいラムダとリストが作られる
items.filter { it.isActive }.forEach { ActiveItem(it, onClick = { handle(it) }) }

// 良い例 — 各アイテムにキーを付けてコールバックが正しい行に紐づくようにする
val activeItems = remember(items) { items.filter { it.isActive } }
activeItems.forEach { item ->
    key(item.id) {
        ActiveItem(item, onClick = { handle(item) })
    }
}

テーマ設定

Material 3ダイナミックテーマ

kotlin
@Composable
fun AppTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit
) {
    val colorScheme = when {
        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            if (darkTheme) dynamicDarkColorScheme(LocalContext.current)
            else dynamicLightColorScheme(LocalContext.current)
        }
        darkTheme -> darkColorScheme()
        else -> lightColorScheme()
    }

    MaterialTheme(colorScheme = colorScheme, content = content)
}

避けるべきアンチパターン

  • ライフサイクルに対してより安全なcollectAsStateWithLifecycleを使用したMutableStateFlowがある場合にViewModelでmutableStateOfを使用すること
  • コンポーザブルの深い階層にNavControllerを渡すこと — 代わりにラムダコールバックを渡す
  • @Composable関数内の重い計算 — ViewModelかremember {}に移動する
  • 一部の設定では設定変更のたびに再実行されるため、ViewModel initの代替としてLaunchedEffect(Unit)を使用すること
  • コンポーザブルのパラメータに新しいオブジェクトインスタンスを作成すること — 不必要なリコンポジションを引き起こす

参照

スキル: モジュール構造とレイヤーについてはandroid-clean-architectureを参照。 スキル: コルーチンとFlowパターンについてはkotlin-coroutines-flowsを参照。

Frequently asked questions

What does the Compose Multiplatform Patterns AI skill do?

KMPプロジェクト向けのCompose MultiplatformおよびJetpack Composeパターン — 状態管理、ナビゲーション、テーマ設定、パフォーマンス、プラットフォーム固有のUI。

Why use Compose Multiplatform Patterns on TypingMind?

Because you install it once and use it with any model. Compose Multiplatform Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Compose Multiplatform Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/mturac/everything-openai-codex/tree/main/docs/ja-JP/skills/compose-multiplatform-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Compose Multiplatform Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Compose Multiplatform Patterns?

As many as you like. As long as a model supports skills, you can use Compose Multiplatform Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Compose Multiplatform Patterns AI skill free?

Yes. It is published on GitHub by mturac under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇