require 'asciidoctor'

# Official attributes: the template reads these straight from DEFAULT_ATTRIBUTES.
# Equivalent to :xxx: definitions in the header of every .adoc file, so there is
# no need to type a toc;; directive inside leo-editor.
# If a single document defines the same attribute, the document value overrides
# the default set here.
Asciidoctor::DEFAULT_ATTRIBUTES['stem'] = 'latexmath'
{
  'author' => 'https://github.com/wangzhaohe/swot-learning',
  'source-highlighter' => 'pygments',
  'icons' => 'font',
  'font-size' => '16px',
  'scripts' => 'cjk',
  'experimental' => '',
  'toc' => 'right',
  'toc-title' => '目录',
  'toclevels' => '3',
  'tip-caption' => '⚡',
  'note-caption' => '❕',
  'important-caption' => '❗',
  'caution-caption' => '⚠️',
  'warning-caption' => '‼️'
}.each { |key, value| Asciidoctor::DEFAULT_ATTRIBUTES[key] = value }

# postprocessor:
# 1. Fix misaligned math rendering (the unofficial mathjax-url attribute has no
#    effect, so a string replacement is used instead).
# 2. Globally inject the TOC toolbar (Home + Open TOC), replacing the dir
#    directive in every individual .adoc file.
Asciidoctor::Extensions.register do
  postprocessor do
    process do |doc, output|
      output = output.gsub(
        /(MathJax\.js\?config=)TeX-MML-AM_HTMLorMML/,
        '\1TeX-MML-AM_CHTML'
      )
      # 页脚时间去掉 +0800 偏移，只保留本地墙钟时间；docdatetime 本身已按本机时区格式化
      output = output.gsub(/(Last updated \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) [+-]\d{4}/, '\1')

      # Inject only for the html5 backend; pdf / github backends are skipped
      # automatically (replacing the former double ifndef guard).
      # Skip older documents that already contain the dir-injected toolbar, to
      # avoid duplicate buttons/scripts. Use a marker written only by this
      # postprocessor: checking for id="toc-toolbar" in the output is unsafe,
      # because a document that discusses this very toolbar contains that
      # literal text and would be skipped by mistake.
      marker = '<!-- toc-toolbar injected by options.rb -->'
      if doc.backend == 'html5' && !doc.attributes.key?('env-github') &&
         !output.include?(marker)
        toolbar = <<~HTML
          #{marker}
          <div id="toc-toolbar">
            <a id="homeButton" href="/" title="Back to home">Home</a>
            <button id="toggleButton" type="button">Open TOC</button>
          </div>
          <script>
          (function () {
            // Home: root-domain deployment -> "/"; GitHub Pages project site
            //       -> automatically go back to the project root
            var home = document.getElementById('homeButton');
            var segs = location.pathname.split('/').filter(Boolean);
            home.href = (location.hostname.endsWith('github.io') && segs.length)
              ? '/' + segs[0] + '/' : '/';

            var toc = document.getElementById('toc');
            var btn = document.getElementById('toggleButton');
            // When there is no native TOC, keep only Home and hide the
            // meaningless toggle button.
            if (!toc) { btn.style.display = 'none'; return; }
            btn.addEventListener('click', function () {
              var open = toc.classList.toggle('active');
              btn.textContent = open ? 'Close TOC' : 'Open TOC';
            });
          })();
          </script>
        HTML
        output = output.sub('</body>', "#{toolbar}</body>")
      end

      output
    end
  end
end

## Check whether asciidoctor-diagram is installed
begin
  require 'asciidoctor-diagram'
rescue LoadError
  warn 'asciidoctor-diagram is not installed'
end

## Check whether asciidoctor-kroki is installed
#begin
#  require 'asciidoctor-kroki'
#rescue LoadError
#  warn 'asciidoctor-kroki is not installed'
#end

# Enable data-uri (equivalent to -a data-uri): embed images in the page as base64.
# Asciidoctor::DEFAULT_ATTRIBUTES['data-uri'] = ''
