summaryrefslogtreecommitdiff
path: root/src/clarktown/renderers/link_and_image.clj
blob: 05dccac2ed5bad66fa8d91e97c70cedfa1a53c85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
(ns clarktown.renderers.link-and-image
  (:require
    [clojure.string :as string]))


(defn encode-href
  [href]
  (-> href
      (string/replace "_" "_")))


(defn render
  "Renders all occurring links and images."
  [block _ _]
  (loop [block block
         matches (-> (re-seq #"\!?\[([a-zA-Z0-9\-\_\.\,\']*( [a-zA-Z0-9\-\_\.\,\']+)*)\]\((.*?)\)" block)
                     distinct)]
    (if (empty? matches)
      block
      (let [[whole-match label _ href] (first matches)
            image? (string/starts-with? whole-match "!")
            image (str "<img src=\"" (encode-href href) "\" alt=\"" label "\">")
            link (str "<a href=\"" (encode-href href) "\">" label "</a>")]
        (recur (if image?
                 (string/replace block whole-match image)
                 (string/replace block whole-match link))
               (drop 1 matches))))))