block.cljs 85 KB

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