Published
Edited
Feb 18, 2020
Importers
5 stars
Insert cell
Insert cell
Insert cell
md` ## Here's how those test urls look when rendered

### A Javascript file
${await makeCodeBlockFromURL(testurls.javascript, 4)}
--------------

### A Python file
${await makeCodeBlockFromURL(testurls.python, 4)}

--------------
### A bash script
${await makeCodeBlockFromURL(testurls.bash, 4, 'This title has been overriden')}
`
Insert cell
/*
* makeCodeBlockFromURL
* @param (string) url The URL to fetch
* @param (?number) titleLevel If > 0, will not show a title, otherwise, will create a header block at indicated level
* @param (?string) titleText If not and titleLevel > 0 '' will use as text for title
* @returns Promise
*/
async function makeCodeBlockFromURL(url, titleLevel=0, titleText=url) {
return analyzeCodeFromURL(url)
.then(analysis => formatAnalyzedCode(analysis, {
titleLevel, titleText, url
}))
.then(({codeAsMD}) => codeAsMD )
//const arr = somecode.split('\n')
//return arr.map((v, i) => v.padStart(padding))
}
Insert cell
async function formatAnalyzedCode(analysis, formattinginfo) {
let { titleLevel, titleText, url } = formattinginfo
titleLevel = titleLevel || 0
titleText = titleText || url
const {codedelimiter, mdlineterminator, codeexts, maxheadinglevel, headingchar} = codeformatting

return new Promise((resolve, reject) => {
// console.log(codedelimiter)
analysis.textarr.push(`${codedelimiter}`)
analysis.textarr.unshift(`${codedelimiter}${analysis.codetypename}`)
if( titleLevel > 0){
if (titleLevel > maxheadinglevel) {
titleLevel = maxheadinglevel
}
let title = [
`${Array(titleLevel).fill(headingchar).join('')} `,
`[${titleText}](${url})`,
mdlineterminator
].join('')

analysis.textarr.unshift(title)
}
resolve({
...analysis,
codeAsMD: analysis.textarr.join(mdlineterminator)
})
})
}
Insert cell
async function analyzeCodeFromURL(url) {
const { codeexts } = codeformatting
// console.log(codedelimiter)
const ext = url.split('.').pop()
let codetypename = ''
for (let key in codeexts) {
if (codeexts[key].includes(ext) ) {
codetypename = key
break
}
}
return fetch(url)
.then(res => res.text())
.then(text => {
const textarr = text.split(/\r\n|\r|\n/)
return {
codetypename,
textarr
}
})
}
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more