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

- Ryan
Recent Tweets @theryanjduffy
Gravatar is an service that allows users to specify a public avatar image linked to an email address. I recently decided to allow users to use their Gravatar avatar with my Parse-backed app rather than build in my own avatar system. To simplify things, I’ve hooked beforeSave for the User object to hash the email address and add it to the object. That ensures that any email address change is automatically hashed on the server and allows me to send the hash down to clients rather than the email address to protect privacy.

function MD5(s){ /* one of many publicly available MD5 functions */ }

Parse.Cloud.beforeSave(Parse.User, function(request, response) {
    var email = request.object.get("email");
    request.object.set("emailHash", email? MD5(email) : "");
    response.success();
});

Obviously you can add appCache to existing apps but there are a couple things I think the framework could add here. First, let’s get the appcache events wired into enyo’s event model.

if(window.applicationCache) { enyo.dispatcher.listen(window.application, “updateReady”); // there are other cache states. updateReady seems to be the most useful one }
Second, let’s enhance bootplate to include an appcache manifest in the index.html. Open to naming preferences. Also, provide the default manifest file. Here’s a first cut
CACHE MANIFEST # these will be cached CACHE: index.html build/enyo.js build/app.js build/enyo.css build/app.css assets/* # these resources will always be pulled from the network NETWORK: # /api # these resources will be loaded if the requested fails FALLBACK: # tryFirst.html useOnFail.html
Third, let’s update the build scripts to (optionally) auto-update root/*.appcache with a build time so the manifest is reloaded whenever the app is built. Perhaps a hash of the contents of the build folder instead?

I’ve been playing around with the Cloud9 IDE a bit recently to do some remote development. It’s come a long way from when I first used it and is quite functional. A great addition is an interactive command line with a git client. So I thought, “It’d be nice to get the EnyoJS bootplate up and running here.” Following the general instructions from the wiki, I put together a set of commands that gets everything set up.

TL; DR

Pull in bootplate, update the submodules, and “disconnect” the master branch from the bootplate repo.

git clone https://github.com/enyojs/bootplate.git; rm -rf .git; shopt -s dotglob; mv bootplate/* .; git remote rename origin bootplate; git submodule update --init; printf "\n.c9*" >> .gitignore; git add .gitignore; git config --unset branch.master.remote; git config --unset branch.master.merge;

Assuming your pushing this to a new git repo (on Github or Bitbucket for example), add the remote repo and set the master branch to track it.


git remote add origin 
git fetch origin; git branch --set-upstream master origin/master

Here’s the first command broken up for readability:


# clone the bootplate repo
git clone https://github.com/enyojs/bootplate.git

# remove the existing git config (it'll be overwritten by bootplate)
rm -rf .git

# move the bootplate contents to the root folder (including the .git directory)
shopt -s dotglob
mv bootplate/* .

# rename the origin branch so your repo can be origin
git remote rename origin bootplate

# update the submodules
git submodule update --init

# add .c9* to .gitignore so the cloud9 revision tracker isn't added to git
printf "\n.c9*" >> .gitignore
git add .gitignore

# make master not track the remote bootplate repo
git config --unset branch.master.remote
git config --unset branch.master.merge

Since there seemed to be a little interest in my gist for create() override, I put together a few others that might be useful and dropped them into a new github repo. I also included a build system to kick off tools/deploy if you’re using bootplate.

If you have Package Control, you can add the github repo as a custom repository and then install the package. If not, you can download the source/clone the repo into your Packages folder for Sublime.

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;
            }
        }
    }
});