Materialize Highs and Lows

Written by Pete Corey on Mar 25, 2015.

After reading Nick Wientge’s great post on using the Materialize framework to add Material Design ideals to your Meteor project, I was eager to jump on board.

The CSS and static component side of the Materialize framework is fantastic! After a few hours, I had converted a Bootstrap project over to a more Material Design inspired aesthetic, complete with schnazzy animations and transitions.

Unfortunately, I began to hit a few roadblocks when I started combining Materialize’s javascript components with reactive data from Meteor.

Form Select

The application I was converting to Materialize made heavy use of reactively populated select elements. I figured the transition to Materialize would be as simple as calling material_select when the select was rendered:

Template.select.rendered = function() {
    this.$('select').material_select();
};

But, since Materialize mirrors the options data in a hidden list in the DOM, we’ll need to re-initialize the select plugin every time the data changes. No problem:

Template.select.rendered = function() {
    this.autorun(function() {
        this.data.options; //autorun trigger goes here
        this.$('select').material_select();
    });
};

And, it doesn’t work! At least with the most current Materialize release at the time of this post (v0.95.3). In v0.95.3, re-running the material_select plugin will not re-generate the options list, even if new options have been added to the select. Thankfully, this has been reported as a bug and subsequently fixed, but you’ll need to grab to latest code for yourself to make use of the fix.

These issues can also be entirely avoided by adding the browser-default class to your select. This will cause Materialize to not mirror your select’s options in the DOM and use a styled version of the native select instead. Reactivity will work out of the box, as it would for any other select element.

Collapsible Elements

Collapsible elements also have issues with dynamic content. Collapsible elements are initialized by calling the collapsible plugin on the collapsible list. This will turn all of the child list items into collapsible containers:

<template name="collapsible">
    <ul class="collapsible">
        {{#each items}}
            <li>
                <div class="collapsible-header">{{header}}</div>
                <div class="collapsible-body">{{body}}</div>
            </li>
        {{/each}}
    </ul>
</template>
Template.collapsible.rendered = function() {
    this.$('.collapsible').collapsible();
};

But what happens when another item is added to items? We’ll need to re-initialize the collapsible plugin:

Template.select.rendered = function() {
    this.autorun(function() {
        this.data.items; //autorun trigger goes here
        this.$('.collapsible').collapsible();
    });
};

Unfortunately, this doesn’t work exactly as we expected. While the new item is collapsible, re-initializing the plugin also closes all currently open items. If we dig into the source, we can see why this happens.

Let’s take a look at the “expandable” data path. When the plugin is initialized, it loops over each collapsible-header and checks its active status. If it is active, it calls expandableOpen. Take a look.

expandableOpen toggles the active class on the collapsible-header’s parent (li), and then checks its value. If it is active, it expands the container, otherwise it collapses it. Check it out. The re-initialize issue happens because the parent li already has the active class for previously initialized items. When we toggle the class, we inadvertently close the container.

The accordion data path is a little more complicated, but the same general issue exists.

I’ve created an issue and a pull request to fix this issue with the collapsible plugin. Go open source!

Final Thoughts

Materialize is a great front-end framework. It allowed me to quickly and easily build a Material Design style application.

That being said, I don’t think it’s the best fit for a Meteor application. I’m not interested in dealing with the unnecessary complexity of managing the initialization and re-initialization of each of my components as they’re reactively added to the DOM.

At the end of the day, I believe I’m better off using Polymer as a static component library to build my Material Design applications.

User Fields and Universal Publications

Written by Pete Corey on Mar 16, 2015.

How do you specify which fields are published to the client’s Meteor.users collection? Using universal publications, obviously(1)! Let’s take a look at Meteor’s universal, or unnamed, publications and see how they’re used to accomplish this.

Put simply, a universal, or unnamed, publication is a publication without a name. That may not seem very special at first, but it raises some interesting questions in terms of functionality within the framework.

If a publication has no name, how do I subscribe to it?

You don’t! Universal publications are immediately and unconditionally started by the server and every connected client receives their data. Don’t take my word for it, it’s in the docs:

Name of the record set. If null, the set has no name, and the record set is automatically sent to all connected clients.

If I don’t subscribe to it, how do I know when the subscription is ready?

You don’t! The server never sends ready messages for universal publications. Universal publications just march to the beat of a different drummer.

What if I want to universally publish multiple collections?

Go for it! You can define as many universal publications as you’d like. Meteor does not check for duplicates like it does with named publications.

This does lead to an interesting point about multiple universal publications for a single collection. Imagine that a package, like accounts-base, sets up a universal publication for the Meteor.users collection. Let’s pretend that this publication only returns the profile, username and emails fields for each user.

What if we create another universal publication for the Meteor.users collection that returns some other set of user fields like username and roles?

Meteor.publish(null, function() {
    if (this.userId) {
        return Meteor.users.find(
            {_id: this.userId},
            {fields: {username: 1, roles: 1}});
    } else {
        return null;
    }
});

Interestingly enough, Meteor will run both of these publish handlers and publish the union of the fields returned by each. In our case, profile, username, emails and roles would all be published to the client!

So there’s the answer to our question. How do we publish more fields to the Meteor.users collection? By creating a universal publication that publishes only the fields that we depend on.

Why don’t we just use named publications?

A named publication that publishes additional fields from the Meteor.users collection will work, but you run the risk of accidentally dropping your subscription to that publication. I recently spend some time tracking down a fairly complicated bug in the Orion framework that dealt with this exact issue.

The Orion admin panel defined an adminUsers publication that published additional fields on the Meteor.users collection. It used these additional fields to determine if the current user had permission to view or modify content. The subscription to adminUsers was maintained by SubsManager.

SubsManager only keeps around a certain number of subscriptions before dropping older subscriptions to make room for new ones. After navigating through the Orion admin panel for a few minutes, the old adminUsers subscription was dropped to make room for a new subscription, which caused the Meteor.users collection to fall back to universal publication defined by accounts-base.

This universal publication wasn’t publishing fields required by Orion (isAdmin, permission), so the Orion client was forced to assume that the client wasn’t authorized to view the current page.

The issue was fixed by creating a new universal publication in the Orion core package that returned the isAdmin and permission fields that the client depended on.

(1) This is not an obvious answer.

Meteor Composability

Written by Pete Corey on Mar 9, 2015.

Last week I had the chance to give a talk at the Meteor San Diego Meetup. My goal was to give some techniques and ideas for building component based Meteor applications. You can check out the slides here and read my write-up below!

What do AngularJS, Polymer and React all have in common? They emphasize building complex web applications by combining and composing together simple, independent components. By “component”, I mean a stand-alone piece of functionality (usually) tied to a visual element. Because they’re responsible only for their own view and functionality and communicate with the outside world through an established interface, they’re very easy to understand and digest. Once you start building applications as compositions of components, you’ll start to see them everywhere!

So how about Meteor? Can we build component based web applications with our favorite framework? Templates and inclusion tags are presented as the go-to system for building components in Meteor in just about every beginner resource and in the official docs. In fact, as a beginner I believed that this was the only way to pull templates into my application.

As I began to build more complex applications, I quickly began to realize that this simple template inclusion just wasn’t cutting it. A modal dialog is a fantastic example to illustrate the issues I was having with this system. Suppose I had a basic modal component. It’s purpose was to render content in a container centered on the screen, and to de-emphasise the rest of the content on the page. When the user clicks outside of the content container, the modal would be dismissed.

If I only had one modal in my application, a naive approach would be to create a single template and include it with inclusion tag syntax:

{{> modal}}

What if I wanted other content in the modal? Maybe I would pass it in through the data context:

{{> modal content="This is my content"}}

What if I wanted more complex content? Like a sign-out button? I may either add a flag to my data context, or create an entirely new modal template:

{{> modal content="Content..." signout=true}}
{{> signoutModal content="Content..."}}

If you take the first route, the complexity of your modal template will soon spiral out of control. The modal now has to concern itself with the complexities of the data it contains, along with the complexities of just being a modal. If you go the second route, you’ll quickly have an explosion of modal-esque templates. A change to your modal’s behavior would require updating each of these templates, instead of making your change in a single place. Both of these scenarios are far from ideal.

Custom Block Helpers

Thankfully, there is a solution! Deep within the Spacebars readme, you’ll find a section on custom block helpers. Custom block helpers give us a new syntax for pulling templates into our application, and even allow us to pass content into our templates. Within our template we can use standard inclusion tag syntax to pull in a special block, Template.contentBlock, which injects the content we’ve passed into our template into the DOM at this point. If you’re familiar with AngularJS, you’ll notice that this is very similar to the ng-transclude directive.

Using custom block helpers, we can build a more powerful modal template:

<body>
    {{#modal}}
        <h1>Hello!</h1>
        <p>I'm modal content!</p>
    {{/modal}}
</body>

<template name="modal">
    <div class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                {{> Template.contentBlock}}
            </div>
        </div>
    </div>
</template>
if (Meteor.isClient) {
    Template.modal.rendered = function() {
        $('.modal').modal();
    };
}

Now, our modal template is only concerned with being a modal. The template sets up the DOM structure required to create a Bootstrap modal and instantiates the modal when it’s rendered. It doesn’t have to concern itself with the complexities of the content you want to place inside of it.

Dynamic Template Includes

We can elevate our modal template to the next level by leveraging another powerful Meteor feature, dynamic template includes. Dynamic templates includes let us provide the name of the template we want to include along with a data context at runtime, rather than at compile time.

What if we wanted to define custom content for our modal’s header, content container and footer? With dynamic template includes, it’s easy:

<template name="modal">
    <div class="modal fade" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    {{> Template.dynamic
                        template=header
                        data=headerData}}
                </div>
                {{> Template.dynamic
                    template=content
                    data=contentData}}
                <div class="modal-footer">
                    {{> Template.dynamic
                        template=footer
                        data=footerData}}
                </div>
            </div>
        </div>
    </div>
</template>
<body>
    {{> modal
        header='myHeader'
        content='myContent'
        footer='myFooter'}}
</body>

<template name="myHeader">
    <em>This is the header</em>
</template>

<template name="myContent">
    <p>This is where the content goes.</p>
    <p>There can be multiple elements.</p>
</template>

<template name="myFooter">
    <button>Footer!</button>
</template>

While it is a little more work defining our modal content in templates instead of in-line, it makes our modal template much more powerful and versatile.

Build Your Own Data Context

Our new modal template even allows us to explicitly pass data contexts into our content templates. Check out how we would pass a data context into our footer template:

<body>
    {{> modal
        header='myHeader'
        content='myContent'
        footer='myFooter' footerData=getFooterData}}
</body>
Template.body.helpers({
    getFooterData: function() {
        return {
            runInFooterContext: function() {
                console.log('in footer');
            },
            runInBodyContext: function() {
                console.log('in body');
            }.bind(this)
        };
    }
});

Template.myFooter.events({
    'click button': function() {
        this.runInFooterContext();
        this.runInBodyContext();
    }
});

In this example, we’re building our footer’s data context in a helper method on the body template. This data context has two methods: runInFooterContext and runInBodyContext. When the button in the footer template is clicked, we call both of these functions.

An interesting trick that can be used when juggling data contexts is that methods bound to the current data context can be passed into a child template’s data context. In this example, the runInBodyContext function is bound to the body’s data context before it’s passed into the footer template. When it’s accessed and called within the footer data context, it is executed under the body’s data context.

Final Thoughts

I hope this gave you a few ideas for building more component based systems with Meteor. Check out the slide deck for this talk, and let me know if you have any feedback or questions!