Enable multilevel table of contents
This commit is contained in:
parent
d9fe01d8f6
commit
714f5c838d
1 changed files with 15 additions and 5 deletions
|
@ -2,10 +2,13 @@
|
||||||
(:require [crouton.html :as html]
|
(:require [crouton.html :as html]
|
||||||
[hiccup.core :as hiccup]))
|
[hiccup.core :as hiccup]))
|
||||||
|
|
||||||
|
(def _h [:h1 :h2 :h3 :h4 :h5 :h6])
|
||||||
|
(defn- compare_index [i1 i2] (- (.indexOf _h i2) (.indexOf _h i1)))
|
||||||
|
|
||||||
(defn get-headings [content]
|
(defn get-headings [content]
|
||||||
(reduce
|
(reduce
|
||||||
(fn [headings {:keys [tag attrs content] :as elm}]
|
(fn [headings {:keys [tag attrs content] :as elm}]
|
||||||
(if (some #{tag} [:h1 :h2 :h3])
|
(if (some #{tag} _h)
|
||||||
(conj headings elm)
|
(conj headings elm)
|
||||||
(if-let [more-headings (get-headings content)]
|
(if-let [more-headings (get-headings content)]
|
||||||
(into headings more-headings)
|
(into headings more-headings)
|
||||||
|
@ -13,9 +16,16 @@
|
||||||
[] content))
|
[] content))
|
||||||
|
|
||||||
(defn make-links [headings]
|
(defn make-links [headings]
|
||||||
(into [:ol.contents]
|
(loop [items headings acc nil _last nil]
|
||||||
(for [{[{{name :name} :attrs} title] :content} headings]
|
(if-let [{tag :tag [{{name :name} :attrs} title] :content} (first items)]
|
||||||
[:li [:a {:href (str "#" name)} title]])))
|
(if (nil? name) (recur (rest items) acc nil)
|
||||||
|
(let [entry [:li [:a {:href (str "#" name)} title]]
|
||||||
|
jump (compare_index _last tag)]
|
||||||
|
(cond (> jump 0) (recur (rest items) (str acc "<ol>" (hiccup/html entry)) tag)
|
||||||
|
(= jump 0) (recur (rest items) (str acc (hiccup/html entry)) tag)
|
||||||
|
(< jump 0) (recur (rest items) (str acc (apply str (repeat (* -1 jump) "</ol>"))
|
||||||
|
(hiccup/html entry)) tag))))
|
||||||
|
(str acc "</ol>"))))
|
||||||
|
|
||||||
(defn generate-toc [html]
|
(defn generate-toc [html]
|
||||||
(-> html
|
(-> html
|
||||||
|
@ -25,4 +35,4 @@
|
||||||
:content
|
:content
|
||||||
(get-headings)
|
(get-headings)
|
||||||
(make-links)
|
(make-links)
|
||||||
(hiccup/html)))
|
(clojure.string/replace-first #"ol" "ol class=\"contents\"")))
|
||||||
|
|
Loading…
Reference in a new issue