aboutsummaryrefslogtreecommitdiffstats
path: root/packages/dev-tools-pages/ts/highlight.tsx
blob: 6efba02f82dde1b4653110f24dc0764e03b8318e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const hljs = require('highlight.js/lib/highlight');
const javascript = require('highlight.js/lib/languages/javascript');
const json = require('highlight.js/lib/languages/json');

hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('json', json);

interface PatchInterface {
    [key: string]: string;
}

var PATCH_TYPES: PatchInterface = {
    '+': 'addition',
    '-': 'deletion',
    '!': 'change',
};

function diffHighlight(language: string, code: any, gutter: any) {
    return code
        .split(/\r?\n/g)
        .map((line: string, index: number) => {
            var type;
            if (/^-{3} [^-]+ -{4}$|^\*{3} [^*]+ \*{4}$|^@@ [^@]+ @@$/.test(line)) {
                type = 'chunk';
            } else if (/^Index: |^[+\-*]{3}|^[*=]{5,}$/.test(line)) {
                type = 'header';
            } else {
                type = PATCH_TYPES[line[0] as string] || 'null';
                line = line.replace(/^[+\-! ]/, '');
            }

            const g = gutter[index];

            return `<span data-gutter="${g !== undefined ? g + 'x' : ''}" class="line-${type}">${
                hljs.highlight(language, line).value
            }</span>`;
        })
        .join('\n');
}

interface highlightProps {
    language: string;
    code: string;
    diff?: boolean;
    gutter?: boolean;
    etc?: boolean;
}

function highlight({ language, code, diff, gutter, etc }: highlightProps) {
    if (diff) {
        return diffHighlight(language, code, gutter);
    }

    let hlCode = hljs.highlight(language, code).value;

    if (!etc) {
        return hlCode;
    }

    var hc = hlCode.split(/\r?\n/g);
    hc.splice(1, 0, '    ...');
    hc.splice(hc.length - 1, 0, '    ...');

    return hc.join('\n');
}

export default highlight;