Compare commits

...

6 Commits

Author SHA1 Message Date
Robbie Antenesse 391f2734d8 Add isFrontend check to Choo state 2020-09-21 20:49:02 -06:00
Robbie Antenesse d2c0c289ab Allow search to load on server side render 2020-09-20 17:24:12 -06:00
Robbie Antenesse 8f9fe6e97d Set up server-side rendering of Choo app on public route 2020-09-20 17:23:24 -06:00
Robbie Antenesse 0e956f6c67 Make request.language default to 'en'
Add i18n.pages.default using 'en' locale
2020-09-20 17:23:08 -06:00
Robbie Antenesse 3bfaf5f3df Convert import/export to require/module.exports;Window conditions
Add conditions for whether to use certain things if run from server
2020-09-20 17:19:22 -06:00
Robbie Antenesse 2cfa08abe3 Allow fastify.i18n to be used outside of i18n routes 2020-09-20 16:42:33 -06:00
30 changed files with 246 additions and 146 deletions

View File

@ -1,4 +1,4 @@
export const appListeners = (app, state, emitter) => {
const appListeners = (app, state, emitter) => {
emitter.on(state.events.DOMCONTENTLOADED, () => {
emitter.emit(state.events.DOMTITLECHANGE, app.siteConfig.siteName);
@ -53,10 +53,14 @@ export const appListeners = (app, state, emitter) => {
}).then(result => callback(result));
});
state.i18n.fetchLocaleUI().then(() => {
app.checkIfLoggedIn(state).then(isLoggedIn => {
emitter.emit(state.events.RENDER); // This should hopefully only run once after the DOM is loaded. It prevents routing issues where 'render' hasn't been defined yet
if (state.isFrontend) {
state.i18n.fetchLocaleUI().then(() => {
app.checkIfLoggedIn(state).then(isLoggedIn => {
emitter.emit(state.events.RENDER); // This should hopefully only run once after the DOM is loaded. It prevents routing issues where 'render' hasn't been defined yet
});
});
})
}
});
}
}
module.exports = { appListeners };

View File

@ -1,12 +1,12 @@
import { globalView } from './views/global';
import { homeView } from './views/home';
import { aboutView } from './views/about';
import { loginView } from './views/login';
import { searchView } from './views/search';
import { shelvesView } from './views/shelves';
import { errorView } from './views/404';
const { globalView } = require('./views/global');
const { homeView } = require('./views/home');
const { aboutView } = require('./views/about');
const { loginView } = require('./views/login');
const { searchView } = require('./views/search');
const { shelvesView } = require('./views/shelves');
const { errorView } = require('./views/404');
export const appRoutes = (app) => {
const appRoutes = (app) => {
app.route('/', (state, emit) => globalView(state, emit, homeView));
app.route('/about', (state, emit) => globalView(state, emit, aboutView));
@ -21,3 +21,5 @@ export const appRoutes = (app) => {
app.route('/404', (state, emit) => globalView(state, emit, errorView));
}
module.exports = { appRoutes };

View File

@ -1,11 +1,17 @@
import { I18n } from "./i18n";
const { I18n } = require("./i18n");
const appState = (app, state, emitter) => {
state.isFrontend = typeof window !== 'undefined';
export const appState = (app, state, emitter) => {
state.events.SET_LANGUAGE = 'setLanguage';
state.events.ADD_TO_SHELF = 'addToShelf';
state.language = app.getSettingsItem('lang') ? app.getSettingsItem('lang') : (navigator.language || navigator.userLanguage).split('-')[0];
if (state.isFrontend) {
state.language = app.getSettingsItem('lang') ? app.getSettingsItem('lang') : (window.navigator.language || window.navigator.userLanguage).split('-')[0];
state.isLoggedIn = false;
state.i18n = new I18n(state); // Global I18n class passed to all views
}
state.viewStates = {};
state.isLoggedIn = false;
state.i18n = new I18n(state); // Global I18n class passed to all views
}
}
module.exports = { appState };

View File

@ -1,6 +1,6 @@
export const appUtilities = (app) => {
const appUtilities = (app) => {
app.getSettingsItem = settingsKey => {
let savedSettings = window.localStorage.getItem('settings');
let savedSettings = app.state.isFrontend && window.localStorage.getItem('settings');
if (savedSettings) {
savedSettings = JSON.parse(savedSettings);
if (typeof savedSettings[settingsKey] !== 'undefined') {
@ -10,6 +10,8 @@ export const appUtilities = (app) => {
return null;
}
app.setSettingsItem = (settingsKey, value) => {
if (!app.state.isFrontend) return null;
let savedSettings = window.localStorage.getItem('settings');
if (savedSettings) {
savedSettings = JSON.parse(savedSettings);
@ -21,6 +23,8 @@ export const appUtilities = (app) => {
}
app.checkIfLoggedIn = (appState) => {
if (!app.state.isFrontend) return false;
return fetch('/api/account/validate', { method: 'post' })
.then(response => response.json())
.then(response => {
@ -34,4 +38,6 @@ export const appUtilities = (app) => {
return true;
});
}
}
}
module.exports = { appUtilities };

View File

@ -1,4 +1,4 @@
export class I18n {
class I18n {
constructor(appState) {
this.appState = appState;
this.availableLanguages = null;
@ -56,6 +56,7 @@ export class I18n {
}, Object.assign({}, language));
if (translation === false) {
console.log(this);
if (language.locale !== this.default.locale) {
console.warn(`The translation for "${target}" is not set in the ${this.language.locale} locale. Using ${this.default.name} (${this.default.locale}) instead.`);
return this.translate(target, true);
@ -71,3 +72,5 @@ export class I18n {
return this.translate(translation);
}
}
module.exports = { I18n };

View File

@ -1,33 +1,43 @@
import 'babel-polyfill';
require('babel-polyfill');
import choo from 'choo';
const choo = require('choo');
import config from './config.json';
import { appRoutes } from './appRoutes';
import { appListeners } from './appListeners';
import { appState } from './appState.js';
import { appUtilities } from './appUtilities.js';
const config = require('./config.json');
const { appRoutes } = require('./appRoutes');
const { appListeners } = require('./appListeners');
const { appState } = require('./appState.js');
const { appUtilities } = require('./appUtilities.js');
const app = choo();
function frontend() {
const app = choo();
if (process.env.NODE_ENV !== 'production') {
// Only runs in development and will be stripped from production build.
app.use(require('choo-devtools')()); // Exposes `choo` to the console for debugging!
if (process.env.NODE_ENV !== 'production') {
// Only runs in development and will be stripped from production build.
app.use(require('choo-devtools')()); // Exposes `choo` to the console for debugging!
}
app.use((state, emitter) => {
app.siteConfig = config;
appUtilities(app);
});
app.use((state, emitter) => {
appState(app, state);
// Listeners
appListeners(app, state, emitter);
});
// Routes
appRoutes(app);
app.mount('body'); // Overwrite the `<body>` tag with the content of the Choo app
return app;
}
app.use((state, emitter) => {
app.siteConfig = config;
appUtilities(app);
});
if (typeof window !== 'undefined') {
frontend();
}
app.use((state, emitter) => {
appState(app, state);
// Listeners
appListeners(app, state, emitter);
});
// Routes
appRoutes(app);
app.mount('body'); // Overwrite the `<body>` tag with the content of the Choo app
module.exports = frontend;

View File

@ -1,6 +1,6 @@
import html from 'choo/html';
const html = require('choo/html');
export const errorView = (state, emit, i18n) => {
const errorView = (state, emit, i18n) => {
return html`<section class="error card">
<header>
<h1>${i18n.__('404.header')}</h1>
@ -9,4 +9,6 @@ export const errorView = (state, emit, i18n) => {
<h2>${i18n.__('404.subheader')}</h2>
</footer>
</section>`;
}
}
module.exports = { errorView };

View File

@ -1,6 +1,6 @@
import html from 'choo/html';
const html = require('choo/html');
export const aboutView = (state, emit, i18n) => {
const aboutView = (state, emit, i18n) => {
const content = html`<section class="content"><i class="icon-loading animate-spin"></i></section>`;
const community = html`<section class="content"></section>`;
@ -19,4 +19,6 @@ export const aboutView = (state, emit, i18n) => {
content,
community,
];
}
}
module.exports = { aboutView };

View File

@ -1,4 +1,4 @@
export class ViewController {
class ViewController {
constructor(state, i18n, viewName, defaultState = {}) {
// Store the global app state so it's accessible but out of the way.
this.appState = state;
@ -15,4 +15,6 @@ export class ViewController {
get isLoggedIn () {
return this.appState.isLoggedIn;
}
}
}
module.exports = { ViewController };

View File

@ -1,10 +1,23 @@
import html from 'choo/html';
const html = require('choo/html');
import headerImage from '../../dev/images/header.png';
let headerImage;
export const globalView = (state, emit, view) => {
if (typeof window !== 'undefined') {
// Make Parcel bundler process image
headerImage = require('../../dev/images/header.png');
} else {
// Make server get processed image path
const fs = require('fs');
const path = require('path');
const publicPath = path.resolve('public');
const publicFiles = fs.readdirSync(publicPath);
const headerImageFileName = publicFiles.find(fileName => /header\..+?\.png/.test(fileName));
headerImage = path.relative(publicPath, path.resolve(publicPath, headerImageFileName));
}
const globalView = (state, emit, view) => {
const { i18n } = state;
if (i18n.needsFetch) {
if (state.isFrontend && i18n.needsFetch) {
return html`<body><i class="icon-loading animate-spin"></i></body>`;
}
// Create a wrapper for view content that includes global header/footer
@ -70,4 +83,6 @@ export const globalView = (state, emit, view) => {
</nav>
</footer>
</body>`;
}
}
module.exports = { globalView };

View File

@ -1,6 +1,6 @@
import { ViewController } from '../controller';
const { ViewController } = require('../controller');
export class HomeController extends ViewController {
class HomeController extends ViewController {
constructor(state, i18n) {
// Super passes state, view name, and default state to ViewController,
// which stores state in this.appState and the view controller's state to this.state
@ -19,4 +19,6 @@ export class HomeController extends ViewController {
// either bind the class's 'this' instance to the method first...
// or use `onclick=${() => controller.submit()}` to maintain the 'this' of the class instead.
}
}
}
module.exports = { HomeController }

View File

@ -1,11 +1,11 @@
import html from 'choo/html';
const html = require('choo/html');
import { HomeController } from './controller'; // The controller for this view, where processing should happen.
import { loggedOutView } from './loggedOut';
import { loggedInView } from './loggedIn';
const { HomeController } = require('./controller'); // The controller for this view, where processing should happen.
const { loggedOutView } = require('./loggedOut');
const { loggedInView } = require('./loggedIn');
// This is the view function that is exported and used in the view manager.
export const homeView = (state, emit, i18n) => {
const homeView = (state, emit, i18n) => {
const controller = new HomeController(state, i18n);
// Returning an array in a view allows non-shared parent HTML elements.
@ -16,4 +16,6 @@ export const homeView = (state, emit, i18n) => {
: loggedInView(controller, emit)
),
];
}
}
module.exports = { homeView };

View File

@ -1,6 +1,6 @@
import html from 'choo/html';
const html = require('choo/html');
export const loggedInView = (homeController, emit) => {
const loggedInView = (homeController, emit) => {
const { __ } = homeController.i18n;
return [
@ -36,4 +36,6 @@ export const loggedInView = (homeController, emit) => {
</div>
</section>`,
];
}
}
module.exports = { loggedInView };

View File

@ -1,6 +1,6 @@
import html from 'choo/html';
const html = require('choo/html');
export const loggedOutView = (homeController, emit) => {
const loggedOutView = (homeController, emit) => {
const { __ } = homeController.i18n;
return [
@ -80,4 +80,6 @@ export const loggedOutView = (homeController, emit) => {
<a href="/login" class="large success button">${__('home.logged_out.join_now')}</a>
</section>`,
];
}
}
module.exports = { loggedOutView };

View File

@ -1,6 +1,6 @@
import { ViewController } from '../controller';
const { ViewController } = require('../controller');
export class LoginController extends ViewController {
class LoginController extends ViewController {
constructor(state, emit, i18n) {
// Super passes state, view name, and default state to ViewController,
// which stores state in this.appState and the view controller's state to this.state
@ -178,4 +178,6 @@ export class LoginController extends ViewController {
this.clearCreateAccountForm();
})
}
}
}
module.exports = { LoginController };

View File

@ -1,8 +1,8 @@
import html from 'choo/html';
const html = require('choo/html');
import { LoginController } from './controller';
const { LoginController } = require('./controller');
export const loginView = (state, emit, i18n) => {
const loginView = (state, emit, i18n) => {
const controller = new LoginController(state, emit, i18n);
const { __ } = controller.i18n;
@ -164,4 +164,6 @@ export const loginView = (state, emit, i18n) => {
</div>
</section>`;
}
}
module.exports = { loginView };

View File

@ -1,6 +1,6 @@
import html from 'choo/html';
const html = require('choo/html');
export const modal = (modalId, controller, contentHTML, options = {}) => {
const modal = (modalId, controller, contentHTML, options = {}) => {
/* Options:
* controller <class>: Pass the controller class with state; Requires get/set for openModal in state.
* buttonHTML <choo/html>: Displayed in place of the default button to open the modal
@ -76,4 +76,6 @@ export const modal = (modalId, controller, contentHTML, options = {}) => {
</article>
</div>`,
];
}
}
module.exports = { modal };

View File

@ -1,8 +1,8 @@
import html from 'choo/html';
const html = require('choo/html');
import { starRating } from './starRating';
const { starRating } = require('./starRating');
export const reviewCard = (controller, review) => {
const reviewCard = (controller, review) => {
const { __ } = controller.i18n;
return html`<article class="card">
@ -26,4 +26,6 @@ export const reviewCard = (controller, review) => {
</span>
</footer>
</article>`;
}
}
module.exports = { reviewCard };

View File

@ -1,6 +1,6 @@
import html from 'choo/html';
const html = require('choo/html');
export const starRating = (rating) => {
const starRating = (rating) => {
const wholeStars = Math.floor(rating);
const hasPartial = rating - wholeStars > 0;
const emptyStars = 5 - wholeStars - (hasPartial ? 1 : 0);
@ -16,4 +16,6 @@ export const starRating = (rating) => {
}
return stars;
}
}
module.exports = { starRating };

View File

@ -1,7 +1,7 @@
import { ViewController } from '../controller';
import { ShelvesController } from '../shelves/controller';
const { ViewController } = require('../controller');
const { ShelvesController } = require('../shelves/controller');
export class SearchController extends ViewController {
class SearchController extends ViewController {
constructor(state, emit, i18n) {
// Super passes state, view name, and default state to ViewController,
// which stores state in this.appState and the view controller's state to this.state
@ -33,7 +33,8 @@ export class SearchController extends ViewController {
}
get hasQuery() {
return this.appState.query.hasOwnProperty('for') && this.appState.query.for.trim() !== '';
return this.appState.isFrontend
&& this.appState.query.hasOwnProperty('for') && this.appState.query.for.trim() !== '';
}
get queryIsNew() {
@ -155,4 +156,6 @@ export class SearchController extends ViewController {
this.emit(RENDER);
});
}
}
}
module.exports = { SearchController };

View File

@ -1,11 +1,11 @@
import html from 'choo/html';
const html = require('choo/html');
import { SearchController } from './controller'; // The controller for this view, where processing should happen.
import { resultDetails } from './resultDetails';
import { modal } from '../partials/modal';
const { SearchController } = require('./controller'); // The controller for this view, where processing should happen.
const { resultDetails } = require('./resultDetails');
const { modal } = require('../partials/modal');
// This is the view function that is exported and used in the view manager.
export const searchView = (state, emit, i18n) => {
const searchView = (state, emit, i18n) => {
const controller = new SearchController(state, emit, i18n);
const { __ } = controller.i18n;
@ -156,4 +156,6 @@ export const searchView = (state, emit, i18n) => {
}
</section>`,
];
}
}
module.exports = { searchView };

View File

@ -1,10 +1,10 @@
import html from 'choo/html';
const html = require('choo/html');
import { reviewCard } from '../partials/reviewCard';
import { starRating } from '../partials/starRating';
import { modal } from '../partials/modal';
const { reviewCard } = require('../partials/reviewCard');
const { starRating } = require('../partials/starRating');
const { modal } = require('../partials/modal');
export const resultDetails = (searchController, result, emit = () => {}) => {
const resultDetails = (searchController, result, emit = () => {}) => {
const { __ } = searchController.i18n;
const source = result.sources[0];
const modalId = `result_${source.uri}`;
@ -120,4 +120,6 @@ export const resultDetails = (searchController, result, emit = () => {}) => {
headerText: result.name,
onShow,
});
}
}
module.exports = { resultDetails };

View File

@ -1,6 +1,6 @@
import { ViewController } from '../controller';
const { ViewController } = require('../controller');
export class ShelvesController extends ViewController {
class ShelvesController extends ViewController {
constructor(state, i18n) {
// Super passes state, view name, and default state to ViewController,
// which stores state in this.appState and the view controller's state to this.state
@ -42,4 +42,6 @@ export class ShelvesController extends ViewController {
this.state.loadedShelves[this.targetShelf] = shelf;
});
}
}
}
module.exports = { ShelvesController };

View File

@ -1,11 +1,11 @@
import html from 'choo/html';
const html = require('choo/html');
import { ShelvesController } from './controller'; // The controller for this view, where processing should happen.
import { shelfView } from './shelf';
import { userShelvesView } from './userShelves';
const { ShelvesController } = require('./controller'); // The controller for this view, where processing should happen.
const { shelfView } = require('./shelf');
const { userShelvesView } = require('./userShelves');
// This is the view function that is exported and used in the view manager.
export const shelvesView = (state, emit, i18n) => {
const shelvesView = (state, emit, i18n) => {
const controller = new ShelvesController(state, i18n);
// Returning an array in a view allows non-shared parent HTML elements.
@ -16,4 +16,6 @@ export const shelvesView = (state, emit, i18n) => {
: userShelvesView(controller, emit)
),
];
}
}
module.exports = { shelvesView };

View File

@ -1,9 +1,9 @@
import html from 'choo/html';
const html = require('choo/html');
import { starRating } from '../partials/starRating';
import { modal } from '../partials/modal';
const { starRating } = require('../partials/starRating');
const { modal } = require('../partials/modal');
export const shelfView = (shelvesController, emit) => {
const shelfView = (shelvesController, emit) => {
const { __ } = shelvesController.i18n;
if (shelvesController.targetShelf === null) {
@ -107,4 +107,6 @@ export const shelfView = (shelvesController, emit) => {
})}
</section>`,
];
}
}
module.exports = { shelfView };

View File

@ -1,8 +1,8 @@
import html from 'choo/html';
const html = require('choo/html');
import { modal } from '../../partials/modal';
const { modal } = require('../../partials/modal');
export const editModal = (shelf, shelvesController) => {
const editModal = (shelf, shelvesController) => {
const { __ } = shelvesController.i18n;
const modalId = `editShelf${shelf.id}`;
@ -26,4 +26,6 @@ export const editModal = (shelf, shelvesController) => {
</label>
</footer>`,
});
}
}
module.exports = { editModal };

View File

@ -1,7 +1,7 @@
import html from 'choo/html';
import { editModal } from './editModal';
const html = require('choo/html');
const { editModal } = require('./editModal');
export const userShelvesView = (shelvesController, emit) => {
const userShelvesView = (shelvesController, emit) => {
const { __ } = shelvesController.i18n;
if (!shelvesController.isLoggedIn) {
@ -20,7 +20,7 @@ export const userShelvesView = (shelvesController, emit) => {
];
}
if (shelvesController.state.myShelves.length <= 0) {
if (shelvesController.appState.isFrontend && shelvesController.state.myShelves.length <= 0) {
shelvesController.getUserShelves().then(() => {
emit(shelvesController.appState.events.RENDER);
});
@ -52,4 +52,6 @@ export const userShelvesView = (shelvesController, emit) => {
})}
</section>`,
];
}
}
module.exports = { userShelvesView };

View File

@ -36,6 +36,7 @@ async function plugin (fastify, opts, done) {
// Set the default language to English after parsing locales because it has the most coverage.
i18n.default = i18n.en;
i18n.pages.default = i18n.pages.en;
} catch (ex) {
console.error('Could not get locales folder.\n', ex);
}
@ -47,4 +48,4 @@ async function plugin (fastify, opts, done) {
done();
}
module.exports = plugin;
module.exports = fp(plugin);

View File

@ -100,9 +100,7 @@ fastify.addHook('onRequest', async (request, reply) => {
request.user = user;
}
}
if (typeof request.cookies.lang !== 'undefined') {
request.language = request.cookies.lang;
}
request.language = typeof request.cookies.lang !== 'undefined' ? request.cookies.lang : 'en';
});
// Store i18n files in fastify object and register locales routes

View File

@ -1,16 +1,30 @@
async function routes(fastify, options) {
// This route is not totally necessary because fastify-static serves public/ wholesale, but it's good to be verbose!
fastify.get('/', async (request, reply) => {
return reply.sendFile('index.html');
});
const fs = require('fs');
const path = require('path');
const htmlContainer = fs.readFileSync(path.resolve('public/index.html'));
const chooApp = require('../../app')();
const chooI18n = require('../../app/i18n').I18n;
async function routes(fastify, options) {
// This is overridden by any explicitly named routes, so the API will be fine.
fastify.get('/:chooRoute', async (request, reply) => {
if (/\.\w+$/.test(request.params.chooRoute)) { // If the :chooRoute is a filename, serve the file instead
return reply.sendFile(request.params.chooRoute);
}
// Otherwise, send index.html and allow Choo to route it.
return reply.sendFile('index.html');
// Otherwise, send allow Choo to route it.
const state = Object.assign({}, chooApp.state);
state.language = request.language;
state.isLoggedIn = request.isLoggedInUser;
state.i18n = new chooI18n(state);
state.i18n.availableLanguages = fastify.i18n.available.slice();
state.i18n.default = Object.assign({}, fastify.i18n.default);
const locale = typeof fastify.i18n[state.language] !== 'undefined' ? state.language : 'default';
state.i18n.language = Object.assign({}, fastify.i18n[locale]);
state.i18n.pages = Object.assign({}, fastify.i18n.pages[locale]);
const html = htmlContainer.toString().replace(/\<body\>(.|\n)+?\<\/body\>/, chooApp.toString('/' + request.params.chooRoute, state));
return reply.type('text/html').send(html);
});
}