Last active
March 30, 2023 16:58
-
-
Save patrickfav/b0cacb085e70feb236e2010aa134ec17 to your computer and use it in GitHub Desktop.
A Turndown Plugin parsing figures with captions; creates the format '![imgText](https://example.com/img.png "caption")' Turndown is a JS Markdown Parser see https://www.npmjs.com/package/turndown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const figureCaption = function (service: TurndownService): void { | |
service.addRule('stackOverflowHighlightedCodeBlock', { | |
filter: function (node: HTMLElement, options: Options): boolean | null { | |
const firstChild = node.firstChild | |
const lastChild = node.lastChild | |
return ( | |
node.nodeName === 'FIGURE' && | |
firstChild && firstChild.nodeName === 'IMG' && | |
lastChild && lastChild.nodeName === 'FIGCAPTION' | |
) | |
} as Filter, | |
replacement: function (content: string, node: HTMLElement, options: Options): string { | |
const imgNode = node.firstChild as HTMLImageElement; | |
const captionNode = node.lastChild | |
const altText = imgNode.alt | |
const imgSrc = imgNode.src | |
const caption = captionNode!.textContent | |
return ( | |
`![${altText}](${imgSrc + ' '}"${caption}")\n` | |
) | |
} as ReplacementFunction | |
}) | |
} as TurndownService.Plugin |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import TurndownService from "turndown"; | |
describe('figureCaption', () => { | |
let turndownService: TurndownService; | |
beforeEach(() => { | |
turndownService = new TurndownService(); | |
turndownService.use(figureCaption); | |
}); | |
it('should convert figure with img and figcaption to markdown', () => { | |
const inputHTML = ` | |
<figure> | |
<img src="example.png" alt="Example image"> | |
<figcaption>Example caption</figcaption> | |
</figure> | |
`; | |
const expectedMarkdown = '![Example image](/example.png "Example caption")'; | |
const result = turndownService.turndown(inputHTML); | |
expect(result).toEqual(expectedMarkdown); | |
}); | |
it('should not affect other elements', () => { | |
const inputHTML = ` | |
<p>Some text</p> | |
<img src="another-example.png" alt="Another example"> | |
`; | |
const expectedMarkdown = 'Some text\n\n![Another example](another-example.png)'; | |
const result = turndownService.turndown(inputHTML); | |
expect(result).toEqual(expectedMarkdown); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment