diff.cljs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. [frontend.util :as util]))
  9. ;; TODO: replace with diff-match-patch
  10. (defn diff
  11. [s1 s2]
  12. (-> ((gobj/get jsdiff "diffLines") s1 s2)
  13. bean/->clj))
  14. (defonce dmp (diff-match-patch.))
  15. (defn diffs
  16. [s1 s2]
  17. (.diff_main dmp s1 s2 true))
  18. (defn get-patches
  19. [s1 s2 diffs]
  20. (.patch_make dmp s1 s2 diffs))
  21. (defn apply-patches!
  22. [text patches]
  23. (if (seq patches)
  24. (let [result (.patch_apply dmp patches text)]
  25. (nth result 0))
  26. text))
  27. ;; (find-position "** hello _w_" "hello w")
  28. (defn find-position
  29. [markup text]
  30. (try
  31. (let [pos (loop [t1 (-> markup string/lower-case seq)
  32. t2 (-> text string/lower-case seq)
  33. i1 0
  34. i2 0]
  35. (let [[h1 & r1] t1
  36. [h2 & r2] t2]
  37. (cond
  38. (or (empty? t1) (empty? t2))
  39. i1
  40. (= h1 h2)
  41. (recur r1 r2 (inc i1) (inc i2))
  42. (#{\[ \space \]} h2)
  43. (recur t1 r2 i1 (inc i2))
  44. :else
  45. (recur r1 t2 (inc i1) i2))))]
  46. (if (and (= (util/nth-safe markup pos)
  47. (util/nth-safe markup (inc pos))
  48. "]"))
  49. (+ pos 2)
  50. pos))
  51. (catch js/Error e
  52. (log/error :diff/find-position {:error e})
  53. (count markup))))