Repository: go-gitea/gitea
File: web_src/js/markup/mermaid.ts (TypeScript)

Code before:
import {queryElems} from '../utils/dom.ts';
import {html, htmlRaw} from '../utils/html.ts';
import {load as loadYaml} from 'js-yaml';
import type {MermaidConfig} from 'mermaid';

const {mermaidMaxSourceCharacters} = window.config;

const iframeCss = `:root {color-scheme: normal}
body {margin: 0; padding: 0; overflow: hidden}
#mermaid {display: block; margin: 0 auto}`;

function isSourceTooLarge(source: string) {
  return mermaidMaxSourceCharacters >= 0 && source.length > mermaidMaxSourceCharacters;
}

function configContainsElk(config: MermaidConfig) {
  if (config?.layout === 'elk' || config?.layout?.startsWith('elk.')) return true;
  return Object.values(config).some((value) => value?.defaultRenderer === 'elk');
}

/** detect whether mermaid sources contain elk layout configuration */
export function sourcesContainElk(sources: Array<string>) {
  for (const source of sources) {
    if (isSourceTooLarge(source)) continue;

    const frontmatter = (/---\r?\n([\s\S]*?)\r?\n\s*---/.exec(source) || [])[1];
    if (frontmatter) {
      try {
        if (configContainsElk((loadYaml(frontmatter) as {config: MermaidConfig}).config)) {
          return true;
        }
      } catch {}
    }
    const directive = (/%%\{([\s\S]*)\}%%/.exec(source) || [])[1];
    if (directive) {
      const init = (/init\s*:\s*([\s\S]*)$/.exec(directive) || [])[1];
      if (init) {
        try {
          if (configContainsElk((JSON.parse(init) as MermaidConfig))) {
            return true;
          }
        } catch {}
      }
    }
  }

  return false;
}

async function loadMermaid(sources: Array<string>) {
  const mermaidPromise = import(/* webpackChunkName: "mermaid" */'mermaid');

Review comment (suggestion):
IIRC they are all valid frontmatters.


```
---
---
```

```
----
----
```

```
-----
-----
```

Code after:
import {queryElems} from '../utils/dom.ts';
import {html, htmlRaw} from '../utils/html.ts';
import {load as loadYaml} from 'js-yaml';
import type {MermaidConfig} from 'mermaid';

const {mermaidMaxSourceCharacters} = window.config;

const iframeCss = `:root {color-scheme: normal}
body {margin: 0; padding: 0; overflow: hidden}
#mermaid {display: block; margin: 0 auto}`;

function isSourceTooLarge(source: string) {
  return mermaidMaxSourceCharacters >= 0 && source.length > mermaidMaxSourceCharacters;
}

function parseYamlInitConfig(source: string): MermaidConfig | null {
  // ref: https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/diagram-api/regexes.ts
  const yamlFrontMatterRegex = /^---\s*[\n\r](.*?)[\n\r]---\s*[\n\r]+/s;
  const frontmatter = (yamlFrontMatterRegex.exec(source) || [])[1];
  if (!frontmatter) return null;
  try {
    return (loadYaml(frontmatter) as {config: MermaidConfig})?.config;
  } catch {
    console.error('invalid or unsupported mermaid init YAML config', frontmatter);
  }
  return null;
}

function parseJsonInitConfig(source: string): MermaidConfig | null {
  // https://mermaid.js.org/config/directives.html#declaring-directives
  // Do as dirty as mermaid does: https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/utils.ts
  // It can even accept invalid JSON string like:
  // %%{initialize: { 'logLevel': 'fatal', "theme":'dark', 'startOnLoad': true } }%%
  const jsonInitConfigRegex = /%%\{\s*(init|initialize)\s*:\s*(.*?)\}%%/s;
  const jsonInitText = (jsonInitConfigRegex.exec(source) || [])[2];
  if (!jsonInitText) return null;
  try {
    const processed = jsonInitText.trim().replace(/'/g, '"');
    return JSON.parse(processed);
  } catch {
    console.error('invalid or unsupported mermaid init JSON config', jsonInitText);
  }
  return null;
}

function configValueIsElk(layoutOrRenderer: string | undefined) {
  if (typeof layoutOrRenderer !== 'string') return false;
  return layoutOrRenderer === 'elk' || layoutOrRenderer.startsWith('elk.');
}

function configContainsElk(config: MermaidConfig | null) {