From 1447c8a40aad7fe475293728c2e9cd8df527e7bc Mon Sep 17 00:00:00 2001 From: Anton Wilhelm Date: Wed, 23 Jan 2019 03:54:50 +0100 Subject: [PATCH] feat: Provide code fragments feature (#748) --- docs/_media/example.js | 16 ++++++++++++++++ docs/embed-files.md | 15 +++++++++++++++ src/core/render/compiler.js | 1 + src/core/render/embed.js | 5 +++++ 4 files changed, 37 insertions(+) create mode 100644 docs/_media/example.js diff --git a/docs/_media/example.js b/docs/_media/example.js new file mode 100644 index 000000000..7b6f668cc --- /dev/null +++ b/docs/_media/example.js @@ -0,0 +1,16 @@ +import fetch from 'fetch' + +const URL = 'https://example.com' +const PORT = 8080 + +/// [demo] +const result = fetch(`${URL}:${PORT}`) + .then(function(response) { + return response.json(); + }) + .then(function(myJson) { + console.log(JSON.stringify(myJson)); + }); +/// [demo] + +result.then(console.log).catch(console.error) diff --git a/docs/embed-files.md b/docs/embed-files.md index a935dd374..dab2efe4e 100644 --- a/docs/embed-files.md +++ b/docs/embed-files.md @@ -39,6 +39,21 @@ You will get it [filename](_media/example.md ':include :type=code') +## Embedded code fragments +Sometimes you don't want to embed a whole file. Maybe because you need just a few lines but you want to compile and test the file in CI. + +```markdown +[filename](_media/example.js ':include :type=code :fragment=demo') +``` + +In your code file you need to surround the fragment between `/// [demo]` lines (before and after the fragment). +Alternatively you can use `### [demo]`. + +Example: + +[filename](_media/example.js ':include :type=code :fragment=demo') + + ## Tag attribute If you embed the file as `iframe`, `audio` and `video`, then you may need to set the attributes of these tags. diff --git a/src/core/render/compiler.js b/src/core/render/compiler.js index 9d6536d0f..b086b1476 100644 --- a/src/core/render/compiler.js +++ b/src/core/render/compiler.js @@ -164,6 +164,7 @@ export class Compiler { embed = compileMedia[type].call(this, href, title) embed.type = type } + embed.fragment = config.fragment return embed } diff --git a/src/core/render/embed.js b/src/core/render/embed.js index 85afbe646..821837488 100644 --- a/src/core/render/embed.js +++ b/src/core/render/embed.js @@ -20,6 +20,11 @@ function walkFetchEmbed({embedTokens, compile, fetch}, cb) { if (token.embed.type === 'markdown') { embedToken = compile.lexer(text) } else if (token.embed.type === 'code') { + if (token.embed.fragment) { + const fragment = token.embed.fragment + const pattern = new RegExp(`(?:###|\\/\\/\\/)\\s*\\[${fragment}\\]([\\s\\S]*)(?:###|\\/\\/\\/)\\s*\\[${fragment}\\]`) + text = ((text.match(pattern) || [])[1] || '').trim() + } embedToken = compile.lexer( '```' + token.embed.lang +