From 371fdda4a8c82b5f29dd5c2dd9f04c8ef28dd025 Mon Sep 17 00:00:00 2001 From: Luis Merino Date: Sat, 16 Jun 2018 06:04:46 +0200 Subject: [PATCH] Fix anchors erroring when heading is empty (#772) --- lib/core/__tests__/anchors.test.js | 10 +++++++++- lib/core/anchors.js | 27 +++++++++++++++++---------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/lib/core/__tests__/anchors.test.js b/lib/core/__tests__/anchors.test.js index 4af6032bcde7..2ccd4312b53a 100644 --- a/lib/core/__tests__/anchors.test.js +++ b/lib/core/__tests__/anchors.test.js @@ -6,10 +6,13 @@ */ const anchors = require('../anchors'); +const rules = require('remarkable/lib/rules'); const md = { renderer: { - rules: {}, + rules: { + heading_open: rules.heading_open, + }, }, }; @@ -109,3 +112,8 @@ test('Anchor index resets on each render', () => { 'id="almost-unique-heading-1"' ); }); + +test('Anchor uses default renderer when empty', () => { + expect(render([{hLevel: 1}, {content: null}], 0, {}, {})).toEqual('

'); + expect(render([{hLevel: 2}, {content: ''}], 0, {}, {})).toEqual('

'); +}); diff --git a/lib/core/anchors.js b/lib/core/anchors.js index 1b5a41db0abd..ce6ec27bbae7 100644 --- a/lib/core/anchors.js +++ b/lib/core/anchors.js @@ -11,19 +11,26 @@ const toSlug = require('./toSlug.js'); * The anchors plugin adds GFM-style anchors to headings. */ function anchors(md) { + const originalRender = md.renderer.rules.heading_open; + md.renderer.rules.heading_open = function(tokens, idx, options, env) { const textToken = tokens[idx + 1]; - const anchor = toSlug(textToken.content, env); - return ( - '' - ); + if (textToken.content) { + const anchor = toSlug(textToken.content, env); + + return ( + '' + ); + } + + return originalRender(tokens, idx, options, env); }; }