• Stars
    star
    214
  • Rank 184,678 (Top 4 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 3 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ¦‹ Butterfly helps you to build adaptive and responsive UIs for Android with Jetpack WindowManager.

Butterfly

Google
License API Build Status Kotlin Weekly Android Weekly Dokka


πŸ¦‹ Butterfly helps you to build adaptive and responsive UIs for Android with Jetpack WindowManager.
Also, it supports useful functions for Jetpack Compose and LiveData integration.


Preview

πŸŒ— See dark theme

Dark Theme

Demo Project

The demo project was built with the Stream Chat SDK for Jetpack Compose. It would be helpful to understand the demo project if you check out the links below:

Contribution πŸ’™

Butterfly is maintained by Stream. If you’re interested in adding powerful In-App Messaging to your app, check out the Stream Chat SDK for Android! Also, anyone can contribute to improving code, docs, or something following our Contributing Guideline.

Download

Maven Central

Gradle

Add the codes below to your root build.gradle file (not your module build.gradle file).

allprojects {
    repositories {
        mavenCentral()
    }
}

Next, add the dependency below to your module's build.gradle file.

dependencies {
    implementation "io.getstream:butterfly:1.0.2"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1"
}

Note: Butterfly includes Jetpack WindowManager to compute window internally. So if you're using WindowManager in your project, please make sure your project uses the same version or exclude the dependency to adapt yours.

SNAPSHOT

See how to import the snapshot

Including the SNAPSHOT

Snapshots of the current development version of Butterfly are available, which track the latest versions.

To import snapshot versions on your project, add the code snippet below on your gradle file.

repositories {
   maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}

Next, add the below dependency to your module's build.gradle file.

dependencies {
    implementation "io.getstream:butterfly:1.0.3-SNAPSHOT"
}

Set up Foldable Emulator

If you don't have foldable devices or emulators, you can set up a foldable emulator environment following the below instruction:

πŸ‘‰ Check out the Set up Foldable Emulator (Surface Duo 2)

Usage

Butterfly uses Jetpack WindowManager, so it would be helpful to understand if you have background knowledge of the WindowManager APIs.

WindowSize

WindowSize represents breakpoints, which are the screen size at which a layout will adapt to best fit content and conform to responsive layout requirements. Butterfly follows three breakpoints by Material Design.

  • WindowSize.Compact: Most phones in portrait mode. (0-599 dp range)
  • WindowSize.Medium: Most foldables and tablets in portrait mode. (600-839 dp range)
  • WindowSize.Expanded: Most tablets in landscape mode. (840+ dp range)

You can get an instance of the WindowSize class with getWindowSize() method on your Activity or Fragment as following below:

val windowSize: WindowSize = getWindowSize()
when (windowSize) {
    is WindowSize.Compact -> // the window size is compact.
    is WindowSize.Medium -> // the window size is medium.
    is WindowSize.Expanded -> // the window size is expanded.
}

GlobalWindowSize

You can customize the pre-defined breakpoints, which used to getWindowSize() with GlobalWindowSize object class as following below:

GlobalWindowSize.compactWindowDpSize = 600
GlobalWindowSize.mediumWindowDpSize = 840

Also, you can fully customize a factory function of the WindowSize class as following below:

GlobalWindowSize.windowSizeFactory = { windowPixelSize ->
    when {
        windowPixelSize.width < 0 -> throw IllegalArgumentException("Can't be negative")
        windowPixelSize.width < 600.dp2Px() -> WindowSize.Compact(windowPixelSize)
        windowPixelSize.width < 840.dp2Px() -> WindowSize.Medium(windowPixelSize)
        else -> WindowSize.Expanded(windowPixelSize)
    }
}

Posture

Fold state: FLAT and HALF-OPENED from Google.

Posture class represents device postures in the flexible display or a hinge between two physical display panels.

  • Posture.TableTop - Device posture is in tabletop mode (half open with the hinge horizontal).
  • Posture.Book - Device posture is in book mode (half open with the hinge vertical).
  • Posture.Normal - Device posture is in normal mode.

You can observe the posture as a Kotlin Flow on you Activity or Fragment as following below:

lifecycleScope.launch(Dispatchers.Main) {
    lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        postureFlow.collect { posture ->
            when (posture) {
                Posture.Normal -> // posture is Normal
                is Posture.TableTop -> // posture is TableTop
                is Posture.Book -> // posture is Book
            }
        }
        windowLayoutInfo.collect(::onWindowLayoutInfoUpdated)
    }
}

Note: Make sure your project includes Coroutines and androidx.lifecycle:lifecycle-runtime-ktx:2.4.0 dependencies.

WindowLayoutInfo

WindowLayoutInfo contains the list of DisplayFeature-s located within the window. You can observe the WindowLayoutInfo as following below:

lifecycleScope.launch(Dispatchers.Main) {
    lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        windowLayoutInfo.collect { windowLayoutInfo ->
            // something stuff            
        }
    }
}

You can also get the following information from the WindowLayoutInfo as in the following extensions:

val isSeparating: Boolean = WindowLayoutInfo.isSeparating
val occlusionType: FoldingFeature.OcclusionType = WindowLayoutInfo.occlusionType 
val orientation: FoldingFeature.Orientation = WindowLayoutInfo.orientation
val state: FoldingFeature.State = WindowLayoutInfo.state

FoldingFeature

FoldingFeature that describes a fold in the flexible display or a hinge between two physical display panels. You can utilize the extensions below to check folding states and device postures:

val foldingFeature = windowLayoutInfo.displayFeatures.findFoldingFeature()
val posture = foldingFeature?.toPosture()
val isTableTopPosture = foldingFeature?.isTableTopPosture
val isBookPosture = foldingFeature?.isBookPosture
val isHalfOpened = foldingFeature?.isHalfOpened
val isFlat = foldingFeature?.isFlat
val isVertical = foldingFeature?.isVertical
val isHorizontal = foldingFeature?.isHorizontal

Hinge Size

If your foldable device is separated by a hinge, you can get a hinge size with the extensions below:

val hingePxSize: Int = foldingFeature.hingePxSize
val hingeDpSize: Int = foldingFeature.hingeDpSize
val hingeWidthPxSize: Int = foldingFeature.hingeWidthPxSize
val hingeHeightPxSize: Int = foldingFeature.hingeHeightPxSize
val hingeWidthDpSize: Int = foldingFeature.hingeWidthDpSize
val hingeHeightDpSize: Int = foldingFeature.hingeHeightDpSize

WindowInfoActivity

Butterfly supports WindowInfoActivity, which tracks window configurations and update the WindowLayoutInfo. It has a default windowSize property and onWindowLayoutInfoUpdated abstract method as in the example below:

class MainActivity : WindowInfoActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // windowSize property will be initialized lazily.
        when (windowSize) {
            is WindowSize.Compact -> 
            ...
        }
    }

    override fun onWindowLayoutInfoUpdated(windowLayoutInfo: WindowLayoutInfo) {
        val foldingFeature = windowLayoutInfo.displayFeatures.findFoldingFeature() ?: return
        when (val posture = foldingFeature.toPosture()) {
            Posture.Normal -> Log.d(tag, "[Posture.Normal] ${posture.size}")
            is Posture.TableTop -> Log.d(tag, "[Posture.TableTop] ${posture.size}")
            ...
        }
    }
}

The pre-defined windowSize property will be initialized lazily and the onWindowLayoutInfoUpdated will be updated when the WindowLayoutInfo configuration changed. As the same concept, you can extend WindowInfoFragment for your Fragment.

Butterfly for Jetpack Compose

Maven Central

Butterfly supports Jetpack Compose to build adaptive and responsive UIs. First, add the dependency below to your module's build.gradle file.

dependencies {
    implementation "io.getstream:butterfly-compose:1.0.1"
}

WindowDpSize

WindowDpSize represents breakpoints, which are the screen size at which a layout will adapt to best fit content and conform to responsive layout requirements. Butterfly follows three breakpoints by Material Design.

You can remember an instance of the WindowDpSize class with rememberWindowDpSize() method on your Activity or Fragment as following below:

val windowDpSize: WindowDpSize = rememberWindowDpSize()
when (windowDpSize) {
    is WindowSize.Compact -> MainScreenRegular()
    is WindowSize.Medium -> MainScreenMedium()
    is WindowSize.Expanded -> MainScreenExpanded()
}

Note: Likewise the WindowSize, you can also customize the pre-defined breakpoints, which used to rememberWindowDpSize with the GlobalWindowSize object class.

Posture

You can get a State of Posture to build adaptive and responsive UIs with the postureState extension on your Activity and Fragment as following below:

val postureState: State<Posture> = postureState
when (postureState.value) {
    Posture.Normal -> // posture is Normal
    is Posture.TableTop -> // posture is TableTop
    is Posture.Book -> // posture is Book
}

WindowLayoutInfo

WindowLayoutInfo contains the list of DisplayFeature-s located within the window. You can get the State of the WindowLayoutInfo as following below:

val windowLayoutInfoState: State<WindowLayoutInfo> = windowLayoutInfoState
val foldingFeature = windowLayoutInfoState.value.displayFeatures.findFoldingFeature()
...

CompositionLocal

You can pass instances of the WindowDpSize and Posture down through the Composition implicitly as following below:

CompositionLocalProvider(LocalWindowDpSize provides rememberWindowDpSize()) {
    val windowDpSize = LocalWindowDpSize.current
    ...
}

CompositionLocalProvider(LocalPosture provides postureState.value) {
    val posture = LocalPosture.current
    ...                
}

Hinge Size

If your foldable device is separated by a hinge, you can get a hinge size with the extensions below:

val hingeDp: Dp = FoldingFeature.hingeDp
val hingeDpSize: DpSize = FoldingFeature.hingeDpSize
val hingeWidthDp: Dp = FoldingFeature.hingeWidthDp
val hingeHeightDp: Dp = FoldingFeature.hingeHeightDp

Butterfly for LiveData Integration

Maven Central

Butterfly supports LiveData integration to let observing layout changes as LiveData. First, add the dependency below to your module's build.gradle file.

dependencies {
    implementation "io.getstream:butterfly-livedata:1.0.1"
}

You can observe LiveData of Posture and WindowLayoutInfo on your Activity and Fragment as in the following example below:

postureLiveData().observe(this) { posture ->
    // do something
}

windowLayoutInfoLiveData().observe(this) { windowLayoutInfo ->
    // do something
}

Find this library useful? ❀️

Support it by joining stargazers for this repository. ⭐️
Also, follow Stream on Twitter for our next creations!

License

Copyright 2022 Stream.IO, Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

Winds

A Beautiful Open Source RSS & Podcast App Powered by Getstream.io
JavaScript
8,813
star
2

stream-chat-android

πŸ’¬ Android Chat SDK ➜ Stream Chat API. UI component libraries for chat apps. Kotlin & Jetpack Compose messaging SDK for Android chat
Kotlin
1,443
star
3

vg

Virtualgo: Easy and powerful workspace based development for go
Go
1,311
star
4

whatsApp-clone-compose

πŸ“± WhatsApp clone project demonstrates modern Android development built with Jetpack Compose and Stream Chat/Video SDK for Compose.
Kotlin
1,254
star
5

stream-react-example

Use React and Redux to build your own feature-rich and scalable social network app! Visit cabin.getstream.io for an overview of all 8 tutorials and a live demo.
HTML
923
star
6

stream-chat-flutter

Flutter Chat SDK - Build your own chat app experience using Dart, Flutter and the Stream Chat Messaging API.
Dart
839
star
7

stream-chat-react-native

πŸ’¬ React-Native Chat SDK ➜ Stream Chat. Includes a tutorial on building your own chat app experience using React-Native, React-Navigation and Stream
TypeScript
792
star
8

purposeful-ios-animations

Meaningful iOS animations built to inspire you in creating useful animations for your apps. Each of the animations here was cloned with SwiftUI. Have you seen an app animation you love to rebuild and add to this repo?, contact [@amos_gyamfi](https://twitter.com/amos_gyamfi) and [@stefanjblos](https://twitter.com/stefanjblos) on Twitter.
Swift
763
star
9

stream-chat-swift

πŸ’¬ iOS Chat SDK in Swift - Build your own app chat experience for iOS using the official Stream Chat API
Swift
750
star
10

swiftui-spring-animations

This repository serves as your reference and complete guide for SwiftUI Spring Animations. It demonstrates use cases for the various types of spring animations and spring parameters. No more guessing the values of the parameters for spring animations you create for your next iOS app.
Swift
692
star
11

webrtc-android

πŸ›°οΈ A versatile WebRTC pre-compiled Android library that reflects the recent WebRTC updates to facilitate real-time video chat for Android and Compose.
Kotlin
578
star
12

stream-chat-react

React Chat SDK ➜ Stream Chat πŸ’¬
TypeScript
552
star
13

awesome-saas-services

A curated list of the best in class SaaS services for developers and business owners.
475
star
14

stream-django

Django Client - Build Activity Feeds & Streams with GetStream.io
Python
453
star
15

sketchbook-compose

🎨 Jetpack Compose canvas library that helps you draw paths, images on canvas with color pickers and palettes.
Kotlin
442
star
16

avatarview-android

✨ Supports loading profile images with fractional styles, shapes, borders, indicators, and initials for Android.
Kotlin
432
star
17

webrtc-in-jetpack-compose

πŸ“± This project demonstrates WebRTC protocol to facilitate real-time video communications with Jetpack Compose.
Kotlin
402
star
18

stream-video-android

πŸ“² Android Video SDK. Stream's versatile Core + Compose UI component libraries that allow you to build video calling, audio room, and, live streaming apps based on Webrtc running on Stream's global edge network.
Kotlin
374
star
19

AvengersChat

πŸ’™ Android sample Avengers chat application using Stream Chat SDK based on MVVM (ViewModel, Coroutines, Room, Hilt, Repository) architecture.
Kotlin
367
star
20

stream-draw-android

πŸ›₯ Stream Draw is a real-time multiplayer drawing & chat game app built entirely with Jetpack Compose.
Kotlin
341
star
21

stream-chat-swiftui

SwiftUI Chat SDK ➜ Stream Chat πŸ’¬
Swift
329
star
22

stream-js

JS / Browser Client - Build Activity Feeds & Streams with GetStream.io
JavaScript
329
star
23

effects-library

The Effects Library allows developers to create sophisticated and realistic particle systems such as snow, fire, rain, confetti, fireworks, and smoke with no or minimal effort.
Swift
324
star
24

react-native-example

React Native Activity Feed example application
JavaScript
321
star
25

stream-laravel

Laravel Client - Build Activity Feeds & Streams with GetStream.io
PHP
314
star
26

flutter-samples

A collection of sample apps that use Stream
Dart
298
star
27

stream-rails

Rails Client - Build Activity Feeds & Streams with GetStream.io
Ruby
257
star
28

Streamoji

:godmode: Custom emoji rendering library for iOS apps with support for GIF & still images - plug-in extension for UITextView - performance, cache βœ… - Made with πŸ’˜ by @GetStream
Swift
248
star
29

react-native-bidirectional-infinite-scroll

πŸ“œ React Native - Bidirectional Infinite Smooth Scroll
TypeScript
220
star
30

WhatsApp-Clone-Android

Tutorial which teaches you how to build a whatsapp chat clone on android using Kotlin, viewmodels, navigation component and Stream
Kotlin
218
star
31

slack-clone-react-native

Build a slack clone using react-native, Stream and react-navigation
JavaScript
206
star
32

react-native-activity-feed

Official React Native SDK for Activity Feeds
JavaScript
194
star
33

motionscape-app

MotionScape is your animations playground as a developer. You can see all animations and their parameters in effect with beautifully designed and handcrafted animation examples.
Swift
167
star
34

Android-Samples

πŸ“• Provides a list of samples that utilize modern Android tech stacks and Stream Chat SDK for Android and Compose.
Kotlin
159
star
35

node-express-mongo-api

Starter project for a REST API with Node.js, Express & MongoDB πŸ”‹
JavaScript
151
star
36

stream-chat-js

JS / Browser Client - Build Chat with GetStream.io
TypeScript
149
star
37

meeting-room-compose

πŸŽ™οΈ A real-time meeting room app built with Jetpack Compose to demonstrate video communications.
Kotlin
141
star
38

stream-php

PHP Client - Build Activity Feeds & Streams with GetStream.io
PHP
139
star
39

stream-log

πŸ›₯ Stream Log is a lightweight and extensible logger library for Kotlin Multiplatform.
Kotlin
136
star
40

react-activity-feed

Stream React Activity Feed Components
TypeScript
136
star
41

stream-python

Python Client - Build Activity Feeds & Streams with GetStream.io
Python
136
star
42

flat-list-mvcp

"maintainVisibleContentPosition" prop support for Android react-native
TypeScript
133
star
43

stream-node-orm

NodeJS Client - Build Activity Feeds & Streams with GetStream.io
JavaScript
131
star
44

website-react-examples

TypeScript
122
star
45

stream-video-swift

SwiftUI Video SDK ➑️ Stream Video πŸ“Ή
Swift
117
star
46

react-native-samples

A collection of sample apps built using GetStream and React Native
JavaScript
116
star
47

flutter-instagram-clone

An Instagram clone using Flutter and Stream Feeds
Dart
111
star
48

django_twitter

An example app built using getstream.io
Python
108
star
49

twitter-clone

Learn how to build a functional Twitter clone using Stream, 100ms, Algolia, RevenueCat and Mux 😎
Swift
107
star
50

accessible-inclusive-ios-animations

Provide ways to limit animations/motion people find jarring in your apps. This repo demonstrates accessible and inclusive iOS animations/motion with practical examples and best practices.
Swift
107
star
51

stream-result

🚊 Railway-oriented library to easily model and handle success/failure for Kotlin Multiplatform.
Kotlin
102
star
52

Stream-Example-Nodejs

An example app built using getstream.io
JavaScript
96
star
53

Android-Video-Samples

πŸ“˜ Provides a collection of samples that utilize modern Android tech stacks and Stream Video SDK for Kotlin and Compose.
Kotlin
88
star
54

react-native-audio-player

JavaScript
86
star
55

stream-ruby

Ruby Client - Build Activity Feeds & Streams with GetStream.io
Ruby
83
star
56

stream-tutorial-projects

This repo contains SwiftUI, Jetpack Compose, JS & React Native projects for some of the iOS and Android tutorial series in the Stream Developers YouTube channel (https://youtube.com/playlist?list=PLNBhvhkAJG6tJYnY-5oZ1JCp2fBNbVL_6).
Swift
83
star
57

stream-chat-unity

πŸ’¬ Unity Chat Plugin by Stream ➜ These assets are the solution for adding an in-game text chat system to your Unity game.
C#
83
star
58

stream-go2

GetStream.io Go client
Go
82
star
59

stream-cli

Configure & manage Stream applications from the command line. πŸš€
Go
80
star
60

mongodb-activity-feed

Activity Feed, Timeline, News Feed, Notification Feed with MongoDB, Node and CRDTs
JavaScript
77
star
61

android-video-chat

⚑️ Android Video Chat demonstrates a real-time video chat application by utilizing Stream Chat & Video SDKs.
Kotlin
76
star
62

TinyGraphQL

🌸 Simple and lightweight GraphQL query builder for the Swift language - Made with πŸ’˜ by @GetStream
Swift
76
star
63

slack-clone-expo

Slack clone using Expo, Stream and react-navigation
JavaScript
75
star
64

liveshopping-android

πŸ“Ή A demo app showcasing real-time livestreaming and messaging capabilities built with Jetpack Compose and Stream SDKs.
Kotlin
74
star
65

fullstack-nextjs-whatsapp-clone

A sample codebase showcasing Stream Chat and Video to resembling WhatsApp, using NextJS, TailwindCSS and Vercel.
TypeScript
72
star
66

stream-feed-flutter

Stream Feed official Flutter SDK. Build your own feed experience using Dart and Flutter.
Dart
69
star
67

stream-chat-go

Stream Chat official Golang API Client
Go
67
star
68

stream-video-js

GetStream JavaScript Video SDK
TypeScript
66
star
69

discord-clone-nextjs

Building a discord clone using NextJS, TailwindCSS, and the Stream Chat and Audio and Video SDKs.
TypeScript
64
star
70

SwiftUIMessagesUIClone

The SwiftUI Messages Clone consists of layout and composition clones of the iOS Messages app. It has Messages-like bubble and screen effects, reactions, and animations, all created with SwiftUI.
Swift
62
star
71

Stream-Example-Py

An example app built using getstream.io
CSS
61
star
72

encrypted-web-chat

A web chat application end-to-end encrypted with the Web Crypto API
JavaScript
59
star
73

swift-lambda

Ξ» Write HTTP services in Swift, deploy in seconds - Powered by AWS Lambda Runtime & Serverless Framework - Made with πŸ’˜ by @GetStream
Swift
57
star
74

stream-chat-python

Stream Chat official Python API Client
Python
56
star
75

stream-java

Java Client - Build Activity Feeds & Streams with GetStream.io
Java
53
star
76

stream-video-flutter

Flutter Video SDK - Build your own video app experience using Dart, Flutter and the Stream Video Messaging API.
Dart
46
star
77

Stream-Example-Parse

Stream-Example-Parse
JavaScript
46
star
78

Stream-Example-PHP

An example app built using getstream.io https://getstream.io
PHP
46
star
79

android-chat-tutorial

Sample apps for the Stream Chat Android SDK's official tutorial
Java
46
star
80

stream-meteor

Meteor Client - Build Activity Feeds & Streams with GetStream.io
JavaScript
45
star
81

SwiftUIChristmasTree

🌲 Pure SwiftUI christmas tree with yearly updates. Enjoy πŸŽ„
Swift
45
star
82

python-chat-example

Chat with Python, Django and React
JavaScript
44
star
83

stream-chat-net

Stream Chat official .NET API Client
C#
43
star
84

stream-chat-dart

Dart SDK - Build Chat with GetStream.io
Dart
42
star
85

kmp-sample-template

A minimal Kotlin & Compose Multiplatform template designed to build applications for both Android and iOS.
Kotlin
41
star
86

Stream-Example-Go-Cassandra-API

Go-powered API example using Cassandra
Go
38
star
87

Stream-Example-Rails

An example app built using getstream.io
Ruby
38
star
88

Stream-Example-Android

Java
38
star
89

foldable-chat-android

🦚 Foldable chat Android demonstrates adaptive and responsive UIs with Jetpack WindowManager API.
Kotlin
35
star
90

stream-net

NET Client - Build Activity Feeds & Streams with GetStream.io
C#
35
star
91

stream-swift

Swift client for Stream API
Swift
35
star
92

stream-chat-angular

πŸ’¬ Angular Chat SDK ➜ Stream Chat. Build a chat app with ease.
TypeScript
34
star
93

SwiftUI-open-voip-animations

SwiftUI animations and UI designs for iOS calling, meeting, audio-room, and live streaming use cases. Find something missing? Let @amos_gyamfi know on Twitter.
33
star
94

node-restify-mongo-api

Starter project for a REST API with Node.js, Restify & MongoDB πŸ”‹
JavaScript
32
star
95

stream-chat-unreal

The official Unreal SDK for Stream Chat
C++
32
star
96

build-viking-sample

Sample app for Build Viking.
Dart
31
star
97

swiftui-iMessage-clone

Swift
30
star
98

swift-activity-feed

Stream Swift iOS Activity Feed Components
Swift
29
star
99

stream-chat-ruby

Stream Chat official Ruby API Client
Ruby
29
star
100

sign-in-with-apple-swift-example

iOS + Node.js authentication using Sign in with Apple
Swift
28
star