Brief episodes of technology, often in the presentation layer (webOS, html5, javascript, portals, etc) space.

- Ryan
Recent Tweets @theryanjduffy
Posts tagged "enyo 2"

I have a couple extensions to Enyo that are in varying degrees of maturity that could use some external feedback and development. Below is a summary of each. If you’re using these, something similar, or have some thoughts on where they should go, I’d like to work with you to improve them. Feel free to comment below, catch me on twitter @theryanjduffy or send an email to ryan@tiqtech.com.

View State Framework
The view state framework is a relatively simple but extensible mechanism to manage the state of view controls. The definition of view control is loose but is intended to represent any control on which a user might expect to be able to “go back” to a previous state.

More …

RemoteControl
Retrieves a remote JS file and attempts to instantiate the specified kind as a child component. Provides a pluggable loading spinner. Seems like a building block for a single-page app (sub)framework but that needs some more thought.

More …

Platform-Aware Controls
Pattern/framework to enable native-feeling apps across different platforms by providing generalized components for common interactions.

More …

Wanted to share a preview of a new kind I’ve been working on. The idea stemmed from a recent patch I submitted to fix remote loading of js into enyo. A prime use case for that capbility is to deliver a mobile website in which the entire site could be integrated into a single enyo app without loading the entire source on load. Each view could be managed by a parent enyo.Panels and loaded as requested. To support this idea, I created a new kind called enyo.RemoteControl. In short, it has a load() method that retrieves a remote JS file and attempts to instantiate the specified kind as a child component. To configure what to load, the kind has 2 design-time parameters: href to specify the URL and remoteKind to specify the “kind” to create. It also supports fit which tells the RemoteControl to apply the enyo-fit class to the new child. Finally, it provides a scrim and spinner which displays while the script is fetched and the kind is rendered. This can be overriden through the scrimKind member.

enyo.kind({
	name:"enyo.RemoteControlScrim",
	kind:"onyx.Scrim",
	classes:"onyx-scrim-translucent",
	style:"text-align:center",
	showing:false,
	components:[
		{kind:"onyx.Spinner", style:"position:absolute;top:50%;margin-top:-30px;display:inline-block"}
	]
});

enyo.kind({
	name: "enyo.RemoteControl",
	kind: "Control",
	loadState: 0,
	scrimKind:"enyo.RemoteControlScrim",
	published:{
		animate:true
	},
	events:{
		onLoad:"",
		onLoadFailed:""
	},
	components:[
		{name:"ani", kind:"Animator", startValue:65, endValue:1, onStep:"aniStep", onStop:"aniStop", onEnd:"aniStop"}
	],
	getScrim:function() {
		// defer scrim creation ...
		return this.$.scrim || this.createComponent({name:"scrim", kind:this.scrimKind || "Control", owner:this}).render();
	},
	refresh: function() {
		this.setLoadState(0);
		this.load();
	},
	setLoadState:function(state) {
		this.loadState = state;
		if(this.loadState == 1) {
			this.getScrim().show();
		} else if(this.loadState == 2) {	// what about errors?
			if(this.animate) {
				this.$.ani.play();
			} else {
				this.aniStop();
			}
		}
	},
	load: function() {
		if(this.href && this.loadState == 0) {
			this.setLoadState(1);
			//enyo.job(this.id+"_load", enyo.bind(this, function() {
				enyo.load([this.href], enyo.bind(this, "loaded"));
			//}), 2000);
		}
	},
	loaded: function(block) {
		// should be null unless my pull is changed to always created the failed member
		if(!block.failed || block.failed.length === 0) {
			this.setLoadState(2);
			this.remote = this.createComponent({kind:this.remoteKind, classes:(this.fit) ? "enyo-fit" : ""}).render();

			this.doLoad({remote:this.remote});
		} else {
			this.setLoadState(-1);
			this.doLoadFailed({failed:block.failed});
		}
	},
	aniStep:function(source) {
		this.getScrim().applyStyle("opacity", source.value/100)
	},
	aniStop:function(source) {
		this.getScrim().hide();
	}
});
To see it in action, check out this fiddle which can remotely load several of the enyo samples as well as allowing you to provide your own details.

Update: Latest code available on github

The view state framework is a relatively simple but extensible mechanism to manage the state of view controls. The definition of view control is loose but is intended to represent any control on which a user might expect to be able to “go back” to a previous state. The framework is not a view controller in MVC fashion but can be adapted to that purpose. I’ve done just that by extending the enyo.Panels control.

The view state framework has 3 components: enyo.ViewState, an implementation of ViewStateStrategy, and the consumer control.

ViewState is the consumer API for the framework and consists of a single property, path, and two events, onSaveState and onRestoreState. Each instance of ViewState must declare a unique path (in the traditional /path/to/me format) but all paths need not be at the same depth. The intent is that you could have a view (path:”/home”) that contains additional views (path:”/home/items”) and their paths would represent that heirarchy. In addition to the semantic value, this also allows the framework to persist and restore states of any parent paths of the saved path. So, if you tell ViewState to save the state of /home/items, it will also trigger a save of /home via the onSaveState. Similarly, if the state of /home/items is restored, the state of /home is also restored (via onRestoreState).

The management of view states is done through ViewStateStrategy instances. The ViewStateStrategy kind is basically an abstract base kind. It implements the API for strategies and provides some useful boilerplate code but doesn’t store the state anywhere. The base API has three methods: push, pop, and register. As you might guess, push and pop are responsible for saving and restoring state, respectively. The register method associates a path with an instance of ViewState. This registration enables the magic of cascading save and restore described above.

To get things started, I implemented a couple ViewStateStrategy instances that work well in the browser: HashViewStateStrategy and HistoryViewStateStrategy. HashViewStateStrategy leverages the window.location.hash to store state and window.onhashchange to trigger state restoration. To accomplish this, it includes a portion of the state data (the key member) in the hash following the path. It then parses the key out onhashchange and passes it back to the ViewState owner in the onRestoreState event.

HistoryViewStateStrategy extends HashViewStateStrategy but uses the history API to store the state. This allows for more state data to be saved but still falls back to the key in the hash in absence of that state. This ensures that bookmarking the URL could still restore the application correctly.

N.B. I tried a couple alteratives that leveraged the component heirarchy before landing on the register method approach. Event bubbling seemed to be the most promising but introduced a couple problems. One, events would bubble up from a ViewState to ancestor controls but couldn’t waterfall down to aunt/uncle (to continue the metaphor) controls. It’s easier to explain with a picture but, since it didn’t work out, I won’t bother. Second, it forced the path heirachy to match the control heirarchy. That’s probably safe normally but didn’t seem like a necessary constraint.

The consumer of ViewState has very little work. It must:

  • create an instance of ViewState and provide it a unique path,
  • call enyo.ViewState.save when it wishes to save the state,
  • provide a handler for onRestoreState to update the control with the saved state, and
  • optionally, provide a handler for onSaveState if other ViewState instances have a child path defined

That’s it!

More documentation to come but check out the example to see it in action.

Thoughts/suggestions/questions? Let me know here or on twitter @theryanjduffy.

By default, tapping a row in an Enyo list will “select” it. Sometime you might want finer-grained control over when selection happens and this post will offer a means to accomplish just that.

Selection is managed by an instance of enyo.Selection which is owned by the List control. You can control how selection behaves via two passthrough properties on the List control: toggleSelected and multiSelect.

toggleSelected is false by default which means tapping the row will always select it. By setting toggleSelected to false, tapping the row will toggle the selection back and forth. multiSelect is also false by default which means only one row will be selected at a time. By setting it to true, you can select multiple row (surprising, I know).

When a row is selected or deselected, it is rerendered by the List and your onSetupItem handler is called. In addition to an index property, the event will also have a selected property that reflects the current selection state of the row. Alternatively, if you need to retrieve the selection state of the entire list, you can call getSelection() on the List to get a handle on its underlying Selection instance.

Perhaps you’ve decided to include interactive controls in your list item such as a checkbox or button and have decided that tapping those shouldn’t trigger row selection. Preventing the selection can use the same technique as triggering the selection: the tap method.

FlyweightRepeater does all the work for rendering list items using the flyweight pattern. It also implements a tap() method to catch any taps on child nodes to trigger selection. So, if you want to prevent selection, all you have to do is return true in your ontap handler to cancel bubbling thereby preventing the selection trigger.

What if you had several buttons and only wanted one control (like a checkbox) to control selection? Turns out that any subkind of Control can override tap() to handle ontap events (even without specifying an entry in your handlers hash!) because Control already declares the handler. So, if you create a custom kind which implements tap() to return true, selection will never be triggered. By adding a little exception logical to tap(), you can decide when selection occurs rather than on every tap.

Here’s a working example:


enyo.kind({
    name:"SimpleRow",
    kind:"Control",
    classes:"simple-row",
    published:{
        title:""
    },
    components:[
        {name:"cb", kind:"Button", content:"Select", ontap:"cbTapped"},
        {name:"title"}
    ],
    create:function() {
        this.inherited(arguments);
        this.titleChanged();
    },
    titleChanged:function() {
        this.$.title.setContent(this.title);
    },
    cbTapped:function(source, event) {
        // nothing magical about this property, just made it up
        event.allowBubble = true;
    },
    tap:function(source, event) {
        if(event.allowBubble) {
            event.allowBubble = false;
        } else {
            // cancel bubble without my special flag
            return true;
        }
    }
});

enyo.kind({
    name:"ex.App",
    components:[
        {kind:"List", toggleSelected:true, count:25, onSetupItem:"setupItem", components:[
            {name:"sr", kind:"SimpleRow"}
        ]}
    ],
    setupItem:function(source, event) {
        this.$.sr.setTitle("Item " + event.index);this.$.sr.addRemoveClass("selected", event.selected);
    }
});

new ex.App().renderInto(document.body);
​
Here’s a quick and easy way to make a scrollable multi-line input field.

{kind: "extras.InputDecorator", alwaysLooksFocused:true, style:"width:100%;height:400px", components: [
    {kind:"Scroller", style:"height:100%;width:100%", components:[
        {name:"content", kind: "onyx.RichText", richContent:false, onchange: "inputChange", style:"min-height:100%"}
    ]}
]}
​

You have to set the height of the input decorator (either explicitly or as a fit:true child of a FittableRows instance) as well as the width (either by setting the width or changing it to display:block). By setting the min-height of the RichText control, you ensure that anywhere the user clicks in the area, the control will get focus but it will still expand if the user adds more content than the screen holds.

Live example on jsfiddle.net

N.B. I’ve used my extras.InputDecorator for the alwaysLooksFocused property but it works the same with vanilla onyx.InputDecorator.

Here’s a quick way to adapt the Panels CarouselArranger to peek the previous panel.  By setting peekWidth on the Panels instance, this modified arranger will offset the left by that amount.  It isn’t a perfect implementation (e.g. you can see the prior panel in the background when you slide the current panel away) but it would probably work in many cases.

For simplicity, the kind inherits from CarouselArranger.  I’ve only modified the arrangeNoWrap method so the contents are virtually copied verbatim.  Look for peek to find the customizations.

enyo.kind({
    name: "extras.CarouselArranger",
    kind: "enyo.CarouselArranger",
    arrangeNoWrap: function(inC, inName) {
        var peek = this.container.peekWidth || 0;
        var c$ = this.container.children;
        var s = this.container.clamp(inName);
        var nw = this.containerBounds.width;
        // do we have enough content to fill the width?
        for (var i=s, cw=0, c; c=c$[i]; i++) {
            cw += c.width + c.marginWidth;
            if (cw > nw) {
                break;
            }
        }
        // if content width is less than needed, adjust starting point index and offset
        var n = nw - cw;
        var o = 0;
        if (n > 0) {
            var s1 = s;
            for (var i=s-1, aw=0, c; c=c$[i]; i--) {
                aw += c.width + c.marginWidth;
                if (n - aw <= 0) {
                    o = (n - aw);
                    s = i;
                    break;
                }
            }
        }
        // arrange starting from needed index with detected offset so we fill space
        for (var i=0, e=this.containerPadding.left + o + peek, w, c; c=c$[i]; i++) {
            w = c.width + c.marginWidth;
            if (i === s-1) {
                this.arrangeControl(c, {left: -w+peek});
            } else if (i < s) {
                this.arrangeControl(c, {left: -w});
            } else {
                this.arrangeControl(c, {left: Math.floor(e)});
                e += w;
            }
        }
    }
});

This is very much beta code but wanted to share how to add history to the Enyo2 Panels control.  For flavor, I even added html5 history support so if you’re using a Panels controls as the main view controller (like Pane in Enyo1), you get quick back button support.

Here’s the code as well as a quick example (full screen and in jsfiddle):

enyo.kind({
    name:"extras.Panels",
    kind:"enyo.Panels",
    published:{
        history:""
    },
    create:function() {
        this.historyChanged();
        this.inherited(arguments);
        this.createComponent({kind:"Signals", onBack:"back", onpopstate:"statePopped"});
        enyo.dispatcher.listen(window, "popstate");
    },
    historyChanged:function() {
        this.history = this.history || [];
    },
    back:function() {
        this.history.pop(); // current
        if(this.history.length > 0) {
            var last = this.history.pop();
            this.setIndex(last);
        }
    },
    indexChanged:function() {
        this.inherited(arguments);
        if(this.history[this.history.length-1] !== this.index) {
            this.pushState();
        }
    },
    pushState:function() {
        if(window.history.pushState) {
            var c = this.getControls();
            window.history.pushState({index:this.index}, "", "#"+c[this.index].name);
        }
        this.history.push(this.index);
    },
    statePopped:function(source, event) {
        if(event.state) {
            this.back();
        }
    }
});

If you’re looking to support other browsers, you might check out history.js which appears to be a nice polyfill for the history API.

In enyo v1, making an input control appear focused was easy: simply set alwaysLooksFocused to true.  In enyo v2, the styling is delegated to an InputDecorator but it doesn’t provide this same property.  Fortunately, it’s easy to add to a custom subkind.

enyo.kind({
	name:"extras.InputDecorator",
	kind:"onyx.InputDecorator",
	published:{
		alwaysLooksFocused:false,
	},
	create:function() {
		this.inherited(arguments);
		this.alwaysLooksFocusedChanged();
	},
	alwaysLooksFocusedChanged:function() {
		this.addRemoveClass("onyx-focused", this.alwaysLooksFocused);
	},
	receiveBlur:function() {
		if(!this.alwaysLooksFocused) {
			this.inherited(arguments);
		}
	}
});