• Stars
    star
    192
  • Rank 202,019 (Top 4 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 13 years ago
  • Updated over 3 years ago

Reviews

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

Repository Details

CALayer-style API for building rich, high-performance UI graphics in WebKit

UILayer

UILayer provides a JavaScript API on top of WebKit for working with the concept of layers. Instead of manipulating DOM elements using a myriad of mixed concepts, you go though a single, well defined API.

Demo and example

Note: UILayer only works in WebKit-based environments, such as web views on Apple iOS, OS X and Android or in web browsers like Google Chrome and Safari.

Here's a simple example: A layer inside another layer which moves 50px to the right when touched, rotating the inner layer like a wheel:

layer1 = UILayer({ x:10, y:10, width:300, height:300, animated:true });
layer2 = UILayer({ x:50, y:50, width:200, height:200, animated:true });
layer1.addSublayer(layer2);
layer1.backgroundColor = 'salmon'
layer1.on('touchstart', function () {
  layer1.frame.x += 50
  layer2.rotation.z += 20
});
document.body.appendChild(layer1.element)

Try it (written in Move) β†’
Try it (written in JavaScript) β†’

Usage

If you use Move, either use the precompiled uilayer.js or use the Move source files in the "src" directory directly.

If you don't use Move, use uilayer-standalone.js JavaScript library.

<script src="https://raw.github.com/rsms/uilayer/master/uilayer-standalone.js"></script>
<script>
var UILayer = Move.require('UILayer');
...
</script>

You can also build a JavaScript library from the source files (requires move >=0.4.4):

move compile -d src -o uilayer.js

API

UILayer(x, y, z, width, height, scale, frame, element, animated, style, sublayers, ..) β†’ layer

Create a new UILayer with optional initial properties.

Geometry

layer.frame ⇄ UIFrame {x:number, y:number, z:number, width:number, height:number}

The position and size of the layer in the coordinate space of its parent layer.

The returned UIFrame object is a mutable proxy which when modified affects the layer. That is you can do layer.frame.x = 10 to move the layer to x position 10, rather than frame = layer.frame; frame.x = 10; layer.frame = frame.

Providing a width and/or height of 0 (zero) makes the layer span the width and/or height of it's parent.

layer.anchor ⇄ object | string

Layer anchor defined in superlayer coordinates controls which edges of the superlayer the layer is attached to, or originates from. Defaults to {top:0, left:0}.

This property always returns an object (never a string) which might contain any or none of the following values:

{ top:number|string, right::number|string,
  bottom:number|string, left:number|string}

If a value is undefined, that edge is not part of the layers anchor.

Example of having a layer originating from the bottom right corner of its superview:

layer.anchor = 'bottom right'
print layer.anchor  # -> { bottom: 0, right: 0 }

Example of having a layer originating from the bottom right corner of its superview with an offset of 20 pixels:

layer.anchor = {bottom:20, right:20}
print layer.anchor  # -> { bottom: 20, right: 0 }

Example of making a layer span the entire width of its superlayer, automatically being resized as the superlayer's frame size changes (note that we do not specify a frame size):

layer = UILayer {anchor:'top right bottom left'}

Example of creating a layer that spans the width of its superlayer, attached to the bottom:

layer = UILayer {anchor:'left bottom right', height:100}

Example: examples/anchor.html

layer.moveBy(x, y:0, z:0)

Modify position of the layer.

layer.rotation ⇄ Rotation {x:number, y:number, z:number}

Rotation of the layer. Defaults to {x:0, y:0, z:0}. The returned object is a proxy, meaning it's possible to manipulate the values directly (e.g. layer.rotation.x = 45). Angles are expressed in degrees (0-360).

When setting this value (rather than manipulating the returned proxy object), you only need to pass the values which you would like to modify. There's also a single "change:rotation" event emitted, rather than one even per axis, as implied by manipulating the proxy object.

Example of rotating a layer around its Z-axis (spinning like a wheel):

layer.rotation.z = 45

Example of setting several axis, causing a single change event to be emitted:

layer.rotation = {x:20, z:45}

Example: examples/rotation.html

layer.scale ⇄ number (0-inf]

Scale of the layer. Defaults to 1.0 (100%).

layer.scaleBy(x, y:0, z:0)

Modify scale of the layer.

layer.transformOrigin ⇄ [x, y, z]

Defines the transformation origin of the layer's bounds rectangle. Affects how transformations like scale and rotation behaves. Animatable.

Described in the unit coordinate space. Defaults to (0.5, 0.5, 0), the center of the bounds rectangle.

Example: examples/transformOrigin.html

layer.zPosition ⇄ number

Layers with a larger zPosition will be placed in front of those with a smaller one. Defaults to 0.

Style attributes

UILayer.debug ⇄ bool

If set to true, new layers will be assigned a random semi-opaque background color, aiding in development. Defaults to false.

Example: examples/debug.html

layer.doubleSided ⇄ bool

Determines whether the receiver is displayed when facing away from the viewer. Defaults to false.

layer.cornerRadius ⇄ number

Specifies a radius used to draw the rounded corners of the receiver’s background. Defaults to 0.

Note: cornerRadius does not affect hit testing.

layer.backgroundColor ⇄ string

The background color of the layer. Defaults to "transparent" (no background color).

Accepts any CSS 3 color value as a string, including:

Also accepts (but will canonicalize) arrays of relative RGBA values:

  • R, G, B, A -- [0-1, 0-1, 0-1, 0-1]
  • R, G, B -- [0-1, 0-1, 0-1]
  • RGB, A -- [0-1, 0-1]
  • RGB -- [0-1]

layer.color ⇄ string

Foreground (text) color of the layer. Defaults to the inherited value (from the environment, i.e. default browser style or host website style).

Accepts any CSS 3 color value as a string. See description of layer.backgroundColor for more information.

layer.opacity ⇄ number [0-1]

Opacity of the layer. Defaults to 1 (fully opaque).

layer.hidden ⇄ bool

Hide or show the layer. Defaults to false.

A hidden view disappears from its window and does not receive input events. It remains in its superview’s list of sublayers, however, and participates in autoresizing as usual. Hiding a view with sublayers has the effect of hiding those sublayers and any view descendants they might have. This effect is implicit and does not alter the hidden state of the receiver’s descendants.

If you want to know if a layer is in a DOM tree (no matter if it's visible), see layer.document.

layer.computedStyle β†’ Style

Returns a style object defining the layers computed style (equivalent to window.computedStyle for an element).

layer.style ⇄ Style

The explicit (CSS) style of the layer.

layer.masksToBounds ⇄ bool

Determines whether sublayers are confined to the bounds of the receiver. Defaults to false.

Setting this value to true causes sublayers to be clipped to the bounds of the receiver. If set to false, sublayers whose frames extend beyond the visible bounds of the receiver are not clipped.

Example: examples/masksToBounds.html

layer.perspective ⇄ number

Used to give an illusion of depth; it determines how layers change size based on their z-offset from the z=0 plane. You can think of it as though you're looking at the page from a distance p away. Layers on the z=0 plane appear in their normal size. Something at a z offset of p/2 (halfway between the viewer and the z=0 plane) will look twice as big, and something at a z offset of -p will look half as big. Thus, large values give a little foreshortening effect, and small values lots of foreshortening. Values between 500 and 1000 give a reasonable-looking result for most content.

Defaults to "none" (i.e. "no perspective" or "orthographic projection").

The default origin for the perspective effect is the center of the layer, but you can control this with perspectiveOrigin.

Example: examples/perspective.html

layer.perspectiveOrigin ⇄ [x, y, z]

Perspective origin. Defaults to [0.5, 0.5, 0].

layer.preserve3d ⇄ bool

When set to false (the default value), transformed sublayers are flattened into the plane of their superlayer (think of the 3D transform as simply a painting effect). However, when setting this to true, the layer to which it is assigned does not flatten its sublayers into it; instead, those sublayers live in a shared 3D space with the superlayer.

Animation

layer.animated ⇄ bool | string

Animate property changes. Defaults to false.

The value true indicates all properties should be animated. A string value signifies only a subset of properties should be animated. For instance:

  • "all" -- animate all properties. Equivalent to true
  • "geometry" -- animate changes to geometry
  • "opacity" -- animate changes to opacity

You can define a list of CSS properties to be animated by separating them with a comma. E.g. a value of "width, height, opacity" would cause frame size and opacity to be animated, but not scale, position, etc.

Example:

layer = UILayer {x:0, y:0, width:100, height:100}
layer.animated = true
layer.on 'touchstart', ^{ layer.frame.x += 100 }
# Layer moves 100 px to the right during 500ms when touched

layer.animationDuration ⇄ number (0-inf]

Duration in milliseconds of animations implied by changing properties. Only effective if layer.animated is set to true.

Example:

layer = UILayer {x:0, y:0, width:100, height:100}
layer.animated = true
layer.animationDuration = 200
layer.on 'touchstart', ^{ layer.frame.x += 100 }
# Layer moves 100 px to the right during 200ms when touched

layer.animationTimingFunction ⇄ string

Available timing functions:

  • "linear" – The linear function just returns as its output the input that it received.
  • "ease" – The default function, ease, is equivalent to cubic-bezier(0.25, 0.1, 0.25, 1.0).
  • "ease-in" – The ease-in function is equivalent to cubic-bezier(0.42, 0, 1.0, 1.0).
  • "ease-out" – The ease-out function is equivalent to cubic-bezier(0, 0, 0.58, 1.0).
  • "ease-in-out" – The ease-in-out function is equivalent to cubic-bezier(0.42, 0, 0.58, 1.0)
  • "cubic-bezier(x1, y1, x2, y2)" – Specifies a cubic-bezier curve whose P0 and P3 points are (0,0) and (1,1) respectively. The four values specify points P1 and P2 of the curve as (x1, y1, x2, y2).

Example:

layer = UILayer {x:0, y:0, width:100, height:100}
layer.animated = true
layer.animationTimingFunction = 'ease-out'
layer.frame.x = 100
# Layer moves 100 px to the right during 500ms,
# slowing down in the end

Custom drawing

layer.drawContent ⇄ ^{...}

Provide a function to perform custom drawing of the layer's content. This function will be invoked every time the frame size changes or the layer is added to the DOM.

Note: A layer that implements custom drawing can not have sublayers.

Example of drawing a triangle:

layer = UILayer {width:300, height:300, drawContent:^{
  g = @graphicsContext2D
  g.strokeStyle = 'red'
  g.moveTo 50,50
  g.lineTo 250,50
  g.lineTo 150,250
  g.lineTo 50,50
  g.stroke()
}}

Example: examples/drawContent.html

layer.graphicsContext2D β†’ CanvasRenderingContext2D

The 2D drawing context for a layer with a drawContent implementation.

See HTML Canvas 2D Context for reference.

layer.graphicsContext3D β†’ CanvasRenderingContext3D

The 3D (WebGL) drawing context for a layer with a drawContent implementation.

See WebGL Specification for reference.

Layer hierarchy

layer.superlayer β†’ layer

Parent layer.

layer.sublayers β†’ [layer, ..]

A list of all sublayers (other layers that are owned by, or live within, the layer).

layer.firstSublayer β†’ layer

First sublayer (equivalent to layer.sublayers[0] but better performing in cases where a layer have many sublayers).

layer.addSublayer(layer:sublayer) β†’ sublayer

Add a layer as a sublayer to the receiving layer. Returns the same sublayer that was passed as input.

layer.removeSublayer(layer:sublayer, index:number) β†’ sublayer

Remove a sublayer by reference or index. Returns the sublayer removed or undefined if no matching sublayer was found.

layer.removeAllSublayers() β†’ [layer, ..]

Remove all sublayers. Returns the layers that was removed.

layer.removeFromSuperlayer()

Removes the layer from the superlayer.

layer.isSublayerOf(layer:superlayer) β†’ bool

Test if a layer is a sublayer of another layer.

Hit testing

UILayer.hitTest(x, y) β†’ layer

Returns the farthest descendant of the layer hierarchy that contains a specified point.

Example: examples/hitTest.html

layer.excludedFromHitTesting ⇄ bool

Controls whether the layer is included in hit testing. Defaults to true. Setting this to false causes the layer to stop accepting user input -- such as touches and clicks -- and also being ignored by UILayer.hitTest.

DOM

layer.element β†’ HTMLElement

The DOM node which is used to represent the layer in the document. Can be assigned during creation, but not later.

layer.ownerDocument β†’ HTMLDocument

The DOM document which this layer is owned by (created by). Note that a layer always have a ownerDocument, even if it's not in a DOM tree.

layer.document β†’ HTMLDocument

The DOM document which this layer is currently presented in, if any. You can use this to test if the layer is part of the DOM tree or not.

If you just want to know if a layer is visible or not, see layer.hidden.

Handling events

layer.on(type:string, handler:^(event)) β†’ handler

Register handler to be triggered each time event is emitted on the receiving layer. type can be any string, including DOM Level 3 events and custom, arbitrary events.

layer.removeEventListener(type:string, handler:^(event)) β†’ bool

Remove an event handler.

layer.emit(type, bubbles:true, cancelable:true, ...) β†’ bool

layer.emit(type, {bubbles:true, cancelable:true, ...}) β†’ bool

Emit (or: trigger/raise/send) an event on the receiving layer.

type can be any string, including DOM Level 3 events and custom, arbitrary events. All arguments or options (in positional call-style) except "type" will be added to the event object that is then sent to all listening event handlers.

Example:

layer.on 'my-custom-event', ^(ev) {
  print 'my-custom-event triggered with foo:', ev.foo
}
layer.emit 'my-custom-event', { foo:'Hello' }

Performance and edge-cases

layer.is3DBacked β†’ bool

Indicates whether the layer is backed by high-performance 3D rendering or not.

Identifying the layer at runtime

layer.tag ⇄ string

Assign a document-wide unique tag to this layer. This will effectively set id="tag" on the underlying element.

Example: examples/tag.html

UILayer.layerWithTag(tag:string) β†’ layer

Find a layer anywhere in the document which has the specified tag.

Events

A layer can emit any DOM Level 3 Events as well as arbitrary, user-defined events. Listed below are the UILayer-specific events.

uilayer:added-to-superlayer {superlayer:UILayer}

The receiving layer was added as a sublayer to another layer (superlayer).

uilayer:removed-from-superlayer {superlayer:UILayer}

The receiving layer was removed from a layer (superlayer).

uilayer:added-sublayer {sublayer:UILayer}

A sublayer was added to the receiving layer.

uilayer:removed-sublayer {sublayer:UILayer}

A sublayer was removed from the receiving layer.

change:frame {oldValues:{x:, y:, z:, width:, height:}}

Emitted when layer.rotation changed. The oldValues object contains the old values of changes properties.

change:rotation {oldValues:{x:, y:, z:}}

Emitted when layer.rotation changed. The oldValues object contains the old values of changes properties.

More Repositories

1

inter

The Inter font family
Python
16,727
star
2

peertalk

iOS and Mac Cocoa library for communicating over USB
Objective-C
3,424
star
3

fb-mac-messenger

⚑️ Mac app wrapping Facebook's Messenger for desktop
Objective-C
2,856
star
4

kod

Programmers' editor for OS X [DEAD PROJECT]
Objective-C
2,296
star
5

node-imagemagick

Imagemagick module for NodeJS β€” NEW MAINTAINER: @yourdeveloper
JavaScript
1,807
star
6

markdown-wasm

Very fast Markdown parser and HTML generator implemented in WebAssembly, based on md4c
C
1,446
star
7

gotalk

Async peer communication protocol & library
Go
1,193
star
8

estrella

Lightweight and versatile build tool based on the esbuild compiler
TypeScript
1,098
star
9

raster

Raster β€” simple CSS grid system
CSS
806
star
10

js-lru

A fast, simple & universal Least Recently Used (LRU) map for JavaScript
JavaScript
774
star
11

sol

A sunny little virtual machine
C
516
star
12

scrup

Take a screenshot (in OS X) β€” paste the URL somewhere a second later
Objective-C
405
star
13

chromium-tabs

[historical] Chromium tabs for cocoa applications (project no longer maintained)
Objective-C
388
star
14

wasm-util

WebAssembly utilities
TypeScript
353
star
15

figplug

Figma plugin builder
TypeScript
336
star
16

cocui

Cocoa meets WebKit for more rapid UI development
Objective-C
329
star
17

ec2-webapp

A template I use to quickly set up Node.js-backed web apps on Amazon EC2
324
star
18

llvmbox

Self contained, fully static llvm tools & libs
C
317
star
19

move

A simple, functional-biased, prototypal and powerful programming language that runs on any ES3 (or better) JavaScript platform, aimed toward people new to programming
JavaScript
302
star
20

immutable-cpp

Persistent immutable data structures for C++
C++
281
star
21

rsm

Virtual computer
C
267
star
22

compis

Contemporary systems programming language in the spirit of C
C
196
star
23

sublime-theme

My Sublime Text theme
Python
187
star
24

scripter

The Scripter Figma plugin
JavaScript
178
star
25

hue

A functional programming language
C++
170
star
26

gitblog

Git-based blog/cms for PHP, meant as a replacement for Wordpress
PHP
164
star
27

co

A programming language in early development
TypeScript
147
star
28

graphviz

Graphviz web app
JavaScript
118
star
29

LazyDispatch

Thin API and concept on top of libdispatch (aka Grand Central Dispatch) for Cocoa Objective-C code.
Objective-C
102
star
30

afcgi

Asynchronous/multiplexing FastCGI for nginx (incl. ref server implementation)
C
101
star
31

rsms-utils

Collection of CLI programs to help with everyday computer life
Shell
99
star
32

colang

Programming language and compiler β€”WORK IN PROGRESSβ€”
C
71
star
33

xsys

A well-defined system API for abstracting the OS platform
C
68
star
34

figma-plugins

Collection of Figma plugins
TypeScript
67
star
35

mkweb

simple static website generator
JavaScript
63
star
36

fontkit

JS & WASM library for working with fonts
C
62
star
37

js-object-merge

3-way JavaScript Object merging -- Object.merge(v1, v1a, v1b) -> v2
JavaScript
54
star
38

tc

Tokyo Cabinet Python bindings β€” In need of a new maintainer
C
54
star
39

smolmsg

Simple messages
Go
54
star
40

js-wasmc

Simplifies building of WebAssembly modules in C/C++ and JS
JavaScript
53
star
41

sigi-pixel-font

Sigi pixel fonts [archived]
52
star
42

WebView-OSX-Screensaver

WebKit web view as a screensaver on OS X
Objective-C
52
star
43

Go.tmbundle

TextMate bundle for the Go programming language
51
star
44

oui

Web-app client-server framework developed as part of dropular.net
JavaScript
49
star
45

wlang

Programming language in development
C
47
star
46

smisk

High performance web service framework, written in C but controlled by Python. Used by Spotify infra 2009–2015.
Python
45
star
47

memex

Software for archiving my digital stuff like tweets
Go
45
star
48

workenv

My personal work environment
Emacs Lisp
44
star
49

ckit

The little C kit
C
44
star
50

dropub

DroPub β€” drop and publish. Simple OS X MenuItem managing secure transfer of files in the background
Objective-C
42
star
51

serve-http

Simple, safe single-file local web server
JavaScript
42
star
52

go-uuid

Binary sortable universally unique identifier
Go
38
star
53

ghp

Go Hypertext Preprocessor
Go
38
star
54

TypoFig

Mac app for assisting type design in Figma
Objective-C
38
star
55

opencv-face-track-basics

Basic code for tracking faces and eyes using OpenCV
C++
37
star
56

qemu-macos-x86-arm64

Run arm64 Linux Alpine virtualized on macOS x86_64 with QEMU
Shell
35
star
57

tspkg

Create small, fast and easily-distributable packages from TypeScript projects
JavaScript
34
star
58

go-immutable

Immutable data structures for Go
Go
34
star
59

webkit-editor

Experimental text editor which runs in the browser
JavaScript
32
star
60

html5-video

Video player in HTML5
JavaScript
30
star
61

hovden-stitch

A typeface weekend project from 2002 with a classic "stitching"/"embroidery" look
30
star
62

jo

Go-style JavaScript ES6 compiler and packager, based on Babel
JavaScript
30
star
63

libcss-osx

Building libcss as Mac OS X universal binary. Developed as part of Kod (rsms/kod)
Objective-C
29
star
64

tumblr-theme-hunch

The theme used on my blog
28
star
65

dawn-lib

Builds Dawn on Linux and macOS as one single easier-to-use library
Shell
28
star
66

browser-require

CommonJS module require() for web browsers
JavaScript
25
star
67

jsont

A minimal and portable JSON tokenizer for building highly effective and strict parsers (in C and C++)
C
25
star
68

prog-lang-tutorial

JavaScript
25
star
69

node-fsdocs

Simple, ACID and versioned file-system based document database
JavaScript
25
star
70

js-fragment

Client-side templating for modern thinkers
JavaScript
24
star
71

node-couchdb-min

Simplistic CouchDB client with a minimal level of abstraction and connection pooling.
JavaScript
24
star
72

fontctrl

Font manager, keeping font files up to date with a distributed repository model
Go
23
star
73

web-clipboard-promise

Demonstrates lazily-evaluated clipboard data on the Web platform
JavaScript
22
star
74

bezier-tangent

BΓ©zier curve toy
JavaScript
22
star
75

twitter-icon

Alternative icon for Twitter.app
21
star
76

dropular-2010

Redacted snapshot of dropular.net, May 2010
JavaScript
21
star
77

dawn-wire-example

[WIP] Demo of a minimal but functional Dawn-based WebGPU client and server
C++
21
star
78

phpab

Abstract Base – universal PHP runtime library
PHP
18
star
79

NodeCocoa

Embed node.js in Cocoa or write whole Cocoa apps in node.js
Objective-C
17
star
80

ortho-remote

Some code for playing with the Teenage Engineering Ortho Remote
Objective-C
16
star
81

ml-kern

Kerning done by machines (a project to learn more about ML)
JavaScript
16
star
82

asl-logging

Convenience functions and example code for using ASL (Apple System Log facility)
C
14
star
83

js-miniglob

Minimal glob JavaScript implementation ported from Go's path/filepath
JavaScript
13
star
84

hunch-cocoa

An assortment of Cocoa β€” mixed extensions and additions to Cocoa
Objective-C
13
star
85

wasm-loader

WebAssembly module loader with import resolution
TypeScript
12
star
86

cgui

super duper simple gui for C, wrapping imgui and stb
C
12
star
87

cmdr

Helps writing command-line programs with subcommands in Go
Go
12
star
88

spotifycocoa

Cocoa framework of libspotify
Objective-C
12
star
89

macfusion

Fork of http://svn.macfusionapp.org/macfusion2/trunk/ β€” With mainly UI changes like menu item icon and OS-standard volume icons) β€” Download latest release build: http://cloud.github.com/downloads/rsms/Macfusion/Macfusion.zip
Objective-C
12
star
90

hunch-upload

Multiple concurrent files uploads with progress in pure HTML
JavaScript
11
star
91

functional.js

Work in a functional style with JavaScript and TypeScript
JavaScript
11
star
92

coxlang

Programming language w/ subproject that implements the Go scheduler in C++
C++
11
star
93

lolcatos

The lolcat operating system
Assembly
11
star
94

cometps

Simple comet pub/sub
C
9
star
95

node-imgdb

Image fingerprinting
C++
8
star
96

ssl-client-auth-demo

Demonstrates "client-authenticated TLS handshake"
Shell
8
star
97

connect_facebook

Facebook session support for Connect
8
star
98

mode

Node module manager and repository
JavaScript
8
star
99

flup

Drag-and-drop to quickly put images on Flickr
Objective-C
8
star
100

ipvec

Educational persistent vector implementation in C
C
8
star