Skip to content
This repository has been archived by the owner on Sep 10, 2022. It is now read-only.

Commit

Permalink
Moving to a JSON api rather html partials. Renaming a few bits and bobs
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Gaunt authored and addyosmani committed Nov 24, 2015
1 parent 3ba5808 commit 4cd9621
Show file tree
Hide file tree
Showing 14 changed files with 124 additions and 105 deletions.
9 changes: 3 additions & 6 deletions gulp-tasks/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,13 @@ gulp.task('service-worker', function(cb) {
],
dynamicUrlToDependencies: {
'/app-shell': ['server/views/layouts/app-shell.handlebars'],
'/partials/': [
'server/views/layouts/partial.handlebars',
'/api/': [
'server/views/index.handlebars'
],
'/partials/url-1': [
'server/views/layouts/partial.handlebars',
'/api/url-1': [
'server/views/url-1.handlebars'
],
'/partials/url-2': [
'server/views/layouts/partial.handlebars',
'/api/url-2': [
'server/views/url-2.handlebars'
]
},
Expand Down
8 changes: 5 additions & 3 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@

var serverController = require('./controllers/server-controller');
var StaticPageController = require('./controllers/static-page-controller');
var PartialsController = require('./controllers/partials-controller');
var APIController = require('./controllers/api-controller');

// PartialsController serves up the HTML without any HTML body or head
serverController.addEndpoint('/partials*', new PartialsController());
// APIController serves up the HTML without any HTML body or head
serverController.addEndpoint('/api*', new APIController(
serverController.getHandleBarsInstance()
));
// The static page controller serves the basic form of the pages
serverController.addEndpoint('/*', new StaticPageController());
53 changes: 53 additions & 0 deletions server/controllers/api-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

var path = require('path');

var pathConfigs = require('../models/path-config.js');

function APIController(handlebarsInstance) {
this.handlebarsInstance = handlebarsInstance;
}

// This method looks at the request path and renders the appropriate handlebars
// template
APIController.prototype.onRequest = function(req, res) {
var urlSections = req.path.split('/');
urlSections = urlSections.filter(function(sectionString) {
return sectionString.length > 0;
});

var urlPath = null;
if (urlSections.length === 1) {
urlPath = '/';
} else {
urlPath = '/' + urlSections[1];
}

var pathConfig = pathConfigs.getConfig(urlPath);
if (!pathConfig) {
res.status(404).send();
return;
}

var viewPath = path.join(
__dirname,
'/../views',
pathConfig.data.view + '.handlebars'
);

this.handlebarsInstance.render(viewPath, pathConfig)
.then(function(renderedTemplate) {
res.json({
title: pathConfig.data.title,
partialinlinestyles: pathConfig.data.inlineStyles,
partialremotestyles: pathConfig.data.remoteStyles,
partialscripts: pathConfig.data.remoteScripts,
partialhtml: renderedTemplate
});
})
.catch(function(err) {
res.status(500).send();
});
};

module.exports = APIController;
34 changes: 0 additions & 34 deletions server/controllers/partials-controller.js

This file was deleted.

19 changes: 12 additions & 7 deletions server/controllers/server-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ var exphbs = require('express-handlebars');

function ServerController() {
var expressApp = express();
var expressServer = this.setUpServer(expressApp);
var handleBarsInstance = exphbs.create({
defaultLayout: 'default',
layoutsDir: path.join(__dirname, '/../views/layouts'),
partialsDir: path.join(__dirname, '/../views/partials')
});
var expressServer = this.setUpServer(expressApp, handleBarsInstance);

this.getExpressApp = function() {
return expressApp;
Expand All @@ -13,16 +18,16 @@ function ServerController() {
this.getExpressServer = function() {
return expressServer;
};

this.getHandleBarsInstance = function() {
return handleBarsInstance;
};
}

ServerController.prototype.setUpServer = function(app) {
ServerController.prototype.setUpServer = function(app, handleBarsInstance) {
// Set up the use of handle bars and set the path for views and layouts
app.set('views', path.join(__dirname, '/../views'));
app.engine('handlebars', exphbs({
defaultLayout: 'default',
layoutsDir: path.join(__dirname, '/../views/layouts'),
partialsDir: path.join(__dirname, '/../views/partials'),
}));
app.engine('handlebars', handleBarsInstance.engine);
app.set('view engine', 'handlebars');

// Define static assets path - i.e. styles, scripts etc.
Expand Down
2 changes: 1 addition & 1 deletion server/controllers/static-page-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ StaticPageController.prototype.onRequest = function(req, res) {
return;
default:
// Use default layout
res.render(pathConfig.view, pathConfig);
res.render(pathConfig.data.view, pathConfig);
return;
}
};
Expand Down
10 changes: 7 additions & 3 deletions server/models/path-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,31 @@ var path = require('path');
var pathConfigs = {
'/': {
view: 'index',
title: 'Index',
inlineStyles: getFileContents(['/styles/core.css']),
remoteStyles: ['https://fonts.googleapis.com/css?family=Roboto:' +
'400,300,700,500,400italic'],
remoteScripts: ['/scripts/static-page.js']
},
'/url-1': {
view: 'url-1',
title: 'URL 1',
inlineStyles: getFileContents(['/styles/core.css']),
remoteStyles: ['https://fonts.googleapis.com/css?family=Roboto:' +
'400,300,700,500,400italic'],
remoteScripts: ['/scripts/static-page.js']
},
'/url-2': {
view: 'url-2',
title: 'URL 2',
inlineStyles: getFileContents(['/styles/core.css']),
remoteStyles: ['https://fonts.googleapis.com/css?family=Roboto:' +
'400,300,700,500,400italic'],
remoteScripts: ['/scripts/static-page.js']
},
'/app-shell': {
view: '',
title: 'App Shell',
inlineStyles: getFileContents(['/styles/core.css']),
remoteStyles: ['https://fonts.googleapis.com/css?family=Roboto:' +
'400,300,700,500,400italic'],
Expand Down Expand Up @@ -53,8 +57,8 @@ module.exports = {
return null;
}

// This needed to ensure changes made to the objects dont stick / alter
// the original object
return Object.create(object);
return {
'data': object
};
}
};
9 changes: 0 additions & 9 deletions server/views/layouts/partial.handlebars

This file was deleted.

6 changes: 3 additions & 3 deletions server/views/partials/async-css.handlebars
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{{#if remoteStyles}}
{{#if data.remoteStyles}}
<script>
var remoteStyles = [
{{#each remoteStyles}}
{{#each data.remoteStyles}}
'{{this}}',
{{~/each}}
];
Expand All @@ -26,7 +26,7 @@

<!-- In case the browser has JS disabled -->
<noscript>
{{#each remoteStyles}}
{{#each data.remoteStyles}}
<link href="{{this}}" rel="stylesheet" property="stylesheet" media="all">
{{~/each}}
</noscript>
Expand Down
2 changes: 1 addition & 1 deletion server/views/partials/close-page.handlebars
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

{{> async-css }}

{{#each remoteScripts}}
{{#each data.remoteScripts}}
<script src="{{this}}" async></script>
{{~/each}}
</body>
Expand Down
4 changes: 2 additions & 2 deletions server/views/partials/open-page.handlebars
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ limitations under the License.
<html>
<head>
<meta charset="utf-8">
<title>App Shell</title>
<title>{{data.title}}</title>

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
Expand All @@ -29,7 +29,7 @@ limitations under the License.
<link rel="manifest" href="/manifest.json">
<link rel="icon" href="/images/chrome-touch-icon-192x192.png" sizes="192x192" type="image/png">

<style type="text/css">{{{inlineStyles}}}</style>
<style type="text/css">{{{data.inlineStyles}}}</style>
</head>
<body>

Expand Down
8 changes: 4 additions & 4 deletions src/old-sw.es6.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ self.oninstall = function(event) {
'/favicon.ico',
'/manifest.json',

'/partials/',
'/partials/url-1',
'/partials/url-2',
'/partials/index'
'/api/',
'/api/url-1',
'/api/url-2',
'/api/index'
];

urls = urls.map(function(url) {
Expand Down
10 changes: 5 additions & 5 deletions src/scripts/controller/ApplicationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import Controller from './Controller';
import RouterSingleton from '../libs/RouterSingleton';
import ActivityController from './ActivityController';
import PageController from './PageController';
import NavDrawerView from './../view/NavDrawerView';

export default class ApplicationController extends Controller {
Expand Down Expand Up @@ -51,10 +51,10 @@ export default class ApplicationController extends Controller {
}

var router = RouterSingleton.getRouter();
router.addRoute('/', new ActivityController());
router.addRoute('/url-1', new ActivityController());
router.addRoute('/url-2', new ActivityController());
router.setDefaultRoute(new ActivityController());
router.addRoute('/', new PageController());
router.addRoute('/url-1', new PageController());
router.addRoute('/url-2', new PageController());
router.setDefaultRoute(new PageController());
router.requestStateUpdate();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default class ActivityController {
export default class PageController {
constructor() {
this.loader = document.querySelector('.js-global-loader');
this.mainContainer = document.querySelector('.js-global-main');
Expand All @@ -16,41 +16,42 @@ export default class ActivityController {

this.updateNavDrawer(path);

fetch('/partials' + path)
fetch('/api' + path)
.then((response) => {
if (response.status === 404) {
this.show404();
return null;
}

return response.text();
return response.json();
})
.then((responseText) => {
if (responseText !== null) {
/**
* NOTE: We could move the script tags in the partial to the
* bottom of the body, but I don't think it'll change browser
* behaviour so it should be fine to inline the script tag in
* the main element.
**/

// Parse the response string
var parser = new DOMParser();
var partialElement =
parser.parseFromString(responseText, 'text/html');

// Add style element to the document head
var styleElement = partialElement.querySelector('.js-partial-styles');
document.head.appendChild(styleElement);

// Add content from partial to page
var contentElement =
partialElement.querySelector('.js-partial-content');
this.mainContainer.innerHTML = contentElement.innerHTML;
}

.then((responseObject) => {
// Hide loading dialog
this.loader.classList.add('is-hidden');

if (responseObject === null) {
throw new Error('Unexpected response from Server.');
}

/**
* NOTE: We could move the script tags in the partial to the
* bottom of the body, but I don't think it'll change browser
* behaviour so it should be fine to inline the script tag in
* the main element.
**/
document.title = responseObject.title;

// Add style element to the document head
var styleElement = document.createElement('style');
styleElement.textContent = responseObject.partialinlinestyles;
document.head.appendChild(styleElement);

// Add content from partial to page
this.mainContainer.innerHTML = responseObject.partialhtml;

// TODO: Handle remote scripts

// TODO: Handle remote styles
})
.catch((error) => {
this.showError('There was a problem loading this page');
Expand Down

0 comments on commit 4cd9621

Please sign in to comment.