;; content-on-sx — anchored-heading HTML render.
;;
;; Like asHTML, but headings carry an id attribute (the block id), so the TOC's
;; #id links resolve. A separate render so the plain asHTML stays unchanged.
;; Tree-aware (sections recurse); other blocks use their normal asHTML.
;;
;; Requires (loaded by harness): block.sx, doc.sx, render.sx (asHTML +
;; htmlEscaped).

(define
  anch-section?
  (fn (b) (and (st-instance? b) (= (get b :class) "CtSection"))))
(define anch-esc (fn (s) (str (st-send s "htmlEscaped" (list)))))

(define
  anchor-block
  (fn
    (b)
    (cond
      ((= (blk-type b) "heading")
        (let
          ((l (str (blk-get b "level"))) (id (blk-id b)))
          (str
            "<h"
            l
            " id=\""
            id
            "\">"
            (anch-esc (str (blk-get b "text")))
            "</h"
            l
            ">")))
      ((anch-section? b)
        (let
          ((ch (st-iv-get b "children")))
          (str
            "<section>"
            (anchor-blocks (if (list? ch) ch (list)))
            "</section>")))
      (else (str (st-send b "asHTML" (list)))))))

(define
  anchor-blocks
  (fn
    (blocks)
    (if
      (= (len blocks) 0)
      ""
      (str (anchor-block (first blocks)) (anchor-blocks (rest blocks))))))

(define content/html-anchored (fn (doc) (anchor-blocks (doc-blocks doc))))
