Skip to content
This repository has been archived by the owner on Nov 17, 2021. It is now read-only.

Commit

Permalink
fix(Editor): Fix asset resolution for example articles
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-ketch committed Mar 9, 2020
1 parent 81af97a commit 160c892
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 56 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"build:browser": "webpack --mode production && tsc --emitDeclarationOnly --project tsconfig.browser.json",
"build:lib": "tsc --project tsconfig.lib.json",
"dev": "webpack-dev-server --mode development --hot --open",
"docs": "npm run docs:readme && npm run docs:gallery && npm run docs:app",
"docs": "npm run build:lib && npm run docs:readme && npm run docs:gallery && npm run docs:app",
"docs:readme": "ts-node --files src/scripts/readme.ts",
"docs:gallery": "ts-node --files src/scripts/gallery.ts",
"docs:app": "webpack --mode production --env.docs=true",
Expand Down
2 changes: 1 addition & 1 deletion src/galleryTemplate.ejs → src/demo/templates/gallery.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<header id="header"></header>

<main>
<%= require("./gallery.ejs")() %>
<%= require("../../gallery.ejs")() %>
</main>
</body>
</html>
2 changes: 1 addition & 1 deletion src/template.html → src/demo/templates/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ <h4>Pull Request</h4>
</menu>

<main>
<iframe id="preview" src="./examples/articleReadme.html"></iframe>
<iframe id="preview" src="/examples/articleReadme.html"></iframe>
</main>

<div id="modalTarget"></div>
Expand Down
4 changes: 2 additions & 2 deletions src/demo/utils/preview.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { append, create } from '../../util'
import { keys } from '.'
import { examples, resolveExample } from '../../examples'
import { append, create } from '../../util'

export const getExample = (): string => {
return (
Expand All @@ -21,7 +21,7 @@ export const setExample = (example: string): void => {

const preview = getPreview()
if (preview !== null && !preview.getAttribute('src')?.includes(example)) {
preview.setAttribute('src', `examples/${resolveExample(example)}.html`)
preview.setAttribute('src', `/examples/${resolveExample(example)}.html`)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/demo/utils/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {

export const getThemeCSS = (theme: string): string => {
const req = new XMLHttpRequest()
req.open('GET', `themes/${theme}/styles.css`, false)
req.open('GET', `/themes/${theme}/styles.css`, false)
req.send(null)
return req.responseText
}
Expand Down
23 changes: 22 additions & 1 deletion src/scripts/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,29 @@ function articleAntibodies(): Promise<string | undefined> {
)
}

/**
* Transforms implicit relative URLs (`somePath.jpg`) found in the generated example HTML documents, into
* explicitly relative paths ('./somePath.jpg'). This allows the assets to be discovered inside the Theme Editor iframe.
*/
const qualifyRelativeUrls = (): void => {
EXAMPLES.map(example => {
const filePath = `${ex(example.name)}.html`
const contents = fs
.readFileSync(filePath)
.toString()
.replace(
/((?:src|href)=["'])(?!(?:https?)?:\/\/)([^/#.][^'"]+)/gm,
'$1./$2'
)

fs.writeFileSync(filePath, contents)
})
}

// Run each function
Promise.all(EXAMPLES.map(example => example())).catch(err => console.error(err))
Promise.all(EXAMPLES.map(example => example()))
.then(() => qualifyRelativeUrls())
.catch(err => console.error(err))

// Generate `../examples/examples.ts`
fs.writeFileSync(
Expand Down
8 changes: 4 additions & 4 deletions src/scripts/gallery.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
*
* Run using `npm run docs:gallery`. Noting that this
* uses built themes in `docs/themes` so `npm run docs:app`
* uses built themes in `dist/themes` so `npm run build:lib`
* needs to be done first.
*/

Expand All @@ -26,7 +26,7 @@ import { themes } from '../themes/index'
const themesDir = path.join(__dirname, '..', 'themes')
const examplesDir = path.join(__dirname, '..', 'examples')
const srcDir = path.join(__dirname, '..')
const docsDir = path.join(__dirname, '..', '..', 'docs')
const distDir = path.join(__dirname, '..', '..', 'dist')

const stencila = organization({
name: 'Stencila',
Expand Down Expand Up @@ -120,7 +120,7 @@ async function generateGallery(): Promise<void> {
await write(gallery, path.join(srcDir, 'gallery.ejs'), {
isStandalone: false,
format: 'html',
theme: path.join(srcDir, 'themes', 'galleria')
theme: path.join(distDir, 'themes', 'galleria')
})

await shutdown()
Expand Down Expand Up @@ -148,7 +148,7 @@ async function generateSummary(
const screenshot = path.join(tmpdir(), 'screenshots', `${theme}.png`)

await write(example, screenshot, {
theme: path.join(docsDir, 'themes', theme),
theme: path.join(distDir, 'themes', theme),
size: { height: 500, width: 800 }
})

Expand Down
59 changes: 14 additions & 45 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ module.exports = (env = {}, { mode }) => {
const contentBase = isDocs ? 'docs' : 'dist'

const entries = [
'./src/**/*.{css,ts,tsx,html,ttf,woff,woff2}',
// template.html is used as a basis for HtmlWebpackPlugin, and should not be used as an entry point
'!./src/{gallery,template}.html',
'./src/**/*.{css,ts,tsx,ttf,woff,woff2}',
// Don’t compile test files for package distribution
'!**/*.{d,test}.ts',
// These files make use of Node APIs, and do not need to be packaged for Browser targets
Expand All @@ -45,7 +43,7 @@ module.exports = (env = {}, { mode }) => {
// Don’t build HTML demo files for package distribution
...(isDocs || isDevelopment
? ['./src/**/*.{jpg,png,gif}']
: ['!**/*.html', '!**/demo/*', '!**/examples/*'])
: ['!**/demo/*', '!**/examples/*'])
]

const entry = globby.sync(entries).reduce(
Expand All @@ -63,13 +61,13 @@ module.exports = (env = {}, { mode }) => {
isDocs || isDevelopment
? [
new HtmlWebpackPlugin({
filename: 'editor.html',
template: './src/template.html',
filename: 'editor/index.html',
template: './src/demo/templates/template.html',
chunks: ['demo/styles', 'themes/stencila/styles', 'demo/app.tsx']
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/galleryTemplate.ejs',
template: './src/demo/templates/gallery.ejs',
chunks: [
'demo/styles',
'demo/gallery.tsx',
Expand All @@ -82,7 +80,7 @@ module.exports = (env = {}, { mode }) => {
return {
entry,
resolve: {
extensions: ['.ts', '.tsx', '.js', '.css', '.html']
extensions: ['.ts', '.tsx', '.js', '.css']
},
mode: mode || 'development',
output: {
Expand All @@ -91,27 +89,7 @@ module.exports = (env = {}, { mode }) => {
},
devServer: {
contentBase: path.join(__dirname, contentBase),
overlay: true,
staticOptions: {
extensions: ['.html', '.htm']
},
// Resolve URLS without explicit file extensions
// the above `devServer.staticOptions.extensions` seems to have no effect
before: function(app, server, compiler) {
app.use(function(req, res, next) {
if (req.path !== '/' && req.path.indexOf('.') === -1) {
let url = req.url.split('?')
let [reqPath, ...rest] = url

if (url.length > 1) {
req.url = [reqPath, '.html', '?', ...rest].join('')
} else {
req.url = `${reqPath}.html`
}
next()
} else next()
})
}
overlay: true
},
plugins: [
new CleanWebpackPlugin(),
Expand All @@ -127,7 +105,14 @@ module.exports = (env = {}, { mode }) => {
// non TypeScript/JavaScript files (i.e. for font and CSS files).
new FileManagerPlugin({
onEnd: {
copy: [
{
source: 'src/examples/*.{html,html.media}',
destination: `${contentBase}/examples/`
}
],
delete: [
`${contentBase}/**/styles.js`,
`${contentBase}/**/styles.js`,
`${contentBase}/fonts/**/*.js`,
`${contentBase}/generate`,
Expand All @@ -149,22 +134,6 @@ module.exports = (env = {}, { mode }) => {
}
},
{ test: /\.ejs$/, loader: 'ejs-loader' },
{
test: /\.html$/i,
// Don't transform HtmlWebpackPlugin generated file
exclude: /template\.html$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: fileLoaderOutputPath
}
},
'extract-loader',
'html-loader'
]
},
{
test: /\.(css)$/,
use: [
Expand Down

0 comments on commit 160c892

Please sign in to comment.