Giter VIP home page Giter VIP logo

few.swift's Introduction

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.

few.swift's People

Contributors

joshaber avatar adlai-holler avatar

Watchers

Josh Holtz avatar James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.