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

Add author and keywords directives and CLI options for setting metadata #370

Merged
merged 6 commits into from
Aug 10, 2021
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 @@

- PDF metadata support ([#367](https://github.com/marp-team/marp-cli/issues/367), [#369](https://github.com/marp-team/marp-cli/pull/369))
- `--pdf-notes` option to add presenter notes into PDF as annotations ([#261](https://github.com/marp-team/marp-cli/issues/261), [#369](https://github.com/marp-team/marp-cli/pull/369))
- `author` and `keywords` metadata options / global directives ([#367](https://github.com/marp-team/marp-cli/issues/367), [#370](https://github.com/marp-team/marp-cli/pull/370))

## v1.2.0 - 2021-07-22

Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,8 @@ Through [global directives] or CLI options, you can set metadata for a converted
| :-----------------: | :-------------: | :------------------------------ | :-------------- |
| `title` | `--title` | Define title of the slide deck | HTML, PDF, PPTX |
| `description` | `--description` | Define description of the slide | HTML, PDF, PPTX |
| `author` | `--author` | Define author of the slide deck | HTML, PDF, PPTX |
| `keywords` | `--keywords` | Define comma-separated keywords | HTML, PDF |
| `url` | `--url` | Define [canonical URL] \* | HTML |
| `image` | `--og-image` | Define [Open Graph] image URL | HTML |

Expand All @@ -300,6 +302,8 @@ Marp CLI supports _additional [global directives]_ to specify metadata in Markdo
---
title: Marp slide deck
description: An example slide deck created by Marp CLI
author: Yuki Hattori
keywords: marp,marp-cli,slide
url: https://marp.app/
image: https://marp.app/og-image.jpg
---
Expand All @@ -311,7 +315,7 @@ image: https://marp.app/og-image.jpg

### By CLI option

Marp CLI prefers CLI option to global directives. You can override metadata values by `--title`, `--description`, `--url`, and `--og-image`.
Marp CLI prefers CLI option to global directives. You can override metadata values by `--title`, `--description`, `--author`, `--keywords`, `--url`, and `--og-image`.

## Theme

Expand Down Expand Up @@ -445,6 +449,7 @@ If you want to prevent looking up a configuration file, you can pass `--no-confi
| Key | Type | CLI option | Description |
| :---------------- | :-------------------------: | :-------------------: | :----------------------------------------------------------------------------------------------------- |
| `allowLocalFiles` | boolean | `--allow-local-files` | Allow to access local files from Markdown while converting PDF _(NOT SECURE)_ |
| `author` | string | `--author` | Define author of the slide deck |
| `bespoke` | object | | Setting options for `bespoke` template |
| ┗ `osc` | boolean | `--bespoke.osc` | \[Bespoke\] Use on-screen controller (`true` by default) |
| ┗ `progress` | boolean | `--bespoke.progress` | \[Bespoke\] Use progress bar (`false` by default) |
Expand All @@ -456,6 +461,7 @@ If you want to prevent looking up a configuration file, you can pass `--no-confi
| `imageScale` | number | `--image-scale` | The scale factor for rendered images (`1` by default, or `2.5` for PPTX conversion) |
| `inputDir` | string | `--input-dir` `-I` | The base directory to find markdown and theme CSS |
| `jpegQuality` | number | `--jpeg-quality` | Setting JPEG image quality (`85` by default) |
| `keywords` | string \| string[] | `--keywords` | Define keywords for the slide deck (Accepts comma-separated string and array of string) |
| `lang` | string | | Define the language of converted HTML |
| `ogImage` | string | `--og-image` | Define [Open Graph] image URL |
| `options` | object | | The base options for the constructor of engine |
Expand Down
6 changes: 6 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import osLocale from 'os-locale'
import { info, warn } from './cli'
import { ConverterOption, ConvertType } from './converter'
import resolveEngine, { ResolvableEngine, ResolvedEngine } from './engine'
import { keywordsAsArray } from './engine/meta-plugin'
import { error } from './error'
import { TemplateOption } from './templates'
import { Theme, ThemeSet } from './theme'
Expand All @@ -17,6 +18,7 @@ type Overwrite<T, U> = Omit<T, Extract<keyof T, keyof U>> & U
interface IMarpCLIArguments {
_?: string[]
allowLocalFiles?: boolean
author?: string
baseUrl?: string
bespoke?: {
osc?: boolean
Expand All @@ -31,6 +33,7 @@ interface IMarpCLIArguments {
imageScale?: number
inputDir?: string
jpegQuality?: number
keywords?: string
ogImage?: string
output?: string | false
pdf?: boolean
Expand All @@ -51,6 +54,7 @@ export type IMarpCLIConfig = Overwrite<
{
engine?: ResolvableEngine | ResolvableEngine[]
html?: ConverterOption['html']
keywords?: string | string[]
lang?: string
options?: ConverterOption['options']
themeSet?: string | string[]
Expand Down Expand Up @@ -211,8 +215,10 @@ export class MarpCLIConfig {
baseUrl: this.args.baseUrl ?? this.conf.baseUrl,
engine: this.engine.klass,
globalDirectives: {
author: this.args.author ?? this.conf.author,
description: this.args.description ?? this.conf.description,
image: this.args.ogImage ?? this.conf.ogImage,
keywords: keywordsAsArray(this.args.keywords ?? this.conf.keywords),
theme: theme instanceof Theme ? theme.name : theme,
title: this.args.title ?? this.conf.title,
url: this.args.url ?? this.conf.url,
Expand Down
9 changes: 7 additions & 2 deletions src/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,9 @@ export class Converter {

if (tpl.rendered.title) pdfDoc.setTitle(tpl.rendered.title)
if (tpl.rendered.description) pdfDoc.setSubject(tpl.rendered.description)
if (tpl.rendered.author) pdfDoc.setAuthor(tpl.rendered.author)
if (tpl.rendered.keywords)
pdfDoc.setKeywords([tpl.rendered.keywords.join('; ')])

if (this.options.pdfNotes) {
const pages = pdfDoc.getPages()
Expand All @@ -282,7 +285,9 @@ export class Converter {
Subtype: 'Text',
Rect: [0, 20, 20, 20],
Contents: PDFHexString.fromText(notes),
// Title: PDFString.of('Author'), // TODO: Set author
T: tpl.rendered.author
? PDFHexString.fromText(tpl.rendered.author)
: undefined,
Name: 'Note',
Subj: PDFString.of('Note'),
C: [1, 0.92, 0.42], // RGB
Expand Down Expand Up @@ -377,7 +382,7 @@ export class Converter {
const pptx = new (await import('pptxgenjs')).default()
const layoutName = `${tpl.rendered.size.width}x${tpl.rendered.size.height}`

pptx.author = CREATED_BY_MARP
pptx.author = tpl.rendered.author ?? CREATED_BY_MARP
pptx.company = CREATED_BY_MARP

pptx.defineLayout({
Expand Down
6 changes: 5 additions & 1 deletion src/engine/info-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
export interface EngineInfo {
theme: string | undefined
author: string | undefined
description: string | undefined
image: string | undefined
keywords: string[] | undefined
length: number
size: { height: number; width: number }
theme: string | undefined
title: string | undefined
url: string | undefined
}
Expand All @@ -22,8 +24,10 @@ export default function infoPlugin(md: any) {

const info: EngineInfo = {
theme,
author: globalDirectives.marpCLIAuthor,
description: globalDirectives.marpCLIDescription,
image: globalDirectives.marpCLIImage,
keywords: globalDirectives.marpCLIKeywords,
title: globalDirectives.marpCLITitle,
url: globalDirectives.marpCLIURL,
size: {
Expand Down
29 changes: 29 additions & 0 deletions src/engine/meta-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,40 @@ import { URL } from 'url'
import { Marpit } from '@marp-team/marpit'
import { warn } from '../cli'

export const keywordsAsArray = (keywords: unknown): string[] | undefined => {
let kws: any[] | undefined

if (Array.isArray(keywords)) {
kws = keywords
} else if (typeof keywords === 'string') {
kws = keywords.split(',').map((s) => s.trim())
}

if (kws) {
const filtered = [
...new Set(
kws.filter(
(kw: unknown): kw is string => typeof kw === 'string' && !!kw
)
).values(),
]

if (filtered.length > 0) return filtered
}

return undefined
}

export default function metaPlugin({ marpit }: { marpit: Marpit }) {
Object.assign(marpit.customDirectives.global, {
author: (v) => (typeof v === 'string' ? { marpCLIAuthor: v } : {}),
description: (v) =>
typeof v === 'string' ? { marpCLIDescription: v } : {},
image: (v) => (typeof v === 'string' ? { marpCLIImage: v } : {}),
keywords: (v) => {
const marpCLIKeywords = keywordsAsArray(v)
return marpCLIKeywords ? { marpCLIKeywords } : {}
},
title: (v) => (typeof v === 'string' ? { marpCLITitle: v } : {}),
url: (v) => {
// URL validation
Expand Down
12 changes: 11 additions & 1 deletion src/marp-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ enum OptionGroup {
Basic = 'Basic Options:',
Converter = 'Converter Options:',
Template = 'Template Options:',
Meta = 'Meta Options:',
Meta = 'Metadata Options:',
Marp = 'Marp / Marpit Options:',
}

Expand Down Expand Up @@ -190,6 +190,16 @@ export const marpCli = async (
group: OptionGroup.Meta,
type: 'string',
},
author: {
describe: 'Define author of the slide deck',
group: OptionGroup.Meta,
type: 'string',
},
keywords: {
describe: 'Define comma-separated keywords for the slide deck',
group: OptionGroup.Meta,
type: 'string',
},
url: {
describe: 'Define canonical URL',
group: OptionGroup.Meta,
Expand Down
2 changes: 2 additions & 0 deletions src/templates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ interface TemplateCoreOption {
}

export interface TemplateMeta {
author: string | undefined
description: string | undefined
image: string | undefined
keywords: string[] | undefined
title: string | undefined
url: string | undefined
}
Expand Down
7 changes: 7 additions & 0 deletions src/templates/layout.pug
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,17 @@ html(lang=lang)
if image
meta(property="og:image:alt", content=title)

if author
meta(name="author", content=author)
meta(property="article:author", content=author)

if description
meta(name="description", content=description)
meta(property="og:description", content=description)

if keywords && keywords.length > 1
meta(name="keywords", content=keywords.join(','))

if url
link(rel="canonical", href=url)
meta(property="og:url", content=url)
Expand Down
52 changes: 47 additions & 5 deletions test/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Marp from '@marp-team/marp-core'
import { Options } from '@marp-team/marpit'
import cheerio from 'cheerio'
import { imageSize } from 'image-size'
import { PDFDocument, PDFDict, PDFName, PDFString, PDFHexString } from 'pdf-lib'
import { PDFDocument, PDFDict, PDFName, PDFHexString } from 'pdf-lib'
import { Page } from 'puppeteer-core/lib/cjs/puppeteer/common/Page'
import yauzl from 'yauzl'
import { Converter, ConvertType, ConverterOption } from '../src/converter'
Expand Down Expand Up @@ -139,13 +139,19 @@ describe('Converter', () => {
globalDirectives: {
title: 'Title',
description: 'Desc',
author: 'Author',
keywords: ['a', '"b"', 'c'],
url: 'https://example.com/canonical',
image: 'https://example.com/image.jpg',
},
}).convert('---\ntitle: original\n---')

expect(result).toContain('<title>Title</title>')
expect(result).toContain('<meta name="description" content="Desc">')
expect(result).toContain('<meta name="author" content="Author">')
expect(result).toContain(
'<meta name="keywords" content="a,&quot;b&quot;,c">'
)
expect(result).toContain(
'<link rel="canonical" href="https://example.com/canonical">'
)
Expand All @@ -154,15 +160,24 @@ describe('Converter', () => {
)
})

it('allows reset meta values by empty string', async () => {
it('allows reset meta values by empty string / array', async () => {
const { result } = await instance({
globalDirectives: { title: '', description: '', url: '', image: '' },
globalDirectives: {
title: '',
description: '',
author: '',
keywords: [],
url: '',
image: '',
},
}).convert(
'---\ntitle: A\ndescription: B\nurl: https://example.com/\nimage: /hello.jpg\n---'
'---\ntitle: A\ndescription: B\nauthor: C\nkeywords: D\nurl: https://example.com/\nimage: /hello.jpg\n---'
)

expect(result).not.toContain('<title>')
expect(result).not.toContain('<meta name="description"')
expect(result).not.toContain('<meta name="author"')
expect(result).not.toContain('<meta name="keywords"')
expect(result).not.toContain('<link rel="canonical"')
expect(result).not.toContain('<meta property="og:image"')
})
Expand Down Expand Up @@ -304,13 +319,20 @@ describe('Converter', () => {

await pdfInstance({
output: 'test.pdf',
globalDirectives: { title: 'title', description: 'description' },
globalDirectives: {
title: 'title',
description: 'description',
author: 'author',
keywords: ['a', 'b', 'c'],
},
}).convertFile(new File(onePath))

const pdf = await PDFDocument.load(write.mock.calls[0][1])

expect(pdf.getTitle()).toBe('title')
expect(pdf.getSubject()).toBe('description')
expect(pdf.getAuthor()).toBe('author')
expect(pdf.getKeywords()).toBe('a; b; c')
},
puppeteerTimeoutMs
)
Expand Down Expand Up @@ -377,6 +399,24 @@ describe('Converter', () => {
},
puppeteerTimeoutMs
)

it('sets a comment author to notes if set author global directive', async () => {
const write = (<any>fs).__mockWriteFile()

await pdfInstance({
output: 'test.pdf',
pdfNotes: true,
globalDirectives: { author: 'author' },
}).convertFile(new File(threePath))

const pdf = await PDFDocument.load(write.mock.calls[0][1])
const annotaionRef = pdf.getPage(0).node.Annots()?.get(0)
const annotation = pdf.context.lookup(annotaionRef, PDFDict)

expect(annotation.get(PDFName.of('T'))).toStrictEqual(
PDFHexString.fromText('author')
)
})
})
})

Expand Down Expand Up @@ -467,6 +507,7 @@ describe('Converter', () => {
globalDirectives: {
title: 'Test meta',
description: 'Test description',
author: 'author',
},
}).convertFile(new File(onePath))

Expand All @@ -475,6 +516,7 @@ describe('Converter', () => {

expect(meta['dc:title']).toBe('Test meta')
expect(meta['dc:subject']).toBe('Test description')
expect(meta['dc:creator']).toBe('author')

// Custom scale
expect(setViewport).toHaveBeenCalledWith(
Expand Down