Welcome to mirror list, hosted at ThFree Co, Russian Federation.

asset_resolver.js « services « content_editor « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0d4396fc176cb464e4a74773b74931df26b26e80 (plain)
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
import { memoize } from 'lodash';

const parser = new DOMParser();

export default class AssetResolver {
  constructor({ renderMarkdown }) {
    this.renderMarkdown = renderMarkdown;
  }

  resolveUrl = memoize(async (canonicalSrc) => {
    const html = await this.renderMarkdown(`[link](${canonicalSrc})`);
    if (!html) return canonicalSrc;

    const { body } = parser.parseFromString(html, 'text/html');
    return body.querySelector('a').getAttribute('href');
  });

  resolveReference = memoize(async (originalText) => {
    const text = originalText.replace(/(\+|\+s)$/, '');
    const toRender = `${text} ${text}+ ${text}+s`;
    const html = await this.renderMarkdown(toRender);

    if (!html) return {};

    const { body } = parser.parseFromString(html, 'text/html');
    const a = body.querySelectorAll('a');
    if (!a.length) return {};

    return {
      href: a[0].getAttribute('href'),
      text: a[0].textContent,
      expandedText: a[1].textContent,
      fullyExpandedText: a[2].textContent,
    };
  });

  renderDiagram = memoize(async (code, language) => {
    const backticks = '`'.repeat(4);
    const html = await this.renderMarkdown(`${backticks}${language}\n${code}\n${backticks}`);

    const { body } = parser.parseFromString(html, 'text/html');
    const img = body.querySelector('img');
    if (!img) return '';

    return img.dataset.src || img.getAttribute('src');
  });
}