editor.cljs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. (ns frontend.components.editor
  2. (:require [clojure.string :as string]
  3. [goog.string :as gstring]
  4. [frontend.commands :as commands
  5. :refer [*angle-bracket-caret-pos *first-command-group *matched-block-commands *matched-commands *show-block-commands *show-commands *slash-caret-pos]]
  6. [frontend.components.block :as block]
  7. [frontend.components.datetime :as datetime-comp]
  8. [frontend.components.search :as search]
  9. [frontend.components.svg :as svg]
  10. [frontend.db :as db]
  11. [frontend.db.model :as db-model]
  12. [frontend.extensions.zotero :as zotero]
  13. [frontend.handler.editor :as editor-handler :refer [get-state]]
  14. [frontend.handler.editor.lifecycle :as lifecycle]
  15. [frontend.handler.page :as page-handler]
  16. [frontend.mixins :as mixins]
  17. [frontend.modules.shortcut.core :as shortcut]
  18. [frontend.state :as state]
  19. [frontend.ui :as ui]
  20. [frontend.util :as util]
  21. [frontend.util.cursor :as cursor]
  22. [frontend.util.keycode :as keycode]
  23. [goog.dom :as gdom]
  24. [promesa.core :as p]
  25. [rum.core :as rum]
  26. [frontend.mobile.footer :as footer]))
  27. (rum/defc commands < rum/reactive
  28. [id format]
  29. (let [matched (util/react *matched-commands)]
  30. (when (util/react *show-commands)
  31. (ui/auto-complete
  32. matched
  33. {:get-group-name
  34. (fn [item]
  35. (get *first-command-group (first item)))
  36. :item-render
  37. (fn [item]
  38. (let [command-name (first item)
  39. command-doc (get item 2)
  40. doc (when (state/show-command-doc?) command-doc)]
  41. (cond
  42. (string? doc)
  43. [:div {:title doc}
  44. command-name]
  45. (vector? doc)
  46. [:div.has-help
  47. command-name
  48. (ui/tippy
  49. {:html doc
  50. :interactive true
  51. :fixed-position? true
  52. :position "right"}
  53. [:small (svg/help-circle)])]
  54. :else
  55. [:div command-name])))
  56. :on-chosen
  57. (fn [chosen-item]
  58. (let [command (first chosen-item)]
  59. (reset! commands/*current-command command)
  60. (let [command-steps (get (into {} matched) command)
  61. restore-slash? (or
  62. (contains? #{"Today" "Yesterday" "Tomorrow" "Current time"} command)
  63. (and
  64. (not (fn? command-steps))
  65. (not (contains? (set (map first command-steps)) :editor/input))
  66. (not (contains? #{"Date picker" "Template" "Deadline" "Scheduled" "Upload an image"} command))))]
  67. (editor-handler/insert-command! id command-steps
  68. format
  69. {:restore? restore-slash?})
  70. (state/pub-event! [:instrument {:type :editor/command-triggered
  71. :payload {:command command}}]))))
  72. :class
  73. "black"}))))
  74. (rum/defc block-commands < rum/reactive
  75. [id format]
  76. (when (util/react *show-block-commands)
  77. (let [matched (util/react *matched-block-commands)]
  78. (ui/auto-complete
  79. (map first matched)
  80. {:on-chosen (fn [chosen]
  81. (editor-handler/insert-command! id (get (into {} matched) chosen)
  82. format
  83. {:last-pattern commands/angle-bracket}))
  84. :class "black"}))))
  85. (defn- in-sidebar? [el]
  86. (not (.contains (.getElementById js/document "left-container") el)))
  87. (rum/defc page-search < rum/reactive
  88. {:will-unmount (fn [state] (reset! editor-handler/*selected-text nil) state)}
  89. "Embedded page searching popup"
  90. [id format]
  91. (when (state/sub :editor/show-page-search?)
  92. (let [pos (state/get-editor-last-pos)
  93. input (gdom/getElement id)]
  94. (when input
  95. (let [current-pos (cursor/pos input)
  96. edit-content (or (state/sub [:editor/content id]) "")
  97. sidebar? (in-sidebar? input)
  98. q (or
  99. @editor-handler/*selected-text
  100. (when (state/sub :editor/show-page-search-hashtag?)
  101. (util/safe-subs edit-content pos current-pos))
  102. (when (> (count edit-content) current-pos)
  103. (util/safe-subs edit-content pos current-pos))
  104. "")
  105. matched-pages (when-not (string/blank? q)
  106. (editor-handler/get-matched-pages q))
  107. matched-pages (cond
  108. (contains? (set (map util/page-name-sanity-lc matched-pages)) (util/page-name-sanity-lc (string/trim q))) ;; if there's a page name fully matched
  109. matched-pages
  110. (string/blank? q)
  111. nil
  112. (empty? matched-pages)
  113. (cons (str "New page: " q) matched-pages)
  114. ;; reorder, shortest and starts-with first.
  115. :else
  116. (let [matched-pages (remove nil? matched-pages)
  117. matched-pages (sort-by
  118. (fn [m]
  119. [(not (gstring/caseInsensitiveStartsWith m q)) (count m)])
  120. matched-pages)]
  121. (if (gstring/caseInsensitiveStartsWith (first matched-pages) q)
  122. (cons (first matched-pages)
  123. (cons (str "New page: " q) (rest matched-pages)))
  124. (cons (str "New page: " q) matched-pages))))]
  125. (ui/auto-complete
  126. matched-pages
  127. {:on-chosen (page-handler/on-chosen-handler input id q pos format)
  128. :on-enter #(page-handler/page-not-exists-handler input id q current-pos)
  129. :item-render (fn [page-name chosen?]
  130. [:div.preview-trigger-wrapper
  131. (block/page-preview-trigger
  132. {:children [:div (search/highlight-exact-query page-name q)]
  133. :open? chosen?
  134. :manual? true
  135. :fixed-position? true
  136. :tippy-distance 24
  137. :tippy-position (if sidebar? "left" "right")}
  138. page-name)])
  139. :empty-placeholder [:div.text-gray-500.text-sm.px-4.py-2 "Search for a page"]
  140. :class "black"}))))))
  141. (rum/defcs block-search-auto-complete < rum/reactive
  142. {:init (fn [state]
  143. (assoc state ::result (atom nil)))
  144. :did-update (fn [state]
  145. (let [result (::result state)
  146. [edit-block _ _ q] (:rum/args state)]
  147. (p/let [matched-blocks (when-not (string/blank? q)
  148. (editor-handler/get-matched-blocks q (:block/uuid edit-block)))]
  149. (reset! result matched-blocks)))
  150. state)}
  151. [state _edit-block input id q format]
  152. (let [result (rum/react (get state ::result))
  153. chosen-handler (editor-handler/block-on-chosen-handler input id q format)
  154. non-exist-block-handler (editor-handler/block-non-exist-handler input)]
  155. (when result
  156. (ui/auto-complete
  157. result
  158. {:on-chosen chosen-handler
  159. :on-enter non-exist-block-handler
  160. :empty-placeholder [:div.text-gray-500.pl-4.pr-4 "Search for a block"]
  161. :item-render (fn [{:block/keys [page uuid]}] ;; content returned from search engine is normalized
  162. (let [page (or (:block/original-name page)
  163. (:block/name page))
  164. repo (state/sub :git/current-repo)
  165. format (db/get-page-format page)
  166. block (db-model/query-block-by-uuid uuid)
  167. content (:block/content block)]
  168. [:.py-2 (search/block-search-result-item repo uuid format content q :block)]))
  169. :class "black"}))))
  170. (rum/defcs block-search < rum/reactive
  171. {:will-unmount (fn [state]
  172. (reset! editor-handler/*selected-text nil)
  173. (state/clear-search-result!)
  174. state)}
  175. [state id _format]
  176. (when (state/sub :editor/show-block-search?)
  177. (let [pos (state/get-editor-last-pos)
  178. input (gdom/getElement id)
  179. [id format] (:rum/args state)
  180. current-pos (cursor/pos input)
  181. edit-content (state/sub [:editor/content id])
  182. edit-block (state/get-edit-block)
  183. q (or
  184. @editor-handler/*selected-text
  185. (when (> (count edit-content) current-pos)
  186. (subs edit-content pos current-pos)))]
  187. (when input
  188. (block-search-auto-complete edit-block input id q format)))))
  189. (rum/defc template-search < rum/reactive
  190. {:will-unmount (fn [state] (reset! editor-handler/*selected-text nil) state)}
  191. [id _format]
  192. (when (state/sub :editor/show-template-search?)
  193. (let [pos (state/get-editor-last-pos)
  194. input (gdom/getElement id)]
  195. (when input
  196. (let [current-pos (cursor/pos input)
  197. edit-content (state/sub [:editor/content id])
  198. q (or
  199. (when (>= (count edit-content) current-pos)
  200. (subs edit-content pos current-pos))
  201. "")
  202. matched-templates (editor-handler/get-matched-templates q)
  203. non-exist-handler (fn [_state]
  204. (state/set-editor-show-template-search! false))]
  205. (ui/auto-complete
  206. matched-templates
  207. {:on-chosen (editor-handler/template-on-chosen-handler id)
  208. :on-enter non-exist-handler
  209. :empty-placeholder [:div.text-gray-500.px-4.py-2.text-sm "Search for a template"]
  210. :item-render (fn [[template _block-db-id]]
  211. template)
  212. :class "black"}))))))
  213. (rum/defcs input < rum/reactive
  214. (rum/local {} ::input-value)
  215. (mixins/event-mixin
  216. (fn [state]
  217. (mixins/on-key-down
  218. state
  219. {;; enter
  220. 13 (fn [state e]
  221. (let [input-value (get state ::input-value)
  222. input-option (get @state/state :editor/show-input)]
  223. (when (seq @input-value)
  224. ;; no new line input
  225. (util/stop e)
  226. (let [[_id on-submit] (:rum/args state)
  227. {:keys [pos]} @*slash-caret-pos
  228. command (:command (first input-option))]
  229. (on-submit command @input-value pos))
  230. (reset! input-value nil))))})))
  231. [state _id on-submit]
  232. (when-let [input-option (state/sub :editor/show-input)]
  233. (let [{:keys [pos]} (util/react *slash-caret-pos)
  234. input-value (get state ::input-value)]
  235. (when (seq input-option)
  236. (let [command (:command (first input-option))]
  237. [:div.p-2.rounded-md.shadow-lg
  238. (for [{:keys [id placeholder type autoFocus] :as input-item} input-option]
  239. [:div.my-3 {:key id}
  240. [:input.form-input.block.w-full.pl-2.sm:text-sm.sm:leading-5
  241. (merge
  242. (cond->
  243. {:key (str "modal-input-" (name id))
  244. :id (str "modal-input-" (name id))
  245. :type (or type "text")
  246. :on-change (fn [e]
  247. (swap! input-value assoc id (util/evalue e)))
  248. :auto-complete (if (util/chrome?) "chrome-off" "off")}
  249. placeholder
  250. (assoc :placeholder placeholder)
  251. autoFocus
  252. (assoc :auto-focus true))
  253. (dissoc input-item :id))]])
  254. (ui/button
  255. "Submit"
  256. :on-click
  257. (fn [e]
  258. (util/stop e)
  259. (on-submit command @input-value pos)))])))))
  260. (rum/defc absolute-modal < rum/static
  261. [cp set-default-width? {:keys [top left rect]}]
  262. (let [max-height 370
  263. max-width 300
  264. offset-top 24
  265. vw-height js/window.innerHeight
  266. vw-width js/window.innerWidth
  267. to-max-height (if (and (seq rect) (> vw-height max-height))
  268. (let [delta-height (- vw-height (+ (:top rect) top offset-top))]
  269. (if (< delta-height max-height)
  270. (- (max (* 2 offset-top) delta-height) 16)
  271. max-height))
  272. max-height)
  273. right-sidebar? (:ui/sidebar-open? @state/state)
  274. editing-key (first (keys (:editor/editing? @state/state)))
  275. *el (rum/use-ref nil)
  276. _ (rum/use-effect! (fn []
  277. (when-let [^js/HTMLElement cnt
  278. (and right-sidebar? editing-key
  279. (js/document.querySelector "#main-content-container"))]
  280. (when (.contains cnt (js/document.querySelector (str "#" editing-key)))
  281. (let [el (rum/deref *el)
  282. ofx (- (.-scrollWidth cnt) (.-clientWidth cnt))]
  283. (when (> ofx 0)
  284. (set! (.-transform (.-style el)) (str "translateX(-" (+ ofx 20) "px)")))))))
  285. [right-sidebar? editing-key])
  286. x-overflow-vw? (when (and (seq rect) (> vw-width max-width))
  287. (let [delta-width (- vw-width (+ (:left rect) left))]
  288. (< delta-width (* max-width 0.5))))
  289. pos-rect (when (and (seq rect) editing-key)
  290. (:rect (cursor/get-caret-pos (state/get-input))))
  291. y-diff (when pos-rect (- (:height pos-rect) (:height rect)))]
  292. [:div.absolute.rounded-md.shadow-lg.absolute-modal
  293. {:ref *el
  294. :class (if x-overflow-vw? "is-overflow-vw-x" "")
  295. :on-mouse-down (fn [e]
  296. (.stopPropagation e))
  297. :style (merge
  298. {:top (+ top offset-top (if (int? y-diff) y-diff 0))
  299. :max-height to-max-height
  300. :max-width 700
  301. ;; TODO: auto responsive fixed size
  302. :width "fit-content"
  303. :z-index 11}
  304. (when set-default-width?
  305. {:width max-width})
  306. (let [^js/HTMLElement textarea
  307. (js/document.querySelector "textarea.ls-textarea")]
  308. (if (<= (.-clientWidth textarea) (+ left (if set-default-width? max-width 500)))
  309. {:right 0}
  310. {:left (if (and y-diff (= y-diff 0)) left 0)})))}
  311. cp]))
  312. (rum/defc transition-cp < rum/reactive
  313. [cp set-default-width? pos]
  314. (when pos
  315. (when-let [pos (rum/react pos)]
  316. (ui/css-transition
  317. {:class-names "fade"
  318. :timeout {:enter 500
  319. :exit 300}}
  320. (absolute-modal cp set-default-width? pos)))))
  321. (rum/defc image-uploader < rum/reactive
  322. [id format]
  323. [:div.image-uploader
  324. [:input
  325. {:id "upload-file"
  326. :type "file"
  327. :on-change (fn [e]
  328. (let [files (.-files (.-target e))]
  329. (editor-handler/upload-asset id files format editor-handler/*asset-uploading? false)))
  330. :hidden true}]
  331. #_:clj-kondo/ignore
  332. (when-let [uploading? (util/react editor-handler/*asset-uploading?)]
  333. (let [processing (util/react editor-handler/*asset-uploading-process)]
  334. (transition-cp
  335. [:div.flex.flex-row.align-center.rounded-md.shadow-sm.bg-base-2.px-1.py-1
  336. (ui/loading
  337. (util/format "Uploading %s%" (util/format "%2d" processing)))]
  338. false
  339. *slash-caret-pos)))])
  340. (defn- set-up-key-down!
  341. [state format]
  342. (mixins/on-key-down
  343. state
  344. {}
  345. {:not-matched-handler (editor-handler/keydown-not-matched-handler format)}))
  346. (defn- set-up-key-up!
  347. [state input input-id search-timeout]
  348. (mixins/on-key-up
  349. state
  350. {}
  351. (editor-handler/keyup-handler state input input-id search-timeout)))
  352. (def search-timeout (atom nil))
  353. (defn- setup-key-listener!
  354. [state]
  355. (let [{:keys [id format]} (get-state)
  356. input-id id
  357. input (gdom/getElement input-id)]
  358. (set-up-key-down! state format)
  359. (set-up-key-up! state input input-id search-timeout)))
  360. (def starts-with? clojure.string/starts-with?)
  361. (defn get-editor-style-class
  362. "Get textarea css class according to it's content"
  363. [content format]
  364. (let [content (if content (str content) "")]
  365. ;; as the function is binding to the editor content, optimization is welcome
  366. (str
  367. "ls-textarea "
  368. (if (or (> (.-length content) 1000)
  369. (string/includes? content "\n"))
  370. "multiline-block"
  371. "uniline-block")
  372. " "
  373. (case format
  374. :markdown
  375. (cond
  376. (starts-with? content "# ") "h1"
  377. (starts-with? content "## ") "h2"
  378. (starts-with? content "### ") "h3"
  379. (starts-with? content "#### ") "h4"
  380. (starts-with? content "##### ") "h5"
  381. (starts-with? content "###### ") "h6"
  382. (and (starts-with? content "---\n") (.endsWith content "\n---")) "page-properties"
  383. :else "normal-block")
  384. ;; other formats
  385. (cond
  386. (and (starts-with? content "---\n") (.endsWith content "\n---")) "page-properties"
  387. :else "normal-block")))))
  388. (defn editor-row-height-unchanged?
  389. "Check if the row height of editor textarea is changed, which happens when font-size changed"
  390. []
  391. ;; FIXME: assuming enter key is the only trigger of the height changing (under markdown editing of headlines)
  392. ;; FIXME: looking for an elegant & robust way to track the change of font-size, or wait for our own WYSIWYG text area
  393. (let [last-key (state/get-last-key-code)]
  394. (and (not= keycode/enter (:key-code last-key))
  395. (not= keycode/enter-code (:code last-key)))))
  396. (rum/defc mock-textarea <
  397. rum/static
  398. {:did-update
  399. (fn [state]
  400. (when-not (:editor/on-paste? @state/state)
  401. (try (editor-handler/handle-last-input)
  402. (catch js/Error _e
  403. nil)))
  404. (state/set-state! :editor/on-paste? false)
  405. state)}
  406. [content]
  407. [:div#mock-text
  408. {:style {:width "100%"
  409. :height "100%"
  410. :position "absolute"
  411. :visibility "hidden"
  412. :top 0
  413. :left 0}}
  414. (let [content (str content "0")]
  415. (for [[idx c] (map-indexed
  416. vector
  417. (string/split content ""))]
  418. (if (= c "\n")
  419. [:span {:id (str "mock-text_" idx)
  420. :key idx} "0" [:br]]
  421. [:span {:id (str "mock-text_" idx)
  422. :key idx} c])))])
  423. (rum/defc mock-textarea-wrapper < rum/reactive
  424. []
  425. (let [content (state/sub-edit-content)]
  426. (mock-textarea content)))
  427. (defn animated-modal
  428. [key component set-default-width? *pos]
  429. (when *pos
  430. (ui/css-transition
  431. {:key key
  432. :class-names {:enter "origin-top-left opacity-0 transform scale-95"
  433. :enter-done "origin-top-left transition opacity-100 transform scale-100"
  434. :exit "origin-top-left transition opacity-0 transform scale-95"}
  435. :timeout {:enter 0
  436. :exit 150}}
  437. (fn [_]
  438. (absolute-modal
  439. component
  440. set-default-width?
  441. *pos)))))
  442. (rum/defc modals < rum/reactive
  443. "React to atom changes, find and render the correct modal"
  444. [id format]
  445. (ui/transition-group
  446. (cond
  447. (and (util/react *show-commands)
  448. (not (state/sub :editor/show-page-search?))
  449. (not (state/sub :editor/show-block-search?))
  450. (not (state/sub :editor/show-template-search?))
  451. (not (state/sub :editor/show-input))
  452. (not (state/sub :editor/show-zotero))
  453. (not (state/sub :editor/show-date-picker?)))
  454. (animated-modal "commands" (commands id format) true (util/react *slash-caret-pos))
  455. (and (util/react *show-block-commands) @*angle-bracket-caret-pos)
  456. (animated-modal "block-commands" (block-commands id format) true (util/react *angle-bracket-caret-pos))
  457. (state/sub :editor/show-page-search?)
  458. (animated-modal "page-search" (page-search id format) true (util/react *slash-caret-pos))
  459. (state/sub :editor/show-block-search?)
  460. (animated-modal "block-search" (block-search id format) false (util/react *slash-caret-pos))
  461. (state/sub :editor/show-template-search?)
  462. (animated-modal "template-search" (template-search id format) true (util/react *slash-caret-pos))
  463. (state/sub :editor/show-date-picker?)
  464. (animated-modal "date-picker" (datetime-comp/date-picker id format nil) false (util/react *slash-caret-pos))
  465. (state/sub :editor/show-input)
  466. (animated-modal "input" (input id
  467. (fn [command m _pos]
  468. (editor-handler/handle-command-input command id format m)))
  469. true (util/react *slash-caret-pos))
  470. (state/sub :editor/show-zotero)
  471. (animated-modal "zotero-search" (zotero/zotero-search id) false (util/react *slash-caret-pos))
  472. :else
  473. nil)))
  474. (rum/defcs box < rum/reactive
  475. {:init (fn [state]
  476. (assoc state ::heading-level (:heading-level (first (:rum/args state)))
  477. ::id (str (random-uuid))))
  478. :did-mount (fn [state]
  479. (state/set-editor-args! (:rum/args state))
  480. state)}
  481. (mixins/event-mixin setup-key-listener!)
  482. (shortcut/mixin :shortcut.handler/block-editing-only)
  483. lifecycle/lifecycle
  484. [state {:keys [format block]} id _config]
  485. (let [content (state/sub-edit-content)
  486. heading-class (get-editor-style-class content format)]
  487. [:div.editor-inner {:class (if block "block-editor" "non-block-editor")}
  488. (when (= (state/sub :editor/record-status) "RECORDING")
  489. [:div#audio-record-toolbar
  490. (footer/audio-record-cp)])
  491. (ui/ls-textarea
  492. {:id id
  493. :cacheMeasurements (editor-row-height-unchanged?) ;; check when content updated (as the content variable is binded)
  494. :default-value (or content "")
  495. :minRows (if (state/enable-grammarly?) 2 1)
  496. :on-click (editor-handler/editor-on-click! id)
  497. :on-change (editor-handler/editor-on-change! block id search-timeout)
  498. :on-paste (editor-handler/editor-on-paste! id)
  499. :auto-focus false
  500. :class heading-class})
  501. (mock-textarea-wrapper)
  502. (modals id format)
  503. (when format
  504. (image-uploader id format))]))