Browse Source

fix: only reorder the first matched ordered list

Tienson Qin 3 years ago
parent
commit
98ac07d990
2 changed files with 41 additions and 20 deletions
  1. 15 6
      src/main/frontend/util/list.cljs
  2. 26 14
      src/test/frontend/util/list_test.cljs

+ 15 - 6
src/main/frontend/util/list.cljs

@@ -40,19 +40,28 @@
       (cursor/move-cursor-to input current-pos)
       @end-pos)))
 
+(defn- newline?
+  [line]
+  (or (= line "\n") (= line "\r\n")))
+
 (defn re-order-items
   [lines start-idx]
   (loop [lines lines
          idx start-idx
-         result nil]
+         result []
+         double-newlines? false]
     (let [[line & others] lines]
       (if (empty? lines)
-        result
+        (->> result
+             (map (fn [line] (if (newline? line) "" line)))
+             (string/join "\n"))
         (let [[_ num-str] (re-find #"^(\d+){1}\." line)
               num (if num-str (util/safe-parse-int num-str) nil)
-              [idx' result'] (if num
+              double-newlines?' (or double-newlines?
+                                     (and (newline? line) (seq others) (newline? (first others))))
+              [idx' result'] (if (and (not double-newlines?') num)
                                (let [idx' (inc idx)
                                      line' (string/replace-first line (str num ".") (str idx' "."))]
-                                 [idx' (if result (str result "\n" line') line')])
-                               [idx (str result "\n" line)])]
-          (recur others idx' result'))))))
+                                 [idx' (conj result line')])
+                               [idx (conj result line)])]
+          (recur others idx' result' double-newlines?'))))))

+ 26 - 14
src/test/frontend/util/list_test.cljs

@@ -1,18 +1,30 @@
 (ns frontend.util.list-test
-  (:require [cljs.test :refer [deftest is]]
+  (:require [cljs.test :refer [deftest is testing]]
             [frontend.util.list :as list-util]))
 
 (deftest test-re-order-items
-  (is (= (list-util/re-order-items
-          ["2. x"
-           "3. x"]
-          2)
-         "3. x\n4. x"))
-  (is (= (list-util/re-order-items
-          ["7. x"
-           "foo"
-           "bar 3."
-           "5. x"
-           "baz"]
-          2)
-         "3. x\nfoo\nbar 3.\n4. x\nbaz")))
+  (testing "Single list"
+    (is (= (list-util/re-order-items
+            ["2. x"
+             "3. x"]
+            2)
+           "3. x\n4. x"))
+    (is (= (list-util/re-order-items
+            ["7. x"
+             "foo"
+             "bar 3."
+             "5. x"
+             "baz"]
+            2)
+           "3. x\nfoo\nbar 3.\n4. x\nbaz")))
+  (testing "Only reorder the first list"
+    (is (= (list-util/re-order-items
+            ["7. x"
+             "foo"
+             "\n"
+             "\n"
+             "bar 3."
+             "5. x"
+             "baz"]
+            2)
+           "3. x\nfoo\n\n\nbar 3.\n5. x\nbaz"))))