From 714f5c838dd4d69bb80925dc1aec1b4810a08c42 Mon Sep 17 00:00:00 2001 From: Martin Kremers Date: Sun, 14 Dec 2014 15:07:25 +0100 Subject: [PATCH] Enable multilevel table of contents --- src/cryogen_core/toc.clj | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/cryogen_core/toc.clj b/src/cryogen_core/toc.clj index b30f60b..e44c212 100644 --- a/src/cryogen_core/toc.clj +++ b/src/cryogen_core/toc.clj @@ -2,10 +2,13 @@ (:require [crouton.html :as html] [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] (reduce (fn [headings {:keys [tag attrs content] :as elm}] - (if (some #{tag} [:h1 :h2 :h3]) + (if (some #{tag} _h) (conj headings elm) (if-let [more-headings (get-headings content)] (into headings more-headings) @@ -13,9 +16,16 @@ [] content)) (defn make-links [headings] - (into [:ol.contents] - (for [{[{{name :name} :attrs} title] :content} headings] - [:li [:a {:href (str "#" name)} title]]))) + (loop [items headings acc nil _last nil] + (if-let [{tag :tag [{{name :name} :attrs} title] :content} (first items)] + (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 "
    " (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) "
")) + (hiccup/html entry)) tag)))) + (str acc "")))) (defn generate-toc [html] (-> html @@ -25,4 +35,4 @@ :content (get-headings) (make-links) - (hiccup/html))) + (clojure.string/replace-first #"ol" "ol class=\"contents\"")))