Sfoglia il codice sorgente

add fn extract-plain

Tienson Qin 2 anni fa
parent
commit
2e9b1e6fa5

+ 39 - 0
src/main/frontend/format/mldoc.cljs

@@ -8,6 +8,7 @@
             ["mldoc" :as mldoc :refer [Mldoc]]
             [logseq.graph-parser.mldoc :as gp-mldoc]
             [logseq.graph-parser.util :as gp-util]
+            [logseq.graph-parser.text :as text]
             [clojure.walk :as walk]))
 
 (defonce anchorLink (gobj/get Mldoc "anchorLink"))
@@ -92,3 +93,41 @@
          f))
      ast)
     @*result))
+
+(defn extract-plain
+  "Extract plain elements including page refs"
+  [content]
+  (let [ast (->edn content (gp-mldoc/default-config :markdown))]
+    (let [*result (atom [])]
+      (walk/prewalk
+       (fn [f]
+         (cond
+           ;; tag
+           (and (vector? f)
+                (= "Tag" (first f)))
+           nil
+
+           ;; nested page ref
+           (and (vector? f)
+                (= "Nested_link" (first f)))
+           (swap! *result conj (:content (second f)))
+
+           ;; page ref
+           (and (vector? f)
+                (= "Link" (first f))
+                (map? (second f))
+                (vector? (:url (second f)))
+                (= "Page_ref" (first (:url (second f)))))
+           (swap! *result conj
+                  (:full_text (second f)))
+
+           ;; plain
+           (and (vector? f)
+                (= "Plain" (first f)))
+           (swap! *result conj (second f))
+
+           :else
+           f))
+       ast)
+      (-> (string/trim (apply str @*result))
+          text/page-ref-un-brackets!))))

+ 36 - 0
src/test/frontend/format/mldoc_test.cljs

@@ -0,0 +1,36 @@
+(ns frontend.format.mldoc-test
+  (:require [frontend.format.mldoc :as mldoc]
+            [cljs.test :refer [deftest testing are]]))
+
+(deftest test-extract-plain
+  (testing "normalize date values"
+    (are [x y] (= (mldoc/extract-plain x) y)
+      "foo #book #[[nice test]]"
+      "foo"
+
+      "foo   #book #[[nice test]]"
+      "foo"
+
+      "**foo** #book #[[nice test]]"
+      "foo"
+
+      "foo [[bar]] #book #[[nice test]]"
+      "foo [[bar]]"
+
+      "foo  [[bar]] #book #[[nice test]]"
+      "foo  [[bar]]"
+
+      "[[foo bar]]"
+      "foo bar"
+
+      "[[Foo Bar]]"
+      "Foo Bar"
+
+      "[[Foo [[Bar]]]]"
+      "Foo [[Bar]]"
+
+      "foo [[Foo [[Bar]]]]"
+      "foo [[Foo [[Bar]]]]"
+
+      "foo [[Foo [[Bar]]]] #tag"
+      "foo [[Foo [[Bar]]]]")))