|
(ns example.core |
|
(:require-macros [swiss.arrows :refer [-<> -<>>]]) |
|
(:require [reagent.core :as r] |
|
[cljs-css-modules.macro :refer-macros [defstyle]] |
|
[goog.string :as gstring] |
|
[goog.dom :as gdom] |
|
[cemerick.url :refer (url url-encode)] |
|
[js.Fuse])) |
|
|
|
(def $fuse |
|
(let [input-data [{:title "Old Man's War" |
|
:author {:firstName "John" |
|
:lastName "Scalzi"}} |
|
{:title "The Lock Artist" |
|
:author {:firstName "Steve" |
|
:lastName "Hamilton"}} |
|
] |
|
|
|
fuse-options {:shouldSort true |
|
:threshold 0.6 |
|
:location 0 |
|
:distance 100 |
|
:maxPatternLength 32 |
|
:minMatchCharLength 2 |
|
:includeScore true |
|
:includeMatches true |
|
:keys ["title" "author.firstName"] |
|
}] |
|
(js/Fuse. |
|
(clj->js input-data) |
|
(clj->js fuse-options)))) |
|
|
|
(defn transform-to-highlight-labeled-strings |
|
[source-text highlight-indices] |
|
|
|
(comment |
|
(transform-to-highlight-labeled-strings |
|
"lorem ipsum sit dolor" |
|
[[1 2] [3 4] [6 6] [9 20]])) |
|
|
|
(let [text-length (count source-text) |
|
-subs (fn |
|
([beg] (subs source-text beg)) |
|
([beg end] (subs source-text beg end))) |
|
-normal (fn [& args] [:normal (apply -subs args)]) |
|
-highlight (fn [& args] [:highlight (apply -subs args)])] |
|
|
|
(loop [remain-indices highlight-indices |
|
cur-index 0 |
|
out []] |
|
(if (empty? remain-indices) |
|
(let [remain-text (subs source-text cur-index)] |
|
(concat |
|
out |
|
(when (< cur-index text-length) |
|
[(-normal cur-index)]))) |
|
(let [[start end] (first remain-indices) |
|
start+1 (+ 1 start) |
|
end+1 (+ 1 end)] |
|
(recur (rest remain-indices) |
|
end+1 |
|
(->> [(when (< cur-index start) |
|
(-normal cur-index start)) |
|
(-highlight start end+1)] |
|
(remove nil?) |
|
(concat out)))))))) |
|
|
|
(let [results |
|
(-> (.search $fuse "Art") |
|
(js->clj :keywordize-keys true)) |
|
|
|
best-result (first results) |
|
|
|
render-labeled (fn [result] |
|
(let [match (first (:matches result)) |
|
match-key (keyword (:key match)) |
|
match-text (get-in result [:item match-key])] |
|
[:div |
|
[:h3 (count (:matches result)) |
|
" matches; " |
|
"using " match-key] |
|
[:ol |
|
(->> (transform-to-highlight-labeled-strings |
|
match-text (:indices match)) |
|
(map (fn [[label text]] |
|
(case label |
|
:normal [:span text] |
|
:highlight [:span |
|
{:style {:background "yellow" |
|
:border "1px solid red"}} |
|
text |
|
]))))]])) |
|
] |
|
|
|
(r/render |
|
[(fn [] |
|
[:div |
|
[:h2 (count results)] |
|
[:div (get-in best-result [:item :text])] |
|
(render-labeled best-result)])] |
|
(js/document.getElementById "container"))) |