Skip to content
Snippets Groups Projects
kroki.js 1.93 KiB
Newer Older
onnohaldar's avatar
onnohaldar committed
/*
 * Use inline (highlight) coding to get type and source
 * of the diagram. Based on GitLab markdown rendering
 */
function renderInlineKrokiDiagram(elemId, inline, docsURL) {
    const lines = inline.split('\n');
    let diagramSource = '';
    let diagramType = '';
    
    lines.forEach(line => {
        if (line.startsWith('```')) {
          if (diagramType == '') {
              diagramType = line.split('```')[1].trim();
          }
        } else {
            diagramSource += line + '\n';
        }
    });
    
    renderKrokiDiagram(elemId, diagramType, diagramSource, docsURL);
}

function renderKrokiDiagram(elemId, diagramType, diagramSource, docsURL) {
    let parsedDiagramSource = diagramSource;

    if (diagramType == 'plantuml') {
        /* 
            Parse docsURL to make Relative Book Docs linking possible
            from generated PlantUML diagrams
        */
        parsedDiagramSource = parsedDiagramSource
            .replace(/<%= docsURL %>/g, docsURL);
    }

    const krokiUrl = buildKrokiUrl(diagramType, parsedDiagramSource);
    const outputNode = document.getElementById(elemId);
    outputNode.innerHTML = '<object data="' + krokiUrl + '"></object>';    
}

function buildKrokiUrl(diagramType, diagramSource) {
    // Build compressed KROKI URL for SVG
    const data = textEncode(diagramSource);
    const compressed = pako.deflate(data, { level: 9, to: 'string' });
    const krokiParam = btoa(compressed).replace(/\+/g, '-').replace(/\//g, '_');
    return 'https://kroki.io/' + diagramType + '/svg/' + krokiParam;
}

/*
 * Based on https://docs.kroki.io/kroki/setup/encode-diagram/#javascript
 */
function textEncode(str) {
    if (window.TextEncoder) {
        return new TextEncoder('utf-8').encode(str);
    }
    const utf8 = unescape(encodeURIComponent(str));
    const result = new Uint8Array(utf8.length);
    for (let i = 0; i < utf8.length; i++) {
        result[i] = utf8.charCodeAt(i);
    }
    return result;
}