Start the migration from iron-router to flow-router

Motivations:

* Iron-Router foces us to use Tracker.nonreactive black magic in order
  to avoid un-necessary re-renders;
* There is a community consensus (supported by some MDG members) that
  the flow-router API is easier to reason about;
* The useraccounts now supports flow router (that was a blocking
  element when I considered the switch ~3months ago)

On the server we use the Picker router, as encouraged by the Kadira
team (which develop both Flow and Picker routers).

In the current state of things there are some bugs related to the
missing Loading architecure. Previously onRendered callback where
always called when the data the component needed was available, now
we have to handle this ourselves, which we will in a following commit.
This commit is contained in:
Maxime Quandalle 2015-08-22 22:59:03 +02:00
parent f315ee4430
commit d5eec54c72
22 changed files with 137 additions and 197 deletions

View file

@ -14,7 +14,7 @@ kenton:accounts-sandstorm
service-configuration service-configuration
useraccounts:core useraccounts:core
useraccounts:unstyled useraccounts:unstyled
useraccounts:iron-routing useraccounts:flow-routing
# Compilers # Compilers
mquandalle:jade mquandalle:jade
@ -32,8 +32,11 @@ reywood:publish-composite
# Utilities # Utilities
alethes:pages alethes:pages
arillo:flow-router-helpers
audit-argument-checks audit-argument-checks
iron:router kadira:blaze-layout
kadira:flow-router
meteorhacks:picker
meteorhacks:subs-manager meteorhacks:subs-manager
mquandalle:autofocus mquandalle:autofocus
mquandalle:bower mquandalle:bower

View file

@ -3,6 +3,7 @@ accounts-password@1.1.1
aldeed:collection2@2.3.3 aldeed:collection2@2.3.3
aldeed:simple-schema@1.3.3 aldeed:simple-schema@1.3.3
alethes:pages@1.8.4 alethes:pages@1.8.4
arillo:flow-router-helpers@0.4.3
audit-argument-checks@1.0.3 audit-argument-checks@1.0.3
autoupdate@1.2.1 autoupdate@1.2.1
base64@1.0.3 base64@1.0.3
@ -30,6 +31,7 @@ cfs:upload-http@0.0.20
cfs:worker@0.1.4 cfs:worker@0.1.4
check@1.0.5 check@1.0.5
coffeescript@1.0.6 coffeescript@1.0.6
cosmos:browserify@0.5.0
dburles:collection-helpers@1.0.3 dburles:collection-helpers@1.0.3
ddp@1.1.0 ddp@1.1.0
deps@1.0.7 deps@1.0.7
@ -43,16 +45,10 @@ htmljs@1.0.4
http@1.1.0 http@1.1.0
id-map@1.0.3 id-map@1.0.3
idmontie:migrations@1.0.0 idmontie:migrations@1.0.0
iron:controller@1.0.8
iron:core@1.0.8
iron:dynamic-template@1.0.8
iron:layout@1.0.8
iron:location@1.0.9
iron:middleware-stack@1.0.9
iron:router@1.0.9
iron:url@1.0.9
jquery@1.11.3_2 jquery@1.11.3_2
json@1.0.3 json@1.0.3
kadira:blaze-layout@2.0.0
kadira:flow-router@2.3.0
kenton:accounts-sandstorm@0.1.4 kenton:accounts-sandstorm@0.1.4
launch-screen@1.0.2 launch-screen@1.0.2
less@1.0.14 less@1.0.14
@ -65,6 +61,7 @@ meteor@1.1.6
meteor-platform@1.2.2 meteor-platform@1.2.2
meteorhacks:aggregate@1.2.1 meteorhacks:aggregate@1.2.1
meteorhacks:collection-utils@1.2.0 meteorhacks:collection-utils@1.2.0
meteorhacks:picker@1.0.3
meteorhacks:subs-manager@1.5.2 meteorhacks:subs-manager@1.5.2
meteorspark:util@0.2.0 meteorspark:util@0.2.0
minifiers@1.1.5 minifiers@1.1.5
@ -115,7 +112,8 @@ ui@1.0.6
underscore@1.0.3 underscore@1.0.3
url@1.0.4 url@1.0.4
useraccounts:core@1.12.2 useraccounts:core@1.12.2
useraccounts:iron-routing@1.12.2 useraccounts:flow-routing@1.12.2
useraccounts:unstyled@1.12.2 useraccounts:unstyled@1.12.2
webapp@1.2.0 webapp@1.2.0
webapp-hashing@1.0.3 webapp-hashing@1.0.3
zimme:active-route@2.3.1

View file

@ -1,21 +1,15 @@
//-
XXX This template can't be transformed into a component because it is
included by iron-router. That's a bug.
See https://github.com/peerlibrary/meteor-blaze-components/issues/44
template(name="board") template(name="board")
+boardComponent if Template.subscriptionsReady
if currentBoard
template(name="boardComponent") .board-wrapper(class=currentBoard.colorClass)
if this
.board-wrapper(class=colorClass)
.board-canvas( .board-canvas(
class=sidebarSize class=currentBoard.sidebarSize
class="{{#if MultiSelection.isActive}}is-multiselection-active{{/if}}" class="{{#if MultiSelection.isActive}}is-multiselection-active{{/if}}"
class="{{#if draggingActive.get}}is-dragging-active{{/if}}") class="{{#if draggingActive.get}}is-dragging-active{{/if}}")
if showOverlay.get if showOverlay.get
.board-overlay .board-overlay
.lists.js-lists .lists.js-lists
each lists each currentBoard.lists
+list(this) +list(this)
if currentCardIsInThisList if currentCardIsInThisList
+cardDetails(currentCard) +cardDetails(currentCard)
@ -24,6 +18,8 @@ template(name="boardComponent")
+sidebar +sidebar
else else
+message(label="board-no-found") +message(label="board-no-found")
else
+spinner
template(name="addListForm") template(name="addListForm")
.list.js-list.list-composer.js-list-composer .list.js-list.list-composer.js-list-composer

View file

@ -1,11 +1,17 @@
var boardSubsManager = new SubsManager();
BlazeComponent.extendComponent({ BlazeComponent.extendComponent({
template: function() { template: function() {
return 'boardComponent'; return 'board';
}, },
onCreated: function() { onCreated: function() {
this.draggingActive = new ReactiveVar(false); this.draggingActive = new ReactiveVar(false);
this.showOverlay = new ReactiveVar(false); this.showOverlay = new ReactiveVar(false);
// XXX The boardId should be readed from some sort the component "props",
// unfortunatly, Blaze doesn't have this notion.
boardSubsManager.subscribe('board', Session.get('currentBoard'));
}, },
openNewListForm: function() { openNewListForm: function() {
@ -67,7 +73,7 @@ BlazeComponent.extendComponent({
} }
}; };
if (! Meteor.userId() || ! Meteor.user().isBoardMember()) if (! Meteor.user() || ! Meteor.user().isBoardMember())
return; return;
self.$(lists).sortable({ self.$(lists).sortable({
@ -101,7 +107,8 @@ BlazeComponent.extendComponent({
// If there is no data in the board (ie, no lists) we autofocus the list // If there is no data in the board (ie, no lists) we autofocus the list
// creation form by clicking on the corresponding element. // creation form by clicking on the corresponding element.
if (self.data().lists().count() === 0) { var currentBoard = Boards.findOne(Session.get('currentBoard'));
if (currentBoard.lists().count() === 0) {
this.openNewListForm(); this.openNewListForm();
} }
}, },
@ -121,7 +128,7 @@ BlazeComponent.extendComponent({
} }
}]; }];
} }
}).register('boardComponent'); }).register('board');
BlazeComponent.extendComponent({ BlazeComponent.extendComponent({
template: function() { template: function() {

View file

@ -1,20 +1,20 @@
template(name="headerBoard") template(name="headerBoard")
h1.header-board-menu h1.header-board-menu
a(class="{{#if currentUser.isBoardAdmin}}js-edit-board-title{{else}}is-disabled{{/if}}") a(class="{{#if currentUser.isBoardAdmin}}js-edit-board-title{{else}}is-disabled{{/if}}")
= title = currentBoard.title
.board-header-btns.left .board-header-btns.left
unless isSandstorm unless isSandstorm
if currentUser if currentUser
a.board-header-btn.js-star-board(class="{{#if isStarred}}is-active{{/if}}" a.board-header-btn.js-star-board(class="{{#if isStarred}}is-active{{/if}}"
title="{{#if isStarred}}{{_ 'click-to-unstar'}}{{else}}{{_ 'click-to-star'}}{{/if}} {{_ 'starred-boards-description'}}") title="{{#if currentBoard.isStarred}}{{_ 'click-to-unstar'}}{{else}}{{_ 'click-to-star'}}{{/if}} {{_ 'starred-boards-description'}}")
i.fa(class="fa-star{{#unless isStarred}}-o{{/unless}}") i.fa(class="fa-star{{#unless currentBoard.isStarred}}-o{{/unless}}")
if showStarCounter if showStarCounter
span {{_ 'board-nb-stars' stars}} span {{_ 'board-nb-stars' currentBoard.stars}}
a.board-header-btn(class="{{#if currentUser.isBoardAdmin}}js-change-visibility{{else}}is-disabled{{/if}}") a.board-header-btn(class="{{#if currentUser.isBoardAdmin}}js-change-visibility{{else}}is-disabled{{/if}}")
i.fa(class="{{#if isPublic}}fa-globe{{else}}fa-lock{{/if}}") i.fa(class="{{#if currentBoard.isPublic}}fa-globe{{else}}fa-lock{{/if}}")
span {{_ permission}} span {{_ currentBoard.permission}}
.board-header-btns.right .board-header-btns.right
a.board-header-btn.js-open-filter-view( a.board-header-btn.js-open-filter-view(

View file

@ -1,16 +1,9 @@
//-
XXX This template can't be transformed into a component because it is
included by iron-router. That's a bug.
See https://github.com/peerlibrary/meteor-blaze-components/issues/44
template(name="boards")
+boardList
template(name="boardList") template(name="boardList")
if boards.count if boards.count
ul.board-list.clearfix ul.board-list.clearfix
each boards each boards
li(class="{{#if isStarred}}starred{{/if}}" class=colorClass) li(class="{{#if isStarred}}starred{{/if}}" class=colorClass)
a.js-open-board(href="{{ pathFor route='Board' boardId=_id }}") a.js-open-board(href="{{pathFor 'board' id=_id slug=slug}}")
span.details span.details
span.board-list-item-name= title span.board-list-item-name= title
i.fa.fa-star-o.js-star-board( i.fa.fa-star-o.js-star-board(

View file

@ -1,58 +0,0 @@
Meteor.subscribe('boards');
var boardSubsManager = new SubsManager();
Router.route('/boards', {
name: 'Boards',
template: 'boards',
authenticated: true,
onBeforeAction: function() {
Session.set('currentBoard', '');
Filter.reset();
this.next();
}
});
Router.route('/boards/:_id/:slug', {
name: 'Board',
template: 'board',
onAfterAction: function() {
// XXX We probably shouldn't rely on Session
Session.set('sidebarIsOpen', true);
Session.set('menuWidgetIsOpen', false);
},
waitOn: function() {
var params = this.params;
Session.set('currentBoard', params._id);
Session.set('currentCard', null);
return boardSubsManager.subscribe('board', params._id, params.slug);
},
data: function() {
return Boards.findOne(this.params._id);
}
});
Router.route('/boards/:boardId/:slug/:cardId', {
name: 'Card',
template: 'board',
noEscapeActions: true,
onAfterAction: function() {
Tracker.nonreactive(function() {
if (! Session.get('currentCard') && Sidebar) {
Sidebar.hide();
}
});
EscapeActions.executeUpTo('popup');
var params = this.params;
Session.set('currentBoard', params.boardId);
Session.set('currentCard', params.cardId);
},
waitOn: function() {
var params = this.params;
return boardSubsManager.subscribe('board', params.boardId, params.slug);
},
data: function() {
return Boards.findOne(this.params.boardId);
}
});

View file

@ -21,7 +21,7 @@ BlazeComponent.extendComponent({
// comment below provides further details. // comment below provides further details.
onRendered: function() { onRendered: function() {
var self = this; var self = this;
if (! Meteor.userId() || ! Meteor.user().isBoardMember()) if (! Meteor.user() || ! Meteor.user().isBoardMember())
return; return;
var boardComponent = self.componentParent(); var boardComponent = self.componentParent();

View file

@ -10,13 +10,13 @@ template(name="header")
#header-quick-access #header-quick-access
ul ul
li li
+linkTo(route="Boards") a(href="{{pathFor 'home'}}")
span.fa.fa-home span.fa.fa-home
| All boards | All boards
each currentUser.starredBoards each currentUser.starredBoards
li.separator - li.separator -
li(class="{{#if $.Session.equals 'currentBoard' _id}}current{{/if}}") li(class="{{#if $.Session.equals 'currentBoard' _id}}current{{/if}}")
+linkTo(route="Board" data=this) a(href="{{pathFor 'board' id=_id slug=slug}}")
= title = title
else else
li.current Star a board to add a shortcut in this bar. li.current Star a board to add a shortcut in this bar.

View file

@ -8,15 +8,15 @@ template(name="userFormsLayout")
section.auth-layout section.auth-layout
h1.at-form-landing-logo h1.at-form-landing-logo
img(src="/logo.png" title="LibreBoard") img(src="/logo.png" title="LibreBoard")
+yield +Template.dynamic(template=content)
template(name="defaultLayout") template(name="defaultLayout")
#surface #surface
+header +header
#content #content
+yield +Template.dynamic(template=content)
template(name="notfound") template(name="notFound")
+message(label='page-not-found') +message(label='page-not-found')
template(name="message") template(name="message")

View file

@ -0,0 +1,5 @@
Meteor.subscribe('boards');
Template.userFormsLayout.onRendered(function() {
EscapeActions.executeAll();
});

View file

@ -1,5 +0,0 @@
Router.route('/', {
name: 'Home',
redirectLoggedInUsers: true,
authenticated: true
});

View file

@ -162,7 +162,7 @@ Template.labelsWidget.events({
// fields of the current board document. // fields of the current board document.
var draggableMembersLabelsWidgets = function() { var draggableMembersLabelsWidgets = function() {
var self = this; var self = this;
if (! Meteor.userId() || ! Meteor.user().isBoardMember()) if (! Meteor.user() || ! Meteor.user().isBoardMember())
return; return;
self.autorun(function() { self.autorun(function() {

View file

@ -10,7 +10,7 @@ template(name="archivesSidebar")
| - | -
a.js-delete-card Delete a.js-delete-card Delete
if cardIsInArchivedList if cardIsInArchivedList
p.quiet.small (warning: this card is in an archived list) <br> p.quiet.small (warning: this card is in an archived list)
else else
p.no-items-message No archived cards. p.no-items-message No archived cards.

View file

@ -1,15 +0,0 @@
Router.route('/profile/:username', {
name: 'Profile',
template: 'profile',
waitOn: function() {
return Meteor.subscribe('profile', this.params.username);
},
data: function() {
var params = this.params;
return {
profile: function() {
return Users.findOne({ username: params.username });
}
};
}
});

View file

@ -9,20 +9,25 @@ AccountsTemplates.addFields([{
}, emailField, passwordField]); }, emailField, passwordField]);
AccountsTemplates.configure({ AccountsTemplates.configure({
defaultLayout: 'userFormsLayout',
defaultContentRegion: 'content',
confirmPassword: false, confirmPassword: false,
enablePasswordChange: true, enablePasswordChange: true,
sendVerificationEmail: true, sendVerificationEmail: true,
showForgotPasswordLink: true, showForgotPasswordLink: true,
onLogoutHook: function() { onLogoutHook: function() {
Router.go('Home'); var homePage = 'home';
if (FlowRouter.getRouteName() === homePage) {
FlowRouter.reload();
} else {
FlowRouter.go(homePage);
}
} }
}); });
_.each(['signIn', 'signUp', 'resetPwd', 'forgotPwd', 'enrollAccount'], _.each(['signIn', 'signUp', 'resetPwd', 'forgotPwd', 'enrollAccount'],
function(routeName) { function(routeName) {
AccountsTemplates.configureRoute(routeName, { AccountsTemplates.configureRoute(routeName);
layoutTemplate: 'userFormsLayout'
});
}); });
// We display the form to change the password in a popup window that already // We display the form to change the password in a popup window that already

View file

@ -1,44 +1,57 @@
// XXX Switch to Flow-Router? FlowRouter.route('/', {
var previousRoute; name: 'home',
triggersEnter: [AccountsTemplates.ensureSignedIn],
Router.configure({ action: function() {
loadingTemplate: 'spinner',
notFoundTemplate: 'notfound',
layoutTemplate: 'defaultLayout',
onBeforeAction: function() {
var options = this.route.options;
var loggedIn = Tracker.nonreactive(function() {
return !! Meteor.userId();
});
// Redirect logged in users to Boards view when they try to open Login or
// signup views.
if (loggedIn && options.redirectLoggedInUsers) {
return this.redirect('Boards');
}
// Authenticated
if (! loggedIn && options.authenticated) {
return this.redirect('atSignIn');
}
// We want to execute our EscapeActions.executeUpTo method any time the
// route is changed, but not if the stays the same but only the parameters
// change (eg when a user is navigation from a card A to a card B). Iron-
// Router onBeforeAction is a reactive context (which is a bad desig choice
// as explained in
// https://github.com/meteorhacks/flow-router#routercurrent-is-evil) so we
// need to use Tracker.nonreactive
Tracker.nonreactive(function() {
if (! options.noEscapeActions &&
! (previousRoute && previousRoute.options.noEscapeActions))
EscapeActions.executeAll(); EscapeActions.executeAll();
}); Filter.reset();
previousRoute = this.route; Session.set('currentBoard', '');
this.next(); BlazeLayout.render('defaultLayout', { content: 'boardList' });
} }
}); });
FlowRouter.route('/b/:id/:slug', {
name: 'board',
action: function(params) {
EscapeActions.executeAll();
Session.set('currentBoard', params.id);
Session.set('currentCard', null);
BlazeLayout.render('defaultLayout', { content: 'board' });
}
});
FlowRouter.route('/b/:boardId/:slug/:cardId', {
name: 'card',
action: function(params) {
Session.set('currentBoard', params.boardId);
Session.set('currentCard', params.cardId);
EscapeActions.executeUpTo('popup');
BlazeLayout.render('defaultLayout', { content: 'board' });
}
});
FlowRouter.notFound = {
action: function() {
BlazeLayout.render('defaultLayout', { content: 'notFound' });
}
}
// We maintain a list of redirections to ensure that we don't break old URLs
// when we change our routing scheme.
var redirections = {
'/boards': '/',
'/boards/:id/:slug': '/b/:id/:slug',
'/boards/:id/:slug/:cardId': '/b/:id/:slug/:cardId'
};
_.each(redirections, function(newPath, oldPath) {
FlowRouter.route(oldPath, {
triggersEnter: [function(context, redirect) {
redirect(FlowRouter.path(newPath, context.params));
}]
});
});

View file

@ -2,8 +2,8 @@ Utils = {
// XXX We should remove these two methods // XXX We should remove these two methods
goBoardId: function(_id) { goBoardId: function(_id) {
var board = Boards.findOne(_id); var board = Boards.findOne(_id);
return board && Router.go('Board', { return board && FlowRouter.go('board', {
_id: board._id, id: board._id,
slug: board.slug slug: board.slug
}); });
}, },
@ -11,7 +11,7 @@ Utils = {
goCardId: function(_id) { goCardId: function(_id) {
var card = Cards.findOne(_id); var card = Cards.findOne(_id);
var board = Boards.findOne(card.boardId); var board = Boards.findOne(card.boardId);
return board && Router.go('Card', { return board && FlowRouter.go('card', {
cardId: card._id, cardId: card._id,
boardId: board._id, boardId: board._id,
slug: board.slug slug: board.slug

View file

@ -131,7 +131,7 @@ Boards.helpers({
return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 }}); return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 }});
}, },
absoluteUrl: function() { absoluteUrl: function() {
return Router.path('Board', { boardId: this._id, slug: this.slug }); return FlowRouter.path('board', { id: this._id, slug: this.slug });
}, },
colorClass: function() { colorClass: function() {
return 'board-color-' + this.color; return 'board-color-' + this.color;

View file

@ -143,7 +143,7 @@ Cards.helpers({
}, },
absoluteUrl: function() { absoluteUrl: function() {
var board = this.board(); var board = this.board();
return Router.path('Card', { return FlowRouter.path('card', {
boardId: board._id, boardId: board._id,
slug: board.slug, slug: board.slug,
cardId: this._id cardId: this._id

View file

@ -30,23 +30,23 @@ if (isSandstorm && Meteor.isServer) {
// Redirect the user to the hard-coded board. On the first launch the user // Redirect the user to the hard-coded board. On the first launch the user
// will be redirected to the board before its creation. But thats not a // will be redirected to the board before its creation. But thats not a
// problem thanks to the reactive board publication. We used to do this // problem thanks to the reactive board publication. We used to do this
// redirection on the client side but that was sometime visible on loading, // redirection on the client side but that was sometimes visible on loading,
// and the home page was accessible by pressing the back button of the // and the home page was accessible by pressing the back button of the
// browser, a server-side redirection solves both of these issues. // browser, a server-side redirection solves both of these issues.
// //
// XXX Maybe sandstorm manifest could provide some kind of "home url"? // XXX Maybe sandstorm manifest could provide some kind of "home url"?
Router.route('/', function() { Picker.route('/', function(params, request, response) {
var base = this.request.headers['x-sandstorm-base-path']; var base = request.headers['x-sandstorm-base-path'];
// XXX If this routing scheme changes, this will break. We should generation // XXX If this routing scheme changes, this will break. We should generation
// the location url using the router, but at the time of writting, the // the location url using the router, but at the time of writting, the
// router is only accessible on the client. // router is only accessible on the client.
var path = '/boards/' + sandstormBoard._id + '/' + sandstormBoard.slug; var path = '/boards/' + sandstormBoard._id + '/' + sandstormBoard.slug;
this.response.writeHead(301, { response.writeHead(301, {
Location: base + path Location: base + path
}); });
this.response.end(); response.end();
}, { where: 'server' }); });
// On the first launch of the instance a user is automatically created thanks // On the first launch of the instance a user is automatically created thanks
// to the `accounts-sandstorm` package. After its creation we insert the // to the `accounts-sandstorm` package. After its creation we insert the

View file

@ -30,14 +30,12 @@ Meteor.publish('boards', function() {
}); });
}); });
Meteor.publishComposite('board', function(boardId, slug) { Meteor.publishComposite('board', function(boardId) {
check(boardId, String); check(boardId, String);
check(slug, String);
return { return {
find: function() { find: function() {
return Boards.find({ return Boards.find({
_id: boardId, _id: boardId,
slug: slug,
archived: false, archived: false,
// If the board is not public the user has to be a member of it to see // If the board is not public the user has to be a member of it to see
// it. // it.