Skip to content
This repository was archived by the owner on Nov 24, 2020. It is now read-only.

Add suport for remote data sources for code fragments #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,8 @@ var React = require('react')
{%- endcodetabs %}
```

### Remote code sources


Alternatively, you may provide a `url` attribute for a given language. In that case,
the body of the block is ignored and the content of the remote URL is used instead. The
syntax highlighting is still controlled by the `type` attribute.
37 changes: 26 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var escape = require('escape-html');
var fetch = require('node-fetch');

/*
Generate HTML for the tab in the header
Expand Down Expand Up @@ -38,27 +39,41 @@ module.exports = {
blocks: {
codetabs: {
blocks: ['language'],
process: function(parentBlock) {
process: async function(parentBlock) {
var blocks = [parentBlock].concat(parentBlock.blocks);
var tabsContent = '';
var tabsHeader = '';

blocks.forEach(function(block, i) {
let processBlock = async function(block, i) {
var isActive = (i == 0);

if (!block.kwargs.name) {
throw new Error('Code tab requires a "name" property');
}

tabsHeader += createTab(block, i, isActive);
tabsContent += createTabBody(block, i, isActive);
});
if (block.kwargs.url) {
block.body = await fetch(block.kwargs.url).then((res) => res.text());
}

return {
tabHeader: createTab(block, i, isActive),
tabContent: createTabBody(block, i, isActive)
};
};

let buildOutput = function(formattedResults) {
let tabsHeader = '';
let tabsContent = '';
formattedResults.forEach(function(record) {
tabsHeader += record.tabHeader;
tabsContent+= record.tabContent;
});

return '<div class="codetabs">' +
'<div class="codetabs-header">' + tabsHeader + '</div>' +
'<div class="codetabs-body">' + tabsContent + '</div>' +
'</div>';
};

return '<div class="codetabs">' +
'<div class="codetabs-header">' + tabsHeader + '</div>' +
'<div class="codetabs-body">' + tabsContent + '</div>' +
'</div>';
return await Promise.all(blocks.map(processBlock)).then(buildOutput);
}
}
}
Expand Down