1# Copyright 2016-2023 The Khronos Group Inc.
2#
3# SPDX-License-Identifier: Apache-2.0
4
5require 'asciidoctor/extensions' unless RUBY_ENGINE == 'opal'
6
7include ::Asciidoctor
8
9class ReplaceMathjaxWithKatex < Extensions::Postprocessor
10
11  MathJaXScript = /<script type="text\/x-mathjax-config">((?!<\/script>).)+<\/script>/m
12  MathJaXCDN = /<script src="https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/[0-9].[0-9].[0-9]\/MathJax.js\?config=[-_A-Za-z]+"><\/script>/m
13
14  def process document, output
15
16    if document.attr? 'stem'
17      katexpath = document.attr 'katexpath'
18
19      katexScript = '
20<!-- dragged in by font-awesome css included by asciidoctor, but preloaded in this extension for convenience -->
21<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0" as="font" type="font/woff2" crossorigin="">
22
23<!-- Note: Chrome needs crossorigin="" even for same-origin fonts -->
24<link rel="preload" href="../katex/fonts/KaTeX_Main-Bold.woff2" as="font" type="font/woff2" crossorigin="">
25<link rel="preload" href="../katex/fonts/KaTeX_Main-Italic.woff2" as="font" type="font/woff2" crossorigin="">
26<link rel="preload" href="../katex/fonts/KaTeX_Main-Regular.woff2" as="font" type="font/woff2" crossorigin="">
27<link rel="preload" href="../katex/fonts/KaTeX_Math-Italic.woff2" as="font" type="font/woff2" crossorigin="">
28<link rel="preload" href="../katex/fonts/KaTeX_Size1-Regular.woff2" as="font" type="font/woff2" crossorigin="">
29<link rel="preload" href="../katex/fonts/KaTeX_Size2-Regular.woff2" as="font" type="font/woff2" crossorigin="">
30<link rel="preload" href="../katex/fonts/KaTeX_Size3-Regular.woff2" as="font" type="font/woff2" crossorigin="">
31<link rel="preload" href="../katex/fonts/KaTeX_Size4-Regular.woff2" as="font" type="font/woff2" crossorigin="">
32<link rel="preload" href="../katex/fonts/KaTeX_Typewriter-Regular.woff2" as="font" type="font/woff2" crossorigin="">'
33
34      # Load KaTeX stylesheet, but we no longer run a script to convert math
35      # using KaTeX, since that is now done at spec generation time.
36      katexScript += '<link rel="stylesheet" href="' + katexpath + '/katex.min.css">'
37
38      output.sub! MathJaXScript, ''
39      output.sub! MathJaXCDN, ''
40      output.sub! /(?=<\/head>)/, katexScript
41    end
42    output
43  end
44end
45