Логотип Compose Multiplatform

Compose Multiplatform

Спільнота
AThevon
compose-multiplatform

Compose Multiplatform / KMP patterns - expect/actual composables, platform-specific code, density and font handling cross-target, iOS/Android/Desktop interop.

Add to TypingMind

Огляд

ВидавецьAThevon
Репозиторійgenjutsu
Назва навичкиcompose-multiplatform
Зірки
687
Форки
52
Файли в пакеті
2
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 2

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: AThevon. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Compose Multiplatform у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/AThevon/genjutsu/tree/main/skills/_jutsu/compose-multiplatform
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/AThevon/genjutsu.git /tmp/genjutsu
mkdir -p .claude/skills
cp -r /tmp/genjutsu/skills/_jutsu/compose-multiplatform .claude/skills/compose-multiplatform
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Compose Multiplatform в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Compose Multiplatform, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Compose Multiplatform не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Version-sensitive. Every API name, SDK gate and browser-support claim below was verified on 2026-09-08 against primary sources. What against, and when, is in _jutsu/VERSIONS.md. If that date is old, re-verify before acting on a version number.

Compose Multiplatform

Compose Multiplatform (CMP) and Kotlin Multiplatform (KMP) patterns for cross-platform UI. Loaded for projects with org.jetbrains.compose plugin. Foundation: ../compose-motion/SKILL.md for animation API; this file covers what's specific to writing one Compose codebase for Android + iOS + Desktop + Web.


KMP vs CMP - quick clarification

KMP (Kotlin Multiplatform) is the language and build infrastructure: shared Kotlin code compiled to JVM, Native (iOS, macOS, Linux, Windows), and Wasm. CMP (Compose Multiplatform) is the UI framework on top of KMP, built by JetBrains as a port of Jetpack Compose. You write a single Compose codebase in commonMain that runs on Android, iOS, Desktop (JVM), and Web (Wasm). Platform-specific code lives in androidMain, iosMain, desktopMain, wasmJsMain and is wired in via expect/actual declarations.


Project structure

composeApp/
├── src/
│   ├── commonMain/        ← shared Compose code (most of the app)
│   │   └── kotlin/
│   ├── androidMain/       ← Android-specific (uses Activity, Context)
│   ├── iosMain/           ← iOS-specific (uses UIKit/UIView interop)
│   ├── desktopMain/       ← JVM desktop (uses java.awt/swing if needed)
│   └── wasmJsMain/        ← Wasm web target
├── build.gradle.kts
iosApp/                    ← Xcode project consuming the generated framework
androidApp/                ← Android Application module (often merged into composeApp)

The commonMain folder should hold 80-95% of your code in a well-architected CMP project. If iosMain or androidMain start growing past a few hundred lines, you're probably leaking platform concerns into UI logic that could stay shared.


expect/actual pattern

The KMP escape hatch when you genuinely need different implementations per target. Declare the contract once in commonMain, implement it once per target.

kotlin
// commonMain
expect fun openShareSheet(text: String)

// androidMain
actual fun openShareSheet(text: String) {
    val intent = Intent(Intent.ACTION_SEND).apply {
        type = "text/plain"
        putExtra(Intent.EXTRA_TEXT, text)
    }
    context.startActivity(Intent.createChooser(intent, null))
}

// iosMain
actual fun openShareSheet(text: String) {
    val activityVC = UIActivityViewController(
        activityItems = listOf(text),
        applicationActivities = null
    )
    UIApplication.sharedApplication.keyWindow
        ?.rootViewController
        ?.presentViewController(activityVC, true, null)
}

expect/actual works for top-level functions, classes, type aliases, and properties. The signature in actual must match exactly, including modifiers and default values.


expect/actual for composables

Composables follow the same rules. Useful when a feature needs a platform-specific Compose API (Android RuntimeShader, iOS UIKitView, Desktop SwingPanel).

kotlin
// commonMain
@Composable
expect fun PlatformBlur(modifier: Modifier = Modifier, content: @Composable () -> Unit)

// androidMain (uses RuntimeShader on Android 13+)
@Composable
actual fun PlatformBlur(modifier: Modifier, content: @Composable () -> Unit) {
    Box(modifier.graphicsLayer { renderEffect = blurEffect }) { content() }
}

// iosMain (uses UIVisualEffectView via UIKitView)
@Composable
actual fun PlatformBlur(modifier: Modifier, content: @Composable () -> Unit) {
    Box(modifier) {
        UIKitView(
            factory = {
                UIVisualEffectView(
                    effect = UIBlurEffect.effectWithStyle(
                        UIBlurEffectStyle.UIBlurEffectStyleSystemMaterial
                    )
                )
            },
            modifier = Modifier.matchParentSize()
        )
        content()
    }
}

Rule: expect composables should be the exception, not the rule. Most "platform feel" differences can be tuned via tokens (colors, corner radii, spring stiffness) in commonMain, not via separate code paths.


LocalDensity cross-platform

On Android, LocalDensity.current.density reflects the device DPI bucket (1.0, 1.5, 2.0, 3.0...). On iOS, density is computed from UIScreen.scale (typically 2.0 or 3.0 on Retina). On Desktop, density depends on the screen scaling factor (1.0 by default; 2.0 on Retina-class displays; user-configurable on Windows). On Wasm, density follows window.devicePixelRatio.

Don't hardcode Dp to pixel ratios; trust Dp and LocalDensity to handle conversion. If you need an exact pixel value (e.g., for a Canvas draw operation), do the conversion explicitly:

kotlin
val density = LocalDensity.current
val pxValue = with(density) { 16.dp.toPx() }

Avoid reading density inside hot loops; cache the conversion.


LocalConfiguration and platform-aware UI

LocalConfiguration.current is Android-only and lives in androidMain. For CMP, prefer the cross-platform alternatives:

  • LocalWindowInfo.current.containerSize - the window/screen size as IntSize, available in commonMain.
  • LocalDensity.current - density, available in commonMain.
  • LocalLayoutDirection.current - LTR / RTL.
  • BoxWithConstraints { ... } - read maxWidth / maxHeight directly inside layout.

If you need real device characteristics (orientation, idiom, model), wrap the access in expect/actual and pass a typed object like PlatformInfo to the common layer.


Fonts cross-platform via Compose Resources

org.jetbrains.compose.resources is the shared resources plugin. Drop fonts in commonMain/composeResources/font/, and the Gradle plugin generates a typed Res accessor.

composeApp/src/commonMain/composeResources/
├── font/
│   ├── Inter-Regular.ttf
│   └── Inter-Bold.ttf
├── drawable/
│   └── logo.xml            ← Android XML vector. SVG works on every target EXCEPT Android
└── values/
    ├── strings.xml          ← default locale
└── values-fr/
    └── strings.xml          ← French overrides (qualifier goes on the DIRECTORY)

Usage in commonMain:

kotlin
import myproject.composeapp.generated.resources.Inter_Regular
import myproject.composeapp.generated.resources.Inter_Bold
import myproject.composeapp.generated.resources.Res

val InterFamily = FontFamily(
    Font(Res.font.Inter_Regular, FontWeight.Normal),
    Font(Res.font.Inter_Bold, FontWeight.Bold),
)

Text("Hello", fontFamily = InterFamily)

Same pattern for Res.drawable.logo (image) and Res.string.app_name (localized string via stringResource(...)). Raw files are the exception: there is no generated Res.file.* accessor - you pass a path string to the suspend function Res.readBytes(path), e.g. val bytes = Res.readBytes("files/config.json"), for anything under composeResources/files/.


iOS interop with SwiftUI

CMP produces a UIViewController you can drop into a SwiftUI app. KMP generates a top-level Kotlin function (commonly named MainViewController() or ComposeUIViewController { ... }) that returns a UIViewController. Wrap it with UIViewControllerRepresentable.

kotlin
// iosMain/kotlin/main.ios.kt
fun MainViewController(): UIViewController = ComposeUIViewController {
    AppContent()  // commonMain composable
}
swift
// iOS app target
import SwiftUI
import ComposeApp  // KMP-generated framework

struct ComposeContent: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        Main_iosKt.MainViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}

struct ContentView: View {
    var body: some View { ComposeContent().ignoresSafeArea() }
}

The Kotlin function name gets mangled to Main_iosKt.MainViewController() because the file is main.ios.kt. Check the generated framework headers if the symbol name surprises you.


Android entry point

No interop ceremony on Android. The Activity hosts the common composable directly via setContent { ... }.

kotlin
// androidApp/src/main/kotlin/MainActivity.kt
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppContent()  // commonMain composable
        }
    }
}

If you need to pass Context or Activity into commonMain, expose it via a DI graph or an expect class PlatformContext in commonMain with actual class PlatformContext(val context: Context) in androidMain.


Embedding SwiftUI/UIKit inside a Compose iOS view (the reverse direction)

Use UIKitView for a UIView factory or UIKitViewController for a UIViewController factory.

kotlin
// iosMain
UIKitView(
    factory = {
        UISwitch().apply {
            addTarget(target, action = NSSelectorFromString("onToggle:"), forControlEvents = UIControlEventValueChanged)
        }
    },
    modifier = Modifier.size(48.dp, 32.dp)
)

For SwiftUI views: wrap them in a UIHostingController exposed via a Swift @objc bridge function, then call from Kotlin via the generated headers (cinterop). See references/cmp-interop.md for the full pattern.


Animation cross-platform

All animation APIs (animate*AsState, AnimatedVisibility, updateTransition, SharedTransitionLayout) work identically across targets in CMP 1.7+. Spring tuning written in commonMain produces the same physics on Android and iOS. Gestures (Modifier.draggable, Modifier.pointerInput) work cross-platform with the same API surface.

The animation primer lives in ../compose-motion/SKILL.md. Cross-platform deltas to keep in mind:

  • iOS first-frame is slower (Skia bootstrap); a 200ms enter animation feels tighter on Android, slightly delayed on iOS cold start.
  • Wasm motion can stutter on first frame (JIT warmup); pre-warm critical paths or hide motion until interactive.

What does NOT work (gotchas)

  • Drawer state on iOS: native ModalNavigationDrawer swipe-to-open from the leading edge conflicts with iOS's back-swipe gesture. Use a button trigger or move the swipe area inward 30dp+.
  • LayoutDirection.Rtl quirks: Android handles RTL natively, iOS Compose had bugs in 1.6 (text alignment, padding inversions). Improved in 1.7+ but verify with real Arabic/Hebrew strings.
  • Soft keyboard handling: imePadding() / WindowInsets.ime work on Android out of the box and are implemented on iOS too. There is no IOSKeyboardEventListener type in CMP - the real knob is ComposeUIViewControllerConfiguration.onFocusBehavior, which defaults to OnFocusBehavior.FocusableAboveKeyboard (CMP pans the whole Compose view up so the focused field clears the keyboard). If you want to drive the layout yourself with imePadding() / WindowInsets.ime, turn the automatic pan off:
    kotlin
    // iosMain - imports: androidx.compose.ui.window.ComposeUIViewController,
    //                    androidx.compose.ui.uikit.OnFocusBehavior
    fun MainViewController(): UIViewController = ComposeUIViewController(
        configure = { onFocusBehavior = OnFocusBehavior.DoNothing }
    ) {
        AppContent()
    }
    Leaving the default on and applying imePadding() is the classic double-adjustment bug; same if the SwiftUI parent hosting the controller also adjusts for the keyboard.
  • Color.parseHex(...) does not exist in Compose. Use Color(0xFFRRGGBB) or write a tiny extension.
  • System fonts on iOS via Compose: do not fallback to FontFamily.SansSerif and expect SF Pro. Compose on iOS ships its own font fallback chain. Either bundle SF Pro via Compose Resources (license-permitting) or use UIKitView to drop a native UILabel for system-font text.
  • Animations on Web (Wasm): heavier startup, occasional first-frame stutter; profile with browser devtools and lazy-load heavy animation graphs.
  • java.util.UUID, java.io.File and other JVM-only APIs are forbidden in commonMain if you ship to iOS or Wasm. Use kotlinx.uuid, kotlinx-io, or the okio multiplatform port.

CMP version notes

  • Current stable is Compose Multiplatform 1.12.0 (released 25 Aug 2026); 1.10.3 was the previous long-lived line. Treat 1.7 as the historical floor for SharedTransitionLayout cross-platform, iOS keyboard handling and LocalLifecycleOwner on iOS, not as the version to target.
  • Since 1.7, iOS interop lives in androidx.compose.ui.viewinterop (UIKitView, UIKitViewController, UIKitInteropProperties); the old androidx.compose.ui.interop.UIKitView overloads with interactive: / accessibilityEnabled: parameters are @Deprecated.
  • 1.10 added UIKitInteropProperties(placedAsOverlay = true) so an interop view can be composited above Compose content, plus intrinsic-size (sizeThatFits) support for wrapping SwiftUI views in a UIHostingController.
  • Kotlin 2.x with the K2 compiler; pair the latest CMP with the latest Kotlin (2.2.20+ for iOS/web targets).
  • Some Material 3 components have platform-specific look (e.g., Switch on iOS auto-renders with iOS-style proportions; DatePicker stays Material across all targets).
  • compose-multiplatform-resources plugin is the standard for assets; the older moko-resources is no longer recommended for new projects.

Performance considerations

  • iOS first-frame is slower than Android (Skia bootstrapping ~150-300ms cold). Keep your splash visible until the first composition emits, or pre-warm with a transparent root composable.
  • Wasm bundle size: aim for <2MB compressed. Tree-shake heavy deps, lazy-load secondary screens via kotlinx.coroutines deferred composition, and inspect the .wasm output in wasmJsBrowserDistribution.
  • Desktop: cold start is fast on JVM; AOT compilation via Kotlin/Native is overkill for desktop unless you need a single-file binary.
  • Android: same baseline as Jetpack Compose - profile with the Compose compiler stability metrics and Layout Inspector recomposition counts.

Anti-Patterns

BADGOODWhy
Reflection trick or System.getProperty("os.name") to detect platform inside commonMainexpect/actual with a typed Platform objectReflection breaks on Wasm/Native; expect/actual is the contract the compiler enforces
Assuming Android Context is reachable in commonMainInject a typed dependency via expect class PlatformContext or a DI scopeContext does not exist on iOS/Desktop/Wasm; the code will not compile for those targets
Hardcoding Material colors that look great on Android but jarring on iOSDefine a commonMain design system, then optionally adjust 2-3 tokens via actualCross-platform consistency is good, but iOS users notice when a Material blue feels alien on iPhone
LaunchedEffect(Unit) { while(true) { delay(16); ... } } in commonMainrememberInfiniteTransition() or scope to lifecycle eventsTight coroutine loops drain battery on iOS; infinite transitions pause when offscreen

Quick Reference: Loading Sub-skills

NeedLoad
iOS / Android interop deep-divereferences/cmp-interop.md
Per-platform behavior catalogreferences/cmp-platform-quirks.md
Animation API../compose-motion/SKILL.md
Advanced graphics (M3 Expressive, AGSL on Android only)../compose-graphics/SKILL.md
iOS-side native interop with SwiftUI../swiftui-motion/SKILL.md (when target is iOS and SwiftUI native blend wanted)
Mobile UX context../mobile-principles/SKILL.md
Desktop UX context../desktop-principles/SKILL.md
Foundation../motion-principles/SKILL.md

Sources

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Compose Multiplatform?

Compose Multiplatform / KMP patterns - expect/actual composables, platform-specific code, density and font handling cross-target, iOS/Android/Desktop interop.

Навіщо використовувати Compose Multiplatform у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Compose Multiplatform — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Compose Multiplatform у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/AThevon/genjutsu/tree/main/skills/_jutsu/compose-multiplatform. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Compose Multiplatform?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Compose Multiplatform?

Зі скількома забажаєте. У TypingMind ви можете використовувати Compose Multiplatform із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Compose Multiplatform?

На GitHub цю навичку публікує AThevon. Умови ліцензування дивіться в репозиторії. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі
Логотип openclaw

Graincrawl

openclaw
ОрганізаціяПопулярне

Архів Granola: пошук, актуальність синхронізації, нотатки, транскрипти, панелі, підрахунки SQL і робота з репозиторіями Graincrawl.

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Changelog Update

openclaw
ОрганізаціяПопулярне

Повторно створюйте розділи журналу змін релізу OpenClaw на основі історії git перед випусками beta, stable або extended-stable.

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Ci Limits

openclaw
ОрганізаціяПопулярне

Керуйте GitHub Actions для OpenClaw і пропускною здатністю CI у Blacksmith, бюджетами реєстрації раннерів, обмеженнями fanout, одночасним запуском лише одного завдання для кожного push у main, розміром шард, перенесенням завдань на хостовані раннери, станом черги та безпечним…

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Debugging

openclaw
ОрганізаціяПопулярне

Діагностуйте проблеми з моделями, провайдерами, інтерфейсом інструментів, режимом коду, потоковою передачею та роботою OpenClaw у реальному часі/Crabbox. Перш ніж змінювати код, добирайте потрібні журнали, перевірки та спосіб підтвердження, зокрема отримуйте збережені…

82.2K
391K
Файлів: 1
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇