block.cljs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  1. (ns frontend.components.block
  2. (:refer-clojure :exclude [range])
  3. (:require [frontend.config :as config]
  4. [cljs.core.match :refer-macros [match]]
  5. [promesa.core :as p]
  6. [frontend.fs :as fs]
  7. [clojure.string :as string]
  8. [frontend.util :as util]
  9. [rum.core :as rum]
  10. [frontend.state :as state]
  11. [frontend.db :as db]
  12. [frontend.db.model :as model]
  13. [frontend.db.query-dsl :as query-dsl]
  14. [dommy.core :as d]
  15. [datascript.core :as dc]
  16. [goog.dom :as gdom]
  17. [frontend.components.svg :as svg]
  18. [frontend.components.datetime :as datetime-comp]
  19. [frontend.ui :as ui]
  20. [frontend.handler.editor :as editor-handler]
  21. [frontend.handler.block :as block-handler]
  22. [frontend.handler.route :as route-handler]
  23. [frontend.handler.dnd :as dnd]
  24. [frontend.handler.ui :as ui-handler]
  25. [frontend.handler.repeated :as repeated]
  26. [goog.object :as gobj]
  27. [medley.core :as medley]
  28. [cljs.reader :as reader]
  29. [frontend.util :as util :refer-macros [profile]]
  30. [frontend.db-mixins :as db-mixins]
  31. [frontend.extensions.latex :as latex]
  32. [frontend.components.lazy-editor :as lazy-editor]
  33. [frontend.extensions.highlight :as highlight]
  34. [frontend.extensions.sci :as sci]
  35. ["/frontend/utils" :as utils]
  36. [frontend.format.block :as block]
  37. [clojure.walk :as walk]
  38. [cljs-bean.core :as bean]
  39. [frontend.handler.image :as image-handler]
  40. [frontend.format.mldoc :as mldoc]
  41. [frontend.text :as text]
  42. [frontend.utf8 :as utf8]
  43. [frontend.date :as date]
  44. [frontend.security :as security]
  45. [reitit.frontend.easy :as rfe]
  46. [frontend.commands :as commands]
  47. [lambdaisland.glogi :as log]
  48. [frontend.context.i18n :as i18n]
  49. [frontend.template :as template]
  50. [shadow.loader :as loader]
  51. [frontend.search :as search]
  52. [frontend.debug :as debug]
  53. [frontend.modules.outliner.tree :as tree]
  54. [clojure.walk :as walk]))
  55. ;; TODO: remove rum/with-context because it'll make reactive queries not working
  56. (defn safe-read-string
  57. ([s]
  58. (safe-read-string s true))
  59. ([s warn?]
  60. (try
  61. (reader/read-string s)
  62. (catch js/Error e
  63. (println "read-string error:")
  64. (js/console.error e)
  65. (when warn?
  66. [:div.warning {:title "read-string failed"}
  67. s])))))
  68. ;; local state
  69. (defonce *block-children
  70. (atom {}))
  71. (defonce *dragging?
  72. (atom false))
  73. (defonce *dragging-block
  74. (atom nil))
  75. (defonce *move-to-top?
  76. (atom false))
  77. ;; TODO: Improve blocks grouped by pages
  78. (defonce max-blocks-per-page 500)
  79. (defonce virtual-list-scroll-step 450)
  80. (defonce virtual-list-previous 50)
  81. (defonce container-ids (atom {}))
  82. (defonce container-idx (atom 0))
  83. ;; TODO:
  84. ;; add `key`
  85. (defn- remove-nils
  86. [col]
  87. (remove nil? col))
  88. (defn vec-cat
  89. [& args]
  90. (->> (apply concat args)
  91. remove-nils
  92. vec))
  93. (defn ->elem
  94. ([elem items]
  95. (->elem elem nil items))
  96. ([elem attrs items]
  97. (let [elem (keyword elem)]
  98. (if attrs
  99. (vec
  100. (cons elem
  101. (cons attrs
  102. (seq items))))
  103. (vec
  104. (cons elem
  105. (seq items)))))))
  106. (defn- join-lines
  107. [l]
  108. (string/trim (apply str l)))
  109. (defn- string-of-url
  110. [url]
  111. (match url
  112. (:or ["File" s] ["Search" s])
  113. s
  114. ["Complex" m]
  115. (let [{:keys [link protocol]} m]
  116. (if (= protocol "file")
  117. link
  118. (str protocol ":" link)))))
  119. (defn- get-file-absolute-path
  120. [config path]
  121. (let [path (string/replace path "file:" "")
  122. block-id (:block/uuid config)
  123. current-file (and block-id
  124. (:file/path (:block/file (:block/page (db/entity [:block/uuid block-id])))))]
  125. (when current-file
  126. (let [parts (string/split current-file #"/")
  127. parts-2 (string/split path #"/")
  128. current-dir (string/join "/" (drop-last 1 parts))]
  129. (cond
  130. (util/starts-with? path "/")
  131. path
  132. (and (not (util/starts-with? path ".."))
  133. (not (util/starts-with? path ".")))
  134. (str current-dir "/" path)
  135. :else
  136. (let [parts (loop [acc []
  137. parts (reverse parts)
  138. col (reverse parts-2)]
  139. (if (empty? col)
  140. acc
  141. (let [[part parts] (case (first col)
  142. ".."
  143. [(first parts) (rest parts)]
  144. "."
  145. ["" parts]
  146. [(first col) (rest parts)])]
  147. (recur (conj acc part)
  148. parts
  149. (rest col)))))
  150. parts (remove #(string/blank? %) parts)]
  151. (string/join "/" (reverse parts))))))))
  152. (defonce *resizing-image? (atom false))
  153. (rum/defcs resizable-image <
  154. (rum/local nil ::size)
  155. {:will-unmount (fn [state]
  156. (reset! *resizing-image? false)
  157. state)}
  158. [state config title src metadata full_text local?]
  159. (rum/with-context [[t] i18n/*tongue-context*]
  160. (let [size (get state ::size)]
  161. (ui/resize-provider
  162. (ui/resize-consumer
  163. (cond->
  164. {:className "resize image-resize"
  165. :onSizeChanged (fn [value]
  166. (when (and (not @*resizing-image?)
  167. (some? @size)
  168. (not= value @size))
  169. (reset! *resizing-image? true))
  170. (reset! size value))
  171. :onMouseUp (fn []
  172. (when (and @size @*resizing-image?)
  173. (when-let [block-id (:block/uuid config)]
  174. (let [size (bean/->clj @size)]
  175. (editor-handler/resize-image! block-id metadata full_text size))))
  176. (when @*resizing-image?
  177. ;; TODO: need a better way to prevent the clicking to edit current block
  178. (js/setTimeout #(reset! *resizing-image? false) 200)))
  179. :onClick (fn [e]
  180. (when @*resizing-image? (util/stop e)))}
  181. (and (:width metadata) (not (util/mobile?)))
  182. (assoc :style {:width (:width metadata)}))
  183. [:div.asset-container
  184. [:img.rounded-sm.shadow-xl.relative
  185. (merge
  186. {:loading "lazy"
  187. :src src
  188. :title title}
  189. metadata)]
  190. [:span.ctl
  191. [:a.delete
  192. {:title "Delete this image"
  193. :on-click
  194. (fn [e]
  195. (when-let [block-id (:block/uuid config)]
  196. (let [confirm-fn (ui/make-confirm-modal
  197. {:title (t :asset/confirm-delete (.toLocaleLowerCase (t :text/image)))
  198. :sub-title (if local? :asset/physical-delete "")
  199. :sub-checkbox? local?
  200. :on-confirm (fn [e {:keys [close-fn sub-selected]}]
  201. (close-fn)
  202. (editor-handler/delete-asset-of-block!
  203. {:block-id block-id
  204. :local? local?
  205. :repo (state/get-current-repo)
  206. :href src
  207. :title title
  208. :full-text full_text}))})]
  209. (state/set-modal! confirm-fn)
  210. (util/stop e))))}
  211. svg/trash-sm]]])))))
  212. (rum/defcs asset-link < rum/reactive
  213. (rum/local nil ::src)
  214. [state config title href label metadata full_text]
  215. (let [src (::src state)
  216. granted? (state/sub [:nfs/user-granted? (state/get-current-repo)])
  217. href (config/get-local-asset-absolute-path href)]
  218. (when (or granted? (util/electron?))
  219. (p/then (editor-handler/make-asset-url href) #(reset! src %)))
  220. (when @src
  221. (resizable-image config title @src metadata full_text true))))
  222. ;; TODO: safe encoding asciis
  223. ;; TODO: image link to another link
  224. (defn image-link [config url href label metadata full_text]
  225. (let [metadata (if (string/blank? metadata)
  226. nil
  227. (safe-read-string metadata false))
  228. title (second (first label))]
  229. (if (and (config/local-asset? href)
  230. (config/local-db? (state/get-current-repo)))
  231. (asset-link config title href label metadata full_text)
  232. (let [href (if (util/starts-with? href "http")
  233. href
  234. (get-file-absolute-path config href))]
  235. (resizable-image config title href metadata full_text false)))))
  236. (defn repetition-to-string
  237. [[[kind] [duration] n]]
  238. (let [kind (case kind
  239. "Dotted" "."
  240. "Plus" "+"
  241. "DoublePlus" "++")]
  242. (str kind n (string/lower-case (str (first duration))))))
  243. (defn timestamp-to-string
  244. [{:keys [active date time repetition wday active]}]
  245. (let [{:keys [year month day]} date
  246. {:keys [hour min]} time
  247. [open close] (if active ["<" ">"] ["[" "]"])
  248. repetition (if repetition
  249. (str " " (repetition-to-string repetition))
  250. "")
  251. hour (if hour (util/zero-pad hour))
  252. min (if min (util/zero-pad min))
  253. time (cond
  254. (and hour min)
  255. (util/format " %s:%s" hour min)
  256. hour
  257. (util/format " %s" hour)
  258. :else
  259. "")]
  260. (util/format "%s%s-%s-%s %s%s%s%s"
  261. open
  262. (str year)
  263. (util/zero-pad month)
  264. (util/zero-pad day)
  265. wday
  266. time
  267. repetition
  268. close)))
  269. (defn timestamp [{:keys [active date time repetition wday] :as t} kind]
  270. (let [prefix (case kind
  271. "Scheduled"
  272. [:i {:class "fa fa-calendar"
  273. :style {:margin-right 3.5}}]
  274. "Deadline"
  275. [:i {:class "fa fa-calendar-times-o"
  276. :style {:margin-right 3.5}}]
  277. "Date"
  278. nil
  279. "Closed"
  280. nil
  281. "Started"
  282. [:i {:class "fa fa-clock-o"
  283. :style {:margin-right 3.5}}]
  284. "Start"
  285. "From: "
  286. "Stop"
  287. "To: "
  288. nil)]
  289. (let [class (if (= kind "Closed")
  290. "line-through")]
  291. [:span.timestamp (cond-> {:active (str active)}
  292. class
  293. (assoc :class class))
  294. prefix
  295. (timestamp-to-string t)])))
  296. (defn range [{:keys [start stop]} stopped?]
  297. [:div {:class "timestamp-range"
  298. :stopped stopped?}
  299. (timestamp start "Start")
  300. (timestamp stop "Stop")])
  301. (declare map-inline)
  302. (declare markup-element-cp)
  303. (declare markup-elements-cp)
  304. (declare page-reference)
  305. (rum/defc page-cp
  306. [{:keys [html-export? label children contents-page?] :as config} page]
  307. (when-let [page-name (:block/name page)]
  308. (let [page-entity page
  309. page (string/lower-case page-name)
  310. redirect-page-name (cond
  311. (:block/alias? config)
  312. page
  313. (db/page-empty? (state/get-current-repo) page)
  314. (let [source-page (model/get-alias-source-page (state/get-current-repo)
  315. (string/lower-case page-name))]
  316. (or (when source-page (:block/name source-page))
  317. page))
  318. :else
  319. page)
  320. href (if html-export?
  321. (util/encode-str page)
  322. (rfe/href :page {:name redirect-page-name}))]
  323. [:a.page-ref
  324. {:data-ref page-name
  325. :href href
  326. :on-click (fn [e]
  327. (util/stop e)
  328. (if (gobj/get e "shiftKey")
  329. (when-let [page-entity (db/entity [:block/name redirect-page-name])]
  330. (state/sidebar-add-block!
  331. (state/get-current-repo)
  332. (:db/id page-entity)
  333. :page
  334. {:page page-entity}))
  335. (route-handler/redirect! {:to :page
  336. :path-params {:name redirect-page-name}}))
  337. (when (and contents-page?
  338. (state/get-left-sidebar-open?))
  339. (ui-handler/close-left-sidebar!)))}
  340. (if (seq children)
  341. (for [child children]
  342. (if (= (first child) "Label")
  343. (last child)
  344. (let [{:keys [content children]} (last child)
  345. page-name (subs content 2 (- (count content) 2))]
  346. (page-reference html-export? page-name (assoc config :children children) nil))))
  347. (if (and label
  348. (string? label)
  349. (not (string/blank? label))) ; alias
  350. label
  351. (get page-entity :block/original-name page-name)))])))
  352. (rum/defc asset-reference
  353. [title path]
  354. (let [repo-path (config/get-repo-dir (state/get-current-repo))
  355. full-path (.. util/node-path (join repo-path (config/get-local-asset-absolute-path path)))]
  356. [:div
  357. [:a.asset-ref {:target "_blank" :href full-path} (or title path)]
  358. (case (util/get-file-ext full-path)
  359. "pdf"
  360. [:iframe {:src full-path
  361. :fullscreen true
  362. :height 800}]
  363. ;; https://en.wikipedia.org/wiki/HTML5_video
  364. ("mp4" "ogg" "webm")
  365. [:video {:src full-path
  366. :controls true}]
  367. nil)]))
  368. (defonce excalidraw-loaded? (atom false))
  369. (rum/defc excalidraw < rum/reactive
  370. {:init (fn [state]
  371. (p/let [_ (loader/load :excalidraw)]
  372. (reset! excalidraw-loaded? true))
  373. state)}
  374. [file]
  375. (let [loaded? (rum/react excalidraw-loaded?)
  376. draw-component (if loaded?
  377. (resolve 'frontend.extensions.excalidraw/draw))]
  378. (when draw-component
  379. (draw-component {:file file}))))
  380. (rum/defc page-reference < rum/reactive
  381. [html-export? s config label]
  382. (let [show-brackets? (state/show-brackets?)
  383. nested-link? (:nested-link? config)
  384. contents-page? (= "contents" (string/lower-case (str (:id config))))
  385. draw? (string/ends-with? s ".excalidraw")]
  386. (if (string/ends-with? s ".excalidraw")
  387. [:div.draw {:on-click (fn [e]
  388. (.stopPropagation e))}
  389. (excalidraw s)]
  390. [:span.page-reference
  391. (when (and (or show-brackets? nested-link?)
  392. (not html-export?)
  393. (not contents-page?))
  394. [:span.text-gray-500.bracket "[["])
  395. (let [s (string/trim s)]
  396. (page-cp (assoc config
  397. :label (mldoc/plain->text label)
  398. :contents-page? contents-page?) {:block/name s}))
  399. (when (and (or show-brackets? nested-link?)
  400. (not html-export?)
  401. (not contents-page?))
  402. [:span.text-gray-500.bracket "]]"])])))
  403. (defn- latex-environment-content
  404. [name option content]
  405. (if (= (string/lower-case name) "equation")
  406. content
  407. (util/format "\\begin%s\n%s\\end{%s}"
  408. (str "{" name "}" option)
  409. content
  410. name)))
  411. (declare blocks-container)
  412. (rum/defc block-embed < rum/reactive db-mixins/query
  413. [config id]
  414. (let [blocks (db/get-block-and-children (state/get-current-repo) id)]
  415. [:div.color-level.embed-block.bg-base-2 {:style {:z-index 2}}
  416. [:div.px-3.pt-1.pb-2
  417. (blocks-container blocks (assoc (assoc config :id (str id))
  418. :embed? true
  419. :ref? false))]]))
  420. (rum/defc page-embed < rum/reactive db-mixins/query
  421. [config page-name]
  422. (let [page-name (string/trim (string/lower-case page-name))
  423. current-page (state/get-current-page)]
  424. [:div.color-level.embed.embed-page.bg-base-2
  425. {:class (if (:sidebar? config) "in-sidebar")}
  426. [:section.flex.items-center.p-1.embed-header
  427. [:div.mr-3 svg/page]
  428. (page-cp config {:block/name page-name})]
  429. (when (and
  430. (not= (string/lower-case (or current-page ""))
  431. page-name)
  432. (not= (string/lower-case (get config :id ""))
  433. page-name))
  434. (let [blocks (db/get-page-blocks (state/get-current-repo) page-name)]
  435. (blocks-container blocks (assoc config
  436. :embed? true
  437. :ref? false))))]))
  438. (defn- get-label-text
  439. [label]
  440. (and (= 1 (count label))
  441. (let [label (first label)]
  442. (string? (last label))
  443. (last label))))
  444. (defn- get-page
  445. [label]
  446. (when-let [label-text (get-label-text label)]
  447. (db/entity [:block/name (string/lower-case label-text)])))
  448. (defn- macro->text
  449. [name arguments]
  450. (if (and (seq arguments)
  451. (not= arguments ["null"]))
  452. (util/format "{{{%s %s}}}" name (string/join ", " arguments))
  453. (util/format "{{{%s}}}" name)))
  454. (declare block-content)
  455. (rum/defc block-reference < rum/reactive
  456. [config id label]
  457. (when-not (string/blank? id)
  458. (let [block (and (util/uuid-string? id)
  459. (db/pull-block (uuid id)))]
  460. (if block
  461. [:span.block-ref-wrap
  462. {:on-mouse-down
  463. (fn [e]
  464. (util/stop e)
  465. (if (gobj/get e "shiftKey")
  466. (state/sidebar-add-block!
  467. (state/get-current-repo)
  468. (:db/id block)
  469. :block-ref
  470. {:block block})
  471. (route-handler/redirect! {:to :page
  472. :path-params {:name id}})))}
  473. (let [title (let [title (:block/title block)]
  474. (if (empty? title)
  475. ;; display the content
  476. [:div.block-ref
  477. (block-content config block nil (:block/uuid block) (:slide? config))]
  478. (->elem
  479. :span.block-ref
  480. (map-inline config title))))]
  481. (if label
  482. (->elem
  483. :span.block-ref {:title (:block/content block)} ; TODO: replace with a popup
  484. (map-inline config label))
  485. title))]
  486. [:span.warning.mr-1 {:title "Block ref invalid"}
  487. (util/format "((%s))" id)]))))
  488. (defn inline-text
  489. [format v]
  490. (when (string? v)
  491. (let [inline-list (mldoc/inline->edn v (mldoc/default-config format))]
  492. [:div.inline.mr-1 (map-inline {} inline-list)])))
  493. (defn selection-range-in-block? []
  494. (and (= "Range" (. (js/window.getSelection) -type))
  495. (-> (js/window.getSelection)
  496. (.-anchorNode)
  497. (.-parentNode)
  498. (.closest ".block-content"))))
  499. (defn- render-macro
  500. [config name arguments macro-content format]
  501. (if macro-content
  502. (let [ast (->> (mldoc/->edn macro-content (mldoc/default-config format))
  503. (map first))
  504. block? (contains? #{"Paragraph"
  505. "Raw_Html"
  506. "Hiccup"}
  507. (ffirst ast))]
  508. (if block?
  509. [:div
  510. (markup-elements-cp (assoc config :block/format format) ast)]
  511. (inline-text format macro-content)))
  512. [:span.warning {:title (str "Unsupported macro name: " name)}
  513. (macro->text name arguments)]))
  514. (rum/defc nested-link < rum/reactive
  515. [config html-export? link]
  516. (let [show-brackets? (state/show-brackets?)
  517. {:keys [content children]} link]
  518. [:span.page-reference.nested
  519. (when (and show-brackets?
  520. (not html-export?)
  521. (not (= (:id config) "contents")))
  522. [:span.text-gray-500 "[["])
  523. (let [page-name (subs content 2 (- (count content) 2))]
  524. (page-cp (assoc config
  525. :children children
  526. :nested-link? true) {:block/name page-name}))
  527. (when (and show-brackets?
  528. (not html-export?)
  529. (not (= (:id config) "contents")))
  530. [:span.text-gray-500 "]]"])]))
  531. (declare custom-query)
  532. (defn inline
  533. [{:keys [html-export?] :as config} item]
  534. (match item
  535. ["Plain" s]
  536. s
  537. ["Spaces" s]
  538. s
  539. ["Superscript" l]
  540. (->elem :sup (map-inline config l))
  541. ["Subscript" l]
  542. (->elem :sub (map-inline config l))
  543. ["Tag" s]
  544. (when s
  545. (let [s (text/page-ref-un-brackets! s)]
  546. [:a.tag {:data-ref s
  547. :href (rfe/href :page {:name s})
  548. :on-click (fn [e]
  549. (let [repo (state/get-current-repo)
  550. page (db/pull repo '[*] [:block/name (string/lower-case (util/url-decode s))])]
  551. (when (gobj/get e "shiftKey")
  552. (state/sidebar-add-block!
  553. repo
  554. (:db/id page)
  555. :page
  556. {:page page})
  557. (.preventDefault e))))}
  558. (str "#" s)]))
  559. ["Emphasis" [[kind] data]]
  560. (let [elem (case kind
  561. "Bold" :b
  562. "Italic" :i
  563. "Underline" :ins
  564. "Strike_through" :del
  565. "Highlight" :mark)]
  566. (->elem elem (map-inline config data)))
  567. ["Entity" e]
  568. [:span {:dangerouslySetInnerHTML
  569. {:__html (:html e)}}]
  570. ["Latex_Fragment" ["Displayed" s]]
  571. (if html-export?
  572. (latex/html-export s false true)
  573. (latex/latex (str (dc/squuid)) s false true))
  574. ["Latex_Fragment" ["Inline" s]]
  575. (if html-export?
  576. (latex/html-export s false true)
  577. (latex/latex (str (dc/squuid)) s false false))
  578. ["Target" s]
  579. [:a {:id s} s]
  580. ["Radio_Target" s]
  581. [:a {:id s} s]
  582. ["Email" address]
  583. (let [{:keys [local_part domain]} address
  584. address (str local_part "@" domain)]
  585. [:a {:href (str "mainto:" address)}
  586. address])
  587. ["Block_reference" id]
  588. ;; FIXME: alert when self block reference
  589. (block-reference config id nil)
  590. ["Nested_link" link]
  591. (nested-link config html-export? link)
  592. ["Link" link]
  593. (let [{:keys [url label title metadata full_text]} link
  594. img-formats (set (map name (config/img-formats)))]
  595. (match url
  596. ["Search" s]
  597. (cond
  598. (string/blank? s)
  599. [:span.warning {:title "Invalid link"} full_text]
  600. (text/block-ref? s)
  601. (let [block-id (text/block-ref-un-brackets! s)]
  602. (block-reference config block-id label))
  603. (text/page-ref? s)
  604. (let [page (text/page-ref-un-brackets! s)]
  605. (page-reference (:html-export? config) page config label))
  606. ;; image
  607. (text/image-link? img-formats s)
  608. (image-link config url s label metadata full_text)
  609. (= \# (first s))
  610. (->elem :a {:on-click #(route-handler/jump-to-anchor! (mldoc/anchorLink (subs s 1)))} (subs s 1))
  611. ;; FIXME: same headline, see more https://orgmode.org/manual/Internal-Links.html
  612. (and (= \* (first s))
  613. (not= \* (last s)))
  614. (->elem :a {:on-click #(route-handler/jump-to-anchor! (mldoc/anchorLink (subs s 1)))} (subs s 1))
  615. (re-find #"(?i)^http[s]?://" s)
  616. (->elem :a {:href s
  617. :data-href s
  618. :target "_blank"}
  619. (map-inline config label))
  620. (and (util/electron?) (config/local-asset? s))
  621. (asset-reference (second (first label)) s)
  622. :else
  623. (page-reference html-export? s config label))
  624. :else
  625. (let [href (string-of-url url)
  626. protocol (or
  627. (and (= "Complex" (first url))
  628. (:protocol (second url)))
  629. (and (= "File" (first url))
  630. "file"))]
  631. (cond
  632. (and (= "Complex" (first url))
  633. (= protocol "id")
  634. (string? (:link (second url)))
  635. (util/uuid-string? (:link (second url)))) ; org mode id
  636. (block-reference config (:link (second url)) nil)
  637. (= protocol "file")
  638. (if (text/image-link? img-formats href)
  639. (image-link config url href label metadata full_text)
  640. (let [label-text (get-label-text label)
  641. page (if (string/blank? label-text)
  642. {:block/name (db/get-file-page (string/replace href "file:" ""))}
  643. (get-page label))]
  644. (if (and page
  645. (when-let [ext (util/get-file-ext href)]
  646. (config/mldoc-support? ext)))
  647. [:span.page-reference
  648. [:span.text-gray-500 "[["]
  649. (page-cp config page)
  650. [:span.text-gray-500 "]]"]]
  651. (->elem
  652. :a
  653. (cond->
  654. {:href (str "file://" href)
  655. :data-href href
  656. :target "_blank"}
  657. title
  658. (assoc :title title))
  659. (map-inline config label)))))
  660. ;; image
  661. (text/image-link? img-formats href)
  662. (image-link config url href label metadata full_text)
  663. :else
  664. (->elem
  665. :a.external-link
  666. (cond->
  667. {:href href
  668. :target "_blank"}
  669. title
  670. (assoc :title title))
  671. (map-inline config label))))))
  672. ["Verbatim" s]
  673. [:code s]
  674. ["Code" s]
  675. [:code s]
  676. ["Inline_Source_Block" x]
  677. [:code (:code x)]
  678. ["Export_Snippet" "html" s]
  679. (when (not html-export?)
  680. [:span {:dangerouslySetInnerHTML
  681. {:__html s}}])
  682. ;; String to hiccup
  683. ["Inline_Hiccup" s]
  684. (ui/catch-error
  685. [:div.warning {:title "Invalid hiccup"} s]
  686. (-> (safe-read-string s)
  687. (security/remove-javascript-links-in-href)))
  688. ["Inline_Html" s]
  689. (when (not html-export?)
  690. ;; TODO: how to remove span and only export the content of `s`?
  691. [:span {:dangerouslySetInnerHTML
  692. {:__html s}}])
  693. ["Break_Line"]
  694. [:br]
  695. ["Hard_Break_Line"]
  696. [:br]
  697. ["Timestamp" ["Scheduled" t]]
  698. nil
  699. ["Timestamp" ["Deadline" t]]
  700. nil
  701. ["Timestamp" ["Date" t]]
  702. (timestamp t "Date")
  703. ["Timestamp" ["Closed" t]]
  704. (timestamp t "Closed")
  705. ["Timestamp" ["Range" t]]
  706. (range t false)
  707. ["Timestamp" ["Clock" ["Stopped" t]]]
  708. (range t true)
  709. ["Timestamp" ["Clock" ["Started" t]]]
  710. (timestamp t "Started")
  711. ["Cookie" ["Percent" n]]
  712. [:span {:class "cookie-percent"}
  713. (util/format "[d%%]" n)]
  714. ["Cookie" ["Absolute" current total]]
  715. [:span {:class "cookie-absolute"}
  716. (util/format "[%d/%d]" current total)]
  717. ["Footnote_Reference" options]
  718. (let [{:keys [id name]} options
  719. encode-name (util/url-encode name)]
  720. [:sup.fn
  721. [:a {:id (str "fnr." encode-name)
  722. :class "footref"
  723. :on-click #(route-handler/jump-to-anchor! (str "fn." encode-name))}
  724. name]])
  725. ["Macro" options]
  726. (let [{:keys [name arguments]} options
  727. arguments (if (and
  728. (>= (count arguments) 2)
  729. (and (string/starts-with? (first arguments) "[[")
  730. (string/ends-with? (last arguments) "]]"))) ; page reference
  731. (let [title (string/join ", " arguments)]
  732. [title])
  733. arguments)]
  734. (cond
  735. (= name "query")
  736. [:div.dsl-query
  737. (let [query (string/join ", " arguments)]
  738. (custom-query (assoc config :dsl-query? true)
  739. {:title [:code.p-1 (str "Query: " query)]
  740. :query query}))]
  741. (= name "youtube")
  742. (let [url (first arguments)]
  743. (let [YouTube-regex #"^((?:https?:)?//)?((?:www|m).)?((?:youtube.com|youtu.be))(/(?:[\w-]+\?v=|embed/|v/)?)([\w-]+)(\S+)?$"]
  744. (when-let [youtube-id (cond
  745. (== 11 (count url)) url
  746. :else
  747. (nth (re-find YouTube-regex url) 5))]
  748. (when-not (string/blank? youtube-id)
  749. (let [width (min (- (util/get-width) 96)
  750. 560)
  751. height (int (* width (/ 315 560)))]
  752. [:iframe
  753. {:allow-full-screen "allowfullscreen"
  754. :allow
  755. "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope"
  756. :frame-border "0"
  757. :src (str "https://www.youtube.com/embed/" youtube-id)
  758. :height height
  759. :width width}])))))
  760. (= name "vimeo")
  761. (let [url (first arguments)]
  762. (let [Vimeo-regex #"^((?:https?:)?//)?((?:www).)?((?:player.vimeo.com|vimeo.com)?)((?:/video/)?)([\w-]+)(\S+)?$"]
  763. (when-let [vimeo-id (nth (re-find Vimeo-regex url) 5)]
  764. (when-not (string/blank? vimeo-id)
  765. (let [width (min (- (util/get-width) 96)
  766. 560)
  767. height (int (* width (/ 315 560)))]
  768. [:iframe
  769. {:allow-full-screen "allowfullscreen"
  770. :allow
  771. "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope"
  772. :frame-border "0"
  773. :src (str "https://player.vimeo.com/video/" vimeo-id)
  774. :height height
  775. :width width}])))))
  776. ;; TODO: support fullscreen mode, maybe we need a fullscreen dialog?
  777. (= name "bilibili")
  778. (let [url (first arguments)
  779. id-regex #"https?://www\.bilibili\.com/video/([\w\W]+)"]
  780. (when-let [id (cond
  781. (<= (count url) 15) url
  782. :else
  783. (last (re-find id-regex url)))]
  784. (when-not (string/blank? id)
  785. (let [width (min (- (util/get-width) 96)
  786. 560)
  787. height (int (* width (/ 315 560)))]
  788. [:iframe
  789. {:allowfullscreen true
  790. :framespacing "0"
  791. :frameborder "no"
  792. :border "0"
  793. :scrolling "no"
  794. :src (str "https://player.bilibili.com/player.html?bvid=" id "&high_quality=1")
  795. :width width
  796. :height (max 500 height)}]))))
  797. (= name "embed")
  798. (let [a (first arguments)]
  799. (cond
  800. (nil? a) ; empty embed
  801. nil
  802. (and (string/starts-with? a "[[")
  803. (string/ends-with? a "]]"))
  804. (let [page-name (-> (string/replace a "[[" "")
  805. (string/replace "]]" "")
  806. string/trim)]
  807. (when-not (string/blank? page-name)
  808. (page-embed config page-name)))
  809. (and (string/starts-with? a "((")
  810. (string/ends-with? a "))"))
  811. (when-let [s (-> (string/replace a "((" "")
  812. (string/replace "))" "")
  813. string/trim)]
  814. (when-let [id (and s
  815. (let [s (string/trim s)]
  816. (and (util/uuid-string? s)
  817. (uuid s))))]
  818. (block-embed config id)))
  819. :else ;TODO: maybe collections?
  820. nil))
  821. :else
  822. (if-let [block-uuid (:block/uuid config)]
  823. (let [format (get-in config [:block :block/format] :markdown)
  824. macro-content (or
  825. (-> (db/entity [:block/uuid block-uuid])
  826. (:block/page)
  827. (:db/id)
  828. (db/entity)
  829. :block/properties
  830. :macros
  831. (get name))
  832. (get (state/get-macros) name)
  833. (get (state/get-macros) (keyword name)))
  834. macro-content (cond
  835. (= (str name) "img")
  836. (case (count arguments)
  837. 1
  838. (util/format "[:img {:src \"%s\"}]" (first arguments))
  839. 4
  840. (if (and (util/safe-parse-int (nth arguments 1))
  841. (util/safe-parse-int (nth arguments 2)))
  842. (util/format "[:img.%s {:src \"%s\" :style {:width %s :height %s}}]"
  843. (nth arguments 3)
  844. (first arguments)
  845. (util/safe-parse-int (nth arguments 1))
  846. (util/safe-parse-int (nth arguments 2))))
  847. 3
  848. (if (and (util/safe-parse-int (nth arguments 1))
  849. (util/safe-parse-int (nth arguments 2)))
  850. (util/format "[:img {:src \"%s\" :style {:width %s :height %s}}]"
  851. (first arguments)
  852. (util/safe-parse-int (nth arguments 1))
  853. (util/safe-parse-int (nth arguments 2))))
  854. 2
  855. (cond
  856. (and (util/safe-parse-int (nth arguments 1)))
  857. (util/format "[:img {:src \"%s\" :style {:width %s}}]"
  858. (first arguments)
  859. (util/safe-parse-int (nth arguments 1)))
  860. (contains? #{"left" "right" "center"} (string/lower-case (nth arguments 1)))
  861. (util/format "[:img.%s {:src \"%s\"}]"
  862. (string/lower-case (nth arguments 1))
  863. (first arguments))
  864. :else
  865. macro-content)
  866. macro-content)
  867. (and (seq arguments) macro-content)
  868. (block/macro-subs macro-content arguments)
  869. :else
  870. macro-content)
  871. macro-content (when macro-content
  872. (template/resolve-dynamic-template! macro-content))]
  873. (render-macro config name arguments macro-content format))
  874. (let [macro-content (or
  875. (get (state/get-macros) name)
  876. (get (state/get-macros) (keyword name)))
  877. format (get-in config [:block :block/format] :markdown)]
  878. (render-macro config name arguments macro-content format)))))
  879. :else
  880. ""))
  881. (declare blocks-cp)
  882. (rum/defc block-child
  883. [block]
  884. block)
  885. (defn- dnd-same-block?
  886. [uuid]
  887. (= (:block/uuid @*dragging-block) uuid))
  888. (defn- get-data-transfer-attr
  889. [event attr]
  890. (.getData (gobj/get event "dataTransfer") attr))
  891. (defn- bullet-drag-start
  892. [event block uuid block-id]
  893. (editor-handler/highlight-block! uuid)
  894. (.setData (gobj/get event "dataTransfer")
  895. "block-uuid"
  896. uuid)
  897. (.setData (gobj/get event "dataTransfer")
  898. "block-dom-id"
  899. block-id)
  900. (state/clear-selection!)
  901. (reset! *dragging? true)
  902. (reset! *dragging-block block))
  903. (defn- bullet-on-click
  904. [e block config uuid]
  905. (if (gobj/get e "shiftKey")
  906. (do
  907. (state/sidebar-add-block!
  908. (state/get-current-repo)
  909. (:db/id block)
  910. :block
  911. block)
  912. (util/stop e))
  913. (when (:embed? config)
  914. (route-handler/redirect! {:to :page
  915. :path-params {:name (str uuid)}}))))
  916. (rum/defcs block-control < rum/reactive
  917. [state config block uuid block-id body children dummy? *control-show?]
  918. (let [has-child? (and
  919. (not (:pre-block? block))
  920. (or (seq children)
  921. (seq body)))
  922. collapsed? (get (:block/properties block) :collapsed)
  923. control-show? (util/react *control-show?)
  924. dark? (= "dark" (state/sub :ui/theme))]
  925. [:div.bullet.mr-2.flex.flex-row.items-center
  926. {:style {:height 24
  927. :margin-top 0
  928. :float "left"}}
  929. [:a.block-control.opacity-50.hover:opacity-100
  930. {:id (str "control-" uuid)
  931. :style {:width 14
  932. :height 16
  933. :margin-right 2}
  934. :on-click (fn [e]
  935. (util/stop e)
  936. (when-not (and (not collapsed?) (not has-child?))
  937. (editor-handler/set-block-property! uuid :collapsed (not collapsed?))))}
  938. (cond
  939. (and control-show? collapsed?)
  940. (svg/caret-right)
  941. (and control-show? has-child?)
  942. (svg/caret-down)
  943. :else
  944. [:span ""])]
  945. [:a (if (not dummy?)
  946. {:href (rfe/href :page {:name uuid})
  947. :on-click (fn [e] (bullet-on-click e block config uuid))})
  948. [:span.bullet-container.cursor
  949. {:id (str "dot-" uuid)
  950. :draggable true
  951. :on-drag-start (fn [event] (bullet-drag-start event block uuid block-id))
  952. :blockid (str uuid)
  953. :class (str (when collapsed? "bullet-closed")
  954. " "
  955. (when (and (:document/mode? config)
  956. (not collapsed?))
  957. "hide-inner-bullet"))}
  958. [:span.bullet {:blockid (str uuid)}]]]]))
  959. (defn- build-id
  960. [config]
  961. (let [k (pr-str config)
  962. n (or
  963. (get @container-ids k)
  964. (let [n' (swap! container-idx inc)]
  965. (swap! container-ids assoc k n')
  966. n'))]
  967. (str n "-")))
  968. (rum/defc dnd-separator
  969. [block margin-left bottom top? nested?]
  970. (let [id (str (:block/uuid block)
  971. (cond nested?
  972. "-nested"
  973. top?
  974. "-top"
  975. :else
  976. nil))]
  977. [:div.dnd-separator
  978. {:id id
  979. :style (merge
  980. {:position "absolute"
  981. :left margin-left
  982. :width "100%"
  983. :z-index 3}
  984. (if top?
  985. {:top 0}
  986. {:bottom 0}))}]))
  987. (declare block-container)
  988. (defn block-checkbox
  989. [block class]
  990. (let [marker (:block/marker block)
  991. [class checked?] (cond
  992. (nil? marker)
  993. nil
  994. (contains? #{"NOW" "LATER" "DOING" "IN-PROGRESS" "TODO" "WAIT" "WAITING"} marker)
  995. [class false]
  996. (= "DONE" marker)
  997. [(str class " checked") true])]
  998. (when class
  999. (ui/checkbox {:class class
  1000. :style {:margin-top -2
  1001. :margin-right 5}
  1002. :checked checked?
  1003. :on-change (fn [_e]
  1004. ;; FIXME: Log timestamp
  1005. (if checked?
  1006. (editor-handler/uncheck block)
  1007. (editor-handler/check block)))}))))
  1008. (defn list-checkbox
  1009. [checked?]
  1010. (ui/checkbox {:style {:margin-right 6}
  1011. :checked checked?}))
  1012. (defn marker-switch
  1013. [{:block/keys [pre-block? marker] :as block}]
  1014. (when (contains? #{"NOW" "LATER" "TODO" "DOING"} marker)
  1015. (let [set-marker-fn (fn [marker]
  1016. (fn [e]
  1017. (util/stop e)
  1018. (editor-handler/set-marker block marker)))]
  1019. (case marker
  1020. "NOW"
  1021. [:a.marker-switch
  1022. {:title "Change from NOW to LATER"
  1023. :on-click (set-marker-fn "LATER")}
  1024. "N"]
  1025. "LATER"
  1026. [:a.marker-switch
  1027. {:title "Change from LATER to NOW"
  1028. :on-click (set-marker-fn "NOW")}
  1029. "L"]
  1030. "TODO"
  1031. [:a.marker-switch
  1032. {:title "Change from TODO to DOING"
  1033. :on-click (set-marker-fn "DOING")}
  1034. "T"]
  1035. "DOING"
  1036. [:a.marker-switch
  1037. {:title "Change from DOING to TODO"
  1038. :on-click (set-marker-fn "TODO")}
  1039. "D"]
  1040. nil))))
  1041. (defn marker-cp
  1042. [{:block/keys [pre-block? marker] :as block}]
  1043. (when-not pre-block?
  1044. (if (contains? #{"IN-PROGRESS" "WAIT" "WAITING"} marker)
  1045. [:span {:class (str "task-status " (string/lower-case marker))
  1046. :style {:margin-right 3.5}}
  1047. (string/upper-case marker)])))
  1048. (defn priority-cp
  1049. [{:block/keys [pre-block? priority] :as block}]
  1050. (when (and (not pre-block?) priority)
  1051. (ui/tooltip
  1052. [:ul
  1053. (for [p (remove #(= priority %) ["A" "B" "C"])]
  1054. [:a.mr-2.text-base.tooltip-priority {:priority p
  1055. :on-click (fn [] (editor-handler/set-priority block p))}])]
  1056. [:a.opacity-50.hover:opacity-100
  1057. {:class "priority"
  1058. :href (rfe/href :page {:name priority})
  1059. :style {:margin-right 3.5}}
  1060. (util/format "[#%s]" (str priority))])))
  1061. (defn block-tags-cp
  1062. [{:block/keys [pre-block? tags] :as block}]
  1063. (when (and (not pre-block?)
  1064. (seq tags))
  1065. (->elem
  1066. :span
  1067. {:class "block-tags"}
  1068. (mapv (fn [tag]
  1069. (when-let [page (db/entity (:db/id tag))]
  1070. (let [tag (:block/name page)]
  1071. [:a.tag.mx-1 {:data-ref tag
  1072. :key (str "tag-" (:db/id tag))
  1073. :href (rfe/href :page {:name tag})}
  1074. (str "#" tag)])))
  1075. tags))))
  1076. (declare block-content)
  1077. (defn build-block-title
  1078. [{:keys [slide?] :as config} {:block/keys [uuid title tags marker priority anchor meta format content pre-block? dummy? block-refs-count page properties unordered level heading-level]
  1079. :as t}]
  1080. (let [config (assoc config :block t)
  1081. slide? (boolean (:slide? config))
  1082. html-export? (:html-export? config)
  1083. checkbox (when (and (not pre-block?)
  1084. (not html-export?))
  1085. (block-checkbox t (str "mr-1 cursor")))
  1086. marker-switch (when (and (not pre-block?)
  1087. (not html-export?))
  1088. (marker-switch t))
  1089. marker-cp (marker-cp t)
  1090. priority (priority-cp t)
  1091. tags (block-tags-cp t)
  1092. bg-color (:background-color properties)
  1093. elem (if (and (false? unordered)
  1094. heading-level
  1095. (<= heading-level 6))
  1096. (keyword (str "h" heading-level))
  1097. :div)]
  1098. (->elem
  1099. elem
  1100. (merge
  1101. {:id anchor}
  1102. (when (and marker
  1103. (not (string/blank? marker))
  1104. (not= "nil" marker))
  1105. {:class (str (string/lower-case marker))})
  1106. (when bg-color
  1107. {:style {:background-color bg-color
  1108. :padding-left 6
  1109. :padding-right 6
  1110. :color "#FFFFFF"}
  1111. :class "with-bg-color"}))
  1112. (remove-nils
  1113. (concat
  1114. [(when-not slide? checkbox)
  1115. (when-not slide? marker-switch)
  1116. marker-cp
  1117. priority]
  1118. (if title
  1119. (map-inline config title)
  1120. [[:span.opacity-50 "Click here to start writing"]])
  1121. [tags])))))
  1122. (defn show-dnd-separator
  1123. [element-id]
  1124. (when-let [element (gdom/getElement element-id)]
  1125. (when (d/has-class? element "dnd-separator")
  1126. (d/remove-class! element "dnd-separator")
  1127. (d/add-class! element "dnd-separator-cur"))))
  1128. (defn hide-dnd-separator
  1129. [element-id]
  1130. (when-let [element (gdom/getElement element-id)]
  1131. (when (d/has-class? element "dnd-separator-cur")
  1132. (d/remove-class! element "dnd-separator-cur")
  1133. (d/add-class! element "dnd-separator"))))
  1134. (defn- pre-block-cp
  1135. [config content format]
  1136. (rum/with-context [[t] i18n/*tongue-context*]
  1137. (let [ast (mldoc/->edn content (mldoc/default-config format))
  1138. ast (map first ast)
  1139. slide? (:slide? config)
  1140. only-title? (and (= 1 (count ast))
  1141. (= "Properties" (ffirst ast))
  1142. (let [m (second (first ast))]
  1143. (every? #(contains? #{:title :filters} %) (keys m))))
  1144. block-cp [:div {:class (if only-title?
  1145. (util/hiccup->class "pre-block.opacity-50")
  1146. (util/hiccup->class "pre-block.bg-base-2.p-2.rounded"))}
  1147. (if only-title?
  1148. [:span (t :page/edit-properties-placeholder)]
  1149. (markup-elements-cp (assoc config :block/format format) ast))]]
  1150. (if slide?
  1151. [:div [:h1 (:page-name config)]]
  1152. block-cp))))
  1153. (rum/defc span-comma
  1154. []
  1155. [:span ", "])
  1156. (rum/defc property-cp
  1157. [config block k v]
  1158. [:div.my-1
  1159. [:b (name k)]
  1160. [:span.mr-1 ":"]
  1161. (cond
  1162. (int? v)
  1163. v
  1164. (coll? v)
  1165. (let [v (->> (remove string/blank? v)
  1166. (filter string?))
  1167. vals (for [v-item v]
  1168. (page-cp config {:block/name v-item}))
  1169. elems (interpose (span-comma) vals)]
  1170. (for [elem elems]
  1171. (rum/with-key elem (str (random-uuid)))))
  1172. :else
  1173. (let [page-name (string/lower-case (str v))]
  1174. (if (db/entity [:block/name page-name])
  1175. (page-cp config {:block/name page-name})
  1176. (inline-text (:block/format block) (str v)))))])
  1177. (rum/defc properties-cp
  1178. [config block]
  1179. (let [properties (walk/keywordize-keys (:block/properties block))
  1180. properties (apply dissoc properties text/hidden-properties)]
  1181. (when (seq properties)
  1182. [:div.blocks-properties.text-sm.opacity-80.my-1.p-2
  1183. (for [[k v] properties]
  1184. (rum/with-key (property-cp config block k v)
  1185. (str (:block/uuid block) "-" k)))])))
  1186. (rum/defcs timestamp-cp < rum/reactive
  1187. (rum/local false ::show?)
  1188. (rum/local {} ::pos)
  1189. {:will-unmount (fn [state]
  1190. (when-let [show? (::show? state)]
  1191. (reset! show? false))
  1192. state)}
  1193. [state block typ ast]
  1194. (let [show? (get state ::show?)]
  1195. [:div.flex.flex-col
  1196. [:div.text-sm.mt-1.flex.flex-row
  1197. [:div.opacity-50.font-medium {:style {:width 95}}
  1198. (str typ ": ")]
  1199. [:a.opacity-80.hover:opacity-100
  1200. {:on-click (fn []
  1201. (if @show?
  1202. (do
  1203. (reset! show? false)
  1204. (reset! commands/*current-command nil)
  1205. (state/set-editor-show-date-picker! false)
  1206. (state/set-timestamp-block! nil))
  1207. (do
  1208. (reset! show? true)
  1209. (reset! commands/*current-command typ)
  1210. (state/set-editor-show-date-picker! true)
  1211. (state/set-timestamp-block! {:block block
  1212. :typ typ
  1213. :show? show?}))))}
  1214. (repeated/timestamp->text ast)]]
  1215. (when (true? @show?)
  1216. (let [ts (repeated/timestamp->map ast)]
  1217. [:div.my-4
  1218. (datetime-comp/date-picker nil nil ts)]))]))
  1219. (defn- block-content-on-mouse-down
  1220. [e block block-id properties content format edit-input-id]
  1221. (.stopPropagation e)
  1222. (let [target (gobj/get e "target")
  1223. button (gobj/get e "buttons")]
  1224. (when (contains? #{1 0} button)
  1225. (when-not (or
  1226. (d/has-class? target "bullet")
  1227. (util/link? target)
  1228. (util/input? target)
  1229. (util/details-or-summary? target)
  1230. (and (util/sup? target)
  1231. (d/has-class? target "fn"))
  1232. (d/has-class? target "image-resize"))
  1233. (editor-handler/clear-selection! nil)
  1234. (editor-handler/unhighlight-blocks!)
  1235. (let [properties-hidden? (text/properties-hidden? properties)
  1236. content (if properties-hidden? (text/remove-properties! format content) content)
  1237. block (or (db/pull [:block/uuid (:block/uuid block)]) block)
  1238. f #(let [cursor-range (util/caret-range (gdom/getElement block-id))]
  1239. (state/set-editing!
  1240. edit-input-id
  1241. content
  1242. block
  1243. cursor-range
  1244. false))]
  1245. ;; wait a while for the value of the caret range
  1246. (if (util/ios?)
  1247. (f)
  1248. (js/setTimeout f 5)))
  1249. (when block-id (state/set-selection-start-block! block-id))))))
  1250. (defn- block-content-on-drag-over
  1251. [event uuid]
  1252. (util/stop event)
  1253. (when-not (dnd-same-block? uuid)
  1254. (show-dnd-separator (str uuid "-nested"))))
  1255. (defn- block-content-on-drag-leave
  1256. [uuid]
  1257. (hide-dnd-separator (str uuid))
  1258. (hide-dnd-separator (str uuid "-nested"))
  1259. (hide-dnd-separator (str uuid "-top")))
  1260. (defn- block-content-on-drop
  1261. [event block uuid]
  1262. (util/stop event)
  1263. (when (and (not (dnd-same-block? uuid))
  1264. (not (:block/dummy? block)))
  1265. (dnd/move-block @*dragging-block
  1266. block
  1267. false
  1268. true))
  1269. (reset! *dragging? false)
  1270. (reset! *dragging-block nil)
  1271. (editor-handler/unhighlight-blocks!))
  1272. (rum/defc block-content < rum/reactive
  1273. [config {:block/keys [uuid title body meta content marker dummy? page format repo children pre-block? properties idx container block-refs-count scheduled deadline repeated?] :as block} edit-input-id block-id slide?]
  1274. (let [collapsed? (get properties :collapsed)
  1275. dragging? (rum/react *dragging?)
  1276. content (if (string? content) (string/trim content) "")
  1277. mouse-down-key (if (util/ios?)
  1278. :on-click
  1279. :on-mouse-down ; TODO: it seems that Safari doesn't work well with on-mouse-down
  1280. )
  1281. attrs {:blockid (str uuid)
  1282. mouse-down-key (fn [e]
  1283. (block-content-on-mouse-down e block block-id properties content format edit-input-id))
  1284. :on-drag-over (fn [event] (block-content-on-drag-over event uuid))
  1285. :on-drag-leave (fn [_event] (block-content-on-drag-leave uuid))
  1286. :on-drop (fn [event] (block-content-on-drop event block uuid))}]
  1287. [:div.flex.relative {:style {:width "100%"}}
  1288. [:div.flex-1.flex-col.relative.block-content
  1289. (cond-> {:id (str "block-content-" uuid)}
  1290. (not slide?)
  1291. (merge attrs))
  1292. (cond
  1293. pre-block?
  1294. (pre-block-cp config content format)
  1295. dummy?
  1296. [:span.opacity-50 "Click here to start writing"]
  1297. (seq title)
  1298. (build-block-title config block))
  1299. (when (and dragging? (not slide?) (not dummy?))
  1300. (dnd-separator block 0 -4 false true))
  1301. (when deadline
  1302. (when-let [deadline-ast (block-handler/get-deadline-ast block)]
  1303. (timestamp-cp block "DEADLINE" deadline-ast)))
  1304. (when scheduled
  1305. (when-let [scheduled-ast (block-handler/get-scheduled-ast block)]
  1306. (timestamp-cp block "SCHEDULED" scheduled-ast)))
  1307. (when (and (seq properties)
  1308. (let [hidden? (text/properties-hidden? properties)]
  1309. (not hidden?))
  1310. (not (:slide? config)))
  1311. (properties-cp config block))
  1312. (when (and (not pre-block?) (seq body))
  1313. (do
  1314. [:div.block-body {:style {:display (if (and collapsed? (seq title)) "none" "")}}
  1315. ;; TODO: consistent id instead of the idx (since it could be changed later)
  1316. (let [body (block/trim-break-lines! (:block/body block))]
  1317. (for [[idx child] (medley/indexed body)]
  1318. (when-let [block (markup-element-cp config child)]
  1319. (rum/with-key (block-child block)
  1320. (str uuid "-" idx)))))]))]
  1321. (when (and block-refs-count (> block-refs-count 0))
  1322. [:div
  1323. [:a.open-block-ref-link.bg-base-2
  1324. {:title "Open block references"
  1325. :style {:margin-top -1}
  1326. :on-click (fn []
  1327. (state/sidebar-add-block!
  1328. (state/get-current-repo)
  1329. (:db/id block)
  1330. :block-ref
  1331. {:block block}))}
  1332. block-refs-count]])
  1333. (when (and (= marker "DONE")
  1334. (state/enable-timetracking?))
  1335. (let [start-time (or
  1336. (get properties :now)
  1337. (get properties :doing)
  1338. (get properties :in-progress)
  1339. (get properties :later)
  1340. (get properties :todo))
  1341. finish-time (get properties :done)]
  1342. (when (and start-time finish-time (> finish-time start-time))
  1343. [:div.text-sm.absolute.time-spent {:style {:top 0
  1344. :right 0
  1345. :padding-left 2}
  1346. :title (str (date/int->local-time start-time) " ~ " (date/int->local-time finish-time))}
  1347. [:span.opacity-70
  1348. (utils/timeConversion (- finish-time start-time))]])))]))
  1349. (rum/defc block-content-or-editor < rum/reactive
  1350. [config {:block/keys [uuid title body meta content dummy? page format repo children pre-block? idx] :as block} edit-input-id block-id slide?]
  1351. (let [editor-box (get config :editor-box)
  1352. edit? (state/sub [:editor/editing? edit-input-id])]
  1353. (if (and edit? editor-box)
  1354. [:div.editor-wrapper {:id (str "editor-" edit-input-id)}
  1355. (editor-box {:block block
  1356. :block-id uuid
  1357. :block-parent-id block-id
  1358. :format format
  1359. :dummy? dummy?
  1360. :on-hide (fn [value event]
  1361. (when (= event :esc)
  1362. (editor-handler/select-block! uuid)))}
  1363. edit-input-id
  1364. config)]
  1365. (block-content config block edit-input-id block-id slide?))))
  1366. (rum/defc dnd-separator-wrapper < rum/reactive
  1367. [block slide? top?]
  1368. (let [dragging? (rum/react *dragging?)]
  1369. (when (and dragging?
  1370. (not slide?)
  1371. (not (:block/dummy? block))
  1372. (not (:block/pre-block? block)))
  1373. (dnd-separator block 20 0 top? false))))
  1374. (defn non-dragging?
  1375. [e]
  1376. (and (= (gobj/get e "buttons") 1)
  1377. (not (d/has-class? (gobj/get e "target") "bullet-container"))
  1378. (not (d/has-class? (gobj/get e "target") "bullet"))
  1379. (not @*dragging?)))
  1380. (defn block-parents
  1381. ([config repo block-id format]
  1382. (block-parents config repo block-id format true))
  1383. ([config repo block-id format show-page?]
  1384. (let [parents (db/get-block-parents repo block-id 3)
  1385. page (db/get-block-page repo block-id)
  1386. page-name (:block/name page)
  1387. page-original-name (:block/original-name page)]
  1388. (when (or (seq parents)
  1389. show-page?
  1390. page-name)
  1391. (let [parents-atom (atom parents)
  1392. component [:div.block-parents.flex-row.flex-1
  1393. (when show-page?
  1394. [:a {:href (rfe/href :page {:name page-name})}
  1395. (or page-original-name page-name)])
  1396. (when (and show-page? (seq parents) (> (count parents) 1))
  1397. [:span.mx-2.opacity-50 "➤"])
  1398. (when (seq parents)
  1399. (let [parents (doall
  1400. (for [{:block/keys [uuid title name]} parents]
  1401. (when-not name ; not page
  1402. [:a {:href (rfe/href :page {:name uuid})}
  1403. (map-inline config title)])))
  1404. parents (remove nil? parents)]
  1405. (reset! parents-atom parents)
  1406. (when (seq parents)
  1407. (interpose [:span.mx-2.opacity-50 "➤"]
  1408. parents))))]
  1409. component (filterv identity component)]
  1410. (when (or (seq @parents-atom) show-page?)
  1411. component))))))
  1412. (defn- block-drag-over
  1413. [event uuid top? block-id *move-to-top?]
  1414. (util/stop event)
  1415. (when-not (dnd-same-block? uuid)
  1416. (if top?
  1417. (let [element-top (gobj/get (utils/getOffsetRect (gdom/getElement block-id)) "top")
  1418. cursor-top (gobj/get event "clientY")]
  1419. (if (<= (js/Math.abs (- cursor-top element-top)) 16)
  1420. ;; top
  1421. (do
  1422. (hide-dnd-separator (str uuid))
  1423. (show-dnd-separator (str uuid "-top"))
  1424. (reset! *move-to-top? true))
  1425. (do
  1426. (hide-dnd-separator (str uuid "-top"))
  1427. (show-dnd-separator (str uuid)))))
  1428. (show-dnd-separator (str uuid)))))
  1429. (defn- block-drag-leave
  1430. [event uuid *move-to-top?]
  1431. (hide-dnd-separator (str uuid))
  1432. (hide-dnd-separator (str uuid "-nested"))
  1433. (hide-dnd-separator (str uuid "-top"))
  1434. (reset! *move-to-top? false))
  1435. (defn- block-drop
  1436. [event uuid block *move-to-top?]
  1437. (when-not (dnd-same-block? uuid)
  1438. (let [from-dom-id (get-data-transfer-attr event "block-dom-id")]
  1439. (dnd/move-block @*dragging-block
  1440. block
  1441. @*move-to-top?
  1442. false)))
  1443. (reset! *dragging? false)
  1444. (reset! *dragging-block nil)
  1445. (editor-handler/unhighlight-blocks!))
  1446. (defn- block-mouse-over
  1447. [e has-child? *control-show? block-id doc-mode?]
  1448. (util/stop e)
  1449. (when has-child?
  1450. (reset! *control-show? true))
  1451. (when-let [parent (gdom/getElement block-id)]
  1452. (let [node (.querySelector parent ".bullet-container")]
  1453. (when doc-mode?
  1454. (d/remove-class! node "hide-inner-bullet"))))
  1455. (when (and
  1456. (state/in-selection-mode?)
  1457. (non-dragging? e))
  1458. (util/stop e)
  1459. (editor-handler/highlight-selection-area! block-id)))
  1460. (defn- block-mouse-leave
  1461. [e has-child? *control-show? block-id doc-mode?]
  1462. (util/stop e)
  1463. (when has-child?
  1464. (reset! *control-show? false))
  1465. (when doc-mode?
  1466. (when-let [parent (gdom/getElement block-id)]
  1467. (when-let [node (.querySelector parent ".bullet-container")]
  1468. (d/add-class! node "hide-inner-bullet"))))
  1469. (when (and (non-dragging? e)
  1470. (not @*resizing-image?))
  1471. (state/into-selection-mode!)))
  1472. (defn- on-drag-and-mouse-attrs
  1473. [block uuid top? block-id *move-to-top? has-child? *control-show? doc-mode?]
  1474. {:on-drag-over (fn [event]
  1475. (block-drag-over event uuid top? block-id *move-to-top?))
  1476. :on-drag-leave (fn [event]
  1477. (block-drag-leave event uuid *move-to-top?))
  1478. :on-drop (fn [event]
  1479. (block-drop event uuid block *move-to-top?))
  1480. :on-mouse-over (fn [e]
  1481. (block-mouse-over e has-child? *control-show? block-id doc-mode?))
  1482. :on-mouse-leave (fn [e]
  1483. (block-mouse-leave e has-child? *control-show? block-id doc-mode?))})
  1484. (defn- get-data-refs-and-self
  1485. [block refs-with-children]
  1486. (let [refs (model/get-page-names-by-ids
  1487. (->> (map :db/id refs-with-children)
  1488. (remove nil?)))
  1489. data-refs (text/build-data-value refs)
  1490. refs (model/get-page-names-by-ids
  1491. (->> (map :db/id (:block/ref-pages block))
  1492. (remove nil?)))
  1493. data-refs-self (text/build-data-value refs)]
  1494. [data-refs data-refs-self]))
  1495. (rum/defcs block-container < rum/static
  1496. {:init (fn [state]
  1497. (assoc state ::control-show? (atom false)))
  1498. :should-update (fn [old-state new-state]
  1499. (not= (:block/content (second (:rum/args old-state)))
  1500. (:block/content (second (:rum/args new-state)))))}
  1501. [state config {:block/keys [uuid title body meta content dummy? page format repo children pre-block? top? properties refs-with-children heading-level level type] :as block}]
  1502. (let [heading? (and (= type :heading) (<= level 6))
  1503. *control-show? (get state ::control-show?)
  1504. collapsed? (get properties :collapsed)
  1505. ref? (boolean (:ref? config))
  1506. breadcrumb-show? (:breadcrumb-show? config)
  1507. sidebar? (boolean (:sidebar? config))
  1508. slide? (boolean (:slide? config))
  1509. doc-mode? (:document/mode? config)
  1510. embed? (:embed? config)
  1511. unique-dom-id (build-id (dissoc config :block/uuid))
  1512. block-id (str "ls-block-" unique-dom-id uuid)
  1513. has-child? (boolean
  1514. (and
  1515. (not pre-block?)
  1516. (or (seq children)
  1517. (seq body))))
  1518. attrs (on-drag-and-mouse-attrs block uuid top? block-id *move-to-top? has-child? *control-show? doc-mode?)
  1519. [data-refs data-refs-self] (get-data-refs-and-self block refs-with-children)
  1520. edit-input-id (str "edit-block-" unique-dom-id uuid)]
  1521. [:div.ls-block.flex.flex-col.rounded-sm
  1522. (cond->
  1523. {:id block-id
  1524. :data-refs data-refs
  1525. :data-refs-self data-refs-self
  1526. :style {:position "relative"}
  1527. :class (str uuid
  1528. (when dummy? " dummy")
  1529. (when (and collapsed? has-child?) " collapsed")
  1530. (when pre-block? " pre-block"))
  1531. :blockid (str uuid)
  1532. :repo repo
  1533. :haschild (str has-child?)}
  1534. (not slide?)
  1535. (merge attrs)
  1536. (and heading? heading-level)
  1537. (assoc :data-heading-level heading-level))
  1538. (when (and ref? breadcrumb-show?)
  1539. (when-let [comp (block-parents config repo uuid format false)]
  1540. [:div.my-2.opacity-50.ml-4 comp]))
  1541. (dnd-separator-wrapper block slide? top?)
  1542. [:div.flex.flex-row {:class (if heading? "items-center" "")}
  1543. (when (not slide?)
  1544. (block-control config block uuid block-id body children dummy? *control-show?))
  1545. (block-content-or-editor config block edit-input-id block-id slide?)]
  1546. (when (seq children)
  1547. [:div.block-children {:style {:margin-left (if doc-mode? 12 21)
  1548. :display (if collapsed? "none" "")}}
  1549. (for [child children]
  1550. (when (map? child)
  1551. (let [child (dissoc child :block/meta)]
  1552. (rum/with-key (block-container (assoc config :block/uuid (:block/uuid child)) child)
  1553. (:block/uuid child)))))])
  1554. (when ref?
  1555. (let [children (db/get-block-immediate-children repo uuid)
  1556. children (block-handler/filter-blocks repo children (:filters config) false)]
  1557. (when (seq children)
  1558. [:div.ref-children.ml-12
  1559. (blocks-container children (assoc config
  1560. :breadcrumb-show? false
  1561. :ref? true))])))
  1562. (dnd-separator-wrapper block slide? false)]))
  1563. (defn divide-lists
  1564. [[f & l]]
  1565. (loop [l l
  1566. ordered? (:ordered f)
  1567. result [[f]]]
  1568. (if (seq l)
  1569. (let [cur (first l)
  1570. cur-ordered? (:ordered cur)]
  1571. (if (= ordered? cur-ordered?)
  1572. (recur
  1573. (rest l)
  1574. cur-ordered?
  1575. (update result (dec (count result)) conj cur))
  1576. (recur
  1577. (rest l)
  1578. cur-ordered?
  1579. (conj result [cur]))))
  1580. result)))
  1581. (defn list-element
  1582. [l]
  1583. (match l
  1584. [l1 & tl]
  1585. (let [{:keys [ordered name]} l1]
  1586. (cond
  1587. (seq name)
  1588. :dl
  1589. ordered
  1590. :ol
  1591. :else
  1592. :ul))
  1593. :else
  1594. :ul))
  1595. (defn list-item
  1596. [config {:keys [name content checkbox items number] :as l}]
  1597. (let [content (when-not (empty? content)
  1598. (match content
  1599. [["Paragraph" i] & rest]
  1600. (vec-cat
  1601. (map-inline config i)
  1602. (markup-elements-cp config rest))
  1603. :else
  1604. (markup-elements-cp config content)))
  1605. checked? (some? checkbox)
  1606. items (if (seq items)
  1607. (->elem
  1608. (list-element items)
  1609. (for [item items]
  1610. (list-item config item))))]
  1611. (cond
  1612. (seq name)
  1613. [:dl {:checked checked?}
  1614. [:dt (map-inline config name)]
  1615. (->elem :dd
  1616. (vec-cat content [items]))]
  1617. :else
  1618. (if (nil? checkbox)
  1619. (->elem
  1620. :li
  1621. {:checked checked?}
  1622. (vec-cat
  1623. [(->elem
  1624. :p
  1625. content)]
  1626. [items]))
  1627. (->elem
  1628. :li
  1629. {:checked checked?}
  1630. (vec-cat
  1631. [(->elem
  1632. :p
  1633. (list-checkbox checkbox)
  1634. content)]
  1635. [items]))))))
  1636. (defn table
  1637. [config {:keys [header groups col_groups]}]
  1638. (let [tr (fn [elm cols]
  1639. (->elem
  1640. :tr
  1641. (mapv (fn [col]
  1642. (->elem
  1643. elm
  1644. {:scope "col"
  1645. :class "org-left"}
  1646. (map-inline config col)))
  1647. cols)))
  1648. tb-col-groups (try
  1649. (mapv (fn [number]
  1650. (let [col-elem [:col {:class "org-left"}]]
  1651. (->elem
  1652. :colgroup
  1653. (repeat number col-elem))))
  1654. col_groups)
  1655. (catch js/Error e
  1656. []))
  1657. head (if header
  1658. [:thead (tr :th header)])
  1659. groups (mapv (fn [group]
  1660. (->elem
  1661. :tbody
  1662. (mapv #(tr :td %) group)))
  1663. groups)]
  1664. [:div.table-wrapper {:style {:max-width (min 700
  1665. (gobj/get js/window "innerWidth"))}}
  1666. (->elem
  1667. :table
  1668. {:class "table-auto"
  1669. :border 2
  1670. :cell-spacing 0
  1671. :cell-padding 6
  1672. :rules "groups"
  1673. :frame "hsides"}
  1674. (vec-cat
  1675. tb-col-groups
  1676. (cons head groups)))]))
  1677. (defn map-inline
  1678. [config col]
  1679. (map #(inline config %) col))
  1680. (declare ->hiccup)
  1681. (defn built-in-custom-query?
  1682. [title]
  1683. (let [repo (state/get-current-repo)]
  1684. (let [queries (state/sub [:config repo :default-queries :journals])]
  1685. (when (seq queries)
  1686. (boolean (some #(= % title) (map :title queries)))))))
  1687. (defn- trigger-custom-query!
  1688. [state]
  1689. (let [[config query] (:rum/args state)
  1690. repo (state/get-current-repo)
  1691. result-atom (atom nil)
  1692. query-atom (if (:dsl-query? config)
  1693. (let [result (query-dsl/query (state/get-current-repo) (:query query))]
  1694. (cond
  1695. (and (util/electron?) (string? result)) ; full-text search
  1696. (if (string/blank? result)
  1697. (atom [])
  1698. (p/let [blocks (search/block-search repo result {:limit 30})]
  1699. (when (seq blocks)
  1700. (let [result (db/pull-many (state/get-current-repo) '[*] (map (fn [b] [:block/uuid (uuid (:block/uuid b))]) blocks))]
  1701. (reset! result-atom result)))))
  1702. (string? result)
  1703. (atom nil)
  1704. :else
  1705. result))
  1706. (db/custom-query query))
  1707. query-atom (if (instance? Atom query-atom)
  1708. query-atom
  1709. result-atom)]
  1710. (assoc state :query-atom query-atom)))
  1711. (rum/defcs custom-query < rum/reactive
  1712. {:will-mount trigger-custom-query!
  1713. :did-mount (fn [state]
  1714. (when-let [query (last (:rum/args state))]
  1715. (state/add-custom-query-component! query (:rum/react-component state)))
  1716. state)
  1717. :did-remount (fn [_old_state state]
  1718. (trigger-custom-query! state))
  1719. :will-unmount (fn [state]
  1720. (when-let [query (last (:rum/args state))]
  1721. (state/remove-custom-query-component! query)
  1722. (db/remove-custom-query! (state/get-current-repo) query))
  1723. state)}
  1724. [state config {:keys [title query inputs view collapsed? children?] :as q}]
  1725. (ui/catch-error
  1726. [:div.warning
  1727. [:p "Query failed: "]
  1728. [:pre (str q)]]
  1729. (let [dsl-query? (:dsl-query? config)
  1730. query-atom (:query-atom state)]
  1731. (let [current-block-uuid (or (:block/uuid (:block config))
  1732. (:block/uuid config))
  1733. ;; exclude the current one, otherwise it'll loop forever
  1734. remove-blocks (if current-block-uuid [current-block-uuid] nil)
  1735. query-result (and query-atom (rum/react query-atom))
  1736. result (if (and query-result dsl-query?)
  1737. query-result
  1738. (db/custom-query-result-transform query-result remove-blocks q))
  1739. result (if query-result
  1740. (db/custom-query-result-transform query-result remove-blocks q))
  1741. view-f (and view (sci/eval-string (pr-str view)))
  1742. only-blocks? (:block/uuid (first result))
  1743. blocks-grouped-by-page? (and (seq result)
  1744. (coll? (first result))
  1745. (:block/name (ffirst result))
  1746. (:block/uuid (first (second (first result))))
  1747. true)
  1748. built-in? (built-in-custom-query? title)]
  1749. [:div.custom-query.mt-2 (get config :attr {})
  1750. (when-not (and built-in? (empty? result))
  1751. (ui/foldable
  1752. [:div.opacity-70
  1753. title]
  1754. (cond
  1755. (and (seq result) view-f)
  1756. (let [result (try
  1757. (sci/call-fn view-f result)
  1758. (catch js/Error error
  1759. (log/error :custom-view-failed {:error error
  1760. :result result})
  1761. [:div "Custom view failed: "
  1762. (str error)]))]
  1763. (util/hiccup-keywordize result))
  1764. (and (seq result)
  1765. (or only-blocks? blocks-grouped-by-page?))
  1766. (->hiccup result (cond-> (assoc config
  1767. :custom-query? true
  1768. ;; :breadcrumb-show? true
  1769. :group-by-page? blocks-grouped-by-page?
  1770. ;; :ref? true
  1771. )
  1772. children?
  1773. (assoc :ref? true))
  1774. {:style {:margin-top "0.25rem"
  1775. :margin-left "0.25rem"}})
  1776. ;; page list
  1777. (and (seq result)
  1778. (:block/name (first result)))
  1779. [:ul#query-pages.mt-1
  1780. (for [{:block/keys [name original-name] :as page-entity} result]
  1781. [:li.mt-1
  1782. [:a {:href (rfe/href :page {:name name})
  1783. :on-click (fn [e]
  1784. (util/stop e)
  1785. (if (gobj/get e "shiftKey")
  1786. (state/sidebar-add-block!
  1787. (state/get-current-repo)
  1788. (:db/id page-entity)
  1789. :page
  1790. {:page page-entity})
  1791. (route-handler/redirect! {:to :page
  1792. :path-params {:name name}})))}
  1793. (or original-name name)]])]
  1794. (seq result) ;TODO: table
  1795. (let [result (->>
  1796. (for [record result]
  1797. (if (map? record)
  1798. (str (util/pp-str record) "\n")
  1799. record))
  1800. (remove nil?))]
  1801. [:pre result])
  1802. :else
  1803. [:div.text-sm.mt-2.ml-2.font-medium.opacity-50 "Empty"])
  1804. collapsed?))]))))
  1805. (defn admonition
  1806. [config type options result]
  1807. (when-let [icon (case (string/lower-case (name type))
  1808. "note" svg/note
  1809. "tip" svg/tip
  1810. "important" svg/important
  1811. "caution" svg/caution
  1812. "warning" svg/warning
  1813. "pinned" svg/pinned
  1814. nil)]
  1815. [:div.flex.flex-row.admonitionblock.align-items {:class type}
  1816. [:div.pr-4.admonition-icon.flex.flex-col.justify-center
  1817. {:title (string/upper-case type)} (icon)]
  1818. [:div.ml-4.text-lg
  1819. (markup-elements-cp config result)]]))
  1820. (defn markup-element-cp
  1821. [{:keys [html-export?] :as config} item]
  1822. (try
  1823. (match item
  1824. ["Properties" m]
  1825. [:div.properties
  1826. (let [format (:block/format config)]
  1827. (for [[k v] (dissoc m :roam_alias :roam_tags)]
  1828. (when (and (not (and (= k :macros) (empty? v))) ; empty macros
  1829. (not (= k :title))
  1830. (not (= k :filters)))
  1831. [:div.property
  1832. [:span.font-medium.mr-1 (str (name k) ": ")]
  1833. (if (coll? v)
  1834. (let [vals (for [item v]
  1835. (if (coll? v)
  1836. (let [config (if (= k :alias)
  1837. (assoc config :block/alias? true))]
  1838. (page-cp config {:block/name item}))
  1839. (inline-text format item)))]
  1840. (interpose [:span ", "] vals))
  1841. (inline-text format v))])))]
  1842. ["Paragraph" l]
  1843. ;; TODO: speedup
  1844. (if (re-find #"\"Export_Snippet\" \"embed\"" (str l))
  1845. (->elem :div (map-inline config l))
  1846. (->elem :div.is-paragraph (map-inline config l)))
  1847. ["Horizontal_Rule"]
  1848. (when-not (:slide? config)
  1849. [:hr])
  1850. ["Heading" h]
  1851. (block-container config h)
  1852. ["List" l]
  1853. (let [lists (divide-lists l)]
  1854. (if (= 1 (count lists))
  1855. (let [l (first lists)]
  1856. (->elem
  1857. (list-element l)
  1858. (map #(list-item config %) l)))
  1859. [:div.list-group
  1860. (for [l lists]
  1861. (->elem
  1862. (list-element l)
  1863. (map #(list-item config %) l)))]))
  1864. ["Table" t]
  1865. (table config t)
  1866. ["Math" s]
  1867. (if html-export?
  1868. (latex/html-export s true true)
  1869. (latex/latex (str (dc/squuid)) s true true))
  1870. ["Example" l]
  1871. [:pre.pre-wrap-white-space
  1872. (join-lines l)]
  1873. ["Src" options]
  1874. (let [{:keys [language options lines pos_meta]} options
  1875. attr (if language
  1876. {:data-lang language})
  1877. code (join-lines lines)]
  1878. (cond
  1879. html-export?
  1880. (highlight/html-export attr code)
  1881. :else
  1882. (let [language (if (contains? #{"edn" "clj" "cljc" "cljs" "clojure"} language) "text/x-clojure" language)]
  1883. (if (:slide? config)
  1884. (highlight/highlight (str (medley/random-uuid)) {:data-lang language} code)
  1885. [:div
  1886. (lazy-editor/editor config (str (dc/squuid)) attr code pos_meta)
  1887. (when (and (= language "text/x-clojure") (contains? (set options) ":results"))
  1888. (sci/eval-result code))]))))
  1889. ["Quote" l]
  1890. (->elem
  1891. :blockquote
  1892. (markup-elements-cp config l))
  1893. ["Raw_Html" content]
  1894. (when (not html-export?)
  1895. [:div.raw_html {:dangerouslySetInnerHTML
  1896. {:__html content}}])
  1897. ["Export" "html" options content]
  1898. (when (not html-export?)
  1899. [:div.export_html {:dangerouslySetInnerHTML
  1900. {:__html content}}])
  1901. ["Hiccup" content]
  1902. (ui/catch-error
  1903. [:div.warning {:title "Invalid hiccup"}
  1904. content]
  1905. (-> (safe-read-string content)
  1906. (security/remove-javascript-links-in-href)))
  1907. ["Export" "latex" options content]
  1908. (if html-export?
  1909. (latex/html-export content true false)
  1910. (latex/latex (str (dc/squuid)) content true false))
  1911. ["Custom" "query" _options result content]
  1912. (try
  1913. (let [query (reader/read-string content)]
  1914. (custom-query config query))
  1915. (catch js/Error e
  1916. (println "read-string error:")
  1917. (js/console.error e)
  1918. [:div.warning {:title "Invalid query"}
  1919. content]))
  1920. ["Custom" "note" options result content]
  1921. (admonition config "note" options result)
  1922. ["Custom" "tip" options result content]
  1923. (admonition config "tip" options result)
  1924. ["Custom" "important" options result content]
  1925. (admonition config "important" options result)
  1926. ["Custom" "caution" options result content]
  1927. (admonition config "caution" options result)
  1928. ["Custom" "warning" options result content]
  1929. (admonition config "warning" options result)
  1930. ["Custom" "pinned" options result content]
  1931. (admonition config "pinned" options result)
  1932. ["Custom" name options l content]
  1933. (->elem
  1934. :div
  1935. {:class name}
  1936. (markup-elements-cp config l))
  1937. ["Latex_Fragment" l]
  1938. [:p.latex-fragment
  1939. (inline config ["Latex_Fragment" l])]
  1940. ["Latex_Environment" name option content]
  1941. (let [content (latex-environment-content name option content)]
  1942. (if html-export?
  1943. (latex/html-export content true true)
  1944. (latex/latex (str (dc/squuid)) content true true)))
  1945. ["Displayed_Math" content]
  1946. (if html-export?
  1947. (latex/html-export content true true)
  1948. (latex/latex (str (dc/squuid)) content true true))
  1949. ["Footnote_Definition" name definition]
  1950. (let [id (util/url-encode name)]
  1951. [:div.footdef
  1952. [:div.footpara
  1953. (conj
  1954. (markup-element-cp config ["Paragraph" definition])
  1955. [:a.ml-1 {:id (str "fn." id)
  1956. :style {:font-size 14}
  1957. :class "footnum"
  1958. :on-click #(route-handler/jump-to-anchor! (str "fnr." id))}
  1959. [:sup.fn (str name "↩︎")]])]])
  1960. :else
  1961. "")
  1962. (catch js/Error e
  1963. (println "Convert to html failed, error: " e)
  1964. "")))
  1965. (defn markup-elements-cp
  1966. [config col]
  1967. (map #(markup-element-cp config %) col))
  1968. (defn build-slide-sections
  1969. ([blocks config]
  1970. (build-slide-sections blocks config nil))
  1971. ([blocks config build-block-fn]
  1972. (when (seq blocks)
  1973. (let [blocks (map #(dissoc % :block/children) blocks)
  1974. first-block-level (:block/level (first blocks))
  1975. sections (reduce
  1976. (fn [acc block]
  1977. (let [block (dissoc block :block/meta)
  1978. level (:block/level block)
  1979. config (assoc config :block/uuid (:block/uuid block))
  1980. block-cp (if build-block-fn
  1981. (build-block-fn config block)
  1982. (rum/with-key
  1983. (block-container config block)
  1984. (str "slide-" (:block/uuid block))))]
  1985. (if (= first-block-level level)
  1986. ;; new slide
  1987. (conj acc [[block block-cp]])
  1988. (update acc (dec (count acc))
  1989. (fn [sections]
  1990. (conj sections [block block-cp]))))))
  1991. []
  1992. blocks)]
  1993. sections))))
  1994. (defn blocks-container
  1995. [blocks config]
  1996. (let [blocks (map #(dissoc % :block/children) blocks)
  1997. sidebar? (:sidebar? config)
  1998. ref? (:ref? config)
  1999. custom-query? (:custom-query? config)
  2000. blocks->vec-tree #(if (or custom-query? ref?) % (tree/blocks->vec-tree % (:id config)))
  2001. ;; FIXME: blocks->vec-tree not working for the block container (zoom view)
  2002. blocks' (blocks->vec-tree blocks)
  2003. blocks (if (seq blocks') blocks' blocks)]
  2004. (when (seq blocks)
  2005. [:div.blocks-container.flex-1
  2006. {:style {:margin-left (cond
  2007. sidebar?
  2008. 0
  2009. :else
  2010. -10)}}
  2011. (let [first-block (first blocks)
  2012. first-id (:block/uuid (first blocks))]
  2013. (for [[idx item] (medley/indexed blocks)]
  2014. (let [item (->
  2015. (if (:block/dummy? item)
  2016. item
  2017. (dissoc item :block/meta))
  2018. (assoc :block/top? (zero? idx)))
  2019. config (assoc config :block/uuid (:block/uuid item))]
  2020. (rum/with-key
  2021. (block-container config item)
  2022. (:block/uuid item)))))])))
  2023. ;; headers to hiccup
  2024. (defn ->hiccup
  2025. [blocks config option]
  2026. [:div.content
  2027. (cond-> option
  2028. (:document/mode? config)
  2029. (assoc :class "doc-mode"))
  2030. (if (:group-by-page? config)
  2031. [:div.flex.flex-col
  2032. (let [blocks (sort-by (comp :block/journal-day first) > blocks)]
  2033. (for [[page blocks] blocks]
  2034. (let [alias? (:block/alias? page)
  2035. page (db/entity (:db/id page))]
  2036. [:div.my-2 (cond-> {:key (str "page-" (:db/id page))}
  2037. (:ref? config)
  2038. (assoc :class "color-level px-7 py-2 rounded"))
  2039. (ui/foldable
  2040. [:div
  2041. (page-cp config page)
  2042. (when alias? [:span.text-sm.font-medium.opacity-50 " Alias"])]
  2043. (blocks-container blocks config))])))]
  2044. (blocks-container blocks config))])