mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-13 11:35:28 +00:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
419f5c5235 | ||
|
|
4c61ed5fdd | ||
|
|
c19447cf05 | ||
|
|
cb2364f476 | ||
|
|
de427d400e | ||
|
|
e810ead93f | ||
|
|
f5a19ef34b | ||
|
|
b8c03d330b | ||
|
|
6e769496ec | ||
|
|
e46aceb2fe | ||
|
|
a87cac2481 | ||
|
|
608fdb7533 | ||
|
|
80166b5a7d | ||
|
|
24b259f80b | ||
|
|
8a9f4bd268 | ||
|
|
d940da1a77 | ||
|
|
91269f5705 | ||
|
|
80a9818e95 | ||
|
|
478ccf53cc | ||
|
|
b32278e88b | ||
|
|
881d411db0 |
41
connect.js
41
connect.js
@@ -4,10 +4,12 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const glob = require('glob');
|
||||
const rimraf = require('rimraf');
|
||||
const create_routes = require('./utils/create_routes.js');
|
||||
const create_templates = require('./utils/create_templates.js');
|
||||
const create_app = require('./utils/create_app.js');
|
||||
const create_webpack_compiler = require('./utils/create_webpack_compiler.js');
|
||||
const mkdirp = require('mkdirp');
|
||||
const create_routes = require('./lib/utils/create_routes.js');
|
||||
const templates = require('./lib/templates.js');
|
||||
const create_app = require('./lib/utils/create_app.js');
|
||||
const create_webpack_compiler = require('./lib/utils/create_webpack_compiler.js');
|
||||
const escape_html = require('escape-html');
|
||||
const { src, dest, dev } = require('./lib/config.js');
|
||||
|
||||
const esmRequire = esm(module, {
|
||||
@@ -15,8 +17,8 @@ const esmRequire = esm(module, {
|
||||
});
|
||||
|
||||
module.exports = function connect(opts) {
|
||||
rimraf.sync(dest);
|
||||
fs.mkdirSync(dest);
|
||||
mkdirp(dest);
|
||||
rimraf.sync(path.join(dest, '**/*'));
|
||||
|
||||
let routes = create_routes(
|
||||
glob.sync('**/*.+(html|js|mjs)', { cwd: src })
|
||||
@@ -30,14 +32,13 @@ module.exports = function connect(opts) {
|
||||
dev
|
||||
);
|
||||
|
||||
const templates = create_templates();
|
||||
|
||||
return async function(req, res, next) {
|
||||
const url = req.url.replace(/\?.+/, '');
|
||||
|
||||
if (url.startsWith('/client/')) {
|
||||
if (url === '/service-worker.js' || url === '/index.html' || url.startsWith('/client/')) {
|
||||
await webpack_compiler.ready;
|
||||
res.set({
|
||||
'Content-Type': 'application/javascript'
|
||||
'Content-Type': url === '/index.html' ? 'text/html' : 'application/javascript'
|
||||
});
|
||||
fs.createReadStream(`${dest}${url}`).pipe(res);
|
||||
return;
|
||||
@@ -51,21 +52,21 @@ module.exports = function connect(opts) {
|
||||
try {
|
||||
for (const route of routes) {
|
||||
if (route.test(url)) {
|
||||
await webpack_compiler.ready;
|
||||
|
||||
req.params = route.exec(url);
|
||||
|
||||
const chunk = await webpack_compiler.get_chunk(route.id);
|
||||
const mod = require(chunk);
|
||||
const chunk = webpack_compiler.chunks[route.id];
|
||||
const mod = require(path.resolve(dest, 'server', chunk));
|
||||
|
||||
if (route.type === 'page') {
|
||||
const main = await webpack_compiler.client_main;
|
||||
|
||||
let data = { params: req.params, query: req.query };
|
||||
if (mod.default.preload) data = Object.assign(data, await mod.default.preload(data));
|
||||
|
||||
const { html, head, css } = mod.default.render(data);
|
||||
|
||||
const page = templates.render(200, {
|
||||
main,
|
||||
main: webpack_compiler.client_main,
|
||||
html,
|
||||
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
|
||||
styles: (css && css.code ? `<style>${css.code}</style>` : '')
|
||||
@@ -98,13 +99,17 @@ module.exports = function connect(opts) {
|
||||
}
|
||||
|
||||
res.status(404).end(templates.render(404, {
|
||||
title: 'Not found',
|
||||
status: 404,
|
||||
method: req.method,
|
||||
url
|
||||
}));
|
||||
} catch(err) {
|
||||
// TODO nice error pages
|
||||
res.status(500);
|
||||
res.end(err.stack);
|
||||
res.status(500).end(templates.render(500, {
|
||||
title: err.name || 'Internal server error',
|
||||
url,
|
||||
error: escape_html(err.details || err.message || err || 'Unknown error')
|
||||
}));
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
const glob = require('glob');
|
||||
const create_routes = require('../utils/create_routes.js');
|
||||
const create_routes = require('./utils/create_routes.js');
|
||||
const { src } = require('./config.js');
|
||||
|
||||
const route_manager = {
|
||||
|
||||
43
lib/templates.js
Normal file
43
lib/templates.js
Normal file
@@ -0,0 +1,43 @@
|
||||
const fs = require('fs');
|
||||
const glob = require('glob');
|
||||
|
||||
const templates = glob.sync('*.html', { cwd: 'templates' })
|
||||
.map(file => {
|
||||
const template = fs.readFileSync(`templates/${file}`, 'utf-8');
|
||||
const status = file.replace('.html', '').toLowerCase();
|
||||
|
||||
if (!/^[0-9x]{3}$/.test(status)) {
|
||||
throw new Error(`Bad template — should be a valid status code like 404.html, or a wildcard like 2xx.html`);
|
||||
}
|
||||
|
||||
const specificity = (
|
||||
(status[0] === 'x' ? 0 : 4) +
|
||||
(status[1] === 'x' ? 0 : 2) +
|
||||
(status[2] === 'x' ? 0 : 1)
|
||||
);
|
||||
|
||||
const pattern = new RegExp(`^${status.split('').map(d => d === 'x' ? '\\d' : d).join('')}$`);
|
||||
|
||||
return {
|
||||
test: status => pattern.test(status),
|
||||
specificity,
|
||||
render(data) {
|
||||
return template.replace(/%sapper\.(\w+)%/g, (match, key) => {
|
||||
return key in data ? data[key] : '';
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b.specificity - a.specificity);
|
||||
|
||||
exports.render = (status, data) => {
|
||||
const template = templates.find(template => template.test(status));
|
||||
if (template) return template.render(data);
|
||||
|
||||
return `Missing template for status code ${status}`;
|
||||
};
|
||||
|
||||
exports.onchange = fn => {
|
||||
// TODO in dev mode, keep this updated, and allow
|
||||
// webpack compiler etc to hook into it
|
||||
};
|
||||
26
lib/utils/create_app.js
Normal file
26
lib/utils/create_app.js
Normal file
@@ -0,0 +1,26 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const template = fs.readFileSync(path.resolve(__dirname, '../../templates/main.js'), 'utf-8');
|
||||
|
||||
module.exports = function create_app(src, dest, routes, options) {
|
||||
// TODO in dev mode, watch files
|
||||
|
||||
const code = routes
|
||||
.filter(route => route.type === 'page')
|
||||
.map(route => {
|
||||
const params = route.dynamic.length === 0 ?
|
||||
'{}' :
|
||||
`{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ') } }`;
|
||||
|
||||
return `{ pattern: ${route.pattern}, params: match => (${params}), load: () => import('${src}/${route.file}') }`
|
||||
})
|
||||
.join(',\n\t');
|
||||
|
||||
const main = template
|
||||
.replace('__app__', path.resolve(__dirname, '../../runtime/app.js'))
|
||||
.replace('__selector__', options.selector || 'main')
|
||||
.replace('__routes__', code);
|
||||
|
||||
fs.writeFileSync(path.join(dest, 'main.js'), main);
|
||||
};
|
||||
100
lib/utils/create_webpack_compiler.js
Normal file
100
lib/utils/create_webpack_compiler.js
Normal file
@@ -0,0 +1,100 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const glob = require('glob');
|
||||
const webpack = require('webpack');
|
||||
const templates = require('../templates.js');
|
||||
|
||||
module.exports = function create_webpack_compiler(dest, routes, dev) {
|
||||
const compiler = {};
|
||||
|
||||
const client = webpack(
|
||||
require(path.resolve('webpack.client.config.js'))
|
||||
);
|
||||
|
||||
const server = webpack(
|
||||
require(path.resolve('webpack.server.config.js'))
|
||||
);
|
||||
|
||||
if (false) { // TODO watch in dev
|
||||
// TODO how can we invalidate compiler.client_main when watcher restarts?
|
||||
compiler.client_main = new Promise((fulfil, reject) => {
|
||||
client.watch({}, (err, stats) => {
|
||||
if (err || stats.hasErrors()) {
|
||||
// TODO handle errors
|
||||
}
|
||||
|
||||
const filename = stats.toJson().assetsByChunkName.main;
|
||||
fulfil(`/client/${filename}`);
|
||||
});
|
||||
});
|
||||
|
||||
// TODO server
|
||||
} else {
|
||||
compiler.ready = Promise.all([
|
||||
new Promise((fulfil, reject) => {
|
||||
client.run((err, stats) => {
|
||||
console.log(stats.toString({ colors: true }));
|
||||
|
||||
const info = stats.toJson();
|
||||
|
||||
if (err || stats.hasErrors()) {
|
||||
reject(err || info.errors[0]);
|
||||
}
|
||||
|
||||
compiler.client_main = `/client/${info.assetsByChunkName.main}`;
|
||||
compiler.assets = info.assets.map(asset => `/client/${asset.name}`);
|
||||
|
||||
fulfil();
|
||||
});
|
||||
}),
|
||||
|
||||
new Promise((fulfil, reject) => {
|
||||
server.run((err, stats) => {
|
||||
console.log(stats.toString({ colors: true }));
|
||||
|
||||
const info = stats.toJson();
|
||||
|
||||
if (err || stats.hasErrors()) {
|
||||
reject(err || info.errors[0]);
|
||||
}
|
||||
|
||||
compiler.chunks = info.assetsByChunkName;
|
||||
|
||||
fulfil();
|
||||
});
|
||||
})
|
||||
]).then(() => {
|
||||
const assets = glob.sync('**', { cwd: 'assets' });
|
||||
|
||||
const route_code = `[${
|
||||
routes
|
||||
.filter(route => route.type === 'page')
|
||||
.map(route => `{ pattern: ${route.pattern} }`)
|
||||
.join(', ')
|
||||
}]`;
|
||||
|
||||
const service_worker = fs.readFileSync('templates/service-worker.js', 'utf-8')
|
||||
.replace('__timestamp__', Date.now())
|
||||
.replace('__assets__', JSON.stringify(assets))
|
||||
.replace('__shell__', JSON.stringify(compiler.assets.concat('/index.html')))
|
||||
.replace('__routes__', route_code);
|
||||
|
||||
fs.writeFileSync(path.resolve(dest, 'service-worker.js'), service_worker);
|
||||
|
||||
const shell = templates.render(200, {
|
||||
styles: '',
|
||||
head: '',
|
||||
html: '<noscript>Please enable JavaScript!</noscript>',
|
||||
main: compiler.client_main
|
||||
});
|
||||
|
||||
fs.writeFileSync(path.resolve(dest, 'index.html'), shell);
|
||||
});
|
||||
|
||||
compiler.get_chunk = async id => {
|
||||
return path.resolve(dest, 'server', compiler.chunks[id]);
|
||||
};
|
||||
}
|
||||
|
||||
return compiler;
|
||||
};
|
||||
53
package-lock.json
generated
53
package-lock.json
generated
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sapper",
|
||||
"version": "0.0.3",
|
||||
"version": "0.0.9",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
@@ -578,6 +578,11 @@
|
||||
"es6-symbol": "3.1.1"
|
||||
}
|
||||
},
|
||||
"escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
|
||||
},
|
||||
"escape-string-regexp": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
|
||||
@@ -670,18 +675,6 @@
|
||||
"is-extglob": "1.0.0"
|
||||
}
|
||||
},
|
||||
"extract-text-webpack-plugin": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/extract-text-webpack-plugin/-/extract-text-webpack-plugin-3.0.2.tgz",
|
||||
"integrity": "sha512-bt/LZ4m5Rqt/Crl2HiKuAl/oqg0psx1tsTLkvWbJen1CtD+fftkZhMaQ9HOtY2gWsl2Wq+sABmMVi9z3DhKWQQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"async": "2.6.0",
|
||||
"loader-utils": "1.1.0",
|
||||
"schema-utils": "0.3.0",
|
||||
"webpack-sources": "1.1.0"
|
||||
}
|
||||
},
|
||||
"fast-deep-equal": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz",
|
||||
@@ -2095,12 +2088,6 @@
|
||||
"mem": "1.1.0"
|
||||
}
|
||||
},
|
||||
"os-tmpdir": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
|
||||
"integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=",
|
||||
"dev": true
|
||||
},
|
||||
"p-finally": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
|
||||
@@ -2413,15 +2400,6 @@
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz",
|
||||
"integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg=="
|
||||
},
|
||||
"schema-utils": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz",
|
||||
"integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ajv": "5.5.1"
|
||||
}
|
||||
},
|
||||
"semver": {
|
||||
"version": "5.4.1",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz",
|
||||
@@ -2587,16 +2565,6 @@
|
||||
"integrity": "sha512-xRw4pjF19XKfeTxp+TOTE/MQmRS7tRzm0hhh0dr/nc3NuHBfCBXnfve0ZymF8tZ+J/WM0cqfZ83RxZid2zf7qA==",
|
||||
"dev": true
|
||||
},
|
||||
"svelte-loader": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/svelte-loader/-/svelte-loader-2.2.1.tgz",
|
||||
"integrity": "sha512-SNdEPwLpoWqKMk5wjJUVd7LUFK9rQoMPxQ8uJoszWSgTpbYICSnxFCEDvhDvcHbmAFSOOXnoJAdvoCTnBw3+kg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"loader-utils": "1.1.0",
|
||||
"tmp": "0.0.31"
|
||||
}
|
||||
},
|
||||
"tapable": {
|
||||
"version": "0.2.8",
|
||||
"resolved": "https://registry.npmjs.org/tapable/-/tapable-0.2.8.tgz",
|
||||
@@ -2610,15 +2578,6 @@
|
||||
"setimmediate": "1.0.5"
|
||||
}
|
||||
},
|
||||
"tmp": {
|
||||
"version": "0.0.31",
|
||||
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.31.tgz",
|
||||
"integrity": "sha1-jzirlDjhcxXl29izZX6L+yd65Kc=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"os-tmpdir": "1.0.2"
|
||||
}
|
||||
},
|
||||
"to-arraybuffer": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sapper",
|
||||
"version": "0.0.6",
|
||||
"version": "0.0.16",
|
||||
"description": "Combat-ready apps, engineered by Svelte",
|
||||
"main": "connect.js",
|
||||
"directories": {
|
||||
@@ -8,6 +8,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@std/esm": "^0.18.0",
|
||||
"escape-html": "^1.0.3",
|
||||
"mkdirp": "^0.5.1",
|
||||
"rimraf": "^2.6.2",
|
||||
"webpack": "^3.10.0"
|
||||
},
|
||||
|
||||
167
runtime/app.js
167
runtime/app.js
@@ -1,22 +1,171 @@
|
||||
const detach = node => {
|
||||
node.parentNode.removeChild(node);
|
||||
};
|
||||
|
||||
let component;
|
||||
|
||||
const scroll_history = {};
|
||||
let uid = 1;
|
||||
let cid;
|
||||
|
||||
window.scroll_history = scroll_history;
|
||||
|
||||
if ('scrollRestoration' in history) {
|
||||
history.scrollRestoration = 'manual'
|
||||
}
|
||||
|
||||
const app = {
|
||||
init(callback) {
|
||||
init(target, routes) {
|
||||
function select_route(url) {
|
||||
if (url.origin !== window.location.origin) return null;
|
||||
|
||||
for (const route of routes) {
|
||||
const match = route.pattern.exec(url.pathname);
|
||||
if (match) {
|
||||
const params = route.params(match);
|
||||
|
||||
const query = {};
|
||||
for (const [key, value] of url.searchParams) query[key] = value || true;
|
||||
|
||||
return { route, data: { params, query } };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function render(Component, data, scroll) {
|
||||
Promise.resolve(
|
||||
Component.preload ? Component.preload(data) : {}
|
||||
).then(preloaded => {
|
||||
if (component) {
|
||||
component.destroy();
|
||||
} else {
|
||||
// first load — remove SSR'd <head> contents
|
||||
const start = document.querySelector('#sapper-head-start');
|
||||
let end = document.querySelector('#sapper-head-end');
|
||||
|
||||
if (start && end) {
|
||||
while (start.nextSibling !== end) detach(start.nextSibling);
|
||||
detach(start);
|
||||
detach(end);
|
||||
}
|
||||
|
||||
// preload additional routes
|
||||
routes.reduce((promise, route) => promise.then(route.load), Promise.resolve());
|
||||
}
|
||||
|
||||
component = new Component({
|
||||
target,
|
||||
data: Object.assign(data, preloaded),
|
||||
hydrate: !!component
|
||||
});
|
||||
|
||||
window.scrollTo(scroll.x, scroll.y);
|
||||
});
|
||||
}
|
||||
|
||||
function navigate(url, id) {
|
||||
const selected = select_route(url);
|
||||
if (selected) {
|
||||
if (id) {
|
||||
// popstate or initial navigation
|
||||
cid = id;
|
||||
} else {
|
||||
// clicked on a link. preserve scroll state
|
||||
scroll_history[cid] = scroll_state();
|
||||
|
||||
id = cid = ++uid;
|
||||
scroll_history[cid] = { x: 0, y: 0 };
|
||||
|
||||
history.pushState({ id }, '', url.href);
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
selected.route.load().then(mod => {
|
||||
render(mod.default, selected.data, scroll_history[id]);
|
||||
});
|
||||
|
||||
cid = id;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function findAnchor(node) {
|
||||
while (node && node.nodeName.toUpperCase() !== 'A') node = node.parentNode; // SVG <a> elements have a lowercase name
|
||||
return node;
|
||||
}
|
||||
|
||||
window.addEventListener('click', event => {
|
||||
let a = event.target;
|
||||
while (a && a.nodeName !== 'A') a = a.parentNode;
|
||||
// Adapted from https://github.com/visionmedia/page.js
|
||||
// MIT license https://github.com/visionmedia/page.js#license
|
||||
if (which(event) !== 1) return;
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey) return;
|
||||
if (event.defaultPrevented) return;
|
||||
|
||||
const a = findAnchor(event.target);
|
||||
if (!a) return;
|
||||
|
||||
if (callback(new URL(a.href))) {
|
||||
event.preventDefault();
|
||||
history.pushState({}, '', a.href);
|
||||
}
|
||||
event.preventDefault();
|
||||
|
||||
// check if link is inside an svg
|
||||
// in this case, both href and target are always inside an object
|
||||
const svg = typeof a.href === 'object' && a.href.constructor.name === 'SVGAnimatedString';
|
||||
const href = svg ? a.href.baseVal : a.href;
|
||||
|
||||
// Ignore if tag has
|
||||
// 1. 'download' attribute
|
||||
// 2. rel='external' attribute
|
||||
if (a.hasAttribute('download') || a.getAttribute('rel') === 'external') return;
|
||||
|
||||
// Ignore if <a> has a target
|
||||
if (svg ? a.target.baseVal : a.target) return;
|
||||
|
||||
const scroll = scroll_state();
|
||||
|
||||
navigate(new URL(a.href), null);
|
||||
});
|
||||
|
||||
function preload(event) {
|
||||
const a = findAnchor(event.target);
|
||||
if (!a || a.rel !== 'prefetch') return;
|
||||
|
||||
const selected = select_route(new URL(a.href));
|
||||
|
||||
if (selected) {
|
||||
selected.route.load().then(mod => {
|
||||
if (mod.default.preload) mod.default.preload(selected.data);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('touchstart', preload);
|
||||
window.addEventListener('mouseover', preload);
|
||||
|
||||
window.addEventListener('popstate', event => {
|
||||
callback(window.location);
|
||||
if (!event.state) return; // hashchange, or otherwise outside sapper's control
|
||||
scroll_history[cid] = scroll_state();
|
||||
|
||||
console.log(`storing current scroll: ${cid}`, scroll_state());
|
||||
console.log(`navigating to state: ${event.state.id}`, scroll_history[event.state.id]);
|
||||
navigate(new URL(window.location), event.state.id);
|
||||
});
|
||||
|
||||
callback(window.location);
|
||||
const scroll = scroll_history[uid] = scroll_state();
|
||||
|
||||
history.replaceState({ id: uid }, '', window.location.href);
|
||||
navigate(new URL(window.location), uid);
|
||||
}
|
||||
};
|
||||
|
||||
function which(event) {
|
||||
event = event || window.event;
|
||||
return event.which === null ? event.button : event.which;
|
||||
}
|
||||
|
||||
function scroll_state() {
|
||||
return {
|
||||
x: window.scrollX,
|
||||
y: window.scrollY
|
||||
};
|
||||
}
|
||||
|
||||
export default app;
|
||||
@@ -1,47 +1,5 @@
|
||||
import app from 'sapper/runtime/app.js';
|
||||
import { detachNode } from 'svelte/shared.js';
|
||||
import app from '__app__';
|
||||
|
||||
const target = document.querySelector('__selector__');
|
||||
let component;
|
||||
|
||||
app.init(url => {
|
||||
if (url.origin !== window.location.origin) return;
|
||||
|
||||
let match;
|
||||
let params = {};
|
||||
const query = {};
|
||||
|
||||
function render(mod) {
|
||||
const route = { query, params };
|
||||
|
||||
Promise.resolve(
|
||||
mod.default.preload ? mod.default.preload(route) : {}
|
||||
).then(preloaded => {
|
||||
if (component) {
|
||||
component.destroy();
|
||||
} else {
|
||||
// remove SSR'd <head> contents
|
||||
const start = document.querySelector('#sapper-head-start');
|
||||
let end = document.querySelector('#sapper-head-end');
|
||||
|
||||
if (start && end) {
|
||||
while (start.nextSibling !== end) detachNode(start.nextSibling);
|
||||
detachNode(start);
|
||||
detachNode(end);
|
||||
}
|
||||
|
||||
target.innerHTML = '';
|
||||
}
|
||||
|
||||
component = new mod.default({
|
||||
target,
|
||||
data: Object.assign(route, preloaded),
|
||||
hydrate: !!component
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ROUTES
|
||||
|
||||
return true;
|
||||
});
|
||||
app.init(document.querySelector('__selector__'), [
|
||||
__routes__
|
||||
]);
|
||||
@@ -1,41 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const template = fs.readFileSync(path.resolve(__dirname, '../templates/main.js'), 'utf-8');
|
||||
|
||||
module.exports = function create_app(src, dest, routes, options) {
|
||||
// TODO in dev mode, watch files
|
||||
|
||||
const code = routes
|
||||
.filter(route => route.type === 'page')
|
||||
.map(route => {
|
||||
const condition = route.dynamic.length === 0 ?
|
||||
`url.pathname === '/${route.parts.join('/')}'` :
|
||||
`match = ${route.pattern}.exec(url.pathname)`;
|
||||
|
||||
const lines = [];
|
||||
|
||||
route.dynamic.forEach((part, i) => {
|
||||
lines.push(
|
||||
`params.${part} = match[${i + 1}];`
|
||||
);
|
||||
});
|
||||
|
||||
lines.push(
|
||||
`import('${src}/${route.file}').then(render);`
|
||||
);
|
||||
|
||||
return `
|
||||
if (${condition}) {
|
||||
${lines.join(`\n\t\t\t\t\t`)}
|
||||
}
|
||||
`.replace(/^\t{3}/gm, '').trim();
|
||||
})
|
||||
.join(' else ') + ' else return false;';
|
||||
|
||||
const main = template
|
||||
.replace('__selector__', options.selector || 'main')
|
||||
.replace('// ROUTES', code);
|
||||
|
||||
fs.writeFileSync(path.join(dest, 'main.js'), main);
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const glob = require('glob');
|
||||
|
||||
module.exports = function create_templates() {
|
||||
const templates = glob.sync('*.html', { cwd: 'templates' })
|
||||
.map(file => {
|
||||
const template = fs.readFileSync(`templates/${file}`, 'utf-8');
|
||||
const status = file.replace('.html', '').toLowerCase();
|
||||
|
||||
if (!/^[0-9x]{3}$/.test(status)) {
|
||||
throw new Error(`Bad template — should be a valid status code like 404.html, or a wildcard like 2xx.html`);
|
||||
}
|
||||
|
||||
const specificity = (
|
||||
(status[0] === 'x' ? 0 : 4) +
|
||||
(status[1] === 'x' ? 0 : 2) +
|
||||
(status[2] === 'x' ? 0 : 1)
|
||||
);
|
||||
|
||||
const pattern = new RegExp(`^${status.split('').map(d => d === 'x' ? '\\d' : d).join('')}$`);
|
||||
|
||||
return {
|
||||
test: status => pattern.test(status),
|
||||
specificity,
|
||||
render(data) {
|
||||
return template.replace(/%sapper\.(\w+)%/g, (match, key) => {
|
||||
return key in data ? data[key] : '';
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b.specificity - a.specificity);
|
||||
|
||||
return {
|
||||
render: (status, data) => {
|
||||
const template = templates.find(template => template.test(status));
|
||||
if (template) return template.render(data);
|
||||
|
||||
return `Missing template for status code ${status}`;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,62 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
|
||||
module.exports = function create_webpack_compiler(out, routes, dev) {
|
||||
const compiler = {};
|
||||
|
||||
const client = webpack(
|
||||
require(path.resolve('webpack.client.config.js'))
|
||||
);
|
||||
|
||||
const server = webpack(
|
||||
require(path.resolve('webpack.server.config.js'))
|
||||
);
|
||||
|
||||
if (false) { // TODO watch in dev
|
||||
// TODO how can we invalidate compiler.client_main when watcher restarts?
|
||||
compiler.client_main = new Promise((fulfil, reject) => {
|
||||
client.watch({}, (err, stats) => {
|
||||
if (err || stats.hasErrors()) {
|
||||
// TODO handle errors
|
||||
}
|
||||
|
||||
const filename = stats.toJson().assetsByChunkName.main;
|
||||
fulfil(`/client/${filename}`);
|
||||
});
|
||||
});
|
||||
|
||||
// TODO server
|
||||
} else {
|
||||
compiler.client_main = new Promise((fulfil, reject) => {
|
||||
client.run((err, stats) => {
|
||||
if (err || stats.hasErrors()) {
|
||||
console.log(stats.toString({ colors: true }));
|
||||
reject(err);
|
||||
}
|
||||
|
||||
const filename = stats.toJson().assetsByChunkName.main;
|
||||
fulfil(`/client/${filename}`);
|
||||
});
|
||||
});
|
||||
|
||||
const chunks = new Promise((fulfil, reject) => {
|
||||
server.run((err, stats) => {
|
||||
if (err || stats.hasErrors()) {
|
||||
// TODO deal with hasErrors
|
||||
console.log(stats.toString({ colors: true }));
|
||||
reject(err);
|
||||
}
|
||||
|
||||
fulfil(stats.toJson().assetsByChunkName);
|
||||
});
|
||||
});
|
||||
|
||||
compiler.get_chunk = async id => {
|
||||
const assetsByChunkName = await chunks;
|
||||
return path.resolve(out, 'server', assetsByChunkName[id]);
|
||||
};
|
||||
}
|
||||
|
||||
return compiler;
|
||||
};
|
||||
29
yarn.lock
29
yarn.lock
@@ -35,7 +35,7 @@ ajv@^4.9.1:
|
||||
co "^4.6.0"
|
||||
json-stable-stringify "^1.0.1"
|
||||
|
||||
ajv@^5.0.0, ajv@^5.1.5:
|
||||
ajv@^5.1.5:
|
||||
version "5.5.1"
|
||||
resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.1.tgz#b38bb8876d9e86bee994956a04e721e88b248eb2"
|
||||
dependencies:
|
||||
@@ -122,7 +122,7 @@ async-each@^1.0.0:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.1.tgz#19d386a1d9edc6e7c1c85d388aedbcc56d33602d"
|
||||
|
||||
async@^2.1.2, async@^2.4.1:
|
||||
async@^2.1.2:
|
||||
version "2.6.0"
|
||||
resolved "https://registry.yarnpkg.com/async/-/async-2.6.0.tgz#61a29abb6fcc026fea77e56d1c6ec53a795951f4"
|
||||
dependencies:
|
||||
@@ -669,15 +669,6 @@ extglob@^0.3.1:
|
||||
dependencies:
|
||||
is-extglob "^1.0.0"
|
||||
|
||||
extract-text-webpack-plugin@^3.0.2:
|
||||
version "3.0.2"
|
||||
resolved "https://registry.yarnpkg.com/extract-text-webpack-plugin/-/extract-text-webpack-plugin-3.0.2.tgz#5f043eaa02f9750a9258b78c0a6e0dc1408fb2f7"
|
||||
dependencies:
|
||||
async "^2.4.1"
|
||||
loader-utils "^1.1.0"
|
||||
schema-utils "^0.3.0"
|
||||
webpack-sources "^1.0.1"
|
||||
|
||||
extsprintf@1.3.0:
|
||||
version "1.3.0"
|
||||
resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05"
|
||||
@@ -1378,7 +1369,7 @@ os-locale@^2.0.0:
|
||||
lcid "^1.0.0"
|
||||
mem "^1.1.0"
|
||||
|
||||
os-tmpdir@^1.0.0, os-tmpdir@~1.0.2:
|
||||
os-tmpdir@^1.0.0:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"
|
||||
|
||||
@@ -1646,7 +1637,7 @@ right-align@^0.1.1:
|
||||
dependencies:
|
||||
align-text "^0.1.1"
|
||||
|
||||
rimraf@2, rimraf@^2.5.1, rimraf@^2.6.1:
|
||||
rimraf@2, rimraf@^2.5.1, rimraf@^2.6.1, rimraf@^2.6.2:
|
||||
version "2.6.2"
|
||||
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36"
|
||||
dependencies:
|
||||
@@ -1663,12 +1654,6 @@ safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@~5.1.0,
|
||||
version "5.1.1"
|
||||
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853"
|
||||
|
||||
schema-utils@^0.3.0:
|
||||
version "0.3.0"
|
||||
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.3.0.tgz#f5877222ce3e931edae039f17eb3716e7137f8cf"
|
||||
dependencies:
|
||||
ajv "^5.0.0"
|
||||
|
||||
"semver@2 || 3 || 4 || 5", semver@^5.3.0:
|
||||
version "5.4.1"
|
||||
resolved "https://registry.yarnpkg.com/semver/-/semver-5.4.1.tgz#e059c09d8571f0540823733433505d3a2f00b18e"
|
||||
@@ -1865,12 +1850,6 @@ timers-browserify@^2.0.4:
|
||||
dependencies:
|
||||
setimmediate "^1.0.4"
|
||||
|
||||
tmp@0.0.33:
|
||||
version "0.0.33"
|
||||
resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9"
|
||||
dependencies:
|
||||
os-tmpdir "~1.0.2"
|
||||
|
||||
to-arraybuffer@^1.0.0:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz#7d229b1fcc637e466ca081180836a7aabff83f43"
|
||||
|
||||
Reference in New Issue
Block a user