;; content-on-sx — table-of-contents rendering.
;;
;; Turns content/headings into a user-facing TOC: a Markdown bullet list indented
;; by heading level, and an HTML <ul> of anchor links (#id). The blog page links
;; these to heading anchors.
;;
;; Requires (loaded by harness): query.sx (content/headings), render.sx
;; (htmlEscaped).

(define toc-nl (str "\n"))
(define
  toc-join
  (fn
    (sep parts)
    (cond
      ((= (len parts) 0) "")
      ((= (len parts) 1) (first parts))
      (else (str (first parts) sep (toc-join sep (rest parts)))))))

(define
  toc-indent
  (fn
    (n)
    (if (<= n 0) "" (str "  " (toc-indent (- n 1))))))
(define toc-esc (fn (s) (str (st-send s "htmlEscaped" (list)))))

(define
  content/toc-markdown
  (fn
    (doc)
    (toc-join
      toc-nl
      (map
        (fn
          (h)
          (str
            (toc-indent (- (get h :level) 1))
            "- ["
            (get h :text)
            "](#"
            (get h :id)
            ")"))
        (content/headings doc)))))

(define
  content/toc-html
  (fn
    (doc)
    (let
      ((hs (content/headings doc)))
      (if
        (= (len hs) 0)
        ""
        (str
          "<ul>"
          (toc-join
            ""
            (map
              (fn
                (h)
                (str
                  "<li><a href=\"#"
                  (get h :id)
                  "\">"
                  (toc-esc (get h :text))
                  "</a></li>"))
              hs))
          "</ul>")))))
