cryogen-core/src/cryogen_core/hierarchic.clj

55 lines
2 KiB
Clojure
Raw Normal View History

(ns cryogen-core.hierarchic
2019-12-20 14:55:53 +00:00
(:require
[clojure.string :as s]))
(defn normalized-page-root-uri [page-root-uri]
2019-12-20 14:55:53 +00:00
(cond
(= "" page-root-uri) ""
2019-12-20 14:55:53 +00:00
(and
(s/starts-with? page-root-uri "/")
(s/ends-with? page-root-uri "/")) page-root-uri
(and
(s/starts-with? page-root-uri "/")
(not (s/ends-with? page-root-uri "/"))) (str page-root-uri "/")
(and
(not (s/starts-with? page-root-uri "/"))
(s/ends-with? page-root-uri "/")) (str "/" page-root-uri)
(and
(not (s/starts-with? page-root-uri "/"))
(not (s/ends-with? page-root-uri "/"))) (str "/" page-root-uri "/")))
(defn uri-level [uri]
2019-12-20 14:55:53 +00:00
(- (count
(s/split uri #"/"))
1))
(defn filter-pages-for-uri [uri pages]
(let [html? (s/ends-with? uri ".html")
clean? (s/ends-with? uri "/")
2019-12-20 14:55:53 +00:00
clean-uri (cond
html? (subs uri 0 (- (count uri) 5))
clean? (subs uri 0 (- (count uri) 1))
:default uri)]
2019-12-20 14:55:53 +00:00
(filter #(s/starts-with? (:uri %) clean-uri) pages)))
(defn build-hierarchic-level
2017-03-12 09:33:50 +00:00
"builds one level of hierarchic tree recurs to next level."
[parent-uri pages]
(let [current-level (+ 1 (uri-level parent-uri))
pages-of-parent (filter-pages-for-uri parent-uri pages)
pages-on-level (filter #(= current-level (uri-level (:uri %))) pages-of-parent)
2019-12-20 14:55:53 +00:00
pages-on-child-level (filter #(< current-level (uri-level (:uri %))) pages-of-parent)]
(sort-by :page-index
(map #(let [page-on-level %
2019-12-20 14:55:53 +00:00
child-pages (filter-pages-for-uri (:uri page-on-level) pages-on-child-level)]
(if (empty? child-pages)
2019-12-20 14:55:53 +00:00
page-on-level
(merge page-on-level
2019-12-20 14:55:53 +00:00
{:children (build-hierarchic-level (:uri page-on-level) child-pages)}))) pages-on-level))))
(defn build-hierarchic-map
2017-03-12 09:33:50 +00:00
"builds a hierarchic tree from pages"
[page-root-uri pages]
(let [sorted-pages (sort-by :uri pages)]
2019-12-20 14:55:53 +00:00
(build-hierarchic-level (normalized-page-root-uri page-root-uri) sorted-pages)))