Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Experimental] Support opening preview window provided by Carlo #44

Merged
merged 12 commits into from
Dec 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- Support functional engine ([#42](https://github.com/marp-team/marp-cli/pull/42))
- Output the configured engine in `version` (`-v`) option ([#43](https://github.com/marp-team/marp-cli/pull/43))
- Experimental support `--preview` option to open preview window provided by [Carlo](https://github.com/GoogleChromeLabs/carlo) ([#44](https://github.com/marp-team/marp-cli/pull/44))

## v0.0.14 - 2018-11-24

Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,8 @@
"util.promisify": "^1.0.0",
"ws": "^6.1.2",
"yargs": "^12.0.5"
},
"optionalDependencies": {
"carlo": "^0.9.41"
}
}
22 changes: 22 additions & 0 deletions src/__mocks__/preview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { EventEmitter } from 'events'

const preview = require.requireActual('../preview')
const { carlo } = preview

class CarloAppMock extends EventEmitter {
load = jest.fn().mockResolvedValue(0)
exit = jest.fn().mockResolvedValue(0)
}

preview.carloMock = () => {
const app = new CarloAppMock()
const mockedCarlo = { launch: jest.fn(() => app) }

preview.carlo = mockedCarlo
return { app, carlo: mockedCarlo }
}

preview.carloOriginal = () => (preview.carlo = carlo)
preview.carloUndefined = () => (preview.carlo = undefined)

export = preview
25 changes: 24 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { info, warn } from './cli'
import { ConverterOption, ConvertType } from './converter'
import resolveEngine, { ResolvableEngine, ResolvedEngine } from './engine'
import { CLIError } from './error'
import { carlo } from './preview'
import { Theme, ThemeSet } from './theme'

const lstat = promisify(fs.lstat)
Expand All @@ -25,6 +26,7 @@ export interface IMarpCLIArguments {
inputDir?: string
output?: string
pdf?: boolean
preview?: boolean
server?: boolean
template?: string
theme?: string
Expand Down Expand Up @@ -100,6 +102,23 @@ export class MarpCLIConfig {
initialThemes
)

const preview = (() => {
const p = this.pickDefined(this.args.preview, this.conf.preview) || false
let warnMes: string | undefined

if (p) {
if (!carlo) warnMes = 'Preview window is available only in Node >= 7.6.'
if (process.env.IS_DOCKER)
warnMes = 'Preview window cannot show in an official docker image.'
}
if (warnMes) {
warn(`${warnMes} preview option was ignored.`)
return false
}

return p
})()

if (
themeSet.themes.size <= initialThemes.length &&
themeSetPathes.length > 0
Expand All @@ -120,6 +139,7 @@ export class MarpCLIConfig {
html: this.pickDefined(this.args.html, this.conf.html),
lang: this.conf.lang || (await osLocale()).replace(/[_@]/g, '-'),
options: this.conf.options || {},
preview: carlo && preview,
readyScript: this.engine.browserScript
? `<script>${this.engine.browserScript}</script>`
: undefined,
Expand All @@ -132,7 +152,10 @@ export class MarpCLIConfig {
? ConvertType.pdf
: ConvertType.html,
watch:
this.pickDefined(this.args.watch, this.conf.watch) || server || false,
this.pickDefined(this.args.watch, this.conf.watch) ||
preview ||
server ||
false,
}
}

Expand Down
1 change: 1 addition & 0 deletions src/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface ConverterOption {
lang: string
options: MarpitOptions
output?: string
preview?: boolean
readyScript?: string
server?: boolean
template: string
Expand Down
41 changes: 35 additions & 6 deletions src/marp-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import fromArguments from './config'
import { Converter, ConvertedCallback } from './converter'
import { CLIError, error } from './error'
import { File, FileType } from './file'
import { carlo, Preview, ServerPreview } from './preview'
import { Server } from './server'
import templates from './templates'
import version from './version'
Expand Down Expand Up @@ -73,6 +74,17 @@ export default async function(argv: string[] = []): Promise<number> {
group: OptionGroup.Basic,
type: 'boolean',
},
...(process.env.IS_DOCKER
? {}
: {
preview: {
describe: `Open preview window (EXPERIMENTAL)${
carlo ? '' : ` ${chalk.red('[Requires Node >= 7.6.x]')}`
}`,
group: OptionGroup.Basic,
type: 'boolean',
},
}),
pdf: {
describe: 'Convert slide deck into PDF',
group: OptionGroup.Converter,
Expand Down Expand Up @@ -197,22 +209,39 @@ export default async function(argv: string[] = []): Promise<number> {
}
)

let preview: Preview | undefined = undefined

if (cvtOpts.server) {
const server = new Server(converter, {
onConverted,
directoryIndex: ['index.md', 'PITCHME.md'], // GitPitch compatible
})
await server.start()

const url = `http://localhost:${server.port}`
const message = `[Server mode] Start server listened at ${url}/ ...`

cli.info(chalk.green(message))
if (cvtOpts.preview) preview = new ServerPreview(url)
} else {
if (cvtOpts.preview) {
cli.warn(
chalk.yellow(
'Currently a preview window can open only in server mode.'
)
)
}
cli.info(chalk.green('[Watch mode] Start watching...'))
}

if (preview) {
cli.info(
chalk.green(
`[Server mode] Start server listened at http://localhost:${
server.port
}/ ...`
chalk.cyan(
'[Preview window] (EXPERIMENTAL) Opening preview window...'
)
)
} else {
cli.info(chalk.green('[Watch mode] Start watching...'))
await preview.open()
preview.on('exit', () => process.exit())
}
}

Expand Down
62 changes: 62 additions & 0 deletions src/preview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { File } from './file'

export const carlo = (() => {
try {
// tslint:disable-next-line:no-implicit-dependencies
return require('carlo')
} catch (e) {
return undefined
}
})()

export abstract class Preview {
private carlo: any
readonly file: File

constructor(file: File) {
this.file = file
}

async open() {
await this.close()

this.carlo = await carlo.launch({
channel: ['canary', 'stable'],
title: 'Marp CLI',
args: ['--enable-blink-gen-property-trees'],
})

await this.carlo.load(this.file.path)
}

async close() {
if (this.carlo) await this.carlo.exit()
}

on(event: string, callback: Function): void {
if (!this.carlo) throw new Error('Preview window is not yet initialized.')
this.carlo.on(event, callback)
}
}

export class FilePreview extends Preview {
// TODO: Support multiple windows through regular file conversions if Carlo
// could support to hide main window.
//
// @see https://github.com/GoogleChromeLabs/carlo/issues/53
}

export class ServerPreview extends Preview {
private static encodeURIComponentRFC3986 = url =>
encodeURIComponent(url).replace(
/[!'()*]/g,
c => `%${c.charCodeAt(0).toString(16)}`
)

constructor(url: string) {
const encodedUrl = ServerPreview.encodeURIComponentRFC3986(url)
const serverFile = `data:text/html,<html><head><meta http-equiv="refresh" content="0;URL='${encodedUrl}'" /></head></html>`

super(new File(serverFile))
}
}
3 changes: 0 additions & 3 deletions src/templates/bespoke/bespoke.scss
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ $progressHeight: 5px;
width: 100%;
z-index: -1;

/* Hack for incorrect rendering on Chrome */
transform: translateZ(0);

&.bespoke-marp-active {
pointer-events: auto;
z-index: 0;
Expand Down
Loading