Kotlin
A concise multiplatform language developed by JetBrains
Альфа-версия Compose Multiplatform: единое решение для десктопных, веб- и Android-интерфейсов
Этот релиз — еще один шаг к реализации нашего грандиозного плана по унификации разработки интерфейсов на Kotlin. У нас много новостей, касающихся мультиплатформенной разработки пользовательских интерфейсов, в том числе Compose for Desktop и Compose for Web. К тому же недавно Google объявила о выходе стабильной версии Jetpack Compose 1.0 для Android. Вот что ждет вас в этом обновлении:
- Compose for Desktop и Compose for Web перешли на стадию альфа-версии. Версии продуктов объединены в рамках универсального решения Compose Multiplatform. Оно позволяет создавать десктопные, Android- и веб-интерфейсы, используя одни и те же артефакты.
- JetBrains Toolbox App — наше приложение для управления IDE — было полностью переведено на Compose for Desktop.
- Новый плагин для IntelliJ IDEA и Android Studio обеспечивает предварительный просмотр компонентов для Compose for Desktop с помощью аннотации
@Preview. - Compose for Desktop теперь по умолчанию использует API компонуемых окон, обеспечивая поддержку адаптивных размеров окон, единые ресурсы изображений, а также новой платформы — Linux на ARM64. Благодаря этому решение можно запустить на таких устройствах, как Raspberry Pi.
- Compose for Web расширяет возможности DOM и CSS API.
Мы подготовили видео The Compose Story, посвященное истории Compose, и поделились в нем своими планами по дальнейшему развитию мультиплатформенных декларативных интерфейсов. Еще больше информации — в этой статье.

Единый подход к разработке интерфейсов для десктопных, Android- и веб-приложений
История разработки декларативных пользовательских интерфейсов на Kotlin по-настоящему началась с того момента, когда Google представила Jetpack Compose — современный фреймворк для создания нативных интерфейсов для Android. JetBrains использует Jetpack Compose от Google в качестве основы и расширяет сферу применения фреймворка Compose.
Выпуская Compose Multiplatform, мы даем возможность использовать для создания пользовательских интерфейсов десктопных и веб-приложений, написанных на Kotlin/JVM и Kotlin/JS, тот же декларативный подход и те же API, что и для современных Android-приложений. Используя механизмы, предоставленные Kotlin Multiplatform, можно в рамках одного проекта создать любую комбинацию следующих интерфейсов:
- Android (Jetpack Compose)
- Десктоп (Compose for Desktop)
- Веб (Compose for Web)
Раньше Compose for Desktop и Compose for Web использовали отдельные наборы артефактов. Теперь они собраны в один Gradle-плагин и одну группу артефактов. В результате начать разработку интерфейсов для десктопных, Android- и веб-приложений с помощью Compose стало гораздо проще.
Теперь API, которые предлагает Compose Multiplatform, перешли на стадию Alpha и быстро приближаются к своему окончательному виду. Поэтому сейчас самое время подготовить пробную реализацию для ваших приложений, чтобы во всеоружии встретить официальный выход Compose 1.0. Мы планируем выпустить эту версию в 2021 году.
Если вам не терпится самим начать писать современные интерфейсы с помощью Compose Multiplatform, у нас есть уроки и обучающие материалы. Подробнее о возможностях нового релиза читайте далее.
Подробнее о Compose Multiplatform
Как это было: The Compose Story
В ознаменование этого важного шага к мультиплатформенной разработке декларативных пользовательских интерфейсов на Kotlin мы решили рассказать вам всю историю создания Compose. Чтобы дать вам широкое представление о проделанной работе, мы пригласили к участию руководителя проекта Kotlin в JetBrains Романа Елизарова, руководителя команды Compose в JetBrains Николая Иготти, основателя Compose в Google Джима Спроча и разработчика Compose UI Андрея Руденко.
Из видео вы узнаете, как все начиналось, как мы пришли к нынешнему релизу и что планируем делать дальше с Compose Multiplatform.
Compose в продакшене: JetBrains Toolbox App
В последние месяцы мы наблюдали за тем, как сообщество начинает использовать Compose for Desktop и Web в своих проектах: от небольших игр, утилит и демонстрационных приложений до производственных приложений, над которыми работают целые команды.
JetBrains уже использует Compose в нескольких приложениях. Первым из них стал JetBrains Toolbox App — приложение для управления нашими IDE, которым ежемесячно пользуются более 800 000 человек.

В новой версии команда полностью перевела реализацию приложения на Compose for Desktop. При миграции с интерфейса на основе Electron они отметили ряд преимуществ. Вот лишь основные из них:
- значительно снизилось потребление памяти, особенно когда приложение запущено в фоновом режиме;
- размер установщика уменьшился примерно на 50%;
- значительно повысилась общая скорость рендеринга приложения.
Руководитель команды JetBrains Toolbox Виктор Кропп поделился своим мнением о Compose for Desktop:
Compose for Desktop все еще находится на стадии разработки, но уже сейчас понятно, что это оптимальный фреймворк для Toolbox App. С помощью наших коллег, которые работают над его развитием, нам удалось переписать весь интерфейс в кратчайшие сроки. Это позволило объединить усилия разработчиков, так что теперь Toolbox App — это приложение, полностью написанное на языке Kotlin.
История перевода JetBrains Toolbox App на Kotlin и Compose for Desktop очень интересна, и было бы несправедливо уделить ей всего пару абзацев в этом посте. Поэтому мы планируем подготовить всесторонний анализ этого проекта. Если вам интересно подробнее узнать о том, как там все устроено, следите за новостями или подпишитесь на нашу рассылку, чтобы не пропустить эту публикацию.
Новый плагин IntelliJ IDEA и Android Studio для Compose Multiplatform
Вместе с этим релизом мы выпускаем новый плагин для IDE, который поможет вам в разработке: плагин Compose Multiplatform для IntelliJ IDEA и Android Studio. Он выходит вместе с новой версией фреймворка и предлагает более широкие возможности для создания пользовательских интерфейсов.
Первая версия включает в себя долгожданную функцию предварительного просмотра компонентов Compose for Desktop и Android прямо в IDE: вам даже не нужно запускать приложение. Чтобы обеспечить предварительный просмотр @Composable функции без параметров, добавьте к ее объявлению аннотацию @Preview. Тогда на полях редактора появится небольшая иконка, с помощью которой можно включить или отключить панель предварительного просмотра компонента:


Надеемся, что новая функция предпросмотра поможет ускорить разработку и упростит воплощение ваших замыслов в реальные макеты и дизайн на основе Compose. В будущем плагин будет обновляться, а его возможности будут расширены, чтобы еще больше упростить работу с нашими фреймворками для создания интерфейсов.
Чтобы найти и установить новый плагин, введите «Compose Multiplatform IDE Support» в поле поиска на Marketplace или перейдите прямо на страницу плагина по следующей ссылке:
Установить плагин Compose Multiplatform
Новые возможности Compose for Desktop
Мы не только перевели Compose for Desktop на стадию альфа, что очень важно само по себе, но и улучшили API продукта и добавили поддержку новой платформы.
Использование API компонуемых окон по умолчанию
В четвертой предрелизной версии Compose for Desktop мы представили экспериментальный набор API для управления Window, MenuBar и Tray. Все новые API основаны на механизме @Composable и используют те же концепции поведения, управления состоянием и условного рендеринга, что и другие компоненты приложения.
В новом релизе эти компонуемые версии заменили старый API окон и используются по умолчанию для управления окнами, панелями меню и иконками для трея. Если вы еще не пробовали работать с этими API или просто хотите подробнее узнать об их поведении и функциях, рекомендуем обновленные уроки по Compose for Desktop, посвященные управлению окнами и треем.
Адаптивный размер окна
Иногда нужно гарантировать отображение контента целиком, при этом мы не знаем заранее, что именно будет отображаться, то есть не можем определить оптимальный размер окна. Чтобы упростить разработку интерфейса в таких случаях, мы добавили функцию адаптивного размера окна. Если вы установите значение Dp.Unspecified для одного или обоих измерений функции WindowSize вашего окна, Compose for Desktop автоматически изменит его исходный размер в соответствии с размером контента:

Если при этом убрать украшения окна (параметр undecorated = true в определении окна Window в вашем приложении), это дает новый способ создания окон с динамическим размеров. Он открывает множество дополнительных возможностей при написании пользовательских интерфейсов!
Дополнительные возможности для меню компонуемых окон
Современные десктопные приложения обычно имеют большие и сложные меню со множеством опций. В этом релизе мы добавили API для создания таких меню. Их можно структурировать, добавлять иконки, сочетания клавиш и мнемонику, встраивать широко используемую логику флажков и простых списков (переключателей):

Поддержка контекстных меню
В альфа-версии Compose for Desktop добавлена поддержка контекстных меню, вызываемых правой кнопкой мыши — как используемых по умолчанию, так и настраиваемых. Фреймворк предлагает набор пунктов контекстного меню по умолчанию для выделяемого текста и текстовых полей, чтобы пользователи могли выделить, скопировать, вырезать и вставить текст.

Чтобы создать в контекстном меню собственные пункты для своих компонентов, можно задать иерархию компонентов:

API изменения курсора и иконки указателя
Начиная с этой версии Compose for Desktop, при наведении на текстовые поля или на текст, который можно выделить, указатель мыши автоматически превращается в курсор для выделения текста. Таким образом, пользователь видит, какой текст можно выделить, и приложения выглядят более естественно.
Для собственных компонентов можно настроить поведение указателя мыши с помощью нового модификатора pointerIcon, который позволяет изменять форму указателя при наведении на определенный компонент.
Модификатор Mouse Clickable
Для удобного доступа к кнопкам мыши и клавишам-модификаторам на клавиатуре, нажимаемым одновременно со щелчком мыши, мы добавили новый API с модификатором .mouseClickable. Если добавить его к вашему компоненту, можно указать обратный вызов, который получает MouseClickScope, предоставляющий полную информацию о событии:
Обратите внимание: этот API еще находится в разработке и будет в дальнейшем меняться.
Единые ресурсы изображений и редактор иконок
Готовя API Compose for Desktop к стабилизации, мы продолжаем улучшать и упрощать работу с графикой. Вместо разделения графических ресурсов на svgResource, imageResource и vectorXmlResource теперь можно использовать единый ресурс painterResource для всех трех типов изображений:
Кроме того, мы изменили свойство окна icon. Вместо java.awt.Image теперь используется androidx.compose.ui.graphics.painter.Painter, поэтому вы можете использовать векторные иконки, а не только растровые изображения:
Поддержка Linux на ARM64
В новом релизе Compose for Desktop добавлена поддержка Linux на устройствах с процессором на базе ARM64, а не только x86-64. А значит, теперь с помощью Compose for Desktop можно создавать пользовательские интерфейсы для следующих платформ:
- macOS на x64 и arm64
- Linux на x64 и arm64
- Windows на x64
Новые возможности Compose for Web
Compose for Web, как и Compose for Desktop, перешел на стадию альфа-версии. Версии и релизные циклы обоих продуктов были синхронизированы, а существующие возможности расширены с помощью DSL для управления стилями и событиями.
Расширенный CSS API
Мы продолжаем дорабатывать и улучшать наши API для определения стилей с помощью CSS. В новом релизе улучшена поддержка арифметических действий и настройки свойств, а также добавлена поддержка анимации из типобезопасного DSL.
Арифметические действия с единицами CSS
Теперь можно выполнять произвольные операции с числовыми значениями в CSS. Если вы выполняете операцию с двумя значениями одной и той же единицы, то получите новое значение той же единицы, как в этом примере:
CSS API для настройки свойств
Мы расширили типобезопасный доступ ко всем наиболее часто используемым свойствам CSS. Они составляют значительную часть всех свойств CSS, используемых в современных браузерах. Благодаря этому в большинстве случаев вы можете непосредственно пользоваться нашим типобезопасным API. Для более редких свойств или тех, которые пока не поддерживаются, можно выполнить присваивание с помощью функции property, которая получает ключи и значения напрямую:
API анимации
Чтобы сделать пользовательские интерфейсы на основе Compose еще динамичнее, мы добавили возможность создания CSS-анимаций из типобезопасного DSL:
Чтобы самостоятельно познакомиться с возможностями этих API поближе, изучите новые примеры, которые демонстрируют другие возможности работы с анимацией CSS и DOM.
Иерархия событий, прослушиватели событий и новые типы входных данных
Обработка событий, особенно передаваемых компонентами ввода — один из ключевых моментов для реагирования на изменения в приложении Compose. В новой версии мы упростили доступ к свойствам событий и определение прослушивателей, а также добавили новые типы входных данных.
Иерархия типов событий
Раньше большинство API на основе событий требовали использовать непосредственно nativeEvent или eventTarget для доступа к значениям нужного события. Начиная с этой версии Compose for Web, вы получаете доступ к SyntheticEvent, а его подтипы упрощают доступ к соответствующим свойствам передаваемых событий. Например, SyntheticMouseEvent предоставляет координаты, SyntheticInputEvent — текстовые значения, а SyntheticKeyEvent — нажатия клавиш:
Новые типы событий должны предоставлять доступ к тем же свойствам, которые непосредственно доступны для нативных событий, при этом не нужен непосредственный доступ к nativeEvent или eventTarget.
Входные данные
В стандартном HTML для входных данных разных типов — от текстовых полей до флажков — используется один и тот же тег input. Чтобы эти типы входных данных было проще использовать из Kotlin DSL, а подсказки для пользователей стали более точными, мы добавили несколько дополнительных функций для создания входных данных разных типов:
Прослушиватели событий
Мы также унифицировали функции, используемые для прослушивания событий, связанных с разными типами входных данных. Функции для прослушивания отдельных типов входных данных, например onCheckBoxInput, больше не используются. Вместо них можно использовать непосредственно onInput или onChange, то есть вам больше не придется искать обратный вызов с нужным именем:
Попробуйте альфа-версию Compose Multiplatform
Если вы разрабатываете десктопные, Android- или веб-приложения, — а тем более все сразу, — мы надеемся, что вы попробуете альфа-версию Compose Multiplatform.
Выход первой стабильной версии решения Compose Multiplatform 1.0 планируется до конца этого года, но уже сейчас вы можете опередить остальных и понять, как использовать Compose Multiplatform для ваших приложений.
Вам помогут следующие материалы:
- Актуальную информацию, как начать работу с десктопными приложениями вы найдете в уроках по Compose for Desktop.
- Если вы разрабатываете веб-приложения, вам помогут уроки по Compose for Web.
- в набор демонстрационных приложений были добавлены новые примеры, в том числе десктопные, веб- и мультиплатформенные приложения.
Примечания к предрелизной версии
В данный момент Compose Multiplatform находится в стадии альфа-тестирования. Большинство API уже близки к стабильным версиям, но следует помнить, что мы еще можем изменить некоторые из них, чтобы обеспечить оптимальную работу решения. Приближаясь к выпуску стабильного релиза, мы по-прежнему полагаемся на ваши отзывы.
Делитесь впечатлениями и присоединяйтесь к дискуссии
Мы работаем над подготовкой стабильного релиза и ждем ваших отзывов и соображений по поводу работы с Compose Multiplatform. Помогите нам сделать для вас удобное решение: расскажите о возникших проблемах, предложите API, которых вам не хватает, и функции, которые были бы вам полезны. Все это можно сделать в баг-трекере проекта.
Присоединяйтесь к сообществу Kotlin в Slack — там вы сможете напрямую пообщаться с нашей командой и другими разработчиками. Канал #compose-desktop посвящен Compose for Desktop, а в канале #compose можно обсудить общие темы, связанные с Compose и Jetpack Compose для Android.
Успехов в создании отличных интерфейсов с помощью Compose Multiplatform!
Смотрите также
- Превью-версия технологии: Jetpack Compose for Web
- Четвертая предрелизная версия Compose for Desktop
- Третья предрелизная версия Compose for Desktop
- Вторая предрелизная версия Compose for Desktop
- Первая предрелизная версия Compose for Desktop
Ваша команда Kotlin
The Drive to Develop
Автор оригинальной статьи:
Subscribe to Kotlin Blog updates
Discover more
Compose Multiplatform Goes Alpha, Unifying Desktop, Web, and Android UIs
Today’s release marks another step in our grand unified theory of UI development with Kotlin! We have a lot of news to talk about for our multiplatform UI efforts, including Compose for Desktop and Compose for Web. Today’s announcement builds on Google’s news last week that Jetpack Compose is now in 1.0 stable for Android. Here are the highlights:
- Compose for Desktop and Compose for Web are being promoted to Alpha. Their versioning is now aligned under the Compose Multiplatform umbrella, making it possible to build Android, Desktop, and Web UIs with the same artifacts.
- The JetBrains Toolbox App, our management application for IDEs, has finished migration to Compose for Desktop.
- A new plugin for IntelliJ IDEA and Android Studio enables component previews for Compose for Desktop via the
@Previewannotation. - Compose for Desktop now uses the composable window API by default, providing new support for adaptive window sizes, unified image resources, and new platform support for Linux on ARM64, allowing you to run it on targets like Raspberry Pi.
- Compose for Web further extends its DOM and CSS APIs.
We’ve also outlined the path of Compose in our video The Compose Story and shared exciting news about where we want to take declarative multiplatform user interfaces next. Read on and find out more!

Unifying Desktop, Web, and Android UI development
The story of declarative UI development with Kotlin really took off with the introduction of Jetpack Compose by Google, a modern framework for building native user interfaces for Android. JetBrains is building on the foundation of Google’s Jetpack Compose and bringing the Compose framework to new places!
With Compose Multiplatform, we’re making it possible to use the same declarative approach and APIs used for modern Android applications to create user interfaces for desktop and browser apps powered by Kotlin on the JVM and Kotlin/JS. Using the mechanisms provided by Kotlin Multiplatform, you can now target any combination of the following from the same project:
- Android (Jetpack Compose)
- Desktop (Compose for Desktop)
- Browser (Compose for Web)
Previously, Compose for Desktop and Compose for Web used separate sets of artifacts. We have now unified them under a single Gradle plugin and group of artifacts, meaning it’s easier than ever to get started with developing Android, desktop, and web user interfaces based on Compose.
With its new Alpha stability level, the APIs provided by Compose Multiplatform are now rapidly approaching their final form. This makes it a great time to write proof-of-concept implementations for your production applications so that you’ll be ready to go all-in on Compose when we hit 1.0, which we anticipate in 2021.
If you’re itching to try it yourself and you want to start writing your own modern UIs using Compose Multiplatform, feel free to read our official tutorials and learning materials. Or read on to learn more about what’s new in this latest release!
Learn more about Compose Multiplatform
How we got here: The Compose Story
To celebrate this significant step in making declarative, multiplatform user interface development with Kotlin a reality, we want to share our Compose story with you. To give you multiple perspectives on these efforts, we have invited Roman Elizarov, Project Lead for Kotlin at JetBrains; Nikolay Igotti, Lead for Compose at JetBrains; Jim Sproch, founder of Compose at Google; and Andrey Rudenko, Software Engineer in Compose UI.
Watch the story here to find out how it all started, how we got to where we are now, and what we plan to do next with Compose Multiplatform:
Compose in Production: JetBrains Toolbox App
Over the last few months, we’ve been watching our community adopt Compose for Desktop and Web in their projects – from small games, productivity helpers, and little demo apps to teams bringing Compose into their production apps.
At JetBrains, we’re now adopting Compose in some of our production applications, starting with the JetBrains Toolbox App, the management app for JetBrains IDEs with more than 800,000 monthly active users.

In their latest release, the team has completely converted the implementation of the application to Compose for Desktop. During the migration from an Electron-based user interface, the team noticed a number of advantages, some of which we’d like to highlight here:
- Memory consumption was significantly decreased, especially while the application is running in the background
- The installer size has been reduced by approximately 50%
- Overall rendering performance of the application has improved significantly
JetBrains Toolbox team lead Victor Kropp also shared his opinion on Compose for Desktop in the post:
Compose for Desktop is still in its early stages, but it has already proved to be a great choice for the Toolbox App. With support from our colleagues who are developing the framework, we were able to rewrite the whole UI in almost no time. This allowed us to unify the development experience, so from business logic to UI, from application to server, Toolbox is now 100% Kotlin.
The story of the JetBrains Toolbox App adopting Kotlin and Compose for Desktop is an inspiring one, and a few paragraphs in our release post certainly can’t do it justice. For that reason, we are planning to share a full-fledged case study on the project in the future. If you’re interested in a more detailed behind-the-scenes look, keep an eye out or subscribe to our newsletter to hear when it arrives!
New IntelliJ IDEA and Android Studio plugin for Compose Multiplatform
With this release, we’re also announcing a new IDE plugin to support you in your development efforts: the Compose Multiplatform plugin for IntelliJ IDEA and Android Studio. It is being released in tandem with new versions of the framework, and provides additional features to help you bring your user interfaces to life.
This first version includes a long-awaited feature: the ability to preview your Compose for Desktop and Android components right in the IDE, without having to even start your application. To show a preview for a @Composable function that takes no parameters, add the @Preview annotation to its definition. This adds a small gutter icon, which you can use to toggle the preview pane for your component:



We hope this new preview helps you shorten your development cycle and makes it easier for you to translate ideas and thoughts into real designs and layouts based on Compose. We’ll be updating and extending this plugin with additional functionality in the future to further improve the development experience when using our UI frameworks.
To find and install the new plugin, search for “Compose Multiplatform IDE Support” in the Plugins Marketplace, or click below to open the plugin’s page directly:
Install the Compose Multiplatform Plugin
What’s new in Compose for Desktop
Besides taking the big step of promoting Compose for Desktop to Alpha, we’re also improving its APIs and adding support for a new platform in this release.
Composable Window APIs by Default
In Milestone 4 of Compose for Desktop, we introduced an experimental set of APIs for the management of Window, MenuBar, and Tray. These new APIs are all @Composable, using the same concepts of state management, behavior, and conditional rendering as the other components in your application.
In this release, these composable versions are now the default way of managing windows, menu bars, and tray icons, replacing the old window API. If you haven’t given these new APIs a try, or if you just want to learn more about the behavior and functionality they offer, you can refer to our updated Compose for Desktop tutorials on window and tray management.
Adaptive Window Size
Sometimes we want to show some content as a whole without knowing in advance what exactly will be shown, meaning that we don’t know the optimal window dimensions for it. To make development of these UI scenarios easier, we’ve introduced the adaptive window size feature. By setting one or both dimensions of your window’s WindowSize to Dp.Unspecified, Compose for Desktop will automatically adjust the initial size of your window in that dimension to accommodate its content:

Together with removing window decorations (via undecorated = true in your application’s Window definition), we believe this new way of creating dynamically sized windows opens up a lot of additional possibilities for user interfaces that come in all shapes and sizes!
Additional features for composable window menus
Modern desktop applications usually come with rich and complex window menus. In this release, we’ve added additional APIs that allow creating such rich menus. They can be structured, enriched with icons, shortcuts, and mnemonics and integrate widely used logic of checkboxes and single selection lists (radio buttons):

Support for context menus
Compose for Desktop Alpha comes with support for default and custom context menus, which can be triggered by clicking the right mouse button. For selectable text and text fields, the framework provides a set of default context menu items, offering your users to copy, paste, cut, and select.

To specify custom context menu entries for your own components, you can provide a hierarchy of components:

Cursor change behavior and pointer icon API
Starting with this version of Compose for Desktop, the mouse pointer now automatically turns into a text selection cursor when hovering over text fields or selectable text, signalling that a text selection is possible, and making your applications feel yet a bit more native.
For your own components, you can also adjust the behavior of the mouse pointer using the newly added pointerIcon modifier, which enables you to change the pointer when hovering over a specific component.
Mouse Clickable modifier
To give you easy access to the mouse buttons and keyboard modifier keys that are being clicked or pressed while a mouse click is happening, we’re introducing a new API with the .mouseClickable modifier. Adding this modifier to your component allows you to specify a callback that receives a MouseClickScope, which provides you with full information about the event:
Please note that this API is not final yet – we’re continuing its development and are likely to change it in the future.
Unified image resources and icon painter
On our road to stabilizing Compose for Desktop’s APIs further, we’re continuing to improve and simplify the way you work with graphics. Instead of separating graphics resources into svgResource, imageResource, and vectorXmlResource, you can now use a unified painterResource, which can be used for all three types of graphics:
We have also changed the window icon property from java.awt.Image to androidx.compose.ui.graphics.painter.Painter, so you’ll be able to use vector-based icons in addition to raster graphics going forward:
Support for Linux on ARM64
With this release, Compose for Desktop adds support for Linux running on devices with an ARM64-based processor, in addition to the existing x86-64 support. In total, you can now write user interfaces for the following platforms using Compose for Desktop:
- macOS on x64 and arm64
- Linux on x64 and arm64
- Windows on x64
What’s new in Compose for Web
Alongside Compose for Desktop, Compose for Web has also been promoted to Alpha. The two have aligned their versioning scheme and release cycles, as well as extended the available functionality through their DSLs for style and event management.
Extended CSS API
We’re continuing to improve and refine our APIs to specify styling rules through CSS. This latest release adds better support for arithmetic operations, setting properties, and support for animations from within the type-safe DSL.
Arithmetic operations with CSS units
You can now execute any arbitrary operations on CSS numeric values. If you are using an operation on two values of the same unit, you’ll get a new value of the same unit, like in the following example:
CSS API for setting properties
We have expanded the typesafe access to all of the most-used CSS properties, and cover a large portion of all CSS properties that are supported in modern browsers. This means in most cases, you will be able to benefit from our type-safe API directly. For more exotic properties, or properties that are not yet supported, you can also make assignments via the property function, which takes keys and values directly:
Animation API
To make your Compose-based user interfaces even more dynamic, we now provide the option to create CSS animations from within the type-safe DSL:
If you want to explore those APIs more on your own, be sure to check out our newly added examples, which show off some more advanced CSS animation and DOM manipulation functionality.
Event hierarchy, event listeners, and new input types
Handling events, especially those emitted by input components, is one of the key parts of reacting to changes in a Compose app. In this release, we’ve simplified access to event properties, made it easier to define event listeners, and provided different input types.
Event Types Hierarchy
Previously, most event-based APIs required you to work with the nativeEvent or eventTarget directly in order to access the values of the event you were interested in. Starting with this version of Compose for Web, you now have access to a SyntheticEvent, whose subtypes make it easier to access the relevant properties of the emitted events. SyntheticMouseEvent exposes coordinates, SyntheticInputEvent exposes text values, and SyntheticKeyEvent exposes keystrokes, to name just a few examples:
These new event types aim to provide access to the same properties that [are available for in native events](https://developer.mozilla.org/en-US/docs/Web/API/Event) directly, without having to access the nativeEvent or the event’s target directly.
Inputs
In regular HTML, different input types, from text fields to checkboxes, all share the same tag – input. To make it easier to use these different input types from within the Kotlin DSL, and to provide you with more relevant hints, we have introduced a number of additional functions for creating inputs of different types:
Event Listeners
We have further unified the functions used for listening to events for different input types. Input-type specific functions for input listeners like onCheckBoxInput have been removed and you can now use onInput or onChange directly, which means you no longer have to search for the correctly named callback:
Try out Compose Multiplatform Alpha!
Whether you’re targeting the web, desktop, Android, or all three – we hope you’ll give Compose Multiplatform a try!
We’re anticipating Compose Multiplatform 1.0 – our first stable release – later this year, so now is the ideal time to stay ahead of the curve and evaluate Compose Multiplatform for your production applications.
To help you get started, there are a number of resources available:
- For desktop applications, you can find up-to-date information on how to get started in the Compose for Desktop tutorials.
- For browser applications, the Compose for Web tutorials will help you get up and running.
- Our example app showcase includes additional samples to study, including web, desktop, and multiplatform applications.
Pre-release notes
Compose Multiplatform is currently in Alpha. While most APIs are now already closely resembling their stable shape, please keep in mind that we may still alter some of the APIs to ensure the final release provides the best development experience possible. As we approach the stable release, we continue to rely on your feedback to help us achieve this!
Share your feedback and join the discussion
As we continue our path to the stable release, we’d like to hear your thoughts and feedback on working with Compose Multiplatform. Help us help you by reporting problems, telling us about APIs that you feel are missing, and requesting features you’d like to see. All this can be done in the project’s issue tracker.
If you want to talk to other developers and team members, we also invite you to join the discussion on the Kotlin Slack. In #compose-desktop you can find discussions about Compose for Desktop, and in #compose you can discuss general topics involving Compose and Jetpack Compose on Android.
Take care, and go build some awesome user interfaces with Compose Multiplatform!
See also
- Technology Preview: Jetpack Compose for Web
- Compose for Desktop: Milestone 4 Released
- Compose for Desktop: Milestone 3 Released
- Compose for Desktop: Milestone 2 Released
- Compose for Desktop: Milestone 1 Released
