• Stars
    star
    1,522
  • Rank 29,551 (Top 0.7 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated 11 months ago

Reviews

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

Repository Details

Layouts with lambdas 😎

Contour [DEPRECATED]

Contour is deprecated. It has been amazing. It is stable and probably still running in the wild. But its development has ceased. We encourage developers to favor Jetpack Compose UI.

Contour is a typesafe, Kotlin-first API that aims to be the thinnest possible wrapper around Android’s layout APIs. It allows you to build compound views in pure Kotlin without using opaque layout rules - but instead by hooking into the layout phase yourself. The best comparison for Contour would be to ConstraintLayout - but instead of defining constraints in XML you actually provide them as executable lambdas.

Deprecating XML

XML had a good ride but times have changed and we should too. XML is a decent format for declaring static content - but that’s not what UIs are anymore. UIs increasingly have a ton of dynamic behavior - and trying to jerry-rig XML layouts into adopting this dynamic behavior has taken things from bad to worse. What sort of dynamic behaviors do we expect from our UIs?

  • Change configuration based on screen size
  • Lazy loading elements of the UI.
  • A / B testing components at runtime
  • Dynamic theming
  • Add & remove components based on app state

Let’s face it - XML is a static markup language and we’re trying to make it a full-fledged programming language. What’s the alternative? A full-fledged programming language! Kotlin! What sort of things do we get by abandoning the XML model?

  • No findViewById - view declaration exists in scope.
  • No R.id.my_view ambiguity - Kotlin has namespacing & encapsulation!
  • Static typing!
  • Great IDE Support (No more laggy xml editor)
  • ViewHolders aren’t needed
  • Easier DI

Usage

Similar to ConstraintLayout, Contour works by creating relationships between views' position and size. The difference is, instead of providing opaque XML attributes, you provide functions which are directly called during the layout phase. Contour calls these functions "axis solvers" and they're provided using layoutBy(). Here's an example:

class BioView(context: Context) : ContourLayout(context) {
  private val avatar = ImageView(context).apply {
    scaleType = CENTER_CROP
    Picasso.get().load("https://i.imgur.com/ajdangY.jpg").into(this)
  }

  private val bio = TextView(context).apply {
    textSize = 16f
    text = "..."
  }

  init {
    avatar.layoutBy(
      x = leftTo { parent.left() }.widthOf { 60.xdip },
      y = topTo { parent.top() }.heightOf { 60.ydip }
    )
    bio.layoutBy(
      x = leftTo { avatar.right() + 16.xdip }.rightTo { parent.right() },
      y = topTo { parent.top() }
    )
    contourHeightOf { bio.bottom() }
  }
}

Runtime Layout Logic

Because you're writing plain Kotlin, you can reference other Views and use maths in your lambdas for describing your layout. These lambdas can also be used for making runtime decisions that will be evaluated on every layout pass.

bio.layoutBy(
  x = ...
  y = topTo {
    if (isSelected) parent.top() + 16.ydip
    else avatar.centerY() - bio.height() / 2
  }.heightOf {
    if (isSelected) bio.preferredHeight()
    else 48.ydip
  }
)

When paired with an animator, your runtime layout decisions can even act as keyframes for smoothly updating your layout.

setOnClickListener {
  TransitionManager.beginDelayedTransition(this)
  isSelected = !isSelected
  requestLayout()
}

What does the end result of this look like?

contourlayout animation

Context-Aware API

Contour tries to make it easy to do the right thing. As part of this effort, all of the layout functions return interfaces as views of the correct available actions.

For example, when defining a constraint of leftTo, the only exposed methods to chain in this layout are rightTo or widthOf. Another leftTo, or centerHorizontallyTo don't really make sense in this context and are hidden. In short:

layoutBy(
  x = leftTo { name.left() }.leftTo { name.right() },
  y = topTo { name.bottom() }
)

will not compile.

Axis Type Safety

Contour makes heavy use of inline classes to provide axis type safety in layouts. What this means is,

toLeftOf { view.top() }

will not compile either. toLeftOf {} requires a XInt, and top() returns a YInt. In cases where this needs to be forced, casting functions are made available to toY() & toX().

Inline classes are a lightweight compile-time addition that allow this feature with minimal to no performance costs. https://kotlinlang.org/docs/reference/inline-classes.html

Circular Reference Debugging

Circular references are pretty easy to unintentionally introduce in any layout. To accidentally declare

  • name.right aligns to note.left
  • and note.left aligns to name.right

Contour fails fast and loud when these errors are detected, and provides as much context as possible when doing so. The screenshot below is an example of the trace provided when a circular reference is detected.

Comparison with Compose

There is a lot of buzz and interest around writing views in code right now with the development of Jetpack Compose. Compose is a programmatic UI toolkit that uses reactive programming to drive the views. In contrast Contour doesn’t care about the update mechanisms - whether they be FRP or plain old imperative. Contour is only concerned with the nuts and bolts of view layouts - and making them as flexible and easy as possible.

The only similarity between Contour and Compose is that they both realize writing layouts in Kotlin is maximum cool.

Releases

implementation "app.cash.contour:contour:1.1.0"

Snapshots of the development version are available in Sonatype's snapshots repository.

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

License

Copyright 2019 Square, Inc.

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

sqldelight

SQLDelight - Generates typesafe Kotlin APIs from SQL
Kotlin
5,893
star
2

turbine

A small testing library for kotlinx.coroutines Flow
Kotlin
2,318
star
3

paparazzi

Render your Android screens without a physical device or emulator
Kotlin
2,156
star
4

zipline

Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native programs
C
1,904
star
5

molecule

Build a StateFlow stream using Jetpack Compose
Kotlin
1,710
star
6

redwood

Multiplatform reactive UI for Android, iOS, and web using Kotlin and Jetpack Compose
Kotlin
1,435
star
7

InflationInject

Constructor-inject views during XML layout inflation
Kotlin
908
star
8

pranadb

Go
615
star
9

licensee

Gradle plugin which validates the licenses of your dependency graph match what you expect
Kotlin
599
star
10

hermit

🐚 Hermit manages isolated, self-bootstrapping sets of tools in software projects.
Go
553
star
11

AccessibilitySnapshot

Easy regression testing for iOS accessibility
Swift
518
star
12

exhaustive

An annotation and Kotlin compiler plugin for enforcing a when statement is exhaustive
Kotlin
465
star
13

multiplatform-paging

A library that packages AndroidX Paging for Kotlin/Multiplatform.
Kotlin
452
star
14

misk

Microservice Kontainer
Kotlin
385
star
15

copper

A content provider wrapper for reactive queries
Kotlin
300
star
16

paraphrase

A Gradle plugin that generates type-safe formatters for Android string resources in the ICU message format.
Kotlin
157
star
17

barber

Barber 💈 A type safe Kotlin JVM library for building up localized, fillable, themed documents using Mustache templating
Kotlin
154
star
18

stagehand

Modern, type-safe API for building animations on iOS
Swift
126
star
19

hermit-packages

Hermit manages isolated, self-bootstrapping sets of tools in software projects.
HCL
110
star
20

quiver

Quiver is a collection of extension methods and handy functions to make the wonderful functional programming Kotlin library, Arrow, even better.
Kotlin
95
star
21

spirit

Online Schema Change Tool for MySQL 8.0
Go
83
star
22

pivit

Go
82
star
23

tempest

Typesafe DynamoDB for Kotlin and Java.
Kotlin
80
star
24

better-dynamic-features

Making dynamic feature modules better
Kotlin
70
star
25

misk-web

Micro-Frontends React + Redux + Typescript Framework
TypeScript
65
star
26

blip

Sublime MySQL monitoring
Go
59
star
27

logquacious

Logquacious (lq) is a fast and simple log viewer.
TypeScript
58
star
28

wisp

Wisp is a collection of kotlin modules providing various features and utilities, including config, logging, feature flags and more.
Kotlin
58
star
29

certifikit

Kotlin Certificate processing library.
Kotlin
40
star
30

backfila

Service that manages backfill state, calling into other services to do batched work
Kotlin
30
star
31

cash-app-pay-android-sdk

Cash Android PayKit SDK for merchant integrations with Cash App Pay
Kotlin
29
star
32

nostrino

A Kotlin SDK for Nostr
Kotlin
28
star
33

transflect

Kubernetes operator using Istio to set up Envoy's gRPC-JSON transcoding.
Go
24
star
34

cmmc

K8S ConfigMap Merging Controller
Go
20
star
35

cloner

Go
20
star
36

kfsm

Finite state machinery in Kotlin
Kotlin
19
star
37

yet-another-aws-exporter

A Prometheus metrics exporter for AWS that fills in gaps CloudWatch doesn't cover
Go
17
star
38

cash-app-pay-ios-sdk

Swift
14
star
39

protosync

ProtoSync synchronises remote .proto files to a local directory
Go
13
star
40

cash-pay-pay-sdk-android-sample-app

Cash App Pay Kit SDK Sample app for Android.
Kotlin
12
star
41

trifle

Security functionality for interoperability/interaction with core services.
Swift
11
star
42

AardvarkReveal

Generate and attach a Reveal file to your Aardvark bug reports
Swift
10
star
43

ln-invoice

Parse lightning network payment requests (invoices) in Kotlin.
Kotlin
10
star
44

kfactories

Set of factories and utils to create effective and lightweight property-based testing strategies.
Kotlin
9
star
45

jooq-encryption

Kotlin
9
star
46

hermit-ij-plugin

Kotlin
8
star
47

cash-app-pay-sdk-ios-sample-app

Swift
7
star
48

awsu

su for aws roles
Go
7
star
49

check-signature-action

Shell
6
star
50

csop

Go
6
star
51

AardvarkCrashReport

AardvarkCrashReport makes it easy to provide high quality data about crashes in your bug reports
Swift
6
star
52

activate-hermit

Github Action to activate a Hermit environment.
Shell
6
star
53

kruit

TypeScript
4
star
54

chronicler

Kotlin
3
star
55

hermit-build

Relocatable/static builds for Hermit packages
Makefile
3
star
56

s3-copy-gradle-plugin

1
star
57

.github

1
star
58

hermit-package-version

Shell
1
star
59

cash-app-pay-sandbox-releases

1
star