Files
shields/frontend/lib/generate-image-markup.js
Paul Melnikow 6c2b040fa6 Better modal (#2554)
- With examples using `pattern`s, allow building the URL from its component parts, including the query string.
- Provide a button to copy the link, with an animation.

To enable this for other badges, convert them to use a `pattern`: #1961.
2019-01-10 21:04:07 -05:00

101 lines
2.4 KiB
JavaScript

export function bareLink(badgeUrl, link, title = '') {
return badgeUrl
}
export function html(badgeUrl, link, title) {
// To be more robust, this should escape the title.
const img = `<img alt="${title}" src="${badgeUrl}">`
if (link) {
return `<a href=${link}>${img}</a>`
} else {
return img
}
}
export function markdown(badgeUrl, link, title) {
const withoutLink = `![${title || ''}](${badgeUrl})`
if (link) {
return `[${withoutLink}](${link})`
} else {
return withoutLink
}
}
export function reStructuredText(badgeUrl, link, title) {
let result = `.. image:: ${badgeUrl}`
if (title) {
result += ` :alt: ${title}`
}
if (link) {
result += ` :target: ${link}`
}
return result
}
function quoteAsciiDocAttribute(attr) {
if (typeof attr === 'string') {
const withQuotesEscaped = attr.replace(/"/g, '\\"')
return `"${withQuotesEscaped}"`
} else if (attr == null) {
return 'None'
} else {
return attr
}
}
// lodash.mapvalues is huge!
function mapValues(obj, iteratee) {
const result = {}
for (const k in obj) {
result[k] = iteratee(obj[k])
}
return result
}
export function renderAsciiDocAttributes(positional, named) {
// http://asciidoc.org/userguide.html#X21
const needsQuoting =
positional.some(attr => attr.includes(',')) || Object.keys(named).length > 0
if (needsQuoting) {
positional = positional.map(attr => quoteAsciiDocAttribute(attr))
named = mapValues(named, attr => quoteAsciiDocAttribute(attr))
}
const items = positional.concat(
Object.entries(named).map(([k, v]) => `${k}=${v}`)
)
if (items.length) {
return `[${items.join(',')}]`
} else {
return ''
}
}
export function asciiDoc(badgeUrl, link, title) {
const positional = title ? [title] : []
const named = link ? { link } : {}
const attrs = renderAsciiDocAttributes(positional, named)
return `image:${badgeUrl}${attrs}`
}
export default function generateAllMarkup(badgeUrl, link, title) {
// This is a wee bit "clever". It runs each of the three functions on the
// parameters provided, and returns the result in an object.
return mapValues({ markdown, reStructuredText, asciiDoc }, fn =>
fn(badgeUrl, link, title)
)
}
export function generateMarkup({ badgeUrl, link, title, markupFormat }) {
const generatorFn = {
markdown,
rst: reStructuredText,
asciidoc: asciiDoc,
link: bareLink,
html,
}[markupFormat]
return generatorFn(badgeUrl, link, title)
}