• Stars
    star
    1,079
  • Rank 42,873 (Top 0.9 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 8 years ago

Reviews

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

Repository Details

Views as functions of their state.

Few.swift Carthage compatible

React-inspired library for writing AppKit/UIKit UIs which are functions of their state.1

SwiftBox is used for layout.

Why

UIs are big, messy, mutable, stateful bags of sadness.

Few.swift lets us express UIs as stateless, composable, immutable-ish values of their state. When their state changes, Few.swift calls a function to render the UI for that state, and then intelligently applies any changes.

To put it another way, the state is the necessary complexity of the app. The view is a mapping from state to its representation.

Example

Here's a simple example which counts the number of times a button is clicked:

// This function is called every time `component.updateState` is called.
func renderApp(component: Component<Int>, count: Int) -> Element {
	return View()
		// The view itself should be centered.
		.justification(.Center)
		// The children should be centered in the view.
		.childAlignment(.Center)
		// Layout children in a column.
		.direction(.Column)
		.children([
			Label("You've clicked \(count) times!"),
			Button(title: "Click me!", action: {
					component.updateState { $0 + 1 }
				})
				.margin(Edges(uniform: 10))
				.width(100),
		])
}

class AppDelegate: NSObject, NSApplicationDelegate {
	@IBOutlet weak var window: NSWindow!

	private let appComponent = Component(initialState: 0, render: renderApp)

	func applicationDidFinishLaunching(notification: NSNotification) {
		let contentView = window.contentView as NSView
		appComponent.addToView(contentView)
	}
}

Or a slightly more involved example, a temperature converter:

struct ConverterState {
	static let defaultFahrenheit: CGFloat = 32

	let fahrenheit = defaultFahrenheit
	let celcius = f2c(defaultFahrenheit)
}

private func c2f(c: CGFloat) -> CGFloat {
	return (c * 9/5) + 32
}

private func f2c(f: CGFloat) -> CGFloat {
	return (f - 32) * 5/9
}

private func renderLabeledInput(label: String, value: String, autofocus: Bool, fn: String -> ()) -> Element {
	return View()
		// Layout children in a row.
		.direction(.Row)
		.padding(Edges(bottom: 4))
		.children([
			Label(label).width(75),
			Input(
				text: value,
				placeholder: label,
				action: fn)
				// Autofocus means that the Input will become the first responder when
				// it is first added to the window.
				.autofocus(autofocus)
				.width(100),
		])
}

private func render(component: Component<ConverterState>, state: ConverterState) -> Element {
	let numberFormatter = NSNumberFormatter()
	let parseNumber: String -> CGFloat? = { str in
		return (numberFormatter.numberFromString(str)?.doubleValue).map { CGFloat($0) }
	}
	return View()
		// Center the view.
		.justification(.Center)
		// Center the children.
		.childAlignment(.Center)
		.direction(.Column)
		.children([
			// Each time the text fields change, we re-render. But note that Few.swift
			// is smart enough not to interrupt the user's editing or selection.
			renderLabeledInput("Fahrenheit", "\(state.fahrenheit)", true) {
				if let f = parseNumber($0) {
					component.updateState { _ in ConverterState(fahrenheit: f, celcius: f2c(f)) }
				}
			},
			renderLabeledInput("Celcius", "\(state.celcius)", false) {
				if let c = parseNumber($0) {
					component.updateState { _ in ConverterState(fahrenheit: c2f(c), celcius: c) }
				}
			},
		])
}

This is super cool because the only thing that's mutating is the state. Few.swift is in charge of making an in-place changes to the UI when the state changes.

See FewDemo for some more involved examples.

How does this compare to React Native/ComponentKit?

A few of the most notable differences:

  1. Few.swift is written in... Swift. Type safety is cool.
  2. Single-threaded. React Native and ComponentKit both do layout on a non-main thread. Few.swift keeps everything on the main thread currently.
  3. Both React Native and ComponentKit are battle-tested. They've been used in shipping apps. Few.swift has not.
  4. React Native has an awesome live reload feature.

Quirks

Swift's pretty buggy with concrete subclasses of generic superclasses: https://gist.github.com/joshaber/0978209efef7774393e0. This hurts.

Should I use this?

Probably 🍩. See above about how it's not battle-tested yet. Pull requests welcome 💖.

--

1. React, but for Cocoa. A reactive Cocoa, one might say.

More Repositories

1

SwiftBox

Flexbox in Swift, using Facebook's css-layout.
Swift
810
star
2

clojurem

Clojure to Objective-C compiler
Clojure
284
star
3

JAListView

An NSTableView replacement that doesn't suck.
Objective-C
249
star
4

MacShairport

A native Mac Shairport implementation
Objective-C
176
star
5

RACSignupDemo

A ReactiveCocoa signup view
Objective-C
68
star
6

JAViewController

A subclass of NSViewController that's actually useful
Objective-C
62
star
7

Freezer

Database as a value.
Objective-C
54
star
8

ReederDemo

Demo of how Reeder's push/pop animation works
Objective-C
39
star
9

ts2re

Convert TypeScript type declarations to Reason
OCaml
34
star
10

Marketplace

Craigslist, without the ugly.
Objective-C
25
star
11

MoreAnimation

MoreAnimation is a super lazy, super dumbed-down re-implementation of Core Animation.
Objective-C
23
star
12

JAAnimatingContainer

Easier animations
Objective-C
17
star
13

TwUIPushPopTest

A navigation controller test using TwUI
Objective-C
17
star
14

PagesDemo

How to re-create the Pages window zoom animation
Objective-C
12
star
15

Octodo

Your todo list, with Octocats.
Objective-C
11
star
16

MAUIKit

MAUKit was a start at making a modern, gloriously layer-based Mac UI framework.
Objective-C
9
star
17

FloatingViewDemo

Objective-C
8
star
18

CourierDemo

Demo of Courier's envelope animation
Objective-C
7
star
19

this-is-a-cool-project

And it does cool things!
6
star
20

JAWeakReferenceHaterProxy

NSWindowController hating on your weak references? No worries friend.
Objective-C
6
star
21

bucklescript-react-test

OCaml
5
star
22

Temperature

A Cocoa integration test suite
Objective-C
5
star
23

simple-server

It's simple!
JavaScript
3
star
24

WTFXcode

An attempt at making an Xcode plugin
Objective-C
3
star
25

potential-potato

2
star
26

simple-rails-server

Ruby
2
star
27

almost-empty

2
star
28

auto-pretty

JavaScript
2
star
29

empty

2
star
30

simple-docker-compose

1
star
31

no-more-hotdogs

Dockerfile
1
star
32

mean-dad

Dockerfile
1
star
33

haze

JavaScript
1
star
34

joshaber.github.io

CSS
1
star
35

garbage

1
star
36

empty_repo

...so lonely
1
star
37

jupyter-test

Jupyter Notebook
1
star
38

all-maroon

JavaScript
1
star
39

tunnels-test

TypeScript
1
star
40

atom-types

Type declarations. For Atom.
1
star