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

Allow using twemoji via png by added emoji.twemoji.ext option #67

Merged
merged 6 commits into from
Feb 4, 2019
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,18 @@

## [Unreleased]

### Added

- Allow using twemoji via PNG by added `emoji.twemoji.ext` option ([#67](https://github.com/marp-team/marp-core/pull/67))

### Changed

- Normalize known self-closing HTML elements with `xhtmlOut: true` ([#66](https://github.com/marp-team/marp-core/pull/66))

### Deprecated

- `emoji.twemojiBase` option has soft-deprecated in favor of `emoji.twemoji.base` ([#67](https://github.com/marp-team/marp-core/pull/67))

## v0.5.2 - 2019-01-31

### Changed
Expand Down
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,9 @@ const marp = new Marp({
emoji: {
shortcode: true,
unicode: false,
twemojiBase: '/resources/twemoji/',
twemoji: {
base: '/resources/twemoji/',
},
},
math: {
katexFontPath: '/resources/fonts/',
Expand Down Expand Up @@ -221,9 +223,10 @@ Setting about emoji conversions.
- It can convert Unicode emoji into twemoji when setting `"twemoji"`. 🐶 → <img src="https://twemoji.maxcdn.com/2/svg/1f436.svg" alt="🐶" width="16" height="16" valign="middle" /> _(default)_
- If you not want this aggressive conversion, please set `false`.

- **`twemojiBase`**: _`string`_
- **`twemoji`**: _`object`_

- It is corresponded to [twemoji's `base` option](https://github.com/twitter/twemoji#object-as-parameter). By default, marp-core will use online emoji images [through MaxCDN (twemoji's default)](https://github.com/twitter/twemoji#cdn-support).
- **`base`**: _`string`_ - It is corresponded to [twemoji's `base` option](https://github.com/twitter/twemoji#object-as-parameter). By default, marp-core will use online emoji images [through MaxCDN (twemoji's default)](https://github.com/twitter/twemoji#cdn-support).
- **`ext`**: _`"svg"` | `"png"`_ - Setting the file type of twemoji images. _(`svg` by default)_

> **For developers:** When you setting `unicode` option as `true`, Markdown parser will convert Unicode emoji into tokens internally. The rendering result is same as in `false`.

Expand Down
58 changes: 45 additions & 13 deletions src/emoji/emoji.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import emojiRegex from 'emoji-regex'
import Token from 'markdown-it/lib/token'
import markdownItEmoji from 'markdown-it-emoji'
import twemoji from 'twemoji'
import { marpEnabledSymbol } from '../symbol'
import twemojiCSS from './twemoji.scss'

export interface EmojiOptions {
shortcode?: boolean | 'twemoji'
twemojiBase?: string
twemoji?: TwemojiOptions
unicode?: boolean | 'twemoji'

/** @deprecated Use `twemoji.base` instead. */
twemojiBase?: string
}

interface TwemojiOptions {
base?: string
ext?: 'svg' | 'png'
}

const regexForSplit = new RegExp(`(${emojiRegex().source})`, 'g')
Expand All @@ -19,26 +26,51 @@ export const css = (opts: EmojiOptions) =>
: undefined

export function markdown(md, opts: EmojiOptions): void {
const twemojiOpts = opts.twemoji || {}
const twemojiExt = twemojiOpts.ext || 'svg'

const twemojiParse = (content: string): string =>
twemoji
.parse(content, {
base: opts.twemojiBase,
className: '__placeholder__',
ext: '.svg',
size: 'svg',
})
.replace('class="__placeholder__"', 'data-marp-twemoji')
twemoji.parse(content, {
attributes: () => ({ 'data-marp-twemoji': '' }),
base:
twemojiOpts.base || opts.twemojiBase || 'https://twemoji.maxcdn.com/2/',
ext: `.${twemojiExt}`,
size: twemojiExt === 'svg' ? 'svg' : 72,
})

const twemojiRenderer = (token: any[], idx: number): string =>
twemojiParse(token[idx].content)

if (opts.shortcode) {
md.use(markdownItEmoji, { shortcuts: {} })
if (opts.shortcode === 'twemoji') md.renderer.rules.emoji = twemojiRenderer
// Pick rules to avoid collision with other markdown-it plugin
const picker = {
core: { ruler: { push: (_, rule) => (picker.rule = rule) } },
renderer: { rules: { emoji: () => {} } },
rule: <Function>(() => {}),
utils: md.utils,
}

markdownItEmoji(picker, { shortcuts: {} })

md.core.ruler.push('marp_emoji', state => {
const { Token } = state

state.Token = function replacedToken(name, ...args) {
return new Token(name === 'emoji' ? 'marp_emoji' : name, ...args)
}

picker.rule(state)
state.Token = Token
})

md.renderer.rules.marp_emoji =
opts.shortcode === 'twemoji'
? twemojiRenderer
: picker.renderer.rules.emoji
}

if (opts.unicode) {
md.core.ruler.after('inline', 'marp_unicode_emoji', ({ tokens }) => {
md.core.ruler.after('inline', 'marp_unicode_emoji', ({ tokens, Token }) => {
for (const token of tokens) {
if (token.type === 'inline') {
const newChildren: any[] = []
Expand Down
12 changes: 7 additions & 5 deletions src/fitting/fitting.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Token from 'markdown-it/lib/token'
import fittingCSS from './fitting.scss'
import { Marp } from '../marp'
import { marpEnabledSymbol } from '../symbol'
Expand All @@ -12,11 +11,11 @@ export const svgContentWrapAttr = 'data-marp-fitting-svg-content-wrap'

export type ThemeResolver = () => string | undefined

function wrapTokensByFittingToken(tokens: any[]): any[] {
const open = new Token('marp_fitting_open', 'span', 1)
function wrapTokensByFittingToken(token, tokens: any[]): any[] {
const open = new token('marp_fitting_open', 'span', 1)
open.attrSet(attr, 'plain')

return [open, ...tokens, new Token('marp_fitting_close', 'span', -1)]
return [open, ...tokens, new token('marp_fitting_close', 'span', -1)]
}

// Wrap code block and fence renderer by fitting elements.
Expand Down Expand Up @@ -70,7 +69,10 @@ function fittingHeader(md, marp: Marp): void {
}

if (requireWrapping) {
token.children = wrapTokensByFittingToken(token.children)
token.children = wrapTokensByFittingToken(
state.Token,
token.children
)
}
} else if (token.type === 'heading_close') {
target = undefined
Expand Down
1 change: 0 additions & 1 deletion src/marp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export class Marp extends Marpit {
],
emoji: {
shortcode: 'twemoji',
twemojiBase: undefined,
unicode: 'twemoji',
...(opts.emoji || {}),
},
Expand Down
25 changes: 22 additions & 3 deletions test/marp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,35 @@ describe('Marp', () => {
})
})

describe('twemojiBase option', () => {
const instance = (emoji: EmojiOptions = {}) => new Marp({ emoji })
describe('twemoji option', () => {
const instance = (twemoji: EmojiOptions['twemoji'] = {}) =>
new Marp({ emoji: { twemoji } })

it('uses twemoji CDN by default', () => {
it('uses SVG via twemoji CDN by default', () => {
const $ = cheerio.load(instance().render('# :ok_hand:').html)
const src = $('h1 > img[data-marp-twemoji]').attr('src')

expect(src).toBe('https://twemoji.maxcdn.com/2/svg/1f44c.svg')
})

describe('base option', () => {
it('uses specified base', () =>
expect(
instance({ base: '/assets/twemoji/' }).render(':+1:').html
).toContain('/assets/twemoji/svg/1f44d.svg'))
})

describe('ext option', () => {
it('uses PNG emoji by setting png', () =>
expect(instance({ ext: 'png' }).render(':+1:').html).toContain(
'https://twemoji.maxcdn.com/2/72x72/1f44d.png'
))
})
})

describe('twemojiBase option [soft-deprecated]', () => {
const instance = (emoji: EmojiOptions = {}) => new Marp({ emoji })

it('uses specified base when twemojiBase option is defined', () => {
const marp = instance({ twemojiBase: '/assets/twemoji/' })
const $ = cheerio.load(marp.render('# :ok_hand:').html)
Expand Down