diff.cljs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. (ns frontend.diff
  2. (:require [clojure.string :as string]
  3. ["diff" :as jsdiff]
  4. ["diff-match-patch" :as diff-match-patch]
  5. [goog.object :as gobj]
  6. [lambdaisland.glogi :as log]
  7. [cljs-bean.core :as bean]))
  8. ;; TODO: replace with diff-match-patch
  9. (defn diff
  10. [s1 s2]
  11. (-> ((gobj/get jsdiff "diffLines") s1 s2)
  12. bean/->clj))
  13. (defonce dmp (diff-match-patch.))
  14. (defn diffs
  15. [s1 s2]
  16. (.diff_main dmp s1 s2 true))
  17. (defn get-patches
  18. [s1 s2 diffs]
  19. (.patch_make dmp s1 s2 diffs))
  20. (defn apply-patches!
  21. [text patches]
  22. (if (seq patches)
  23. (let [result (.patch_apply dmp patches text)]
  24. (nth result 0))
  25. text))
  26. ;; (find-position "** hello _w_" "hello w")
  27. (defn find-position
  28. [markup text]
  29. (try
  30. (loop [t1 (-> markup string/lower-case seq)
  31. t2 (-> text string/lower-case seq)
  32. i1 0
  33. i2 0]
  34. (let [[h1 & r1] t1
  35. [h2 & r2] t2]
  36. (cond
  37. (or (empty? t1) (empty? t2))
  38. i1
  39. (= h1 h2)
  40. (recur r1 r2 (inc i1) (inc i2))
  41. (#{\[ \space \]} h2)
  42. (recur t1 r2 i1 (inc i2))
  43. :else
  44. (recur r1 t2 (inc i1) i2))))
  45. (catch js/Error e
  46. (log/error :diff/find-position {:error e})
  47. (count markup))))