1
0

hiccup.cljs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  1. (ns frontend.components.hiccup
  2. (:refer-clojure :exclude [range])
  3. (:require [frontend.config :as config]
  4. [cljs.core.match :refer-macros [match]]
  5. [clojure.string :as string]
  6. [frontend.util :as util]
  7. [rum.core :as rum]
  8. [frontend.state :as state]
  9. [frontend.db :as db]
  10. [dommy.core :as d]
  11. [datascript.core :as dc]
  12. [goog.dom :as gdom]
  13. [frontend.handler.expand :as expand]
  14. [frontend.components.svg :as svg]
  15. [frontend.components.draw :as draw]
  16. [frontend.components.block :as block-comp]
  17. [frontend.components.datetime :as datetime-comp]
  18. [frontend.ui :as ui]
  19. [frontend.components.widgets :as widgets]
  20. [frontend.handler.ui :as ui-handler]
  21. [frontend.handler.image :as image-handler]
  22. [frontend.handler.editor :as editor-handler]
  23. [frontend.handler.dnd :as dnd]
  24. [frontend.handler.repeated :as repeated]
  25. [goog.object :as gobj]
  26. [medley.core :as medley]
  27. [cljs.reader :as reader]
  28. [frontend.util :as util :refer-macros [profile]]
  29. [frontend.mixins :as mixins]
  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. (defn safe-read-string
  48. [s]
  49. (try
  50. (reader/read-string s)
  51. (catch js/Error e
  52. (println "read-string error:")
  53. (js/console.error e)
  54. [:div.warning {:title "read-string failed"}
  55. s])))
  56. ;; local state
  57. (defonce *block-children
  58. (atom {}))
  59. (defonce *dragging?
  60. (atom false))
  61. (defonce *dragging-block
  62. (atom nil))
  63. (defonce *move-to-top?
  64. (atom false))
  65. ;; TODO: Improve blocks grouped by pages
  66. (defonce max-blocks-per-page 500)
  67. (defonce virtual-list-scroll-step 450)
  68. (defonce virtual-list-previous 50)
  69. (defonce container-ids (atom {}))
  70. (defonce container-idx (atom 0))
  71. ;; TODO:
  72. ;; add `key`
  73. (defn- remove-nils
  74. [col]
  75. (remove nil? col))
  76. (defn anchor-link
  77. [s]
  78. (.anchorLink js/window.Mldoc s))
  79. (defn vec-cat
  80. [& args]
  81. (->> (apply concat args)
  82. remove-nils
  83. vec))
  84. (defn ->elem
  85. ([elem items]
  86. (->elem elem nil items))
  87. ([elem attrs items]
  88. (let [elem (keyword elem)]
  89. (if attrs
  90. (vec
  91. (cons elem
  92. (cons attrs
  93. (seq items))))
  94. (vec
  95. (cons elem
  96. (seq items)))))))
  97. (defn- join-lines
  98. [l]
  99. (string/trim (apply str l)))
  100. (defn- string-of-url
  101. [url]
  102. (match url
  103. (:or ["File" s] ["Search" s])
  104. s
  105. ["Complex" m]
  106. (let [{:keys [link protocol]} m]
  107. (if (= protocol "file")
  108. link
  109. (str protocol ":" link)))))
  110. (defn- get-file-absolute-path
  111. [config path]
  112. (let [path (string/replace path "file:" "")
  113. block-id (:block/uuid config)
  114. current-file (and block-id
  115. (:file/path (:page/file (:block/page (db/entity [:block/uuid block-id])))))]
  116. (when current-file
  117. (let [parts (string/split current-file #"/")
  118. parts-2 (string/split path #"/")
  119. current-dir (string/join "/" (drop-last 1 parts))]
  120. (cond
  121. (util/starts-with? path "/")
  122. path
  123. (and (not (util/starts-with? path ".."))
  124. (not (util/starts-with? path ".")))
  125. (str current-dir "/" path)
  126. :else
  127. (let [parts (loop [acc []
  128. parts (reverse parts)
  129. col (reverse parts-2)]
  130. (if (empty? col)
  131. acc
  132. (let [[part parts] (case (first col)
  133. ".."
  134. [(first parts) (rest parts)]
  135. "."
  136. ["" parts]
  137. [(first col) (rest parts)])]
  138. (recur (conj acc part)
  139. parts
  140. (rest col)))))
  141. parts (remove #(string/blank? %) parts)]
  142. (string/join "/" (reverse parts))))))))
  143. ;; TODO: safe encoding asciis
  144. ;; TODO: image link to another link
  145. (defn image-link [config url href label]
  146. (let [href (if (util/starts-with? href "http")
  147. href
  148. (get-file-absolute-path config href))]
  149. [:img.rounded-sm.shadow-xl.mb-2.mt-2
  150. {:class "object-contain object-center"
  151. :loading "lazy"
  152. :style {:max-height "24rem"}
  153. ;; :on-error (fn [])
  154. :src href
  155. :title (second (first label))}]))
  156. (defn repetition-to-string
  157. [[[kind] [duration] n]]
  158. (let [kind (case kind
  159. "Dotted" "."
  160. "Plus" "+"
  161. "DoublePlus" "++")]
  162. (str kind n (string/lower-case (str (first duration))))))
  163. (defn timestamp-to-string
  164. [{:keys [active date time repetition wday active]}]
  165. (let [{:keys [year month day]} date
  166. {:keys [hour min]} time
  167. [open close] (if active ["<" ">"] ["[" "]"])
  168. repetition (if repetition
  169. (str " " (repetition-to-string repetition))
  170. "")
  171. hour (if hour (util/zero-pad hour))
  172. min (if min (util/zero-pad min))
  173. time (cond
  174. (and hour min)
  175. (util/format " %s:%s" hour min)
  176. hour
  177. (util/format " %s" hour)
  178. :else
  179. "")]
  180. (util/format "%s%s-%s-%s %s%s%s%s"
  181. open
  182. (str year)
  183. (util/zero-pad month)
  184. (util/zero-pad day)
  185. wday
  186. time
  187. repetition
  188. close)))
  189. (defn timestamp [{:keys [active date time repetition wday] :as t} kind]
  190. (let [prefix (case kind
  191. "Scheduled"
  192. [:i {:class "fa fa-calendar"
  193. :style {:margin-right 3.5}}]
  194. "Deadline"
  195. [:i {:class "fa fa-calendar-times-o"
  196. :style {:margin-right 3.5}}]
  197. "Date"
  198. nil
  199. "Closed"
  200. nil
  201. "Started"
  202. [:i {:class "fa fa-clock-o"
  203. :style {:margin-right 3.5}}]
  204. "Start"
  205. "From: "
  206. "Stop"
  207. "To: "
  208. nil)]
  209. (let [class (if (= kind "Closed")
  210. "line-through")]
  211. [:span.timestamp (cond-> {:active (str active)}
  212. class
  213. (assoc :class class))
  214. prefix
  215. (timestamp-to-string t)])))
  216. (defn range [{:keys [start stop]} stopped?]
  217. [:div {:class "timestamp-range"
  218. :stopped stopped?}
  219. (timestamp start "Start")
  220. (timestamp stop "Stop")])
  221. (declare map-inline)
  222. (declare block-cp)
  223. (declare page-reference)
  224. (defn page-cp
  225. [{:keys [html-export? label children] :as config} page]
  226. (when-let [page-name (:page/name page)]
  227. (let [original-page-name (get page :page/original-name page-name)
  228. original-page-name (if (date/valid-journal-title? original-page-name)
  229. (string/capitalize original-page-name)
  230. original-page-name)
  231. page (string/lower-case page-name)
  232. href (if html-export?
  233. (util/encode-str page)
  234. (rfe/href :page {:name (util/encode-str page)}))]
  235. [:a.page-ref
  236. {:href href
  237. :on-click (fn [e]
  238. (util/stop e)
  239. (when (gobj/get e "shiftKey")
  240. (when-let [page-entity (db/entity [:page/name page])]
  241. (state/sidebar-add-block!
  242. (state/get-current-repo)
  243. (:db/id page-entity)
  244. :page
  245. {:page page-entity}))))}
  246. (if (seq children)
  247. (for [child children]
  248. (if (= (first child) "Label")
  249. [:span (last child)]
  250. (let [{:keys [content children]} (last child)
  251. page-name (subs content 2 (- (count content) 2))]
  252. (page-reference html-export? page-name (assoc config :children children) nil))))
  253. (if (and label
  254. (string? label)
  255. (not (string/blank? label))) ; alias
  256. label
  257. original-page-name))])))
  258. (defn page-reference
  259. [html-export? s config label]
  260. [:span.page-reference
  261. (when (and (not html-export?)
  262. (not (= (:id config) "contents"))
  263. (not (= (:id config) "Contents")))
  264. [:span.text-gray-500 "[["])
  265. (if (string/ends-with? s ".excalidraw")
  266. [:a.page-ref
  267. {:href (rfe/href :draw nil {:file (string/replace s (str config/default-draw-directory "/") "")})
  268. :on-click (fn [e] (util/stop e))}
  269. [:span
  270. (svg/excalidraw-logo)
  271. (string/capitalize (draw/get-file-title s))]]
  272. (page-cp (assoc config
  273. :label (mldoc/plain->text label)) {:page/name s}))
  274. (when (and (not html-export?)
  275. (not (= (:id config) "contents"))
  276. (not (= (:id config) "Contents")))
  277. [:span.text-gray-500 "]]"])])
  278. (defn- latex-environment-content
  279. [name option content]
  280. (if (= (string/lower-case name) "equation")
  281. content
  282. (util/format "\\begin%s\n%s\\end{%s}"
  283. (str "{" name "}" option)
  284. content
  285. name)))
  286. (declare blocks-container)
  287. (rum/defc block-embed < rum/reactive db-mixins/query
  288. [config id]
  289. (let [blocks (db/get-block-and-children (state/get-current-repo) id)]
  290. [:div.embed-block.bg-base-2 {:style {:z-index 2}}
  291. [:code "Embed block:"]
  292. [:div.px-2
  293. (blocks-container blocks (assoc config :embed? true))]]))
  294. (rum/defc page-embed < rum/reactive db-mixins/query
  295. [config page-name]
  296. (let [page-name (string/lower-case page-name)
  297. page-original-name (:page/original-name (db/entity [:page/name page-name]))
  298. blocks (db/get-page-blocks (state/get-current-repo) page-name)]
  299. [:div.embed-page.py-2.my-2.px-3.bg-base-2
  300. [:p
  301. [:code.mr-2 "Embed page:"]
  302. (page-cp config {:page/name page-name})]
  303. (blocks-container blocks (assoc config :embed? true))]))
  304. (defn- get-label-text
  305. [label]
  306. (and (= 1 (count label))
  307. (let [label (first label)]
  308. (string? (last label))
  309. (last label))))
  310. (defn- get-page
  311. [label]
  312. (when-let [label-text (get-label-text label)]
  313. (db/entity [:page/name (string/lower-case label-text)])))
  314. (defn- macro->text
  315. [name arguments]
  316. (if (and (seq arguments)
  317. (not= arguments ["null"]))
  318. (util/format "{{{%s %s}}}" name (string/join ", " arguments))
  319. (util/format "{{{%s}}}" name)))
  320. (defn inline
  321. [{:keys [html-export?] :as config} item]
  322. (match item
  323. ["Plain" s]
  324. s
  325. ["Spaces" s]
  326. s
  327. ["Superscript" l]
  328. (->elem :sup (map-inline config l))
  329. ["Subscript" l]
  330. (->elem :sub (map-inline config l))
  331. ["Tag" s]
  332. (if (and s (util/tag-valid? s))
  333. [:a.tag.mr-1 {:href (rfe/href :page {:name s})
  334. :on-click (fn [e]
  335. (util/stop e)
  336. (let [repo (state/get-current-repo)
  337. page (db/pull repo '[*] [:page/name (string/lower-case (util/url-decode s))])]
  338. (when (gobj/get e "shiftKey")
  339. (state/sidebar-add-block!
  340. repo
  341. (:db/id page)
  342. :page
  343. {:page page}))))}
  344. (str "#" s)]
  345. [:span.warning.mr-1 {:title "Invalid tag, tags only accept alphanumeric characters, \"-\", \"_\", \"@\" and \"%\"."}
  346. (str "#" s)])
  347. ["Emphasis" [[kind] data]]
  348. (let [elem (case kind
  349. "Bold" :b
  350. "Italic" :i
  351. "Underline" :ins
  352. "Strike_through" :del
  353. "Highlight" :mark)]
  354. (->elem elem (map-inline config data)))
  355. ["Entity" e]
  356. [:span {:dangerouslySetInnerHTML
  357. {:__html (:html e)}}]
  358. ["Latex_Fragment" ["Displayed" s]]
  359. (if html-export?
  360. (latex/html-export s false true)
  361. (latex/latex (str (dc/squuid)) s false true))
  362. ["Latex_Fragment" ["Inline" s]]
  363. (if html-export?
  364. (latex/html-export s false true)
  365. (latex/latex (str (dc/squuid)) s false false))
  366. ["Target" s]
  367. [:a {:id s} s]
  368. ["Radio_Target" s]
  369. [:a {:id s} s]
  370. ["Email" address]
  371. (let [{:keys [local_part domain]} address
  372. address (str local_part "@" domain)]
  373. [:a {:href (str "mainto:" address)}
  374. address])
  375. ["Block_reference" id]
  376. ;; FIXME: alert when self block reference
  377. (when-not (string/blank? id)
  378. (let [block (and (util/uuid-string? id)
  379. (db/pull-block (uuid id)))]
  380. (if block
  381. [:span
  382. [:span.text-gray-500 "(("]
  383. [:a {:href (rfe/href :page {:name id})
  384. :on-click (fn [e]
  385. (util/stop e)
  386. (when (gobj/get e "shiftKey")
  387. (state/sidebar-add-block!
  388. (state/get-current-repo)
  389. (:db/id block)
  390. :block-ref
  391. {:block block})))}
  392. (->elem
  393. :span.block-ref
  394. (map-inline config (:block/title block)))]
  395. [:span.text-gray-500 "))"]]
  396. [:span.warning.mr-1 {:title "Block ref invalid"}
  397. (util/format "((%s))" id)])))
  398. ["Nested_link" link]
  399. (let [{:keys [content children]} link]
  400. [:span.page-reference
  401. (when (and (not html-export?)
  402. (not (= (:id config) "contents")))
  403. [:span.text-gray-500 "[["])
  404. (let [page-name (subs content 2 (- (count content) 2))]
  405. (page-cp (assoc config :children children) {:page/name page-name}))
  406. (when (and (not html-export?)
  407. (not (= (:id config) "contents")))
  408. [:span.text-gray-500 "]]"])])
  409. ["Link" link]
  410. (let [{:keys [url label title]} link
  411. img-formats (set (map name (config/img-formats)))]
  412. (match url
  413. ["Search" s]
  414. (cond
  415. ;; image
  416. (some (fn [fmt] (re-find (re-pattern (str "(?i)\\." fmt)) s)) img-formats)
  417. (image-link config url s label)
  418. (= \# (first s))
  419. (->elem :a {:href (str "#" (anchor-link (subs s 1)))} (map-inline config label))
  420. ;; FIXME: same headline, see more https://orgmode.org/manual/Internal-Links.html
  421. (and (= \* (first s))
  422. (not= \* (last s)))
  423. (->elem :a {:href (str "#" (anchor-link (subs s 1)))} (map-inline config label))
  424. (re-find #"^https://" s)
  425. (->elem :a {:href s}
  426. (map-inline config label))
  427. :else
  428. (page-reference html-export? s config label))
  429. :else
  430. (let [href (string-of-url url)
  431. protocol (or
  432. (and (= "Complex" (first url))
  433. (:protocol (second url)))
  434. (and (= "File" (first url))
  435. "file"))]
  436. (cond
  437. (= protocol "file")
  438. (if (some (fn [fmt] (re-find (re-pattern (str "(?i)\\." fmt)) href)) img-formats)
  439. (image-link config url href label)
  440. (let [label-text (get-label-text label)
  441. page (if (string/blank? label-text)
  442. {:page/name (db/get-file-page (string/replace href "file:" ""))}
  443. (get-page label))]
  444. (if (and page
  445. (when-let [ext (util/get-file-ext href)]
  446. (config/mldoc-support? ext)))
  447. [:span.page-reference
  448. [:span.text-gray-500 "[["]
  449. (page-cp config page)
  450. [:span.text-gray-500 "]]"]]
  451. (->elem
  452. :a
  453. (cond->
  454. {:href href}
  455. title
  456. (assoc :title title))
  457. (map-inline config label)))))
  458. ;; image
  459. (some (fn [fmt] (re-find (re-pattern (str "(?i)\\." fmt)) href)) img-formats)
  460. (image-link config url href label)
  461. :else
  462. (->elem
  463. :a
  464. (cond->
  465. {:href href
  466. :target "_blank"}
  467. title
  468. (assoc :title title))
  469. (map-inline config label))))))
  470. ["Verbatim" s]
  471. [:code s]
  472. ["Code" s]
  473. [:code s]
  474. ["Inline_Source_Block" x]
  475. [:code (:code x)]
  476. ["Export_Snippet" "html" s]
  477. (when (not html-export?)
  478. [:span {:dangerouslySetInnerHTML
  479. {:__html s}}])
  480. ;; String to hiccup
  481. ["Inline_Hiccup" s]
  482. (ui/catch-error
  483. [:div.warning {:title "Invalid hiccup"} s]
  484. (-> (safe-read-string s)
  485. (security/remove-javascript-links-in-href)))
  486. ["Break_Line"]
  487. [:br]
  488. ["Hard_Break_Line"]
  489. [:br]
  490. ["Timestamp" ["Scheduled" t]]
  491. (timestamp t "Scheduled")
  492. ["Timestamp" ["Deadline" t]]
  493. (timestamp t "Deadline")
  494. ["Timestamp" ["Date" t]]
  495. (timestamp t "Date")
  496. ["Timestamp" ["Closed" t]]
  497. (timestamp t "Closed")
  498. ["Timestamp" ["Range" t]]
  499. (range t false)
  500. ["Timestamp" ["Clock" ["Stopped" t]]]
  501. (range t true)
  502. ["Timestamp" ["Clock" ["Started" t]]]
  503. (timestamp t "Started")
  504. ["Cookie" ["Percent" n]]
  505. [:span {:class "cookie-percent"}
  506. (util/format "[d%%]" n)]
  507. ["Cookie" ["Absolute" current total]]
  508. [:span {:class "cookie-absolute"}
  509. (util/format "[%d/%d]" current total)]
  510. ["Footnote_Reference" options]
  511. (let [{:keys [id name]} options
  512. encode-name (util/url-encode name)]
  513. [:sup.fn
  514. [:a {:id (str "fnr." encode-name)
  515. :class "footref"
  516. :href (str "#fn." encode-name)}
  517. name]])
  518. ["Macro" options]
  519. (let [{:keys [name arguments]} options
  520. arguments (if (and
  521. (>= (count arguments) 2)
  522. (and (string/starts-with? (first arguments) "[[")
  523. (string/ends-with? (last arguments) "]]"))) ; page reference
  524. (let [title (string/join ", " arguments)]
  525. [title])
  526. arguments)]
  527. (cond
  528. (= name "embed")
  529. (let [a (first arguments)]
  530. (cond
  531. (and (string/starts-with? a "[[")
  532. (string/ends-with? a "]]"))
  533. (let [page-name (-> (string/replace a "[[" "")
  534. (string/replace "]]" "")
  535. string/trim)]
  536. (when-not (string/blank? page-name)
  537. (page-embed config page-name)))
  538. (and (string/starts-with? a "((")
  539. (string/ends-with? a "))"))
  540. (when-let [s (-> (string/replace a "((" "")
  541. (string/replace "))" "")
  542. string/trim)]
  543. (when-let [id (and s
  544. (let [s (string/trim s)]
  545. (and (util/uuid-string? s)
  546. (uuid s))))]
  547. (block-embed config id)))
  548. :else ;TODO: maybe collections?
  549. nil))
  550. :else
  551. (if-let [block-uuid (:block/uuid config)]
  552. (let [macro-content (or
  553. (-> (db/entity [:block/uuid block-uuid])
  554. (:block/page)
  555. (:db/id)
  556. (db/entity)
  557. :page/properties
  558. :macros
  559. (get name))
  560. (get-in (state/get-config) [:macros name])
  561. (get-in (state/get-config) [:macros (keyword name)]))]
  562. [:span
  563. (if (and (seq arguments) macro-content)
  564. (block/macro-subs macro-content arguments)
  565. (or
  566. macro-content
  567. [:span.warning {:title (str "Unsupported macro name: " name)}
  568. (macro->text name arguments)]))])
  569. [:span
  570. (macro->text name arguments)])))
  571. :else
  572. ""))
  573. (declare blocks-cp)
  574. (rum/defc block-child
  575. [block]
  576. block)
  577. (defonce *control-show? (atom {}))
  578. (rum/defcs block-control < rum/reactive
  579. {:will-mount (fn [state]
  580. (let [block (nth (:rum/args state) 1)
  581. collapsed? (:block/collapsed? block)]
  582. (state/set-collapsed-state! (:block/uuid block)
  583. collapsed?))
  584. state)}
  585. [state config block uuid block-id level start-level body children dummy?]
  586. (let [has-child? (and
  587. (not (:pre-block? block))
  588. (or (seq children)
  589. (seq body)))
  590. collapsed? (state/sub [:ui/collapsed-blocks uuid])
  591. collapsed? (and has-child? collapsed?)
  592. control-show (util/react (rum/cursor *control-show? block-id))
  593. dark? (= "dark" (state/sub :ui/theme))
  594. heading? (= (get (:block/properties block) "heading") "true")]
  595. [:div.mr-2.flex.flex-row.items-center
  596. {:style {:height 24
  597. :margin-top (if (and heading? (<= level 6))
  598. (case level
  599. 1
  600. 32
  601. 2
  602. 22
  603. 18)
  604. 0)
  605. :float "left"}}
  606. [:a.block-control.opacity-50.hover:opacity-100
  607. {:id (str "control-" uuid)
  608. :style {:width 14
  609. :height 16
  610. :margin-right 2}
  611. :on-click (fn [e]
  612. (util/stop e)
  613. (if collapsed?
  614. (expand/expand! block)
  615. (expand/collapse! block))
  616. (state/set-collapsed-state! uuid (not collapsed?)))}
  617. (cond
  618. (and control-show collapsed?)
  619. (svg/caret-right)
  620. (and control-show has-child?)
  621. (svg/caret-down)
  622. :else
  623. [:span ""])]
  624. [:a (if (not dummy?)
  625. {:href (rfe/href :page {:name uuid})
  626. :on-click (fn [e]
  627. (util/stop e)
  628. (when (gobj/get e "shiftKey")
  629. (state/sidebar-add-block!
  630. (state/get-current-repo)
  631. (:db/id block)
  632. :block
  633. block)))})
  634. [:span.bullet-container.cursor
  635. {:id (str "dot-" uuid)
  636. :draggable true
  637. :on-drag-start (fn [event]
  638. (editor-handler/highlight-block! uuid)
  639. (.setData (gobj/get event "dataTransfer")
  640. "block-uuid"
  641. uuid)
  642. (.setData (gobj/get event "dataTransfer")
  643. "block-dom-id"
  644. block-id)
  645. (state/clear-selection!)
  646. (reset! *dragging? true)
  647. (reset! *dragging-block block))
  648. :blockid (str uuid)
  649. :class (str (when collapsed? "bullet-closed")
  650. " "
  651. (when (and (:document/mode? config)
  652. (not collapsed?))
  653. "hide-inner-bullet"))}
  654. [:span.bullet {:blockid (str uuid)
  655. :class (if heading? "bullet-heading" "")}]]]]))
  656. (defn- build-id
  657. [config ref? sidebar? embed?]
  658. (let [k (pr-str config)
  659. n (or
  660. (get @container-ids k)
  661. (let [n' (swap! container-idx inc)]
  662. (swap! container-ids assoc k n')
  663. n'))]
  664. (str n "-")))
  665. (rum/defc dnd-separator
  666. [block margin-left bottom top? nested?]
  667. (let [id (str (:block/uuid block)
  668. (cond nested?
  669. "-nested"
  670. top?
  671. "-top"
  672. :else
  673. nil))]
  674. [:div.dnd-separator
  675. {:id id
  676. :style (merge
  677. {:position "absolute"
  678. :left margin-left
  679. :width "100%"
  680. :z-index 3}
  681. (if top?
  682. {:top 0}
  683. {:bottom 0}))}]))
  684. (declare block-container)
  685. (defn block-checkbox
  686. [block class]
  687. (let [marker (:block/marker block)
  688. [class checked?] (cond
  689. (nil? marker)
  690. nil
  691. (contains? #{"NOW" "LATER" "DOING" "IN-PROGRESS" "TODO" "WAIT" "WAITING"} marker)
  692. [class false]
  693. (= "DONE" marker)
  694. [(str class " checked") true])]
  695. (when class
  696. (ui/checkbox {:class class
  697. :style {:margin-top -1
  698. :margin-right 6}
  699. :checked checked?
  700. :on-change (fn [_e]
  701. ;; FIXME: Log timestamp
  702. (if checked?
  703. (editor-handler/uncheck block)
  704. (editor-handler/check block)))}))))
  705. (defn list-checkbox
  706. [checked?]
  707. (ui/checkbox {:style {:margin-right 6
  708. :margin-top -1}
  709. :checked checked?}))
  710. (defn marker-switch
  711. [{:block/keys [pre-block? marker] :as block}]
  712. (when (contains? #{"NOW" "LATER" "TODO" "DOING"} marker)
  713. (let [set-marker-fn (fn [marker]
  714. (fn [e]
  715. (util/stop e)
  716. (editor-handler/set-marker block marker)))]
  717. (case marker
  718. "NOW"
  719. [:a.marker-switch
  720. {:title "Change from NOW to LATER"
  721. :on-click (set-marker-fn "LATER")}
  722. [:span "N"]]
  723. "LATER"
  724. [:a.marker-switch
  725. {:title "Change from LATER to NOW"
  726. :on-click (set-marker-fn "NOW")}
  727. "L"]
  728. "TODO"
  729. [:a.marker-switch
  730. {:title "Change from TODO to DOING"
  731. :on-click (set-marker-fn "DOING")}
  732. "T"]
  733. "DOING"
  734. [:a.marker-switch
  735. {:title "Change from DOING to TODO"
  736. :on-click (set-marker-fn "TODO")}
  737. "D"]
  738. nil))))
  739. (defn marker-cp
  740. [{:block/keys [pre-block? marker] :as block}]
  741. (when-not pre-block?
  742. (if (contains? #{"IN-PROGRESS" "WAIT" "WAITING"} marker)
  743. [:span {:class (str "task-status " (string/lower-case marker))
  744. :style {:margin-right 3.5}}
  745. (string/upper-case marker)])))
  746. (defn priority-cp
  747. [{:block/keys [pre-block? priority] :as block}]
  748. (when (and (not pre-block?) priority)
  749. (ui/tooltip
  750. [:ul
  751. (for [p (remove #(= priority %) ["A" "B" "C"])]
  752. [:a.mr-2.text-base.tooltip-priority {:priority p
  753. :on-click (fn [] (editor-handler/set-priority block p))}])]
  754. [:a.opacity-50.hover:opacity-100
  755. {:class "priority"
  756. :href (rfe/href :page {:name priority})
  757. :style {:margin-right 3.5}}
  758. (util/format "[#%s]" (str priority))])))
  759. (defn block-tags-cp
  760. [{:block/keys [pre-block? tags] :as block}]
  761. (when (and (not pre-block?)
  762. (seq tags))
  763. (->elem
  764. :span
  765. {:class "block-tags"}
  766. (mapv (fn [{:keys [db/id tag/name]}]
  767. (if (util/tag-valid? name)
  768. [:a.tag.mx-1 {:key (str "tag-" id)
  769. :href (rfe/href :page {:name name})}
  770. (str "#" name)]
  771. [:span.warning.mx-1 {:title "Invalid tag, tags only accept alphanumeric characters, \"-\", \"_\", \"@\" and \"%\"."}
  772. (str "#" name)]))
  773. tags))))
  774. (defn build-block-part
  775. [{:keys [slide?] :as config} {:block/keys [uuid title tags marker level priority anchor meta format content pre-block? dummy? block-refs-count page properties]
  776. :as t}]
  777. (let [config (assoc config :block t)
  778. slide? (boolean (:slide? config))
  779. html-export? (:html-export? config)
  780. checkbox (when (and (not pre-block?)
  781. (not html-export?))
  782. (block-checkbox t (str "mr-1 cursor")))
  783. marker-switch (when (and (not pre-block?)
  784. (not html-export?))
  785. (marker-switch t))
  786. marker-cp (marker-cp t)
  787. priority (priority-cp t)
  788. tags (block-tags-cp t)
  789. contents? (= (:id config) "contents")
  790. heading? (= (get properties "heading") "true")
  791. bg-color (get properties "background_color")]
  792. (when level
  793. (let [element (if (and (<= level 6) heading?)
  794. (keyword (str "h" level))
  795. :div)]
  796. (->elem
  797. element
  798. (merge
  799. {:id anchor}
  800. (when (and marker
  801. (not (string/blank? marker))
  802. (not= "nil" marker))
  803. {:class (string/lower-case marker)})
  804. (when bg-color
  805. {:style {:background-color bg-color
  806. :padding-left 6
  807. :padding-right 6
  808. :color "#FFFFFF"}}))
  809. (remove-nils
  810. (concat
  811. [(when-not slide? checkbox)
  812. (when-not slide? marker-switch)
  813. marker-cp
  814. priority]
  815. (cond
  816. dummy?
  817. [[:span.opacity-50 "Click here to start writing"]]
  818. ;; empty item
  819. (and contents? (or
  820. (empty? title)
  821. (= title [["Plain" "[[]]"]])))
  822. [[:span.opacity-50 "Click here to add a page, e.g. [[favorite-page]]"]]
  823. :else
  824. (map-inline config title))
  825. [tags])))))))
  826. (defn dnd-same-block?
  827. [uuid]
  828. (= (:block/uuid @*dragging-block) uuid))
  829. (defn show-dnd-separator
  830. [element-id]
  831. (when-let [element (gdom/getElement element-id)]
  832. (when (d/has-class? element "dnd-separator")
  833. (d/remove-class! element "dnd-separator")
  834. (d/add-class! element "dnd-separator-cur"))))
  835. (defn hide-dnd-separator
  836. [element-id]
  837. (when-let [element (gdom/getElement element-id)]
  838. (when (d/has-class? element "dnd-separator-cur")
  839. (d/remove-class! element "dnd-separator-cur")
  840. (d/add-class! element "dnd-separator"))))
  841. (defn- get-data-transfer-attr
  842. [event attr]
  843. (.getData (gobj/get event "dataTransfer") attr))
  844. (defn- pre-block-cp
  845. [config content format]
  846. (let [ast (mldoc/->edn content (mldoc/default-config format))
  847. ast (map first ast)]
  848. [:div.pre-block.bg-base-2.p-2
  849. (blocks-cp (assoc config :block/format format) ast)]))
  850. (defn property-value
  851. [format v]
  852. (let [inline-list (mldoc/inline->edn v (mldoc/default-config format))]
  853. [:div.inline (map-inline {} inline-list)]))
  854. (rum/defc properties-cp
  855. [block]
  856. (let [properties (apply dissoc (:block/properties block) text/hidden-properties)]
  857. (when (seq properties)
  858. [:div.text-sm.opacity-80.my-1.bg-base-4.p-2
  859. (for [[k v] properties]
  860. [:div.my-1
  861. [:b k]
  862. [:span.mr-1 ":"]
  863. (property-value (:block/format block) v)])])))
  864. (rum/defcs timestamp-cp < rum/reactive
  865. (rum/local false ::show?)
  866. (rum/local {} ::pos)
  867. {:will-unmount (fn [state]
  868. (when-let [show? (::show? state)]
  869. (reset! show? false))
  870. state)}
  871. [state block typ ast]
  872. (let [show? (get state ::show?)]
  873. [:div.flex.flex-col
  874. [:div.text-sm.mt-1.flex.flex-row
  875. [:div.opacity-50.font-medium {:style {:width 95}}
  876. (str typ ": ")]
  877. [:a.opacity-80.hover:opacity-100
  878. {:on-click (fn []
  879. (if @show?
  880. (do
  881. (reset! show? false)
  882. (reset! commands/*current-command nil)
  883. (state/set-editor-show-date-picker false)
  884. (state/set-timestamp-block! nil))
  885. (do
  886. (reset! show? true)
  887. (reset! commands/*current-command typ)
  888. (state/set-editor-show-date-picker true)
  889. (state/set-timestamp-block! {:block block
  890. :typ typ
  891. :show? show?}))))}
  892. (repeated/timestamp->text ast)]]
  893. (when (true? @show?)
  894. (let [ts (repeated/timestamp->map ast)]
  895. [:div.my-4
  896. (datetime-comp/date-picker nil nil ts)]))]))
  897. (rum/defc block-content < rum/reactive
  898. [config {:block/keys [uuid title level body meta content marker dummy? page format repo children pre-block? properties collapsed? idx block-refs-count scheduled scheduled-ast deadline deadline-ast repeated?] :as block} edit-input-id block-id slide?]
  899. (let [dragging? (rum/react *dragging?)
  900. attrs {:blockid (str uuid)
  901. ;; FIXME: Click to copy a selection instead of click first and then copy
  902. ;; It seems that `util/caret-range` can't get the correct range
  903. :on-click (fn [e]
  904. (let [target (gobj/get e "target")]
  905. (when-not (or (util/link? target)
  906. (util/input? target)
  907. (util/details-or-summary? target)
  908. (and (util/sup? target)
  909. (d/has-class? target "fn")))
  910. (editor-handler/clear-selection! nil)
  911. (editor-handler/unhighlight-block!)
  912. (let [cursor-range (util/caret-range (gdom/getElement block-id))
  913. properties-hidden? (text/properties-hidden? properties)
  914. content (text/remove-level-spaces content format)
  915. content (if properties-hidden? (text/remove-properties! content) content)]
  916. (state/set-editing!
  917. edit-input-id
  918. content
  919. block
  920. cursor-range))
  921. (util/stop e))))
  922. :on-drag-over (fn [event]
  923. (util/stop event)
  924. (when-not (dnd-same-block? uuid)
  925. (show-dnd-separator (str uuid "-nested"))))
  926. :on-drag-leave (fn [event]
  927. (hide-dnd-separator (str uuid))
  928. (hide-dnd-separator (str uuid "-nested"))
  929. (hide-dnd-separator (str uuid "-top")))
  930. :on-drop (fn [event]
  931. (util/stop event)
  932. (when-not (dnd-same-block? uuid)
  933. (let [from-dom-id (get-data-transfer-attr event "block-dom-id")]
  934. (dnd/move-block @*dragging-block
  935. block
  936. from-dom-id
  937. false
  938. true)))
  939. (reset! *dragging? false)
  940. (reset! *dragging-block nil)
  941. (editor-handler/unhighlight-block!))}]
  942. [:div.flex.overflow-x-auto.overflow-y-hidden.relative
  943. [:div.flex-1.flex-col.relative.block-content
  944. (cond-> {:id (str "block-content-" uuid)
  945. :style {:cursor "text"
  946. :min-height 24}}
  947. (not slide?)
  948. (merge attrs))
  949. (if pre-block?
  950. (pre-block-cp config (string/trim content) format)
  951. (build-block-part config block))
  952. (when (and dragging? (not slide?))
  953. (dnd-separator block 0 -4 false true))
  954. (when (and deadline deadline-ast)
  955. (timestamp-cp block "DEADLINE" deadline-ast))
  956. (when (and scheduled scheduled-ast)
  957. (timestamp-cp block "SCHEDULED" scheduled-ast))
  958. (when (and (seq properties)
  959. (let [hidden? (text/properties-hidden? properties)]
  960. (not hidden?)))
  961. (properties-cp block))
  962. (when (and (not pre-block?) (seq body))
  963. [:div.block-body {:style {:display (if collapsed? "none" "")}}
  964. ;; TODO: consistent id instead of the idx (since it could be changed later)
  965. (let [body (block/trim-break-lines! (:block/body block))]
  966. (for [[idx child] (medley/indexed body)]
  967. (when-let [block (block-cp config child)]
  968. (rum/with-key (block-child block)
  969. (str uuid "-" idx)))))])]
  970. (when (and block-refs-count (> block-refs-count 0))
  971. [:div
  972. [:a.block.py-0.px-2.rounded.bg-base-2.opacity-50.hover:opacity-100
  973. {:title "Open block references"
  974. :style {:margin-top -1}
  975. :on-click (fn []
  976. (state/sidebar-add-block!
  977. (state/get-current-repo)
  978. (:db/id block)
  979. :block-ref
  980. {:block block}))}
  981. block-refs-count]])
  982. (when (= marker "DONE")
  983. (let [start-time (or
  984. (get properties "now")
  985. (get properties "doing")
  986. (get properties "in-progress")
  987. (get properties "later")
  988. (get properties "todo"))
  989. finish-time (get properties "done")]
  990. (when (and start-time finish-time (> finish-time start-time))
  991. [:div.text-sm.absolute.time-spent {:style {:top 0
  992. :right 0
  993. :padding-left 2
  994. :z-index 4}
  995. :title (str (date/int->local-time start-time) " ~ " (date/int->local-time finish-time))}
  996. [:span.opacity-70
  997. (utils/timeConversion (- finish-time start-time))]])))]))
  998. (rum/defc block-content-or-editor < rum/reactive
  999. [config {:block/keys [uuid title level body meta content dummy? page format repo children pre-block? collapsed? idx] :as block} edit-input-id block-id slide?]
  1000. (let [edit? (state/sub [:editor/editing? edit-input-id])
  1001. editor-box (get config :editor-box)]
  1002. (if (and edit? editor-box)
  1003. [:div.editor-wrapper {:id (str "editor-" edit-input-id)}
  1004. (editor-box {:block block
  1005. :block-id uuid
  1006. :block-parent-id block-id
  1007. :format format
  1008. :dummy? dummy?
  1009. :on-hide (fn [value event]
  1010. (when (= event :esc)
  1011. (editor-handler/highlight-block! uuid)))}
  1012. edit-input-id
  1013. config)]
  1014. (block-content config block edit-input-id block-id slide?))))
  1015. (rum/defc dnd-separator-wrapper < rum/reactive
  1016. [block slide? top?]
  1017. (let [dragging? (rum/react *dragging?)]
  1018. (cond
  1019. (and dragging? (not slide?))
  1020. (dnd-separator block 20 0 top? false)
  1021. :else
  1022. nil)))
  1023. (defn non-dragging?
  1024. [e]
  1025. (and (= (gobj/get e "buttons") 1)
  1026. (not (d/has-class? (gobj/get e "target") "bullet-container"))
  1027. (not (d/has-class? (gobj/get e "target") "bullet"))
  1028. (not @*dragging?)))
  1029. (rum/defc block-container < rum/static
  1030. {:did-mount (fn [state]
  1031. (let [block (nth (:rum/args state) 1)
  1032. collapsed? (:block/collapsed? block)]
  1033. (when collapsed?
  1034. (expand/collapse! block))
  1035. state))}
  1036. [config {:block/keys [uuid title level body meta content dummy? page format repo children collapsed? pre-block? idx properties] :as block}]
  1037. (let [ref? (boolean (:ref? config))
  1038. ref-child? (:ref-child? config)
  1039. sidebar? (boolean (:sidebar? config))
  1040. slide? (boolean (:slide? config))
  1041. doc-mode? (:document/mode? config)
  1042. embed? (:embed? config)
  1043. unique-dom-id (build-id (dissoc config :block/uuid) ref? sidebar? embed?)
  1044. edit-input-id (str "edit-block-" unique-dom-id uuid)
  1045. block-id (str "ls-block-" unique-dom-id uuid)
  1046. has-child? (boolean
  1047. (and
  1048. (not pre-block?)
  1049. (or (seq children)
  1050. (seq body))))
  1051. start-level (or (:start-level config) 1)
  1052. attrs {:on-drag-over (fn [event]
  1053. (util/stop event)
  1054. (when-not (dnd-same-block? uuid)
  1055. (if (zero? idx)
  1056. (let [element-top (gobj/get (utils/getOffsetRect (gdom/getElement block-id)) "top")
  1057. cursor-top (gobj/get event "clientY")]
  1058. (if (<= (js/Math.abs (- cursor-top element-top)) 16)
  1059. ;; top
  1060. (do
  1061. (hide-dnd-separator (str uuid))
  1062. (show-dnd-separator (str uuid "-top"))
  1063. (reset! *move-to-top? true))
  1064. (do
  1065. (hide-dnd-separator (str uuid "-top"))
  1066. (show-dnd-separator (str uuid)))))
  1067. (show-dnd-separator (str uuid)))))
  1068. :on-drag-leave (fn [event]
  1069. (hide-dnd-separator (str uuid))
  1070. (hide-dnd-separator (str uuid "-nested"))
  1071. (hide-dnd-separator (str uuid "-top"))
  1072. (reset! *move-to-top? false))
  1073. :on-drop (fn [event]
  1074. (when-not (dnd-same-block? uuid)
  1075. (let [from-dom-id (get-data-transfer-attr event "block-dom-id")]
  1076. (dnd/move-block @*dragging-block
  1077. block
  1078. from-dom-id
  1079. @*move-to-top?
  1080. false)))
  1081. (reset! *dragging? false)
  1082. (reset! *dragging-block nil)
  1083. (editor-handler/unhighlight-block!))
  1084. :on-mouse-move (fn [e]
  1085. (when (non-dragging? e)
  1086. (state/into-selection-mode!)))
  1087. :on-mouse-down (fn [e]
  1088. (when (and
  1089. (not (state/get-selection-start-block))
  1090. (= (gobj/get e "buttons") 1))
  1091. (when block-id (state/set-selection-start-block! block-id))))
  1092. :on-mouse-over (fn [e]
  1093. (util/stop e)
  1094. (when has-child?
  1095. (swap! *control-show? assoc block-id true))
  1096. (when-let [parent (gdom/getElement block-id)]
  1097. (let [node (.querySelector parent ".bullet-container")
  1098. closed? (d/has-class? node "bullet-closed")]
  1099. (if closed?
  1100. (state/collapse-block! uuid)
  1101. (state/expand-block! uuid))
  1102. (when doc-mode?
  1103. (d/remove-class! node "hide-inner-bullet"))))
  1104. (when (and
  1105. (state/in-selection-mode?)
  1106. (non-dragging? e))
  1107. (util/stop e)
  1108. (editor-handler/highlight-selection-area! block-id)))
  1109. :on-mouse-out (fn [e]
  1110. (util/stop e)
  1111. (when has-child?
  1112. (swap! *control-show?
  1113. assoc block-id false))
  1114. (when doc-mode?
  1115. (when-let [parent (gdom/getElement block-id)]
  1116. (when-let [node (.querySelector parent ".bullet-container")]
  1117. (d/add-class! node "hide-inner-bullet")))))}]
  1118. [:div.ls-block.flex.flex-col.pt-1
  1119. (cond->
  1120. {:id block-id
  1121. :style {:position "relative"}
  1122. :class (str uuid
  1123. (when dummy? " dummy")
  1124. (when (and collapsed? has-child?) " collapsed")
  1125. (when pre-block? " pre-block"))
  1126. :blockid (str uuid)
  1127. :repo repo
  1128. :level level
  1129. :haschild (str has-child?)}
  1130. (not slide?)
  1131. (merge attrs))
  1132. (when (and ref? (not ref-child?))
  1133. (when-let [comp (block-comp/block-parents repo uuid format false)]
  1134. [:div.my-2.opacity-50.ml-4 comp]))
  1135. (dnd-separator-wrapper block slide? (zero? idx))
  1136. [:div.flex-1.flex-row
  1137. (when (not slide?)
  1138. (block-control config block uuid block-id level start-level body children dummy?))
  1139. (block-content-or-editor config block edit-input-id block-id slide?)]
  1140. (when (seq children)
  1141. [:div.block-children {:style {:margin-left (if doc-mode? 12 22)
  1142. :display (if collapsed? "none" "")}}
  1143. (for [child children]
  1144. (when (map? child)
  1145. (let [child (dissoc child :block/meta)]
  1146. (rum/with-key (block-container (assoc config :block/uuid (:block/uuid child)) child)
  1147. (:block/uuid child)))))])
  1148. (when (and ref? (not ref-child?))
  1149. (let [children (-> (db/get-block-children-unsafe repo uuid)
  1150. db/sort-by-pos)]
  1151. (when (seq children)
  1152. [:div.ref-children.ml-12
  1153. (blocks-container children (assoc config
  1154. :ref-child? true
  1155. :ref? true))])))
  1156. (dnd-separator-wrapper block slide? false)]))
  1157. (defn divide-lists
  1158. [[f & l]]
  1159. (loop [l l
  1160. ordered? (:ordered f)
  1161. result [[f]]]
  1162. (if (seq l)
  1163. (let [cur (first l)
  1164. cur-ordered? (:ordered cur)]
  1165. (if (= ordered? cur-ordered?)
  1166. (recur
  1167. (rest l)
  1168. cur-ordered?
  1169. (update result (dec (count result)) conj cur))
  1170. (recur
  1171. (rest l)
  1172. cur-ordered?
  1173. (conj result [cur]))))
  1174. result)))
  1175. (defn list-element
  1176. [l]
  1177. (match l
  1178. [l1 & tl]
  1179. (let [{:keys [ordered name]} l1]
  1180. (cond
  1181. (seq name)
  1182. :dl
  1183. ordered
  1184. :ol
  1185. :else
  1186. :ul))
  1187. :else
  1188. :ul))
  1189. (defn list-item
  1190. [config {:keys [name content checkbox items number] :as l}]
  1191. (let [content (when-not (empty? content)
  1192. (match content
  1193. [["Paragraph" i] & rest]
  1194. (vec-cat
  1195. (map-inline config i)
  1196. (blocks-cp config rest))
  1197. :else
  1198. (blocks-cp config content)))
  1199. checked? (some? checkbox)
  1200. items (if (seq items)
  1201. (->elem
  1202. (list-element items)
  1203. (for [item items]
  1204. (list-item config item))))]
  1205. (cond
  1206. (seq name)
  1207. [:dl {:checked checked?}
  1208. [:dt (map-inline config name)]
  1209. (->elem :dd
  1210. (vec-cat content [items]))]
  1211. :else
  1212. (if (nil? checkbox)
  1213. (->elem
  1214. :li
  1215. {:checked checked?}
  1216. (vec-cat
  1217. [(->elem
  1218. :p
  1219. content)]
  1220. [items]))
  1221. (->elem
  1222. :li
  1223. {:checked checked?}
  1224. (vec-cat
  1225. [(->elem
  1226. :p
  1227. (list-checkbox checkbox)
  1228. content)]
  1229. [items]))))))
  1230. (defn table
  1231. [config {:keys [header groups col_groups]}]
  1232. (let [tr (fn [elm cols]
  1233. (->elem
  1234. :tr
  1235. (mapv (fn [col]
  1236. (->elem
  1237. elm
  1238. {:scope "col"
  1239. :class "org-left"}
  1240. (map-inline config col)))
  1241. cols)))
  1242. tb-col-groups (try
  1243. (mapv (fn [number]
  1244. (let [col-elem [:col {:class "org-left"}]]
  1245. (->elem
  1246. :colgroup
  1247. (repeat number col-elem))))
  1248. col_groups)
  1249. (catch js/Error e
  1250. []))
  1251. head (if header
  1252. [:thead (tr :th header)])
  1253. groups (mapv (fn [group]
  1254. (->elem
  1255. :tbody
  1256. (mapv #(tr :td %) group)))
  1257. groups)]
  1258. [:div.table-wrapper {:style {:max-width (min 700
  1259. (gobj/get js/window "innerWidth"))}}
  1260. (->elem
  1261. :table
  1262. {:class "table-auto"
  1263. :border 2
  1264. :cell-spacing 0
  1265. :cell-padding 6
  1266. :rules "groups"
  1267. :frame "hsides"}
  1268. (vec-cat
  1269. tb-col-groups
  1270. (cons head groups)))]))
  1271. (defn map-inline
  1272. [config col]
  1273. (map #(inline config %) col))
  1274. (declare ->hiccup)
  1275. (defn built-in-custom-query?
  1276. [title]
  1277. (contains? #{"🔨 NOW" "📅 NEXT"}
  1278. title))
  1279. (rum/defcs custom-query < rum/reactive
  1280. {:will-mount (fn [state]
  1281. (let [[config query] (:rum/args state)]
  1282. (let [query-atom (db/custom-query query)]
  1283. (assoc state :query-atom query-atom))))
  1284. :did-mount (fn [state]
  1285. (when-let [query (last (:rum/args state))]
  1286. (state/add-custom-query-component! query (:rum/react-component state)))
  1287. state)
  1288. :will-unmount (fn [state]
  1289. (when-let [query (last (:rum/args state))]
  1290. (state/remove-custom-query-component! query)
  1291. (db/remove-custom-query! (state/get-current-repo) query))
  1292. state)}
  1293. [state config {:keys [title query inputs view collapsed? children?] :as q}]
  1294. (let [query-atom (:query-atom state)]
  1295. (let [current-block-uuid (or (:block/uuid (:block config))
  1296. (:block/uuid config))
  1297. ;; exclude the current one, otherwise it'll loop forever
  1298. remove-blocks (if current-block-uuid [current-block-uuid] nil)
  1299. query-result (and query-atom (rum/react query-atom))
  1300. result (if query-result
  1301. (db/custom-query-result-transform query-result remove-blocks q))
  1302. view-f (sci/eval-string (pr-str view))
  1303. only-blocks? (:block/uuid (first result))
  1304. blocks-grouped-by-page? (and (seq result)
  1305. (coll? (first result))
  1306. (:page/name (ffirst result))
  1307. (:block/uuid (first (second (first result))))
  1308. true)
  1309. built-in? (built-in-custom-query? title)]
  1310. [:div.custom-query.mt-2 (get config :attr {})
  1311. (when-not (and built-in? (empty? result))
  1312. (ui/foldable
  1313. [:div.opacity-70
  1314. title]
  1315. (cond
  1316. (and (seq result) view-f)
  1317. (let [result (sci/call-fn view-f result)]
  1318. (util/hiccup-keywordize result))
  1319. (and (seq result)
  1320. (or only-blocks? blocks-grouped-by-page?))
  1321. (->hiccup result (cond-> (assoc config
  1322. :custom-query? true
  1323. :group-by-page? blocks-grouped-by-page?)
  1324. children?
  1325. (assoc :ref? true))
  1326. {:style {:margin-top "0.25rem"
  1327. :margin-left "0.25rem"}})
  1328. (seq result) ;TODO: table
  1329. [:pre
  1330. (for [record result]
  1331. (if (map? record)
  1332. (str (util/pp-str record) "\n")
  1333. record))]
  1334. :else
  1335. [:div.text-sm.mt-2.ml-2.font-medium.opacity-50 "Empty"])
  1336. collapsed?))])))
  1337. (defn admonition
  1338. [config type options result]
  1339. (when-let [icon (case (string/lower-case (name type))
  1340. "note" svg/note
  1341. "tip" svg/tip
  1342. "important" svg/important
  1343. "caution" svg/caution
  1344. "warning" svg/warning
  1345. nil)]
  1346. [:div.flex.flex-row.admonitionblock.align-items {:class type}
  1347. [:div.pr-4.admonition-icon.flex.flex-col.justify-center
  1348. {:title (string/upper-case type)} (icon)]
  1349. [:div.ml-4.text-lg
  1350. (blocks-cp config result)]]))
  1351. (defn block-cp
  1352. [{:keys [html-export?] :as config} item]
  1353. (try
  1354. (match item
  1355. ["Properties" m]
  1356. [:div.properties
  1357. (let [format (:block/format config)]
  1358. (for [[k v] m]
  1359. (when (and (not (and (= k :macros) (empty? v))) ; empty macros
  1360. (not (= k :title)))
  1361. [:div.property
  1362. [:span.font-medium.mr-1 (string/upper-case (str (name k) ": "))]
  1363. (if (coll? v)
  1364. (for [item v]
  1365. (if (= k :tags)
  1366. (if (string/includes? item "[[")
  1367. (property-value format item)
  1368. (let [tag (-> item
  1369. (string/replace "[" "")
  1370. (string/replace "]" "")
  1371. (string/replace "#" ""))]
  1372. [:a.tag.mr-1 {:href (rfe/href :page {:name tag})}
  1373. tag]))
  1374. (property-value format v)))
  1375. (property-value format v))])))]
  1376. ["Paragraph" l]
  1377. ;; TODO: speedup
  1378. (if (re-find #"\"Export_Snippet\" \"embed\"" (str l))
  1379. (->elem :div (map-inline config l))
  1380. (->elem :p (map-inline config l)))
  1381. ["Horizontal_Rule"]
  1382. (when-not (:slide? config)
  1383. [:hr])
  1384. ["Heading" h]
  1385. (block-container config h)
  1386. ["List" l]
  1387. (let [lists (divide-lists l)]
  1388. (if (= 1 (count lists))
  1389. (let [l (first lists)]
  1390. (->elem
  1391. (list-element l)
  1392. (map #(list-item config %) l)))
  1393. [:div.list-group
  1394. (for [l lists]
  1395. (->elem
  1396. (list-element l)
  1397. (map #(list-item config %) l)))]))
  1398. ["Table" t]
  1399. (table config t)
  1400. ["Math" s]
  1401. (if html-export?
  1402. (latex/html-export s true true)
  1403. (latex/latex (str (dc/squuid)) s true true))
  1404. ["Example" l]
  1405. [:pre.pre-wrap-white-space
  1406. (join-lines l)]
  1407. ["Src" options]
  1408. (let [{:keys [language options lines pos_meta]} options
  1409. attr (if language
  1410. {:data-lang language})
  1411. code (join-lines lines)]
  1412. (cond
  1413. html-export?
  1414. (highlight/html-export attr code)
  1415. :else
  1416. (let [language (if (contains? #{"edn" "clj" "cljc" "cljs" "clojure"} language) "text/x-clojure" language)]
  1417. [:div
  1418. (lazy-editor/editor config (str (dc/squuid)) attr code pos_meta)
  1419. (when (and (= language "clojure") (contains? (set options) ":results"))
  1420. (sci/eval-result code))])))
  1421. ["Quote" l]
  1422. (->elem
  1423. :blockquote
  1424. (blocks-cp config l))
  1425. ["Raw_Html" content]
  1426. (when (not html-export?)
  1427. [:div.raw_html {:dangerouslySetInnerHTML
  1428. {:__html content}}])
  1429. ["Export" "html" options content]
  1430. (when (not html-export?)
  1431. [:div.export_html {:dangerouslySetInnerHTML
  1432. {:__html content}}])
  1433. ["Hiccup" content]
  1434. (ui/catch-error
  1435. [:div.warning {:title "Invalid hiccup"}
  1436. content]
  1437. (-> (safe-read-string content)
  1438. (security/remove-javascript-links-in-href)))
  1439. ["Export" "latex" options content]
  1440. (if html-export?
  1441. (latex/html-export content true false)
  1442. (latex/latex (str (dc/squuid)) content true false))
  1443. ["Custom" "query" _options result content]
  1444. (try
  1445. (let [query (reader/read-string content)]
  1446. (custom-query config query))
  1447. (catch js/Error e
  1448. (println "read-string error:")
  1449. (js/console.error e)
  1450. [:div.warning {:title "Invalid query"}
  1451. content]))
  1452. ["Custom" "note" options result content]
  1453. (admonition config "note" options result)
  1454. ["Custom" "tip" options result content]
  1455. (admonition config "tip" options result)
  1456. ["Custom" "important" options result content]
  1457. (admonition config "important" options result)
  1458. ["Custom" "caution" options result content]
  1459. (admonition config "caution" options result)
  1460. ["Custom" "warning" options result content]
  1461. (admonition config "warning" options result)
  1462. ["Custom" name options l content]
  1463. (->elem
  1464. :div
  1465. {:class name}
  1466. (blocks-cp config l))
  1467. ["Latex_Fragment" l]
  1468. [:p.latex-fragment
  1469. (inline config ["Latex_Fragment" l])]
  1470. ["Latex_Environment" name option content]
  1471. (let [content (latex-environment-content name option content)]
  1472. (if html-export?
  1473. (latex/html-export content true true)
  1474. (latex/latex (str (dc/squuid)) content true true)))
  1475. ["Displayed_Math" content]
  1476. (if html-export?
  1477. (latex/html-export content true true)
  1478. (latex/latex (str (dc/squuid)) content true true))
  1479. ["Footnote_Definition" name definition]
  1480. (let [id (util/url-encode name)]
  1481. [:div.footdef
  1482. [:div.footpara
  1483. (conj
  1484. (block-cp config ["Paragraph" definition])
  1485. [:a.ml-1 {:id (str "fn." id)
  1486. :style {:font-size 14}
  1487. :class "footnum"
  1488. :href (str "#fnr." id)}
  1489. [:sup.fn (str name "↩︎")]])]])
  1490. :else
  1491. "")
  1492. (catch js/Error e
  1493. (println "Convert to html failed, error: " e)
  1494. "")))
  1495. (defn blocks-cp
  1496. [config col]
  1497. (map #(block-cp config %) col))
  1498. (rum/defcs build-blocks < rum/reactive
  1499. {:init (fn [state]
  1500. (let [blocks (first (:rum/args state))
  1501. segment-data (if (> (count blocks) max-blocks-per-page)
  1502. (take max-blocks-per-page blocks)
  1503. blocks)]
  1504. (assoc state
  1505. ::segment (atom segment-data)
  1506. ::idx (atom 0))))
  1507. :did-update (fn [state]
  1508. (let [blocks (first (:rum/args state))
  1509. segment (get state ::segment)
  1510. idx (get state ::idx)]
  1511. (when (and
  1512. (seq @segment)
  1513. (> (count blocks) max-blocks-per-page))
  1514. (reset! segment (->> blocks
  1515. (drop @idx)
  1516. (take max-blocks-per-page))))
  1517. state))}
  1518. [state blocks config]
  1519. (let [segment (get state ::segment)
  1520. idx (get state ::idx)
  1521. custom-query? (:custom-query? config)
  1522. ref? (:ref? config)]
  1523. (let [blocks-cp (fn [blocks segment?]
  1524. (let [first-block (first blocks)
  1525. blocks' (if (and (:block/pre-block? first-block)
  1526. (db/pre-block-with-only-title? (:block/repo first-block) (:block/uuid first-block)))
  1527. (rest blocks)
  1528. blocks)
  1529. first-id (:block/uuid (first blocks'))]
  1530. (for [item blocks']
  1531. (let [item (-> (if (:block/dummy? item)
  1532. item
  1533. (dissoc item :block/meta)))
  1534. item (if (= first-id (:block/uuid item))
  1535. (assoc item :block/idx 0)
  1536. item)
  1537. config (assoc config :block/uuid (:block/uuid item))]
  1538. (rum/with-key
  1539. (block-container config item)
  1540. (:block/uuid item))))))
  1541. blocks->vec-tree #(if (or custom-query? ref?) % (db/blocks->vec-tree %))]
  1542. (if (> (count blocks) max-blocks-per-page)
  1543. (ui/infinite-list
  1544. (blocks-cp (blocks->vec-tree (rum/react segment)) true)
  1545. {:on-load (fn []
  1546. (when (= (count @segment) max-blocks-per-page)
  1547. (if (zero? @idx)
  1548. (reset! idx (dec max-blocks-per-page))
  1549. (swap! idx + virtual-list-scroll-step))
  1550. (let [tail (take-last virtual-list-previous @segment)
  1551. new-segment (->> blocks
  1552. (drop (inc @idx))
  1553. (take virtual-list-scroll-step))]
  1554. (reset! segment
  1555. (->> (concat tail new-segment)
  1556. (remove nil?))))))
  1557. :on-top-reached (fn []
  1558. (when (> @idx 0)
  1559. (if (> @idx (dec max-blocks-per-page))
  1560. (swap! idx - max-blocks-per-page)
  1561. (reset! idx 0))
  1562. (if (zero? @idx)
  1563. (reset! segment
  1564. (take max-blocks-per-page blocks))
  1565. (let [tail (take virtual-list-previous @segment)
  1566. prev (->> blocks
  1567. (drop (inc @idx))
  1568. (take virtual-list-scroll-step))]
  1569. (reset! segment
  1570. (->> (concat prev tail)
  1571. (remove nil?)))
  1572. (util/scroll-to 100)))))})
  1573. (blocks-cp (blocks->vec-tree blocks) false)))))
  1574. (defn build-slide-sections
  1575. ([blocks config]
  1576. (build-slide-sections blocks config nil))
  1577. ([blocks config build-block-fn]
  1578. (when (seq blocks)
  1579. (let [blocks (map #(dissoc % :block/children) blocks)
  1580. first-block-level (:block/level (first blocks))
  1581. sections (reduce
  1582. (fn [acc block]
  1583. (let [block (dissoc block :block/meta)
  1584. level (:block/level block)
  1585. block-cp (if build-block-fn
  1586. (build-block-fn config block)
  1587. (rum/with-key
  1588. (block-container config block)
  1589. (str "slide-" (:block/uuid block))))]
  1590. (if (= first-block-level level)
  1591. ;; new slide
  1592. (conj acc [[block block-cp]])
  1593. (update acc (dec (count acc))
  1594. (fn [sections]
  1595. (conj sections [block block-cp]))))))
  1596. []
  1597. blocks)]
  1598. sections))))
  1599. (rum/defc add-button < rum/reactive
  1600. [config ref? custom-query? blocks]
  1601. (let [editing (state/sub [:editor/editing?])]
  1602. (when-not (or ref? custom-query?
  1603. (:block/dummy? (last blocks))
  1604. (second (first editing)))
  1605. (when-let [last-block (last blocks)]
  1606. [:a.add-button-link {:on-click (fn []
  1607. (editor-handler/insert-new-block-without-save-previous! config last-block))}
  1608. svg/plus-circle]))))
  1609. (rum/defc blocks-container < rum/static
  1610. [blocks config]
  1611. (let [blocks (map #(dissoc % :block/children) blocks)
  1612. sidebar? (:sidebar? config)
  1613. ref? (:ref? config)
  1614. custom-query? (:custom-query? config)]
  1615. (when (seq blocks)
  1616. [:div.blocks-container.flex-1
  1617. {:style {:margin-left (cond
  1618. sidebar?
  1619. 0
  1620. :else
  1621. -18)}}
  1622. (build-blocks blocks config)
  1623. ;; (add-button config ref? custom-query? blocks)
  1624. ])))
  1625. ;; headers to hiccup
  1626. (rum/defc ->hiccup < rum/reactive
  1627. [blocks config option]
  1628. (let [document-mode? (state/sub [:document/mode?])
  1629. config (assoc config
  1630. :document/mode? document-mode?)]
  1631. [:div.content
  1632. (cond-> option
  1633. document-mode?
  1634. (assoc :class "doc-mode"))
  1635. (if (:group-by-page? config)
  1636. [:div.flex.flex-col
  1637. (for [[page blocks] blocks]
  1638. (let [page (db/entity (:db/id page))]
  1639. [:div.my-2 (cond-> {:key (str "page-" (:db/id page))}
  1640. (:ref? config)
  1641. (assoc :class "bg-base-2 px-7 py-2 rounded"))
  1642. (ui/foldable
  1643. (page-cp config page)
  1644. (blocks-container blocks config))]))]
  1645. (blocks-container blocks config))]))
  1646. (comment
  1647. ;; timestamps
  1648. ;; [2020-02-10 Mon 13:22]
  1649. ;; repetition
  1650. (def r1 "<2005-10-01 Sat +1m>")
  1651. ;; TODO: mldoc add supports
  1652. (def r2 "<2005-10-01 Sat +1m -3d>")
  1653. (def l
  1654. "1. First item
  1655. hello world
  1656. 2. Second item
  1657. nice
  1658. 3. Third item")
  1659. (def t
  1660. "| Name | Phone | Age |
  1661. |-------+-------+-----|
  1662. | Peter | 1234 | 17 |
  1663. | Anna | 4321 | 25 |"))