block.cljs 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989
  1. (ns frontend.components.block
  2. (:refer-clojure :exclude [range])
  3. (:require ["/frontend/utils" :as utils]
  4. [cljs-bean.core :as bean]
  5. [cljs.core.match :refer [match]]
  6. [cljs.reader :as reader]
  7. [clojure.string :as string]
  8. [clojure.walk :as walk]
  9. [datascript.core :as d]
  10. [dommy.core :as dom]
  11. [frontend.commands :as commands]
  12. [frontend.components.datetime :as datetime-comp]
  13. [frontend.components.lazy-editor :as lazy-editor]
  14. [frontend.components.svg :as svg]
  15. [frontend.components.macro :as macro]
  16. [frontend.config :as config]
  17. [frontend.context.i18n :refer [t]]
  18. [frontend.date :as date]
  19. [frontend.db :as db]
  20. [frontend.db.utils :as db-utils]
  21. [frontend.db-mixins :as db-mixins]
  22. [frontend.db.model :as model]
  23. [frontend.db.query-dsl :as query-dsl]
  24. [frontend.extensions.highlight :as highlight]
  25. [frontend.extensions.latex :as latex]
  26. [frontend.extensions.sci :as sci]
  27. [frontend.extensions.pdf.assets :as pdf-assets]
  28. [frontend.extensions.zotero :as zotero]
  29. [frontend.extensions.lightbox :as lightbox]
  30. [frontend.extensions.video.youtube :as youtube]
  31. [frontend.format.block :as block]
  32. [frontend.format.mldoc :as mldoc]
  33. [frontend.components.plugins :as plugins]
  34. [frontend.handler.plugin :as plugin-handler]
  35. [frontend.handler.block :as block-handler]
  36. [frontend.handler.dnd :as dnd]
  37. [frontend.handler.editor :as editor-handler]
  38. [frontend.handler.repeated :as repeated]
  39. [frontend.handler.route :as route-handler]
  40. [frontend.handler.ui :as ui-handler]
  41. [frontend.handler.query :as query-handler]
  42. [frontend.handler.common :as common-handler]
  43. [frontend.modules.outliner.tree :as tree]
  44. [frontend.search :as search]
  45. [frontend.security :as security]
  46. [frontend.state :as state]
  47. [frontend.template :as template]
  48. [frontend.text :as text]
  49. [frontend.ui :as ui]
  50. [frontend.util :as util]
  51. [frontend.util.clock :as clock]
  52. [frontend.util.property :as property]
  53. [frontend.util.drawer :as drawer]
  54. [goog.dom :as gdom]
  55. [goog.object :as gobj]
  56. [lambdaisland.glogi :as log]
  57. [medley.core :as medley]
  58. [promesa.core :as p]
  59. [reitit.frontend.easy :as rfe]
  60. [rum.core :as rum]
  61. [shadow.loader :as loader]
  62. [frontend.components.query-table :as query-table]
  63. [frontend.mobile.util :as mobile-util]))
  64. (defn safe-read-string
  65. ([s]
  66. (safe-read-string s true))
  67. ([s warn?]
  68. (try
  69. (reader/read-string s)
  70. (catch :default e
  71. (log/error :read-string-error e :string s)
  72. (when warn?
  73. [:div.warning {:title "read-string failed"}
  74. s])))))
  75. ;; local state
  76. (defonce *dragging?
  77. (atom false))
  78. (defonce *dragging-block
  79. (atom nil))
  80. (defonce *drag-to-block
  81. (atom nil))
  82. (def *move-to (atom nil))
  83. ;; TODO: dynamic
  84. (defonce max-depth-of-links 5)
  85. (defonce *blocks-container-id (atom 0))
  86. ;; TODO:
  87. ;; add `key`
  88. (defn- remove-nils
  89. [col]
  90. (remove nil? col))
  91. (defn vec-cat
  92. [& args]
  93. (->> (apply concat args)
  94. remove-nils
  95. vec))
  96. (defn ->elem
  97. ([elem items]
  98. (->elem elem nil items))
  99. ([elem attrs items]
  100. (let [elem (keyword elem)]
  101. (if attrs
  102. (vec
  103. (cons elem
  104. (cons attrs
  105. (seq items))))
  106. (vec
  107. (cons elem
  108. (seq items)))))))
  109. (defn- join-lines
  110. [l]
  111. (string/trim (apply str l)))
  112. (defn- string-of-url
  113. [url]
  114. (match url
  115. ["File" s]
  116. (-> (string/replace s "file://" "")
  117. ;; "file:/Users/ll/Downloads/test.pdf" is a normal org file link
  118. (string/replace "file:" ""))
  119. ["Complex" m]
  120. (let [{:keys [link protocol]} m]
  121. (if (= protocol "file")
  122. link
  123. (str protocol "://" link)))))
  124. (defn- get-file-absolute-path
  125. [config path]
  126. (let [path (string/replace path "file:" "")
  127. block-id (:block/uuid config)
  128. current-file (and block-id
  129. (:file/path (:block/file (:block/page (db/entity [:block/uuid block-id])))))]
  130. (when current-file
  131. (let [parts (string/split current-file #"/")
  132. parts-2 (string/split path #"/")
  133. current-dir (string/join "/" (drop-last 1 parts))]
  134. (cond
  135. (if util/win32? (utils/win32 path) (util/starts-with? path "/"))
  136. path
  137. (and (not (util/starts-with? path ".."))
  138. (not (util/starts-with? path ".")))
  139. (str current-dir "/" path)
  140. :else
  141. (let [parts (loop [acc []
  142. parts (reverse parts)
  143. col (reverse parts-2)]
  144. (if (empty? col)
  145. acc
  146. (let [[part parts] (case (first col)
  147. ".."
  148. [(first parts) (rest parts)]
  149. "."
  150. ["" parts]
  151. [(first col) (rest parts)])]
  152. (recur (conj acc part)
  153. parts
  154. (rest col)))))
  155. parts (remove #(string/blank? %) parts)]
  156. (string/join "/" (reverse parts))))))))
  157. (defonce *resizing-image? (atom false))
  158. (rum/defcs resizable-image <
  159. (rum/local nil ::size)
  160. {:will-unmount (fn [state]
  161. (reset! *resizing-image? false)
  162. state)}
  163. [state config title src metadata full_text local?]
  164. (let [size (get state ::size)]
  165. (ui/resize-provider
  166. (ui/resize-consumer
  167. (cond->
  168. {:className "resize image-resize"
  169. :onSizeChanged (fn [value]
  170. (when (and (not @*resizing-image?)
  171. (some? @size)
  172. (not= value @size))
  173. (reset! *resizing-image? true))
  174. (reset! size value))
  175. :onMouseUp (fn []
  176. (when (and @size @*resizing-image?)
  177. (when-let [block-id (:block/uuid config)]
  178. (let [size (bean/->clj @size)]
  179. (editor-handler/resize-image! block-id metadata full_text size))))
  180. (when @*resizing-image?
  181. ;; TODO: need a better way to prevent the clicking to edit current block
  182. (js/setTimeout #(reset! *resizing-image? false) 200)))
  183. :onClick (fn [e]
  184. (when @*resizing-image? (util/stop e)))}
  185. (and (:width metadata) (not (util/mobile?)))
  186. (assoc :style {:width (:width metadata)}))
  187. [:div.asset-container
  188. [:img.rounded-sm.shadow-xl.relative
  189. (merge
  190. {:loading "lazy"
  191. :src src
  192. :title title}
  193. metadata)]
  194. [:span.ctl
  195. [:a.delete
  196. {:title "Delete this image"
  197. :on-click
  198. (fn [e]
  199. (when-let [block-id (:block/uuid config)]
  200. (let [confirm-fn (ui/make-confirm-modal
  201. {:title (t :asset/confirm-delete (.toLocaleLowerCase (t :text/image)))
  202. :sub-title (if local? :asset/physical-delete "")
  203. :sub-checkbox? local?
  204. :on-confirm (fn [_e {:keys [close-fn sub-selected]}]
  205. (close-fn)
  206. (editor-handler/delete-asset-of-block!
  207. {:block-id block-id
  208. :local? local?
  209. :delete-local? (first sub-selected)
  210. :repo (state/get-current-repo)
  211. :href src
  212. :title title
  213. :full-text full_text}))})]
  214. (state/set-modal! confirm-fn)
  215. (util/stop e))))}
  216. svg/trash-sm]
  217. [:a.delete.ml-1
  218. {:title "maximize image"
  219. :on-click (fn [^js e] (let [images (js/document.querySelectorAll ".asset-container img")
  220. images (to-array images)
  221. images (if-not (= (count images) 1)
  222. (let [^js _image (.closest (.-target e) ".asset-container")
  223. image (. _image querySelector "img")]
  224. (cons image (remove #(= image %) images)))
  225. images)
  226. images (for [^js it images] {:src (.-src it)
  227. :w (.-naturalWidth it)
  228. :h (.-naturalHeight it)})]
  229. (when (seq images)
  230. (lightbox/preview-images! images))))}
  231. (svg/maximize)]]]))))
  232. (rum/defcs asset-link < rum/reactive
  233. (rum/local nil ::src)
  234. [state config title href metadata full_text]
  235. (let [src (::src state)
  236. granted? (state/sub [:nfs/user-granted? (state/get-current-repo)])
  237. href (config/get-local-asset-absolute-path href)]
  238. (when (or granted? (util/electron?) (mobile-util/is-native-platform?))
  239. (p/then (editor-handler/make-asset-url href) #(reset! src %)))
  240. (when @src
  241. (resizable-image config title @src metadata full_text true))))
  242. (defn ar-url->http-url
  243. [href]
  244. (string/replace href #"^ar://" (str (state/get-arweave-gateway) "/")))
  245. ;; TODO: safe encoding asciis
  246. ;; TODO: image link to another link
  247. (defn image-link [config url href label metadata full_text]
  248. (let [metadata (if (string/blank? metadata)
  249. nil
  250. (safe-read-string metadata false))
  251. title (second (first label))]
  252. (ui/catch-error
  253. [:span.warning full_text]
  254. (if (and (config/local-asset? href)
  255. (config/local-db? (state/get-current-repo)))
  256. (asset-link config title href metadata full_text)
  257. (let [href (cond
  258. (util/starts-with? href "http")
  259. href
  260. (util/starts-with? href "ar")
  261. (ar-url->http-url href)
  262. config/publishing?
  263. (subs href 1)
  264. (= "Embed_data" (first url))
  265. href
  266. :else
  267. (get-file-absolute-path config href))]
  268. (resizable-image config title href metadata full_text false))))))
  269. (defn repetition-to-string
  270. [[[kind] [duration] n]]
  271. (let [kind (case kind
  272. "Dotted" "."
  273. "Plus" "+"
  274. "DoublePlus" "++")]
  275. (str kind n (string/lower-case (str (first duration))))))
  276. (defn timestamp-to-string
  277. [{:keys [_active date time repetition wday active]}]
  278. (let [{:keys [year month day]} date
  279. {:keys [hour min]} time
  280. [open close] (if active ["<" ">"] ["[" "]"])
  281. repetition (if repetition
  282. (str " " (repetition-to-string repetition))
  283. "")
  284. hour (when hour (util/zero-pad hour))
  285. min (when min (util/zero-pad min))
  286. time (cond
  287. (and hour min)
  288. (util/format " %s:%s" hour min)
  289. hour
  290. (util/format " %s" hour)
  291. :else
  292. "")]
  293. (util/format "%s%s-%s-%s %s%s%s%s"
  294. open
  295. (str year)
  296. (util/zero-pad month)
  297. (util/zero-pad day)
  298. wday
  299. time
  300. repetition
  301. close)))
  302. (defn timestamp [{:keys [active _date _time _repetition _wday] :as t} kind]
  303. (let [prefix (case kind
  304. "Scheduled"
  305. [:i {:class "fa fa-calendar"
  306. :style {:margin-right 3.5}}]
  307. "Deadline"
  308. [:i {:class "fa fa-calendar-times-o"
  309. :style {:margin-right 3.5}}]
  310. "Date"
  311. nil
  312. "Closed"
  313. nil
  314. "Started"
  315. [:i {:class "fa fa-clock-o"
  316. :style {:margin-right 3.5}}]
  317. "Start"
  318. "From: "
  319. "Stop"
  320. "To: "
  321. nil)
  322. class (when (= kind "Closed")
  323. "line-through")]
  324. [:span.timestamp (cond-> {:active (str active)}
  325. class
  326. (assoc :class class))
  327. prefix (timestamp-to-string t)]))
  328. (defn range [{:keys [start stop]} stopped?]
  329. [:div {:class "timestamp-range"
  330. :stopped stopped?}
  331. (timestamp start "Start")
  332. (timestamp stop "Stop")])
  333. (declare map-inline)
  334. (declare markup-element-cp)
  335. (declare markup-elements-cp)
  336. (declare page-reference)
  337. (rum/defc page-inner
  338. "The inner div of page reference component
  339. page-name-in-block is the overridable name of the page (legacy)
  340. All page-names are sanitized except page-name-in-block"
  341. [config page-name-in-block page-name redirect-page-name page-entity contents-page? children html-export? label]
  342. (let [tag? (:tag? config)]
  343. [:a
  344. {:class (if tag? "tag" "page-ref")
  345. :data-ref page-name
  346. :on-mouse-down
  347. (fn [e]
  348. (util/stop e)
  349. (let [create-first-block! (fn []
  350. (when-not (editor-handler/add-default-title-property-if-needed! redirect-page-name)
  351. (editor-handler/insert-first-page-block-if-not-exists! redirect-page-name)))]
  352. (if (gobj/get e "shiftKey")
  353. (do
  354. (js/setTimeout create-first-block! 310)
  355. (when-let [page-entity (db/entity [:block/name redirect-page-name])]
  356. (state/sidebar-add-block!
  357. (state/get-current-repo)
  358. (:db/id page-entity)
  359. :page
  360. {:page page-entity})))
  361. (do
  362. (create-first-block!)
  363. (route-handler/redirect-to-page! redirect-page-name))))
  364. (when (and contents-page?
  365. (util/mobile?)
  366. (state/get-left-sidebar-open?))
  367. (ui-handler/close-left-sidebar!)))}
  368. (if (and (coll? children) (seq children))
  369. (for [child children]
  370. (if (= (first child) "Label")
  371. (last child)
  372. (let [{:keys [content children]} (last child)
  373. page-name (subs content 2 (- (count content) 2))]
  374. (rum/with-key (page-reference html-export? page-name (assoc config :children children) nil) page-name))))
  375. (cond
  376. (and label
  377. (string? label)
  378. (not (string/blank? label))) ; alias
  379. label
  380. (coll? label)
  381. (->elem :span (map-inline config label))
  382. :else
  383. (let [original-name (util/get-page-original-name page-entity)
  384. s (if (not= (util/safe-page-name-sanity-lc original-name) page-name-in-block)
  385. page-name-in-block ;; page-name-in-block might be overrided (legacy)
  386. original-name)
  387. _ (when-not page-entity (js/console.warn "page-inner's page-entity is nil, given page-name: " page-name
  388. " page-name-in-block: " page-name-in-block))]
  389. (if tag? (str "#" s) s))))]))
  390. (rum/defc page-preview-trigger
  391. [{:keys [children sidebar? tippy-position tippy-distance fixed-position? open? manual?] :as config} page-name]
  392. (let [page-name (util/page-name-sanity-lc page-name)
  393. redirect-page-name (or (model/get-redirect-page-name page-name (:block/alias? config))
  394. page-name)
  395. page-original-name (model/get-page-original-name redirect-page-name)
  396. html-template (fn []
  397. (when redirect-page-name
  398. [:div.tippy-wrapper.overflow-y-auto.p-4
  399. {:style {:width 600
  400. :text-align "left"
  401. :font-weight 500
  402. :max-height 600
  403. :padding-bottom 64}}
  404. (if (and (string? page-original-name) (string/includes? page-original-name "/"))
  405. [:div.my-2
  406. (->>
  407. (for [page (string/split page-original-name #"/")]
  408. (when (and (string? page) page)
  409. (page-reference false page {} nil)))
  410. (interpose [:span.mx-2.opacity-30 "/"]))]
  411. [:h2.font-bold.text-lg (if (= page-name redirect-page-name)
  412. page-original-name
  413. [:span
  414. [:span.text-sm.mr-2 "Alias:"]
  415. page-original-name])])
  416. (let [page (db/entity [:block/name (util/page-name-sanity-lc redirect-page-name)])]
  417. (editor-handler/insert-first-page-block-if-not-exists! redirect-page-name)
  418. (when-let [f (state/get-page-blocks-cp)]
  419. (f (state/get-current-repo) page {:sidebar? sidebar? :preview? true})))]))]
  420. (if (or (not manual?) open?)
  421. (ui/tippy {:html html-template
  422. :interactive true
  423. :delay [1000, 100]
  424. :fixed-position? fixed-position?
  425. :position (or tippy-position "top")
  426. :distance (or tippy-distance 10)}
  427. children)
  428. children)))
  429. (rum/defc page-cp
  430. "Accepts {:block/name sanitized / unsanitized page-name}"
  431. [{:keys [html-export? redirect-page-name label children contents-page? preview?] :as config} page]
  432. (when-let [page-name-in-block (:block/name page)]
  433. (let [page-name-in-block (util/remove-boundary-slashes page-name-in-block)
  434. page-name (util/page-name-sanity-lc page-name-in-block)
  435. page-entity (db/entity [:block/name page-name])
  436. redirect-page-name (or (and (= :org (state/get-preferred-format))
  437. (:org-mode/insert-file-link? (state/get-config))
  438. redirect-page-name)
  439. (model/get-redirect-page-name page-name (:block/alias? config)))
  440. inner (page-inner config
  441. page-name-in-block
  442. page-name
  443. redirect-page-name page-entity contents-page? children html-export? label)]
  444. (if (and (not (util/mobile?)) (not preview?))
  445. (page-preview-trigger (assoc config :children inner) page-name)
  446. inner))))
  447. (rum/defc asset-reference
  448. [config title path]
  449. (let [repo-path (config/get-repo-dir (state/get-current-repo))
  450. full-path (if (util/absolute-path? path)
  451. path
  452. (.. util/node-path (join repo-path (config/get-local-asset-absolute-path path))))
  453. ext-name (util/get-file-ext full-path)
  454. title-or-path (cond
  455. (string? title)
  456. title
  457. (seq title)
  458. (->elem :span (map-inline config title))
  459. :else
  460. path)]
  461. [:div.asset-ref-wrap
  462. {:data-ext ext-name}
  463. (if (= "pdf" ext-name)
  464. [:a.asset-ref.is-pdf
  465. {:on-mouse-down (fn [e]
  466. (when-let [current (pdf-assets/inflate-asset full-path)]
  467. (util/stop e)
  468. (state/set-state! :pdf/current current)))}
  469. title-or-path]
  470. [:a.asset-ref {:target "_blank" :href full-path}
  471. title-or-path])
  472. (case ext-name
  473. ;; https://en.wikipedia.org/wiki/HTML5_video
  474. ("mp4" "ogg" "webm" "mov")
  475. [:video {:src full-path
  476. :controls true}]
  477. nil)]))
  478. (defonce excalidraw-loaded? (atom false))
  479. (rum/defc excalidraw < rum/reactive
  480. {:init (fn [state]
  481. (p/let [_ (loader/load :excalidraw)]
  482. (reset! excalidraw-loaded? true))
  483. state)}
  484. [file block-uuid]
  485. (let [loaded? (rum/react excalidraw-loaded?)
  486. draw-component (when loaded?
  487. (resolve 'frontend.extensions.excalidraw/draw))]
  488. (when draw-component
  489. (draw-component {:file file :block-uuid block-uuid}))))
  490. (rum/defc page-reference < rum/reactive
  491. [html-export? s config label]
  492. (let [show-brackets? (state/show-brackets?)
  493. nested-link? (:nested-link? config)
  494. contents-page? (= "contents" (string/lower-case (str (:id config))))
  495. block-uuid (:block/uuid config)]
  496. (if (string/ends-with? s ".excalidraw")
  497. [:div.draw {:on-click (fn [e]
  498. (.stopPropagation e))}
  499. (excalidraw s block-uuid)]
  500. [:span.page-reference
  501. {:data-ref s}
  502. (when (and (or show-brackets? nested-link?)
  503. (not html-export?)
  504. (not contents-page?))
  505. [:span.text-gray-500.bracket "[["])
  506. (let [s (string/trim s)]
  507. (page-cp (assoc config
  508. :label (mldoc/plain->text label)
  509. :contents-page? contents-page?)
  510. {:block/name s}))
  511. (when (and (or show-brackets? nested-link?)
  512. (not html-export?)
  513. (not contents-page?))
  514. [:span.text-gray-500.bracket "]]"])])))
  515. (defn- latex-environment-content
  516. [name option content]
  517. (if (= (string/lower-case name) "equation")
  518. content
  519. (util/format "\\begin%s\n%s\\end{%s}"
  520. (str "{" name "}" option)
  521. content
  522. name)))
  523. (declare blocks-container)
  524. (defn- edit-parent-block [e config]
  525. (when-not (state/editing?)
  526. (.stopPropagation e)
  527. (editor-handler/edit-block! config :max (:block/uuid config))))
  528. (rum/defc block-embed < rum/reactive db-mixins/query
  529. [config id]
  530. (let [blocks (db/sub-block-and-children (state/get-current-repo) id)]
  531. [:div.color-level.embed-block.bg-base-2
  532. {:style {:z-index 2}
  533. :on-double-click #(edit-parent-block % config)
  534. :on-mouse-down (fn [e] (.stopPropagation e))}
  535. [:div.px-3.pt-1.pb-2
  536. (blocks-container blocks (assoc config
  537. :id (str id)
  538. :embed-id id
  539. :embed? true
  540. :embed-parent (:block config)
  541. :ref? false))]]))
  542. (rum/defc page-embed < rum/reactive db-mixins/query
  543. [config page-name]
  544. (let [page-name (util/page-name-sanity-lc (string/trim page-name))
  545. current-page (state/get-current-page)]
  546. [:div.color-level.embed.embed-page.bg-base-2
  547. {:class (when (:sidebar? config) "in-sidebar")
  548. :on-double-click #(edit-parent-block % config)
  549. :on-mouse-down #(.stopPropagation %)}
  550. [:section.flex.items-center.p-1.embed-header
  551. [:div.mr-3 svg/page]
  552. (page-cp config {:block/name page-name})]
  553. (when (and
  554. (not= (util/page-name-sanity-lc (or current-page ""))
  555. page-name)
  556. (not= (util/page-name-sanity-lc (get config :id ""))
  557. page-name))
  558. (let [blocks (db/get-page-blocks (state/get-current-repo) page-name)]
  559. (blocks-container blocks (assoc config
  560. :id page-name
  561. :embed? true
  562. :page-embed? true
  563. :ref? false))))]))
  564. (defn- get-label-text
  565. [label]
  566. (and (= 1 (count label))
  567. (let [label (first label)]
  568. (string? (last label))
  569. (last label))))
  570. (defn- get-page
  571. [label]
  572. (when-let [label-text (get-label-text label)]
  573. (db/entity [:block/name (util/page-name-sanity-lc label-text)])))
  574. (defn- macro->text
  575. [name arguments]
  576. (if (and (seq arguments)
  577. (not= arguments ["null"]))
  578. (util/format "{{{%s %s}}}" name (string/join ", " arguments))
  579. (util/format "{{{%s}}}" name)))
  580. (declare block-content)
  581. (declare block-container)
  582. (declare block-parents)
  583. (rum/defc block-reference < rum/reactive
  584. db-mixins/query
  585. [config id label]
  586. (when (and
  587. (not (string/blank? id))
  588. (util/uuid-string? id))
  589. (let [block-id (uuid id)
  590. block (db/pull-block block-id)
  591. block-type (keyword (get-in block [:block/properties :ls-type]))
  592. hl-type (get-in block [:block/properties :hl-type])
  593. repo (state/get-current-repo)]
  594. (if (and block (:block/content block))
  595. (let [title [:span {:class "block-ref"}
  596. (block-content (assoc config :block-ref? true)
  597. block nil (:block/uuid block)
  598. (:slide? config))]
  599. inner (if label
  600. (->elem
  601. :span.block-ref
  602. (map-inline config label))
  603. title)]
  604. [:div.block-ref-wrap.inline
  605. {:data-type (name (or block-type :default))
  606. :data-hl-type hl-type
  607. :on-mouse-down
  608. (fn [^js/MouseEvent e]
  609. (if (util/right-click? e)
  610. (state/set-state! :block-ref/context {:block (:block config)
  611. :block-ref block-id})
  612. (when (and
  613. (or (gobj/get e "shiftKey")
  614. (not (.. e -target (closest ".blank"))))
  615. (not (util/right-click? e)))
  616. (util/stop e)
  617. (if (gobj/get e "shiftKey")
  618. (state/sidebar-add-block!
  619. (state/get-current-repo)
  620. (:db/id block)
  621. :block-ref
  622. {:block block})
  623. (match [block-type (util/electron?)]
  624. ;; pdf annotation
  625. [:annotation true] (pdf-assets/open-block-ref! block)
  626. ;; default open block page
  627. :else (route-handler/redirect-to-page! id))))))}
  628. (if (and (not (util/mobile?)) (not (:preview? config)) (nil? block-type))
  629. (ui/tippy {:html (fn []
  630. [:div.tippy-wrapper.overflow-y-auto.p-4
  631. {:style {:width 735
  632. :text-align "left"
  633. :max-height 600}}
  634. [(block-parents config repo block-id {:indent? true})
  635. (blocks-container
  636. (db/get-block-and-children repo block-id)
  637. (assoc config :id (str id) :preview? true))]])
  638. :interactive true
  639. :delay [1000, 100]} inner)
  640. inner)])
  641. [:span.warning.mr-1 {:title "Block ref invalid"}
  642. (util/format "((%s))" id)]))))
  643. (defn inline-text
  644. ([format v]
  645. (inline-text {} format v))
  646. ([config format v]
  647. (when (string? v)
  648. (let [inline-list (mldoc/inline->edn v (mldoc/default-config format))]
  649. [:div.inline.mr-1 (map-inline config inline-list)]))))
  650. (defn- render-macro
  651. [config name arguments macro-content format]
  652. (if macro-content
  653. (let [ast (->> (mldoc/->edn macro-content (mldoc/default-config format))
  654. (map first))
  655. paragraph? (and (= 1 (count ast))
  656. (= "Paragraph" (ffirst ast)))]
  657. (if (and (not paragraph?)
  658. (mldoc/block-with-title? (ffirst ast)))
  659. [:div
  660. (markup-elements-cp (assoc config :block/format format) ast)]
  661. (inline-text format macro-content)))
  662. [:span.warning {:title (str "Unsupported macro name: " name)}
  663. (macro->text name arguments)]))
  664. (rum/defc nested-link < rum/reactive
  665. [config html-export? link]
  666. (let [show-brackets? (state/show-brackets?)
  667. {:keys [content children]} link]
  668. [:span.page-reference.nested
  669. (when (and show-brackets?
  670. (not html-export?)
  671. (not (= (:id config) "contents")))
  672. [:span.text-gray-500 "[["])
  673. (let [page-name (subs content 2 (- (count content) 2))]
  674. (page-cp (assoc config
  675. :children children
  676. :nested-link? true) {:block/name page-name}))
  677. (when (and show-brackets?
  678. (not html-export?)
  679. (not (= (:id config) "contents")))
  680. [:span.text-gray-500 "]]"])]))
  681. (rum/defcs tutorial-video <
  682. (rum/local true)
  683. [state]
  684. (let [lite-mode? (:rum/local state)]
  685. [:div.tutorial-video-container.relative
  686. {:style {:height 367 :width 653}}
  687. (if @lite-mode?
  688. [:div
  689. [:img.w-full.h-full.absolute
  690. {:src "https://img.youtube.com/vi/Afmqowr0qEQ/maxresdefault.jpg"}]
  691. [:button
  692. {:class "absolute bg-red-300 w-16 h-16 -m-8 top-1/2 left-1/2 rounded-full"
  693. :on-click (fn [_] (swap! lite-mode? not))}
  694. (svg/play)]]
  695. [:iframe.w-full.h-full
  696. {:allow-full-screen "allowfullscreen"
  697. :allow
  698. "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope"
  699. :frame-border "0"
  700. :src "https://www.youtube.com/embed/Afmqowr0qEQ?autoplay=1"}])]))
  701. (declare custom-query)
  702. (defn- show-link?
  703. [config metadata s full-text]
  704. (let [img-formats (set (map name (config/img-formats)))
  705. metadata-show (:show (safe-read-string metadata))
  706. format (get-in config [:block :block/format])]
  707. (or
  708. (and
  709. (= :org format)
  710. (or
  711. (and
  712. (nil? metadata-show)
  713. (or
  714. (config/local-asset? s)
  715. (text/image-link? img-formats s)))
  716. (true? (boolean metadata-show))))
  717. ;; markdown
  718. (string/starts-with? (string/triml full-text) "!")
  719. ;; image http link
  720. (and (or (string/starts-with? full-text "http://")
  721. (string/starts-with? full-text "https://"))
  722. (text/image-link? img-formats s)))))
  723. (defn- relative-assets-path->absolute-path
  724. [path]
  725. (if (util/absolute-path? path)
  726. path
  727. (.. util/node-path
  728. (join (config/get-repo-dir (state/get-current-repo))
  729. (config/get-local-asset-absolute-path path)))))
  730. (rum/defc namespace-hierarchy-aux
  731. [config namespace children]
  732. [:ul
  733. (for [child children]
  734. [:li {:key (str "namespace-" namespace "-" (:db/id child))}
  735. (let [shorten-name (some-> (or (:block/original-name child) (:block/name child))
  736. (string/split "/")
  737. last)]
  738. (page-cp {:label shorten-name} child))
  739. (when (seq (:namespace/children child))
  740. (namespace-hierarchy-aux config (:block/name child)
  741. (:namespace/children child)))])])
  742. (rum/defc namespace-hierarchy
  743. [config namespace children]
  744. [:div.namespace
  745. [:div.font-medium.flex.flex-row.items-center.pb-2
  746. [:span.text-sm.mr-1 "Namespace "]
  747. (page-cp config {:block/name namespace})]
  748. (namespace-hierarchy-aux config namespace children)])
  749. (defn ^:large-vars/cleanup-todo inline
  750. [{:keys [html-export?] :as config} item]
  751. (match item
  752. ["Plain" s]
  753. s
  754. ["Spaces" s]
  755. s
  756. ["Superscript" l]
  757. (->elem :sup (map-inline config l))
  758. ["Subscript" l]
  759. (->elem :sub (map-inline config l))
  760. ["Tag" _s]
  761. (when-let [s (block/get-tag item)]
  762. (let [s (text/page-ref-un-brackets! s)]
  763. (page-cp (assoc config :tag? true) {:block/name s})))
  764. ["Emphasis" [[kind] data]]
  765. (let [elem (case kind
  766. "Bold" :b
  767. "Italic" :i
  768. "Underline" :ins
  769. "Strike_through" :del
  770. "Highlight" :mark)]
  771. (->elem elem (map-inline config data)))
  772. ["Entity" e]
  773. [:span {:dangerouslySetInnerHTML
  774. {:__html (:html e)}}]
  775. ["Latex_Fragment" ["Displayed" s]]
  776. (if html-export?
  777. (latex/html-export s false true)
  778. (latex/latex (str (d/squuid)) s false true))
  779. ["Latex_Fragment" ["Inline" s]]
  780. (if html-export?
  781. (latex/html-export s false true)
  782. (latex/latex (str (d/squuid)) s false false))
  783. ["Target" s]
  784. [:a {:id s} s]
  785. ["Radio_Target" s]
  786. [:a {:id s} s]
  787. ["Email" address]
  788. (let [{:keys [local_part domain]} address
  789. address (str local_part "@" domain)]
  790. [:a {:href (str "mainto:" address)}
  791. address])
  792. ["Nested_link" link]
  793. (nested-link config html-export? link)
  794. ["Link" link]
  795. (let [{:keys [url label title metadata full_text]} link]
  796. (match url
  797. ["Block_ref" id]
  798. (let [label* (if (seq (mldoc/plain->text label)) label nil)
  799. {:keys [link-depth]} config
  800. link-depth (or link-depth 0)]
  801. (if (> link-depth max-depth-of-links)
  802. [:p.warning.text-sm "Block ref nesting is too deep"]
  803. (block-reference (assoc config
  804. :reference? true
  805. :link-depth (inc link-depth)
  806. :block/uuid id)
  807. id label*)))
  808. ["Page_ref" page]
  809. (let [format (get-in config [:block :block/format])]
  810. (if (and (= format :org)
  811. (show-link? config nil page page)
  812. (not (contains? #{"pdf" "mp4" "ogg" "webm"} (util/get-file-ext page))))
  813. (image-link config url page nil metadata full_text)
  814. (let [label* (if (seq (mldoc/plain->text label)) label nil)]
  815. (if (and (string? page) (string/blank? page))
  816. [:span (util/format "[[%s]]" page)]
  817. (page-reference (:html-export? config) page config label*)))))
  818. ["Embed_data" src]
  819. (image-link config url src nil metadata full_text)
  820. ["Search" s]
  821. (cond
  822. (string/blank? s)
  823. [:span.warning {:title "Invalid link"} full_text]
  824. (= \# (first s))
  825. (->elem :a {:on-click #(route-handler/jump-to-anchor! (mldoc/anchorLink (subs s 1)))} (subs s 1))
  826. ;; FIXME: same headline, see more https://orgmode.org/manual/Internal-Links.html
  827. (and (= \* (first s))
  828. (not= \* (last s)))
  829. (->elem :a {:on-click #(route-handler/jump-to-anchor! (mldoc/anchorLink (subs s 1)))} (subs s 1))
  830. (text/block-ref? s)
  831. (let [id (text/get-block-ref s)]
  832. (block-reference config id label))
  833. (not (string/includes? s "."))
  834. (page-reference (:html-export? config) s config label)
  835. (util/url? s)
  836. (->elem :a {:href s
  837. :data-href s
  838. :target "_blank"}
  839. (map-inline config label))
  840. ;; image
  841. (and (show-link? config metadata s full_text)
  842. (not (contains? #{"pdf" "mp4" "ogg" "webm" "mov"} (util/get-file-ext s))))
  843. (image-link config url s label metadata full_text)
  844. (and (util/electron?)
  845. (show-link? config metadata s full_text))
  846. (asset-reference config label s)
  847. (util/electron?)
  848. (let [path (cond
  849. (string/starts-with? s "file://")
  850. (string/replace s "file://" "")
  851. (string/starts-with? s "/")
  852. s
  853. :else
  854. (relative-assets-path->absolute-path s))]
  855. (->elem
  856. :a
  857. (cond->
  858. {:href (str "file://" path)
  859. :data-href path
  860. :target "_blank"}
  861. title
  862. (assoc :title title))
  863. (map-inline config label)))
  864. :else
  865. (page-reference (:html-export? config) s config label))
  866. :else
  867. (let [href (string-of-url url)
  868. [protocol path] (or (and (= "Complex" (first url)) url)
  869. (and (= "File" (first url)) ["file" (second url)]))]
  870. (cond
  871. (and (= (get-in config [:block :block/format]) :org)
  872. (= "Complex" protocol)
  873. (= (string/lower-case (:protocol path)) "id")
  874. (string? (:link path))
  875. (util/uuid-string? (:link path))) ; org mode id
  876. (let [id (uuid (:link path))
  877. block (db/entity [:block/uuid id])]
  878. (if (:block/pre-block? block)
  879. (let [page (:block/page block)]
  880. (page-reference html-export? (:block/name page) config label))
  881. (block-reference config (:link path) label)))
  882. (= protocol "file")
  883. (cond
  884. (and (show-link? config metadata href full_text)
  885. (not (contains? #{"pdf" "mp4" "ogg" "webm" "mov"} (util/get-file-ext href))))
  886. (image-link config url href label metadata full_text)
  887. (and (util/electron?)
  888. (show-link? config metadata href full_text))
  889. (asset-reference config label href)
  890. :else
  891. (let [redirect-page-name (when (string? path) (text/get-page-name path))
  892. config (assoc config :redirect-page-name redirect-page-name)
  893. label-text (get-label-text label)
  894. page (if (string/blank? label-text)
  895. {:block/name (db/get-file-page (string/replace href "file:" "") false)}
  896. (get-page label))]
  897. (if (and page
  898. (when-let [ext (util/get-file-ext href)]
  899. (config/mldoc-support? ext)))
  900. [:span.page-reference
  901. [:span.text-gray-500 "[["]
  902. (page-cp config page)
  903. [:span.text-gray-500 "]]"]]
  904. (let [href*
  905. (if (util/electron?)
  906. (relative-assets-path->absolute-path href)
  907. href)]
  908. (->elem
  909. :a
  910. (cond->
  911. {:href (str "file://" href*)
  912. :data-href href*
  913. :target "_blank"}
  914. title
  915. (assoc :title title))
  916. (map-inline config label))))))
  917. ;; image
  918. (and (show-link? config metadata href full_text)
  919. (not (contains? #{"pdf"} (util/get-file-ext href))))
  920. (image-link config url href label metadata full_text)
  921. ;; pdf link
  922. (and
  923. (util/electron?)
  924. (= (util/get-file-ext href) "pdf")
  925. (show-link? config metadata href full_text))
  926. [:a.asset-ref.is-pdf
  927. {:href "javascript:void(0);"
  928. :on-mouse-down (fn [_event]
  929. (when-let [current (pdf-assets/inflate-asset href)]
  930. (state/set-state! :pdf/current current)))}
  931. (get-label-text label)]
  932. (= protocol "ar")
  933. (->elem
  934. :a.external-link
  935. (cond->
  936. {:href (ar-url->http-url href)
  937. :target "_blank"}
  938. title
  939. (assoc :title title))
  940. (map-inline config label))
  941. :else
  942. (->elem
  943. :a.external-link
  944. (cond->
  945. {:href href
  946. :target "_blank"}
  947. title
  948. (assoc :title title))
  949. (map-inline config label))))))
  950. ["Verbatim" s]
  951. [:code s]
  952. ["Code" s]
  953. [:code s]
  954. ["Inline_Source_Block" x]
  955. [:code (:code x)]
  956. ["Export_Snippet" "html" s]
  957. (when (not html-export?)
  958. [:span {:dangerouslySetInnerHTML
  959. {:__html s}}])
  960. ;; String to hiccup
  961. ["Inline_Hiccup" s]
  962. (ui/catch-error
  963. [:div.warning {:title "Invalid hiccup"} s]
  964. (-> (safe-read-string s)
  965. (security/remove-javascript-links-in-href)))
  966. ["Inline_Html" s]
  967. (when (not html-export?)
  968. ;; TODO: how to remove span and only export the content of `s`?
  969. [:span {:dangerouslySetInnerHTML
  970. {:__html s}}])
  971. ["Break_Line"]
  972. [:br]
  973. ["Hard_Break_Line"]
  974. [:br]
  975. ["Timestamp" ["Scheduled" _timestamp]]
  976. nil
  977. ["Timestamp" ["Deadline" _timestamp]]
  978. nil
  979. ["Timestamp" ["Date" t]]
  980. (timestamp t "Date")
  981. ["Timestamp" ["Closed" t]]
  982. (timestamp t "Closed")
  983. ["Timestamp" ["Range" t]]
  984. (range t false)
  985. ["Timestamp" ["Clock" ["Stopped" t]]]
  986. (range t true)
  987. ["Timestamp" ["Clock" ["Started" t]]]
  988. (timestamp t "Started")
  989. ["Cookie" ["Percent" n]]
  990. [:span {:class "cookie-percent"}
  991. (util/format "[d%%]" n)]
  992. ["Cookie" ["Absolute" current total]]
  993. [:span {:class "cookie-absolute"}
  994. (util/format "[%d/%d]" current total)]
  995. ["Footnote_Reference" options]
  996. (let [{:keys [name]} options
  997. encode-name (util/url-encode name)]
  998. [:sup.fn
  999. [:a {:id (str "fnr." encode-name)
  1000. :class "footref"
  1001. :on-click #(route-handler/jump-to-anchor! (str "fn." encode-name))}
  1002. name]])
  1003. ["Macro" options]
  1004. (let [{:keys [name arguments]} options
  1005. arguments (if (and
  1006. (>= (count arguments) 2)
  1007. (and (string/starts-with? (first arguments) "[[")
  1008. (string/ends-with? (last arguments) "]]"))) ; page reference
  1009. (let [title (string/join ", " arguments)]
  1010. [title])
  1011. arguments)]
  1012. (cond
  1013. (= name "query")
  1014. [:div.dsl-query
  1015. (let [query (->> (string/join ", " arguments)
  1016. (string/trim))]
  1017. (when-not (string/blank? query)
  1018. (custom-query (assoc config :dsl-query? true)
  1019. {:title (ui/tippy {:html commands/query-doc
  1020. :interactive true}
  1021. [:span.font-medium.px-2.py-1.query-title.text-sm.rounded-md.shadow-xs
  1022. (str "Query: " query)])
  1023. :query query})))]
  1024. (= name "function")
  1025. (or
  1026. (when (:query-result config)
  1027. (when-let [query-result (rum/react (:query-result config))]
  1028. (let [fn-string (-> (util/format "(fn [result] %s)" (first arguments))
  1029. (common-handler/safe-read-string "failed to parse function")
  1030. (query-handler/normalize-query-function query-result)
  1031. (str))
  1032. f (sci/eval-string fn-string)]
  1033. (when (fn? f)
  1034. (try (f query-result)
  1035. (catch js/Error e
  1036. (js/console.error e)))))))
  1037. [:span.warning
  1038. (util/format "{{function %s}}" (first arguments))])
  1039. (= name "namespace")
  1040. (let [namespace (first arguments)]
  1041. (when-not (string/blank? namespace)
  1042. (let [namespace (string/lower-case (text/page-ref-un-brackets! namespace))
  1043. children (model/get-namespace-hierarchy (state/get-current-repo) namespace)]
  1044. (namespace-hierarchy config namespace children))))
  1045. (= name "youtube")
  1046. (when-let [url (first arguments)]
  1047. (let [YouTube-regex #"^((?:https?:)?//)?((?:www|m).)?((?:youtube.com|youtu.be))(/(?:[\w-]+\?v=|embed/|v/)?)([\w-]+)(\S+)?$"]
  1048. (when-let [youtube-id (cond
  1049. (== 11 (count url)) url
  1050. :else
  1051. (nth (util/safe-re-find YouTube-regex url) 5))]
  1052. (when-not (string/blank? youtube-id)
  1053. (youtube/youtube-video youtube-id)))))
  1054. (= name "youtube-timestamp")
  1055. (when-let [timestamp (first arguments)]
  1056. (when-let [seconds (youtube/parse-timestamp timestamp)]
  1057. (youtube/timestamp seconds)))
  1058. (= name "tutorial-video")
  1059. (tutorial-video)
  1060. (= name "zotero-imported-file")
  1061. (let [[item-key filename] arguments]
  1062. (when (and item-key filename)
  1063. [:span.ml-1 (zotero/zotero-imported-file item-key filename)]))
  1064. (= name "zotero-linked-file")
  1065. (when-let [path (first arguments)]
  1066. [:span.ml-1 (zotero/zotero-linked-file path)])
  1067. (= name "vimeo")
  1068. (when-let [url (first arguments)]
  1069. (let [Vimeo-regex #"^((?:https?:)?//)?((?:www).)?((?:player.vimeo.com|vimeo.com)?)((?:/video/)?)([\w-]+)(\S+)?$"]
  1070. (when-let [vimeo-id (nth (util/safe-re-find Vimeo-regex url) 5)]
  1071. (when-not (string/blank? vimeo-id)
  1072. (let [width (min (- (util/get-width) 96)
  1073. 560)
  1074. height (int (* width (/ 315 560)))]
  1075. [:iframe
  1076. {:allow-full-screen "allowfullscreen"
  1077. :allow
  1078. "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope"
  1079. :frame-border "0"
  1080. :src (str "https://player.vimeo.com/video/" vimeo-id)
  1081. :height height
  1082. :width width}])))))
  1083. ;; TODO: support fullscreen mode, maybe we need a fullscreen dialog?
  1084. (= name "bilibili")
  1085. (when-let [url (first arguments)]
  1086. (let [id-regex #"https?://www\.bilibili\.com/video/([^? ]+)"]
  1087. (when-let [id (cond
  1088. (<= (count url) 15) url
  1089. :else
  1090. (last (util/safe-re-find id-regex url)))]
  1091. (when-not (string/blank? id)
  1092. (let [width (min (- (util/get-width) 96)
  1093. 560)
  1094. height (int (* width (/ 315 560)))]
  1095. [:iframe
  1096. {:allowfullscreen true
  1097. :framespacing "0"
  1098. :frameborder "no"
  1099. :border "0"
  1100. :scrolling "no"
  1101. :src (str "https://player.bilibili.com/player.html?bvid=" id "&high_quality=1")
  1102. :width width
  1103. :height (max 500 height)}])))))
  1104. (contains? #{"tweet" "twitter"} name)
  1105. (when-let [url (first arguments)]
  1106. (let [id-regex #"/status/(\d+)"]
  1107. (when-let [id (cond
  1108. (<= (count url) 15) url
  1109. :else
  1110. (last (util/safe-re-find id-regex url)))]
  1111. (ui/tweet-embed id))))
  1112. (= name "embed")
  1113. (let [a (first arguments)
  1114. {:keys [link-depth]} config
  1115. link-depth (or link-depth 0)]
  1116. (cond
  1117. (nil? a) ; empty embed
  1118. nil
  1119. (> link-depth max-depth-of-links)
  1120. [:p.warning.text-sm "Embed depth is too deep"]
  1121. (and (string/starts-with? a "[[")
  1122. (string/ends-with? a "]]"))
  1123. (let [page-name (text/get-page-name a)]
  1124. (when-not (string/blank? page-name)
  1125. (page-embed (assoc config :link-depth (inc link-depth)) page-name)))
  1126. (and (string/starts-with? a "((")
  1127. (string/ends-with? a "))"))
  1128. (when-let [s (-> (string/replace a "((" "")
  1129. (string/replace "))" "")
  1130. string/trim)]
  1131. (when-let [id (and s
  1132. (let [s (string/trim s)]
  1133. (and (util/uuid-string? s)
  1134. (uuid s))))]
  1135. (block-embed (assoc config :link-depth (inc link-depth)) id)))
  1136. :else ;TODO: maybe collections?
  1137. nil))
  1138. (and plugin-handler/lsp-enabled? (= name "renderer"))
  1139. (when-let [block-uuid (str (:block/uuid config))]
  1140. (plugins/hook-ui-slot :macro-renderer-slotted (assoc options :uuid block-uuid)))
  1141. (get @macro/macros name)
  1142. ((get @macro/macros name) config options)
  1143. :else
  1144. (if-let [block-uuid (:block/uuid config)]
  1145. (let [format (get-in config [:block :block/format] :markdown)
  1146. macro-content (or
  1147. (-> (db/entity [:block/uuid block-uuid])
  1148. (:block/page)
  1149. (:db/id)
  1150. (db/entity)
  1151. :block/properties
  1152. :macros
  1153. (get name))
  1154. (get (state/get-macros) name)
  1155. (get (state/get-macros) (keyword name)))
  1156. macro-content (cond
  1157. (= (str name) "img")
  1158. (case (count arguments)
  1159. 1
  1160. (util/format "[:img {:src \"%s\"}]" (first arguments))
  1161. 4
  1162. (when (and (util/safe-parse-int (nth arguments 1))
  1163. (util/safe-parse-int (nth arguments 2)))
  1164. (util/format "[:img.%s {:src \"%s\" :style {:width %s :height %s}}]"
  1165. (nth arguments 3)
  1166. (first arguments)
  1167. (util/safe-parse-int (nth arguments 1))
  1168. (util/safe-parse-int (nth arguments 2))))
  1169. 3
  1170. (when (and (util/safe-parse-int (nth arguments 1))
  1171. (util/safe-parse-int (nth arguments 2)))
  1172. (util/format "[:img {:src \"%s\" :style {:width %s :height %s}}]"
  1173. (first arguments)
  1174. (util/safe-parse-int (nth arguments 1))
  1175. (util/safe-parse-int (nth arguments 2))))
  1176. 2
  1177. (cond
  1178. (util/safe-parse-int (nth arguments 1))
  1179. (util/format "[:img {:src \"%s\" :style {:width %s}}]"
  1180. (first arguments)
  1181. (util/safe-parse-int (nth arguments 1)))
  1182. (contains? #{"left" "right" "center"} (string/lower-case (nth arguments 1)))
  1183. (util/format "[:img.%s {:src \"%s\"}]"
  1184. (string/lower-case (nth arguments 1))
  1185. (first arguments))
  1186. :else
  1187. macro-content)
  1188. macro-content)
  1189. (and (seq arguments) macro-content)
  1190. (block/macro-subs macro-content arguments)
  1191. :else
  1192. macro-content)
  1193. macro-content (when macro-content
  1194. (template/resolve-dynamic-template! macro-content))]
  1195. (render-macro config name arguments macro-content format))
  1196. (let [macro-content (or
  1197. (get (state/get-macros) name)
  1198. (get (state/get-macros) (keyword name)))
  1199. format (get-in config [:block :block/format] :markdown)]
  1200. (render-macro config name arguments macro-content format)))))
  1201. :else
  1202. ""))
  1203. (rum/defc block-child
  1204. [block]
  1205. block)
  1206. (defn- dnd-same-block?
  1207. [uuid]
  1208. (= (:block/uuid @*dragging-block) uuid))
  1209. (defn- bullet-drag-start
  1210. [event block uuid block-id]
  1211. (editor-handler/highlight-block! uuid)
  1212. (.setData (gobj/get event "dataTransfer")
  1213. "block-uuid"
  1214. uuid)
  1215. (.setData (gobj/get event "dataTransfer")
  1216. "block-dom-id"
  1217. block-id)
  1218. (state/clear-selection!)
  1219. (reset! *dragging? true)
  1220. (reset! *dragging-block block))
  1221. (defn- bullet-on-click
  1222. [e block uuid]
  1223. (if (gobj/get e "shiftKey")
  1224. (do
  1225. (state/sidebar-add-block!
  1226. (state/get-current-repo)
  1227. (:db/id block)
  1228. :block
  1229. block)
  1230. (util/stop e))
  1231. (route-handler/redirect-to-page! uuid)))
  1232. (defn- toggle-block-children
  1233. [_e children]
  1234. (let [block-ids (map :block/uuid children)]
  1235. (dorun
  1236. (if (some editor-handler/collapsable? block-ids)
  1237. (map editor-handler/collapse-block! block-ids)
  1238. (map editor-handler/expand-block! block-ids)))))
  1239. (rum/defc block-children < rum/reactive
  1240. [config children collapsed?]
  1241. (let [ref? (:ref? config)
  1242. children (and (coll? children) (filter map? children))]
  1243. (when (and (coll? children)
  1244. (seq children)
  1245. (not collapsed?))
  1246. (let [doc-mode? (state/sub :document/mode?)]
  1247. [:div.block-children-container.flex {:style {:margin-left (if doc-mode? 18
  1248. (if (or (mobile-util/native-android?)
  1249. (mobile-util/native-iphone?))
  1250. 22
  1251. 29))}}
  1252. [:div.block-children-left-border {:on-click (fn [event] (toggle-block-children event children))}]
  1253. [:div.block-children.w-full {:style {:display (if collapsed? "none" "")}}
  1254. (for [child children]
  1255. (when (map? child)
  1256. (let [child (dissoc child :block/meta)
  1257. config (cond->
  1258. (-> config
  1259. (assoc :block/uuid (:block/uuid child))
  1260. (dissoc :breadcrumb-show? :embed-parent))
  1261. ref?
  1262. (assoc :ref-child? true))]
  1263. (rum/with-key (block-container config child)
  1264. (:block/uuid child)))))]]))))
  1265. (defn- block-content-empty?
  1266. [{:block/keys [properties title body]}]
  1267. (and
  1268. (or
  1269. (empty? properties)
  1270. (property/properties-built-in? properties))
  1271. (empty? title)
  1272. (every? #(= % ["Horizontal_Rule"]) body)))
  1273. (rum/defcs block-control < rum/reactive
  1274. [state config block uuid block-id collapsed? *control-show? edit?]
  1275. (let [doc-mode? (state/sub :document/mode?)
  1276. control-show? (util/react *control-show?)
  1277. ref? (:ref? config)
  1278. empty-content? (block-content-empty? block)]
  1279. [:div.mr-1.flex.flex-row.items-center.sm:mr-2
  1280. {:style {:height 24
  1281. :margin-top 0
  1282. :float "left"}}
  1283. [:a.block-control
  1284. {:id (str "control-" uuid)
  1285. :on-click (fn [event]
  1286. (util/stop event)
  1287. (if ref?
  1288. (state/toggle-collapsed-block! uuid)
  1289. (if collapsed?
  1290. (editor-handler/expand-block! uuid)
  1291. (editor-handler/collapse-block! uuid))))}
  1292. [:span {:class (if control-show? "control-show cursor-pointer" "control-hide")}
  1293. (ui/rotating-arrow collapsed?)]]
  1294. (let [bullet [:a {:on-click (fn [event]
  1295. (bullet-on-click event block uuid))}
  1296. [:span.bullet-container.cursor
  1297. {:id (str "dot-" uuid)
  1298. :draggable true
  1299. :on-drag-start (fn [event]
  1300. (bullet-drag-start event block uuid block-id))
  1301. :blockid (str uuid)
  1302. :class (str (when collapsed? "bullet-closed")
  1303. " "
  1304. (when (and (:document/mode? config)
  1305. (not collapsed?))
  1306. "hide-inner-bullet"))}
  1307. [:span.bullet {:blockid (str uuid)}]]]]
  1308. (cond
  1309. (and (or (mobile-util/is-native-platform?)
  1310. (:ui/show-empty-bullets? (state/get-config)))
  1311. (not doc-mode?))
  1312. bullet
  1313. (or
  1314. (and empty-content?
  1315. (not edit?)
  1316. (not (:block/top? block))
  1317. (not (:block/bottom? block))
  1318. (not (util/react *control-show?)))
  1319. (and doc-mode?
  1320. (not collapsed?)
  1321. (not (util/react *control-show?))))
  1322. ;; hidden
  1323. [:span.bullet-container]
  1324. :else
  1325. bullet))]))
  1326. (rum/defc dnd-separator
  1327. [move-to block-content?]
  1328. [:div.relative
  1329. [:div.dnd-separator.absolute
  1330. {:style {:left (cond-> (if (= move-to :nested) 40 20)
  1331. block-content?
  1332. (- 34))
  1333. :top 0
  1334. :width "100%"
  1335. :z-index 3}}]])
  1336. (defn block-checkbox
  1337. [block class]
  1338. (let [marker (:block/marker block)
  1339. [class checked?] (cond
  1340. (nil? marker)
  1341. nil
  1342. (contains? #{"NOW" "LATER" "DOING" "IN-PROGRESS" "TODO" "WAIT" "WAITING"} marker)
  1343. [class false]
  1344. (= "DONE" marker)
  1345. [(str class " checked") true])]
  1346. (when class
  1347. (ui/checkbox {:class class
  1348. :style {:margin-top -2
  1349. :margin-right 5}
  1350. :checked checked?
  1351. :on-mouse-down (fn [e]
  1352. (util/stop-propagation e))
  1353. :on-change (fn [_e]
  1354. (if checked?
  1355. (editor-handler/uncheck block)
  1356. (editor-handler/check block)))}))))
  1357. (defn list-checkbox
  1358. [checked?]
  1359. (ui/checkbox {:style {:margin-right 6}
  1360. :checked checked?}))
  1361. (defn marker-switch
  1362. [{:block/keys [marker] :as block}]
  1363. (when (contains? #{"NOW" "LATER" "TODO" "DOING"} marker)
  1364. (let [set-marker-fn (fn [new-marker]
  1365. (fn [e]
  1366. (util/stop e)
  1367. (editor-handler/set-marker block new-marker)))
  1368. next-marker (case marker
  1369. "NOW" "LATER"
  1370. "LATER" "NOW"
  1371. "TODO" "DOING"
  1372. "DOING" "TODO")]
  1373. [:a
  1374. {:class (str "marker-switch block-marker " marker)
  1375. :title (util/format "Change from %s to %s" marker next-marker)
  1376. :on-mouse-down (set-marker-fn next-marker)}
  1377. marker])))
  1378. (defn marker-cp
  1379. [{:block/keys [pre-block? marker] :as _block}]
  1380. (when-not pre-block?
  1381. (when (contains? #{"IN-PROGRESS" "WAIT" "WAITING"} marker)
  1382. [:span {:class (str "task-status block-marker " (string/lower-case marker))
  1383. :style {:margin-right 3.5}}
  1384. (string/upper-case marker)])))
  1385. (rum/defc set-priority
  1386. [block priority]
  1387. [:div
  1388. (let [priorities (sort (remove #(= priority %) ["A" "B" "C"]))]
  1389. (for [p priorities]
  1390. [:a.mr-2.text-base.tooltip-priority {:key (str (random-uuid))
  1391. :priority p
  1392. :on-click (fn [] (editor-handler/set-priority block p))}]))])
  1393. (rum/defc priority-text
  1394. [priority]
  1395. [:a.opacity-50.hover:opacity-100
  1396. {:class "priority"
  1397. :href (rfe/href :page {:name priority})
  1398. :style {:margin-right 3.5}}
  1399. (util/format "[#%s]" (str priority))])
  1400. (defn priority-cp
  1401. [{:block/keys [pre-block? priority] :as block}]
  1402. (when (and (not pre-block?) priority)
  1403. (ui/tippy
  1404. {:interactive true
  1405. :html (set-priority block priority)}
  1406. (priority-text priority))))
  1407. (defn block-tags-cp
  1408. [{:block/keys [pre-block? tags] :as _block}]
  1409. (when (and (not pre-block?)
  1410. (seq tags))
  1411. (->elem
  1412. :span
  1413. {:class "block-tags"}
  1414. (mapv (fn [tag]
  1415. (when-let [page (db/entity (:db/id tag))]
  1416. (let [tag (:block/name page)]
  1417. [:a.tag.mx-1 {:data-ref tag
  1418. :key (str "tag-" (:db/id tag))
  1419. :href (rfe/href :page {:name tag})}
  1420. (str "#" tag)])))
  1421. tags))))
  1422. (declare block-content)
  1423. (defn build-block-title
  1424. [config {:block/keys [title marker pre-block? properties level heading-level]
  1425. :as t}]
  1426. (let [config (assoc config :block t)
  1427. slide? (boolean (:slide? config))
  1428. block-ref? (:block-ref? config)
  1429. block-type (or (keyword (:ls-type properties)) :default)
  1430. html-export? (:html-export? config)
  1431. checkbox (when (and (not pre-block?)
  1432. (not html-export?))
  1433. (block-checkbox t (str "mr-1 cursor")))
  1434. marker-switch (when (and (not pre-block?)
  1435. (not html-export?))
  1436. (marker-switch t))
  1437. marker-cp (marker-cp t)
  1438. priority (priority-cp t)
  1439. tags (block-tags-cp t)
  1440. bg-color (:background-color properties)
  1441. heading-level (or (and heading-level
  1442. (<= heading-level 6)
  1443. heading-level)
  1444. (and (get properties :heading)
  1445. (<= level 6)
  1446. level))
  1447. elem (if heading-level
  1448. (keyword (str "h" heading-level
  1449. (when block-ref? ".inline")))
  1450. :span.inline)]
  1451. (->elem
  1452. elem
  1453. (merge
  1454. {:data-hl-type (:hl-type properties)}
  1455. (when (and marker
  1456. (not (string/blank? marker))
  1457. (not= "nil" marker))
  1458. {:class (str (string/lower-case marker))})
  1459. (when bg-color
  1460. {:style {:background-color bg-color
  1461. :padding-left 6
  1462. :padding-right 6
  1463. :color "#FFFFFF"}
  1464. :class "with-bg-color"}))
  1465. (remove-nils
  1466. (concat
  1467. [(when-not slide? checkbox)
  1468. (when-not slide? marker-switch)
  1469. marker-cp
  1470. priority]
  1471. (if title
  1472. (conj
  1473. (map-inline config title)
  1474. (when (and (util/electron?) (not= block-type :default))
  1475. [:a.prefix-link
  1476. {:on-click #(case block-type
  1477. ;; pdf annotation
  1478. :annotation (pdf-assets/open-block-ref! t)
  1479. (.preventDefault %))}
  1480. [:span.hl-page
  1481. [:strong.forbid-edit (str "P" (or (:hl-page properties) "?"))]
  1482. [:label.blank " "]]
  1483. (when-let [st (and (= :area (keyword (:hl-type properties)))
  1484. (:hl-stamp properties))]
  1485. (pdf-assets/area-display t st))]))
  1486. [[:span.opacity-50 "Click here to start writing, type '/' to see all the commands."]])
  1487. [tags])))))
  1488. (rum/defc span-comma
  1489. []
  1490. [:span ", "])
  1491. (rum/defc property-cp
  1492. [config block k v]
  1493. (let [date (and (= k :date) (date/get-locale-string (str v)))]
  1494. [:div
  1495. [:span.page-property-key.font-medium (name k)]
  1496. [:span.mr-1 ":"]
  1497. (cond
  1498. (int? v)
  1499. v
  1500. date
  1501. date
  1502. (coll? v)
  1503. (let [v (->> (remove string/blank? v)
  1504. (filter string?))
  1505. vals (for [v-item v]
  1506. (page-cp config {:block/name v-item}))
  1507. elems (interpose (span-comma) vals)]
  1508. (for [elem elems]
  1509. (rum/with-key elem (str (random-uuid)))))
  1510. (and (string? v) (util/wrapped-by-quotes? v))
  1511. (util/unquote-string v)
  1512. :else
  1513. (inline-text config (:block/format block) (str v)))]))
  1514. (rum/defc properties-cp
  1515. [config block]
  1516. (let [properties (walk/keywordize-keys (:block/properties block))
  1517. properties-order (:block/properties-order block)
  1518. properties (apply dissoc properties (property/built-in-properties))
  1519. properties-order (remove (property/built-in-properties) properties-order)
  1520. pre-block? (:block/pre-block? block)
  1521. properties (if pre-block?
  1522. (let [repo (state/get-current-repo)
  1523. properties (dissoc properties :title :filters)
  1524. aliases (db/get-page-alias-names repo
  1525. (:block/name (db/pull (:db/id (:block/page block)))))]
  1526. (if (seq aliases)
  1527. (if (:alias properties)
  1528. (update properties :alias (fn [c]
  1529. (util/distinct-by string/lower-case (concat c aliases))))
  1530. (assoc properties :alias aliases))
  1531. properties))
  1532. properties)
  1533. properties-order (if pre-block?
  1534. (remove #{:title :filters} properties-order)
  1535. properties-order)
  1536. properties (if (seq properties-order)
  1537. (map (fn [k] [k (get properties k)]) properties-order)
  1538. properties)]
  1539. (cond
  1540. (seq properties)
  1541. [:div.block-properties
  1542. {:class (when pre-block? "page-properties")
  1543. :title (if pre-block?
  1544. "Click to edit this page's properties"
  1545. "Click to edit this block's properties")}
  1546. (for [[k v] properties]
  1547. (rum/with-key (property-cp config block k v)
  1548. (str (:block/uuid block) "-" k)))]
  1549. (and pre-block? properties)
  1550. [:span.opacity-50 "Properties"]
  1551. :else
  1552. nil)))
  1553. (rum/defcs timestamp-cp < rum/reactive
  1554. (rum/local false ::show?)
  1555. (rum/local {} ::pos)
  1556. {:will-unmount (fn [state]
  1557. (when-let [show? (::show? state)]
  1558. (reset! show? false))
  1559. state)}
  1560. [state block typ ast]
  1561. (let [show? (get state ::show?)]
  1562. [:div.flex.flex-col.timestamp
  1563. [:div.text-sm.flex.flex-row
  1564. [:div.opacity-50.font-medium.timestamp-label
  1565. (str typ ": ")]
  1566. [:a.opacity-80.hover:opacity-100
  1567. {:on-mouse-down (fn [e]
  1568. (util/stop e)
  1569. (if @show?
  1570. (do
  1571. (reset! show? false)
  1572. (reset! commands/*current-command nil)
  1573. (state/set-editor-show-date-picker! false)
  1574. (state/set-timestamp-block! nil))
  1575. (do
  1576. (reset! show? true)
  1577. (reset! commands/*current-command typ)
  1578. (state/set-editor-show-date-picker! true)
  1579. (state/set-timestamp-block! {:block block
  1580. :typ typ
  1581. :show? show?}))))}
  1582. [:span.time-start "<"] [:time (repeated/timestamp->text ast)] [:span.time-stop ">"]]]
  1583. (when (true? @show?)
  1584. (let [ts (repeated/timestamp->map ast)]
  1585. [:div.my-4
  1586. (datetime-comp/date-picker nil nil ts)]))]))
  1587. (defn- target-forbidden-edit?
  1588. [target]
  1589. (or
  1590. (dom/has-class? target "forbid-edit")
  1591. (dom/has-class? target "bullet")
  1592. (dom/has-class? target "logbook")
  1593. (util/link? target)
  1594. (util/time? target)
  1595. (util/input? target)
  1596. (util/details-or-summary? target)
  1597. (and (util/sup? target)
  1598. (dom/has-class? target "fn"))
  1599. (dom/has-class? target "image-resize")))
  1600. (defn- block-content-on-mouse-down
  1601. [e block block-id _content edit-input-id]
  1602. (.stopPropagation e)
  1603. (let [target (gobj/get e "target")
  1604. button (gobj/get e "buttons")
  1605. shift? (gobj/get e "shiftKey")]
  1606. (when (contains? #{1 0} button)
  1607. (when-not (target-forbidden-edit? target)
  1608. (if (and shift? (state/get-selection-start-block))
  1609. (editor-handler/highlight-selection-area! block-id)
  1610. (do
  1611. (editor-handler/clear-selection!)
  1612. (editor-handler/unhighlight-blocks!)
  1613. (let [f #(let [block (or (db/pull [:block/uuid (:block/uuid block)]) block)
  1614. cursor-range (util/caret-range (gdom/getElement block-id))
  1615. {:block/keys [content format]} block
  1616. content (->> content
  1617. (property/remove-built-in-properties format)
  1618. (drawer/remove-logbook))]
  1619. ;; save current editing block
  1620. (let [{:keys [value] :as state} (editor-handler/get-state)]
  1621. (editor-handler/save-block! state value))
  1622. (state/set-editing!
  1623. edit-input-id
  1624. content
  1625. block
  1626. cursor-range
  1627. false))]
  1628. ;; wait a while for the value of the caret range
  1629. (if (util/ios?)
  1630. (f)
  1631. (js/setTimeout f 5))
  1632. (when block-id (state/set-selection-start-block! block-id)))))))))
  1633. (rum/defc dnd-separator-wrapper < rum/reactive
  1634. [block block-id slide? top? block-content?]
  1635. (let [dragging? (rum/react *dragging?)
  1636. drag-to-block (rum/react *drag-to-block)]
  1637. (when (and
  1638. (= block-id drag-to-block)
  1639. dragging?
  1640. (not slide?)
  1641. (not (:block/pre-block? block)))
  1642. (let [move-to (rum/react *move-to)]
  1643. (when-not
  1644. (or (and top? (not= move-to :top))
  1645. (and (not top?) (= move-to :top))
  1646. (and block-content? (not= move-to :nested))
  1647. (and (not block-content?)
  1648. (seq (:block/children block))
  1649. (= move-to :nested)))
  1650. (dnd-separator move-to block-content?))))))
  1651. (defn clock-summary-cp
  1652. [block body]
  1653. (when (and (state/enable-timetracking?)
  1654. (or (= (:block/marker block) "DONE")
  1655. (contains? #{"TODO" "LATER"} (:block/marker block))))
  1656. (let [summary (clock/clock-summary body true)]
  1657. (when (and summary
  1658. (not= summary "0m")
  1659. (not (string/blank? summary)))
  1660. [:div {:style {:max-width 100}}
  1661. (ui/tippy {:html (fn []
  1662. (when-let [logbook (drawer/get-logbook body)]
  1663. (let [clocks (->> (last logbook)
  1664. (filter #(string/starts-with? % "CLOCK:"))
  1665. (remove string/blank?))]
  1666. [:div.p-4
  1667. [:div.font-bold.mb-2 "LOGBOOK:"]
  1668. [:ul
  1669. (for [clock (take 10 (reverse clocks))]
  1670. [:li clock])]])))
  1671. :interactive true
  1672. :delay [1000, 100]}
  1673. [:div.text-sm.time-spent.ml-1 {:style {:padding-top 3}}
  1674. [:a.fade-link
  1675. summary]])]))))
  1676. (rum/defc block-content < rum/reactive
  1677. [config {:block/keys [uuid content children properties scheduled deadline format pre-block?] :as block} edit-input-id block-id slide?]
  1678. (let [{:block/keys [title body] :as block} (if (:block/title block) block
  1679. (merge block (block/parse-title-and-body uuid format pre-block? content)))
  1680. collapsed? (util/collapsed? block)
  1681. block-ref? (:block-ref? config)
  1682. block-ref-with-title? (and block-ref? (seq title))
  1683. block-type (or (:ls-type properties) :default)
  1684. content (if (string? content) (string/trim content) "")
  1685. mouse-down-key (if (util/ios?)
  1686. :on-click
  1687. :on-mouse-down ; TODO: it seems that Safari doesn't work well with on-mouse-down
  1688. )
  1689. attrs (cond->
  1690. {:blockid (str uuid)
  1691. :data-type (name block-type)
  1692. :style {:width "100%"}}
  1693. (not block-ref?)
  1694. (assoc mouse-down-key (fn [e]
  1695. (block-content-on-mouse-down e block block-id content edit-input-id))))]
  1696. [:div.block-content.inline
  1697. (cond-> {:id (str "block-content-" uuid)
  1698. :on-mouse-up (fn [e]
  1699. (when (and
  1700. (state/in-selection-mode?)
  1701. (not (string/includes? content "```"))
  1702. (not (gobj/get e "shiftKey")))
  1703. ;; clear highlighted text
  1704. (util/clear-selection!)))}
  1705. (not slide?)
  1706. (merge attrs))
  1707. [:<>
  1708. [:div.flex.flex-row.justify-between
  1709. [:div.flex-1
  1710. (cond
  1711. (seq title)
  1712. (build-block-title config block)
  1713. :else
  1714. nil)]
  1715. (clock-summary-cp block body)]
  1716. (when (seq children)
  1717. (dnd-separator-wrapper block block-id slide? false true))
  1718. (when deadline
  1719. (when-let [deadline-ast (block-handler/get-deadline-ast block)]
  1720. (timestamp-cp block "DEADLINE" deadline-ast)))
  1721. (when scheduled
  1722. (when-let [scheduled-ast (block-handler/get-scheduled-ast block)]
  1723. (timestamp-cp block "SCHEDULED" scheduled-ast)))
  1724. (when (and (seq properties)
  1725. (let [hidden? (property/properties-built-in? properties)]
  1726. (not hidden?))
  1727. (not (and block-ref? (or (seq title) (seq body))))
  1728. (not (:slide? config)))
  1729. (properties-cp config block))
  1730. (when (and (not block-ref-with-title?) (seq body))
  1731. [:div.block-body {:style {:display (if (and collapsed? (seq title)) "none" "")}}
  1732. ;; TODO: consistent id instead of the idx (since it could be changed later)
  1733. (let [body (block/trim-break-lines! (:block/body block))]
  1734. (for [[idx child] (medley/indexed body)]
  1735. (when-let [block (markup-element-cp config child)]
  1736. (rum/with-key (block-child block)
  1737. (str uuid "-" idx)))))])
  1738. (case (:block/warning block)
  1739. :multiple-blocks
  1740. [:p.warning.text-sm "Full content is not displayed, Logseq doesn't support multiple unordered lists or headings in a block."]
  1741. nil)]]))
  1742. (rum/defc block-refs-count < rum/reactive db-mixins/query
  1743. [block]
  1744. (if-let [block-refs-count (model/get-block-refs-count (:db/id block))]
  1745. (when (> block-refs-count 0)
  1746. [:a.open-block-ref-link.bg-base-2.text-sm.ml-2.fade-link
  1747. {:title "Open block references"
  1748. :on-click (fn []
  1749. (state/sidebar-add-block!
  1750. (state/get-current-repo)
  1751. (:db/id block)
  1752. :block-ref
  1753. {:block block}))}
  1754. block-refs-count])
  1755. nil))
  1756. (rum/defc block-content-or-editor < rum/reactive
  1757. [config {:block/keys [uuid format] :as block} edit-input-id block-id heading-level edit?]
  1758. (let [editor-box (get config :editor-box)
  1759. editor-id (str "editor-" edit-input-id)
  1760. slide? (:slide? config)]
  1761. (if (and edit? editor-box)
  1762. [:div.editor-wrapper {:id editor-id}
  1763. (ui/catch-error
  1764. (ui/block-error "Something wrong in the editor" {})
  1765. (editor-box {:block block
  1766. :block-id uuid
  1767. :block-parent-id block-id
  1768. :format format
  1769. :heading-level heading-level
  1770. :on-hide (fn [_value event]
  1771. (when (= event :esc)
  1772. (editor-handler/escape-editing)))}
  1773. edit-input-id
  1774. config))]
  1775. [:div.flex.flex-row.block-content-wrapper
  1776. [:div.flex-1.w-full {:style {:display (if (:slide? config) "block" "flex")}}
  1777. (ui/catch-error
  1778. (ui/block-error "Block Render Error:"
  1779. {:content (:block/content block)
  1780. :section-attrs
  1781. {:on-click #(state/set-editing! edit-input-id (:block/content block) block "")}})
  1782. (block-content config block edit-input-id block-id slide?))]
  1783. [:div.flex.flex-row.items-center
  1784. (when (and (:embed? config)
  1785. (:embed-parent config))
  1786. [:a.opacity-30.hover:opacity-100.svg-small.inline
  1787. {:on-mouse-down (fn [e]
  1788. (util/stop e)
  1789. (when-let [block (:embed-parent config)]
  1790. (editor-handler/edit-block! block :max (:block/uuid block))))}
  1791. svg/edit])
  1792. (block-refs-count block)]])))
  1793. (defn non-dragging?
  1794. [e]
  1795. (and (= (gobj/get e "buttons") 1)
  1796. (not (dom/has-class? (gobj/get e "target") "bullet-container"))
  1797. (not (dom/has-class? (gobj/get e "target") "bullet"))
  1798. (not @*dragging?)))
  1799. (rum/defc breadcrumb-fragment
  1800. [config block label]
  1801. (if (= block :page) ; page
  1802. (when label
  1803. (let [page (db/entity [:block/name (util/page-name-sanity-lc label)])]
  1804. (page-cp config page)))
  1805. [:a {:on-mouse-down
  1806. (fn [e]
  1807. (if (gobj/get e "shiftKey")
  1808. (do
  1809. (util/stop e)
  1810. (state/sidebar-add-block!
  1811. (state/get-current-repo)
  1812. (:db/id block)
  1813. :block-ref
  1814. {:block block}))
  1815. (route-handler/redirect-to-page! (:block/uuid block))))}
  1816. label]))
  1817. (rum/defc breadcrumb-separator [] [:span.mx-2.opacity-50 "➤"])
  1818. (defn block-parents
  1819. [config repo block-id {:keys [show-page? indent? level-limit]
  1820. :or {show-page? true
  1821. level-limit 3}}]
  1822. (let [parents (db/get-block-parents repo block-id (inc level-limit))
  1823. page (db/get-block-page repo block-id)
  1824. page-name (:block/name page)
  1825. page-original-name (:block/original-name page)
  1826. show? (or (seq parents) show-page? page-name)
  1827. parents (if (= page-name (:block/name (first parents)))
  1828. (rest parents)
  1829. parents)
  1830. more? (> (count parents) level-limit)
  1831. parents (if more? (take-last level-limit parents) parents)]
  1832. (when show?
  1833. (let [page-name-props (when show-page?
  1834. [:page
  1835. (or page-original-name page-name)])
  1836. parents-props (doall
  1837. (for [{:block/keys [uuid name content] :as block} parents]
  1838. (when-not name ; not page
  1839. (let [{:block/keys [title body]} (block/parse-title-and-body
  1840. uuid
  1841. (:block/format block)
  1842. (:block/pre-block? block)
  1843. content)
  1844. config (assoc config :block/uuid uuid)]
  1845. [block
  1846. (if (seq title)
  1847. (->elem :span (map-inline config title))
  1848. (->elem :div (markup-elements-cp config body)))]))))
  1849. breadcrumb (->> (into [] parents-props)
  1850. (concat [page-name-props] (when more? [:more]))
  1851. (filterv identity)
  1852. (map (fn [x] (if (vector? x)
  1853. (let [[block label] x]
  1854. (breadcrumb-fragment config block label))
  1855. [:span.opacity-70 "⋯"])))
  1856. (interpose (breadcrumb-separator)))]
  1857. [:div.block-parents.flex-row.flex-1
  1858. {:class (when (seq breadcrumb)
  1859. (str (when-not (:search? config)
  1860. " my-2")
  1861. (when indent?
  1862. " ml-4")))}
  1863. breadcrumb]))))
  1864. (defn- block-drag-over
  1865. [event uuid top? block-id *move-to]
  1866. (util/stop event)
  1867. (when-not (dnd-same-block? uuid)
  1868. (let [over-block (gdom/getElement block-id)
  1869. rect (utils/getOffsetRect over-block)
  1870. element-top (gobj/get rect "top")
  1871. element-left (gobj/get rect "left")
  1872. x-offset (- (.. event -pageX) element-left)
  1873. cursor-top (gobj/get event "clientY")
  1874. move-to-value (cond
  1875. (and top? (<= (js/Math.abs (- cursor-top element-top)) 16))
  1876. :top
  1877. (> x-offset 50)
  1878. :nested
  1879. :else
  1880. :sibling)]
  1881. (reset! *drag-to-block block-id)
  1882. (reset! *move-to move-to-value))))
  1883. (defn- block-drag-leave
  1884. [*move-to]
  1885. (reset! *move-to nil))
  1886. (defn- block-drop
  1887. [event uuid block *move-to]
  1888. (util/stop event)
  1889. (when-not (dnd-same-block? uuid)
  1890. (dnd/move-block event @*dragging-block
  1891. block
  1892. @*move-to))
  1893. (reset! *dragging? false)
  1894. (reset! *dragging-block nil)
  1895. (reset! *drag-to-block nil)
  1896. (reset! *move-to nil)
  1897. (editor-handler/unhighlight-blocks!))
  1898. (defn- block-drag-end
  1899. [_event *move-to]
  1900. (reset! *dragging? false)
  1901. (reset! *dragging-block nil)
  1902. (reset! *drag-to-block nil)
  1903. (reset! *move-to nil)
  1904. (editor-handler/unhighlight-blocks!))
  1905. (defn- block-mouse-over
  1906. [uuid e *control-show? block-id doc-mode?]
  1907. (util/stop e)
  1908. (when (or
  1909. (model/block-collapsed? uuid)
  1910. (editor-handler/collapsable? uuid {:semantic? true}))
  1911. (reset! *control-show? true))
  1912. (when-let [parent (gdom/getElement block-id)]
  1913. (let [node (.querySelector parent ".bullet-container")]
  1914. (when doc-mode?
  1915. (dom/remove-class! node "hide-inner-bullet"))))
  1916. (when (and
  1917. (state/in-selection-mode?)
  1918. (non-dragging? e))
  1919. (util/stop e)
  1920. (editor-handler/highlight-selection-area! block-id)))
  1921. (defn- block-mouse-leave
  1922. [e *control-show? block-id doc-mode?]
  1923. (util/stop e)
  1924. (reset! *control-show? false)
  1925. (when doc-mode?
  1926. (when-let [parent (gdom/getElement block-id)]
  1927. (when-let [node (.querySelector parent ".bullet-container")]
  1928. (dom/add-class! node "hide-inner-bullet"))))
  1929. (when (and (non-dragging? e)
  1930. (not @*resizing-image?))
  1931. (state/into-selection-mode!)))
  1932. (defn- on-drag-and-mouse-attrs
  1933. [block uuid top? block-id *move-to]
  1934. {:on-drag-over (fn [event]
  1935. (block-drag-over event uuid top? block-id *move-to))
  1936. :on-drag-leave (fn [_event]
  1937. (block-drag-leave *move-to))
  1938. :on-drop (fn [event]
  1939. (block-drop event uuid block *move-to))
  1940. :on-drag-end (fn [event]
  1941. (block-drag-end event *move-to))})
  1942. (defn- build-refs-data-value
  1943. [refs]
  1944. (let [refs (model/get-page-names-by-ids
  1945. (->> (map :db/id refs)
  1946. (remove nil?)))]
  1947. (text/build-data-value refs)))
  1948. (defn- get-children-refs
  1949. [children]
  1950. (let [refs (atom [])]
  1951. (walk/postwalk
  1952. (fn [m]
  1953. (when (and (map? m) (:block/refs m))
  1954. (swap! refs concat (:block/refs m)))
  1955. m)
  1956. children)
  1957. (distinct @refs)))
  1958. (defn- root-block?
  1959. [config block]
  1960. (and (:block? config)
  1961. (util/collapsed? block)
  1962. (= (:id config)
  1963. (str (:block/uuid block)))))
  1964. (rum/defcs ^:large-vars/cleanup-todo block-container < rum/reactive
  1965. {:init (fn [state]
  1966. (let [[config block] (:rum/args state)
  1967. block-id (:block/uuid block)]
  1968. (cond
  1969. (:ref? config)
  1970. (state/set-collapsed-block! block-id
  1971. (editor-handler/block-default-collapsed? block config))
  1972. (root-block? config block)
  1973. (state/set-collapsed-block! block-id false)
  1974. :else
  1975. nil)
  1976. (assoc state ::control-show? (atom false))))
  1977. :should-update (fn [old-state new-state]
  1978. (let [compare-keys [:block/uuid :block/content :block/parent :block/collapsed? :block/children
  1979. :block/properties :block/left :block/children :block/_refs]
  1980. config-compare-keys [:show-cloze?]
  1981. b1 (second (:rum/args old-state))
  1982. b2 (second (:rum/args new-state))
  1983. result (or
  1984. (not= (select-keys b1 compare-keys)
  1985. (select-keys b2 compare-keys))
  1986. (not= (select-keys (first (:rum/args old-state)) config-compare-keys)
  1987. (select-keys (first (:rum/args new-state)) config-compare-keys)))]
  1988. (boolean result)))}
  1989. [state config {:block/keys [uuid children pre-block? top? refs heading-level level type format content] :as block}]
  1990. (let [repo (state/get-current-repo)
  1991. block (merge block (block/parse-title-and-body uuid format pre-block? content))
  1992. blocks-container-id (:blocks-container-id config)
  1993. config (update config :block merge block)
  1994. ;; Each block might have multiple queries, but we store only the first query's result
  1995. config (if (nil? (:query-result config))
  1996. (assoc config :query-result (atom nil))
  1997. config)
  1998. heading? (and (= type :heading) heading-level (<= heading-level 6))
  1999. *control-show? (get state ::control-show?)
  2000. ref? (:ref? config)
  2001. db-collapsed? (util/collapsed? block)
  2002. collapsed? (cond
  2003. (or ref? (root-block? config block))
  2004. (state/sub-collapsed uuid)
  2005. :else
  2006. db-collapsed?)
  2007. breadcrumb-show? (:breadcrumb-show? config)
  2008. slide? (boolean (:slide? config))
  2009. custom-query? (boolean (:custom-query? config))
  2010. doc-mode? (:document/mode? config)
  2011. embed? (:embed? config)
  2012. reference? (:reference? config)
  2013. block-id (str "ls-block-" blocks-container-id "-" uuid)
  2014. has-child? (boolean
  2015. (and
  2016. (not pre-block?)
  2017. (coll? children)
  2018. (seq children)))
  2019. attrs (on-drag-and-mouse-attrs block uuid top? block-id *move-to)
  2020. children-refs (get-children-refs children)
  2021. data-refs (build-refs-data-value children-refs)
  2022. data-refs-self (build-refs-data-value refs)
  2023. edit-input-id (str "edit-block-" blocks-container-id "-" uuid)
  2024. edit? (state/sub [:editor/editing? edit-input-id])
  2025. card? (string/includes? data-refs-self "\"card\"")
  2026. review-cards? (:review-cards? config)]
  2027. [:div.ls-block
  2028. (cond->
  2029. {:id block-id
  2030. :data-refs data-refs
  2031. :data-refs-self data-refs-self
  2032. :data-collapsed (and collapsed? has-child?)
  2033. :class (str uuid
  2034. (when pre-block? " pre-block")
  2035. (when (and card? (not review-cards?)) " shadow-xl"))
  2036. :blockid (str uuid)
  2037. :haschild (str has-child?)}
  2038. level
  2039. (assoc :level level)
  2040. (not slide?)
  2041. (merge attrs)
  2042. (or reference? embed?)
  2043. (assoc :data-transclude true)
  2044. embed?
  2045. (assoc :data-embed true)
  2046. custom-query?
  2047. (assoc :data-query true))
  2048. (when (and ref? breadcrumb-show?)
  2049. (block-parents config repo uuid {:show-page? false
  2050. :indent? true}))
  2051. ;; only render this for the first block in each container
  2052. (when top?
  2053. (dnd-separator-wrapper block block-id slide? true false))
  2054. [:div.flex.flex-row.pr-2
  2055. {:class (if (and heading? (seq (:block/title block))) "items-baseline" "")
  2056. :on-mouse-over (fn [e]
  2057. (block-mouse-over uuid e *control-show? block-id doc-mode?))
  2058. :on-mouse-leave (fn [e]
  2059. (block-mouse-leave e *control-show? block-id doc-mode?))}
  2060. (when (not slide?)
  2061. (block-control config block uuid block-id collapsed? *control-show? edit?))
  2062. (block-content-or-editor config block edit-input-id block-id heading-level edit?)]
  2063. (block-children config children collapsed?)
  2064. (dnd-separator-wrapper block block-id slide? false false)]))
  2065. (defn divide-lists
  2066. [[f & l]]
  2067. (loop [l l
  2068. ordered? (:ordered f)
  2069. result [[f]]]
  2070. (if (seq l)
  2071. (let [cur (first l)
  2072. cur-ordered? (:ordered cur)]
  2073. (if (= ordered? cur-ordered?)
  2074. (recur
  2075. (rest l)
  2076. cur-ordered?
  2077. (update result (dec (count result)) conj cur))
  2078. (recur
  2079. (rest l)
  2080. cur-ordered?
  2081. (conj result [cur]))))
  2082. result)))
  2083. (defn list-element
  2084. [l]
  2085. (match l
  2086. [l1 & _tl]
  2087. (let [{:keys [ordered name]} l1]
  2088. (cond
  2089. (seq name)
  2090. :dl
  2091. ordered
  2092. :ol
  2093. :else
  2094. :ul))
  2095. :else
  2096. :ul))
  2097. (defn list-item
  2098. [config {:keys [name content checkbox items number] :as _list}]
  2099. (let [content (when-not (empty? content)
  2100. (match content
  2101. [["Paragraph" i] & rest]
  2102. (vec-cat
  2103. (map-inline config i)
  2104. (markup-elements-cp config rest))
  2105. :else
  2106. (markup-elements-cp config content)))
  2107. checked? (some? checkbox)
  2108. items (when (seq items)
  2109. (->elem
  2110. (list-element items)
  2111. (for [item items]
  2112. (list-item config item))))]
  2113. (cond
  2114. (seq name)
  2115. [:dl {:checked checked?}
  2116. [:dt (map-inline config name)]
  2117. (->elem :dd
  2118. (vec-cat content [items]))]
  2119. :else
  2120. (if (nil? checkbox)
  2121. (->elem
  2122. :li
  2123. (cond->
  2124. {:checked checked?}
  2125. number
  2126. (assoc :value number))
  2127. (vec-cat
  2128. [(->elem
  2129. :p
  2130. content)]
  2131. [items]))
  2132. (->elem
  2133. :li
  2134. {:checked checked?}
  2135. (vec-cat
  2136. [(->elem
  2137. :p
  2138. (list-checkbox checkbox)
  2139. content)]
  2140. [items]))))))
  2141. (defn table
  2142. [config {:keys [header groups col_groups]}]
  2143. (let [tr (fn [elm cols]
  2144. (->elem
  2145. :tr
  2146. (mapv (fn [col]
  2147. (->elem
  2148. elm
  2149. {:scope "col"
  2150. :class "org-left"}
  2151. (map-inline config col)))
  2152. cols)))
  2153. tb-col-groups (try
  2154. (mapv (fn [number]
  2155. (let [col-elem [:col {:class "org-left"}]]
  2156. (->elem
  2157. :colgroup
  2158. (repeat number col-elem))))
  2159. col_groups)
  2160. (catch js/Error _e
  2161. []))
  2162. head (when header
  2163. [:thead (tr :th header)])
  2164. groups (mapv (fn [group]
  2165. (->elem
  2166. :tbody
  2167. (mapv #(tr :td %) group)))
  2168. groups)]
  2169. [:div.table-wrapper {:style {:max-width (min 700
  2170. (gobj/get js/window "innerWidth"))}}
  2171. (->elem
  2172. :table
  2173. {:class "table-auto"
  2174. :border 2
  2175. :cell-spacing 0
  2176. :cell-padding 6
  2177. :rules "groups"
  2178. :frame "hsides"}
  2179. (vec-cat
  2180. tb-col-groups
  2181. (cons head groups)))]))
  2182. (defn logbook-cp
  2183. [log]
  2184. (let [clocks (filter #(string/starts-with? % "CLOCK:") log)
  2185. clocks (reverse (sort-by str clocks))
  2186. ;; TODO: diplay states change log
  2187. ; states (filter #(not (string/starts-with? % "CLOCK:")) log)
  2188. ]
  2189. (when (seq clocks)
  2190. (let [tr (fn [elm cols] (->elem :tr
  2191. (mapv (fn [col] (->elem elm col)) cols)))
  2192. head [:thead.overflow-x-scroll (tr :th.py-0 ["Type" "Start" "End" "Span"])]
  2193. clock-tbody (->elem
  2194. :tbody.overflow-scroll.sm:overflow-auto
  2195. (mapv (fn [clock]
  2196. (let [cols (->> (string/split clock #": |--|=>")
  2197. (map string/trim))]
  2198. (mapv #(tr :td.py-0 %) [cols])))
  2199. clocks))]
  2200. [:div.overflow-x-scroll.sm:overflow-auto
  2201. (->elem
  2202. :table.m-0
  2203. {:class "logbook-table"
  2204. :border 0
  2205. :style {:width "max-content"}
  2206. :cell-spacing 15}
  2207. (cons head [clock-tbody]))]))))
  2208. (defn map-inline
  2209. [config col]
  2210. (map #(inline config %) col))
  2211. (declare ->hiccup)
  2212. (defn built-in-custom-query?
  2213. [title]
  2214. (let [repo (state/get-current-repo)
  2215. queries (state/sub [:config repo :default-queries :journals])]
  2216. (when (seq queries)
  2217. (boolean (some #(= % title) (map :title queries))))))
  2218. (defn- trigger-custom-query!
  2219. [state]
  2220. (let [[config query] (:rum/args state)
  2221. repo (state/get-current-repo)
  2222. result-atom (atom nil)
  2223. query-atom (if (:dsl-query? config)
  2224. (let [q (:query query)
  2225. form (safe-read-string q false)]
  2226. (cond
  2227. ;; Searches like 'foo' or 'foo bar' come back as symbols
  2228. ;; and are meant to go directly to full text search
  2229. (and (util/electron?) (symbol? form)) ; full-text search
  2230. (p/let [blocks (search/block-search repo (string/trim (str form)) {:limit 30})]
  2231. (when (seq blocks)
  2232. (let [result (db/pull-many (state/get-current-repo) '[*] (map (fn [b] [:block/uuid (uuid (:block/uuid b))]) blocks))]
  2233. (reset! result-atom result))))
  2234. (symbol? form)
  2235. (atom nil)
  2236. :else
  2237. (query-dsl/query (state/get-current-repo) q)))
  2238. (db/custom-query query))
  2239. query-atom (if (instance? Atom query-atom)
  2240. query-atom
  2241. result-atom)]
  2242. (assoc state :query-atom query-atom)))
  2243. (rum/defcs ^:large-vars/cleanup-todo custom-query* < rum/reactive
  2244. {:will-mount trigger-custom-query!
  2245. :did-mount (fn [state]
  2246. (when-let [query (last (:rum/args state))]
  2247. (state/add-custom-query-component! query (:rum/react-component state)))
  2248. state)
  2249. :did-remount (fn [_old_state state]
  2250. (trigger-custom-query! state))
  2251. :will-unmount (fn [state]
  2252. (when-let [query (last (:rum/args state))]
  2253. (state/remove-custom-query-component! query)
  2254. (db/remove-custom-query! (state/get-current-repo) query))
  2255. state)}
  2256. [state config {:keys [title query view collapsed? children? breadcrumb-show?] :as q}]
  2257. (let [dsl-query? (:dsl-query? config)
  2258. query-atom (:query-atom state)
  2259. current-block-uuid (or (:block/uuid (:block config))
  2260. (:block/uuid config))
  2261. current-block (db/entity [:block/uuid current-block-uuid])
  2262. ;; exclude the current one, otherwise it'll loop forever
  2263. remove-blocks (if current-block-uuid [current-block-uuid] nil)
  2264. query-result (and query-atom (rum/react query-atom))
  2265. table? (or (get-in current-block [:block/properties :query-table])
  2266. (and (string? query) (string/ends-with? (string/trim query) "table")))
  2267. transformed-query-result (when query-result
  2268. (db/custom-query-result-transform query-result remove-blocks q))
  2269. not-grouped-by-page? (or table?
  2270. (boolean (:result-transform q))
  2271. (and (string? query) (string/includes? query "(by-page false)")))
  2272. result (if (and (:block/uuid (first transformed-query-result)) (not not-grouped-by-page?))
  2273. (db-utils/group-by-page transformed-query-result)
  2274. transformed-query-result)
  2275. _ (when-let [query-result (:query-result config)]
  2276. (let [result (remove (fn [b] (some? (get-in b [:block/properties :template]))) result)]
  2277. (reset! query-result result)))
  2278. view-f (and view (sci/eval-string (pr-str view)))
  2279. only-blocks? (:block/uuid (first result))
  2280. blocks-grouped-by-page? (and (seq result)
  2281. (not not-grouped-by-page?)
  2282. (coll? (first result))
  2283. (:block/name (ffirst result))
  2284. (:block/uuid (first (second (first result))))
  2285. true)
  2286. built-in? (built-in-custom-query? title)
  2287. page-list? (and (seq result)
  2288. (:block/name (first result)))
  2289. nested-query? (:custom-query? config)]
  2290. (if nested-query?
  2291. [:code (if dsl-query?
  2292. (util/format "{{query %s}}" query)
  2293. "{{query hidden}}")]
  2294. [:div.custom-query.mt-4 (get config :attr {})
  2295. (when-not (and built-in? (empty? result))
  2296. (ui/foldable
  2297. [:div.custom-query-title
  2298. [:span.title-text title]
  2299. [:span.opacity-60.text-sm.ml-2.results-count
  2300. (str (count transformed-query-result) " results")]]
  2301. (fn []
  2302. [:div
  2303. (when current-block
  2304. [:div.flex.flex-row.align-items.mt-2 {:on-mouse-down (fn [e] (util/stop e))}
  2305. (when-not page-list?
  2306. [:div.flex.flex-row
  2307. [:div.mx-2 [:span.text-sm "Table view"]]
  2308. [:div {:style {:margin-top 5}}
  2309. (ui/toggle table?
  2310. (fn []
  2311. (editor-handler/set-block-property! current-block-uuid
  2312. "query-table"
  2313. (not table?)))
  2314. true)]])
  2315. [:a.mx-2.block.fade-link
  2316. {:on-click (fn []
  2317. (let [all-keys (query-table/get-keys result page-list?)]
  2318. (state/pub-event! [:modal/set-query-properties current-block all-keys])))}
  2319. [:span.table-query-properties
  2320. [:span.text-sm.mr-1 "Set properties"]
  2321. svg/settings-sm]]])
  2322. (cond
  2323. (and (seq result) view-f)
  2324. (let [result (try
  2325. (sci/call-fn view-f result)
  2326. (catch js/Error error
  2327. (log/error :custom-view-failed {:error error
  2328. :result result})
  2329. [:div "Custom view failed: "
  2330. (str error)]))]
  2331. (util/hiccup-keywordize result))
  2332. page-list?
  2333. (query-table/result-table config current-block result {:page? true} map-inline page-cp ->elem inline-text)
  2334. table?
  2335. (query-table/result-table config current-block result {:page? false} map-inline page-cp ->elem inline-text)
  2336. (and (seq result) (or only-blocks? blocks-grouped-by-page?))
  2337. (->hiccup result (cond-> (assoc config
  2338. :custom-query? true
  2339. :breadcrumb-show? (if (some? breadcrumb-show?)
  2340. breadcrumb-show?
  2341. true)
  2342. :group-by-page? blocks-grouped-by-page?
  2343. :ref? true)
  2344. children?
  2345. (assoc :ref? true))
  2346. {:style {:margin-top "0.25rem"
  2347. :margin-left "0.25rem"}})
  2348. (seq result)
  2349. (let [result (->>
  2350. (for [record result]
  2351. (if (map? record)
  2352. (str (util/pp-str record) "\n")
  2353. record))
  2354. (remove nil?))]
  2355. [:pre result])
  2356. :else
  2357. [:div.text-sm.mt-2.ml-2.font-medium.opacity-50 "Empty"])])
  2358. {:default-collapsed? collapsed?
  2359. :title-trigger? true}))])))
  2360. (rum/defc custom-query
  2361. [config q]
  2362. (ui/catch-error
  2363. (ui/block-error "Query Error:" {:content (:query q)})
  2364. (custom-query* config q)))
  2365. (defn admonition
  2366. [config type result]
  2367. (when-let [icon (case (string/lower-case (name type))
  2368. "note" svg/note
  2369. "tip" svg/tip
  2370. "important" svg/important
  2371. "caution" svg/caution
  2372. "warning" svg/warning
  2373. "pinned" svg/pinned
  2374. nil)]
  2375. [:div.flex.flex-row.admonitionblock.align-items {:class type}
  2376. [:div.pr-4.admonition-icon.flex.flex-col.justify-center
  2377. {:title (string/upper-case type)} (icon)]
  2378. [:div.ml-4.text-lg
  2379. (markup-elements-cp config result)]]))
  2380. ;; TODO: move to mldoc
  2381. ;; (defn- convert-md-src-to-custom-block
  2382. ;; [item]
  2383. ;; (let [{:keys [language options lines] :as options} (second item)
  2384. ;; lang (string/lower-case (or language ""))]
  2385. ;; (cond
  2386. ;; (= lang "quote")
  2387. ;; (let [content (string/trim (string/join "\n" lines))]
  2388. ;; ["Quote" (first (mldoc/->edn content (mldoc/default-config :markdown)))])
  2389. ;; (contains? #{"query" "note" "tip" "important" "caution" "warning" "pinned"} lang)
  2390. ;; (let [content (string/trim (string/join "\n" lines))]
  2391. ;; ["Custom" lang nil (first (mldoc/->edn content (mldoc/default-config :markdown))) content])
  2392. ;; :else
  2393. ;; ["Src" options])))
  2394. (rum/defc src-cp < rum/static
  2395. [config options html-export?]
  2396. (when options
  2397. (let [{:keys [lines language]} options
  2398. attr (when language
  2399. {:data-lang language})
  2400. code (apply str lines)]
  2401. (cond
  2402. html-export?
  2403. (highlight/html-export attr code)
  2404. :else
  2405. (let [language (if (contains? #{"edn" "clj" "cljc" "cljs"} language) "clojure" language)]
  2406. (if (:slide? config)
  2407. (highlight/highlight (str (medley/random-uuid))
  2408. {:class (str "language-" language)
  2409. :data-lang language}
  2410. code)
  2411. [:div
  2412. (lazy-editor/editor config (str (d/squuid)) attr code options)
  2413. (let [options (:options options)]
  2414. (when (and (= language "clojure") (contains? (set options) ":results"))
  2415. (sci/eval-result code)))]))))))
  2416. (defn ^:large-vars/cleanup-todo markup-element-cp
  2417. [{:keys [html-export?] :as config} item]
  2418. (let [format (or (:block/format config)
  2419. :markdown)]
  2420. (try
  2421. (match item
  2422. ["Drawer" name lines]
  2423. (when (or (not= name "logbook")
  2424. (and
  2425. (= name "logbook")
  2426. (state/enable-timetracking?)
  2427. (or (get-in (state/get-config) [:logbook/settings :enabled-in-all-blocks])
  2428. (when (get-in (state/get-config)
  2429. [:logbook/settings :enabled-in-timestamped-blocks] true)
  2430. (or (:block/scheduled (:block config))
  2431. (:block/deadline (:block config)))))))
  2432. [:div
  2433. [:div.text-sm
  2434. [:div.drawer {:data-drawer-name name}
  2435. (ui/foldable
  2436. [:div.opacity-50.font-medium.logbook
  2437. (util/format ":%s:" (string/upper-case name))]
  2438. [:div.opacity-50.font-medium
  2439. (if (= name "logbook")
  2440. (logbook-cp lines)
  2441. (apply str lines))
  2442. [:div ":END:"]]
  2443. {:default-collapsed? true
  2444. :title-trigger? true})]]])
  2445. ["Properties" m]
  2446. [:div.properties
  2447. (for [[k v] (dissoc m :roam_alias :roam_tags)]
  2448. (when (and (not (and (= k :macros) (empty? v))) ; empty macros
  2449. (not (= k :title))
  2450. (not (= k :filters)))
  2451. [:div.property
  2452. [:span.font-medium.mr-1 (str (name k) ": ")]
  2453. (if (coll? v)
  2454. (let [vals (for [item v]
  2455. (if (coll? v)
  2456. (let [config (when (= k :alias)
  2457. (assoc config :block/alias? true))]
  2458. (page-cp config {:block/name item}))
  2459. (inline-text format item)))]
  2460. (interpose [:span ", "] vals))
  2461. (inline-text format v))]))]
  2462. ;; for file-level property in orgmode: #+key: value
  2463. ;; only display caption. https://orgmode.org/manual/Captions.html.
  2464. ["Directive" key value]
  2465. [:div.file-level-property
  2466. (when (contains? #{"caption"} (string/lower-case key))
  2467. [:span.font-medium
  2468. [:span.font-bold (string/upper-case key)]
  2469. (str ": " value)])]
  2470. ["Paragraph" l]
  2471. ;; TODO: speedup
  2472. (if (util/safe-re-find #"\"Export_Snippet\" \"embed\"" (str l))
  2473. (->elem :div (map-inline config l))
  2474. (->elem :div.is-paragraph (map-inline config l)))
  2475. ["Horizontal_Rule"]
  2476. (when-not (:slide? config)
  2477. [:hr])
  2478. ["Heading" h]
  2479. (block-container config h)
  2480. ["List" l]
  2481. (let [lists (divide-lists l)]
  2482. (if (= 1 (count lists))
  2483. (let [l (first lists)]
  2484. (->elem
  2485. (list-element l)
  2486. (map #(list-item config %) l)))
  2487. [:div.list-group
  2488. (for [l lists]
  2489. (->elem
  2490. (list-element l)
  2491. (map #(list-item config %) l)))]))
  2492. ["Table" t]
  2493. (table config t)
  2494. ["Math" s]
  2495. (if html-export?
  2496. (latex/html-export s true true)
  2497. (latex/latex (str (d/squuid)) s true true))
  2498. ["Example" l]
  2499. [:pre.pre-wrap-white-space
  2500. (join-lines l)]
  2501. ["Quote" l]
  2502. (->elem
  2503. :blockquote
  2504. (markup-elements-cp config l))
  2505. ["Raw_Html" content]
  2506. (when (not html-export?)
  2507. [:div.raw_html {:dangerouslySetInnerHTML
  2508. {:__html content}}])
  2509. ["Export" "html" _options content]
  2510. (when (not html-export?)
  2511. [:div.export_html {:dangerouslySetInnerHTML
  2512. {:__html content}}])
  2513. ["Hiccup" content]
  2514. (ui/catch-error
  2515. [:div.warning {:title "Invalid hiccup"}
  2516. content]
  2517. (-> (safe-read-string content)
  2518. (security/remove-javascript-links-in-href)))
  2519. ["Export" "latex" _options content]
  2520. (if html-export?
  2521. (latex/html-export content true false)
  2522. (latex/latex (str (d/squuid)) content true false))
  2523. ["Custom" "query" _options _result content]
  2524. (try
  2525. (let [query (reader/read-string content)]
  2526. (custom-query config query))
  2527. (catch :default e
  2528. (log/error :read-string-error e)
  2529. (ui/block-error "Invalid query:" {:content content})))
  2530. ["Custom" "note" _options result _content]
  2531. (admonition config "note" result)
  2532. ["Custom" "tip" _options result _content]
  2533. (admonition config "tip" result)
  2534. ["Custom" "important" _options result _content]
  2535. (admonition config "important" result)
  2536. ["Custom" "caution" _options result _content]
  2537. (admonition config "caution" result)
  2538. ["Custom" "warning" _options result _content]
  2539. (admonition config "warning" result)
  2540. ["Custom" "pinned" _options result _content]
  2541. (admonition config "pinned" result)
  2542. ["Custom" "center" _options l _content]
  2543. (->elem
  2544. :div.text-center
  2545. (markup-elements-cp config l))
  2546. ["Custom" name _options l _content]
  2547. (->elem
  2548. :div
  2549. {:class name}
  2550. (markup-elements-cp config l))
  2551. ["Latex_Fragment" l]
  2552. [:p.latex-fragment
  2553. (inline config ["Latex_Fragment" l])]
  2554. ["Latex_Environment" name option content]
  2555. (let [content (latex-environment-content name option content)]
  2556. (if html-export?
  2557. (latex/html-export content true true)
  2558. (latex/latex (str (d/squuid)) content true true)))
  2559. ["Displayed_Math" content]
  2560. (if html-export?
  2561. (latex/html-export content true true)
  2562. (latex/latex (str (d/squuid)) content true true))
  2563. ["Footnote_Definition" name definition]
  2564. (let [id (util/url-encode name)]
  2565. [:div.footdef
  2566. [:div.footpara
  2567. (conj
  2568. (markup-element-cp config ["Paragraph" definition])
  2569. [:a.ml-1 {:id (str "fn." id)
  2570. :style {:font-size 14}
  2571. :class "footnum"
  2572. :on-click #(route-handler/jump-to-anchor! (str "fnr." id))}
  2573. [:sup.fn (str name "↩︎")]])]])
  2574. ["Src" options]
  2575. (src-cp config options html-export?)
  2576. :else
  2577. "")
  2578. (catch js/Error e
  2579. (println "Convert to html failed, error: " e)
  2580. ""))))
  2581. (defn markup-elements-cp
  2582. [config col]
  2583. (map #(markup-element-cp config %) col))
  2584. (defn- block-list
  2585. [config blocks]
  2586. (for [[idx item] (medley/indexed blocks)]
  2587. (let [item (->
  2588. (dissoc item :block/meta)
  2589. (assoc :block/top? (zero? idx)
  2590. :block/bottom? (= (count blocks) (inc idx))))
  2591. config (assoc config :block/uuid (:block/uuid item))]
  2592. (rum/with-key (block-container config item)
  2593. (str (:block/uuid item))))))
  2594. (defn- custom-query-or-ref?
  2595. [config]
  2596. (let [ref? (:ref? config)
  2597. custom-query? (:custom-query? config)]
  2598. (or custom-query? ref?)))
  2599. ;; TODO: virtual tree for better UX and memory usage reduce
  2600. (defn- get-segment
  2601. [_config flat-blocks idx blocks->vec-tree]
  2602. (let [new-idx (if (< idx block-handler/initial-blocks-length)
  2603. block-handler/initial-blocks-length
  2604. (+ idx block-handler/step-loading-blocks))
  2605. max-idx (count flat-blocks)
  2606. idx (min max-idx new-idx)
  2607. blocks (util/safe-subvec flat-blocks 0 idx)]
  2608. [(blocks->vec-tree blocks)
  2609. idx]))
  2610. (rum/defcs lazy-blocks < rum/reactive
  2611. {:did-remount (fn [_old-state new-state]
  2612. ;; Loading more when pressing Enter or paste
  2613. (let [*last-idx (::last-idx new-state)
  2614. new-idx (if (zero? *last-idx)
  2615. 1
  2616. (inc @*last-idx))]
  2617. (reset! *last-idx new-idx))
  2618. new-state)}
  2619. (rum/local 0 ::last-idx)
  2620. [state config flat-blocks blocks->vec-tree]
  2621. (let [*last-idx (::last-idx state)
  2622. [segment idx] (get-segment config
  2623. flat-blocks
  2624. @*last-idx
  2625. blocks->vec-tree)
  2626. bottom-reached (fn [] (reset! *last-idx idx))
  2627. has-more? (>= (count flat-blocks) (inc idx))]
  2628. [:div#lazy-blocks
  2629. (ui/infinite-list
  2630. "main-content-container"
  2631. (block-list config segment)
  2632. {:on-load bottom-reached
  2633. :bottom-reached (fn []
  2634. (when-let [node (gdom/getElement "lazy-blocks")]
  2635. (ui/bottom-reached? node 1000)))
  2636. :has-more has-more?
  2637. :more (if (or (:preview? config) (:sidebar? config))
  2638. "More"
  2639. (ui/loading "Loading"))})]))
  2640. (rum/defcs blocks-container <
  2641. {:init (fn [state]
  2642. (assoc state ::init-blocks-container-id (atom nil)))}
  2643. [state blocks config]
  2644. (let [*init-blocks-container-id (::init-blocks-container-id state)
  2645. blocks-container-id (if @*init-blocks-container-id
  2646. @*init-blocks-container-id
  2647. (let [id' (swap! *blocks-container-id inc)]
  2648. (reset! *init-blocks-container-id id')
  2649. id'))
  2650. config (assoc config :blocks-container-id blocks-container-id)
  2651. doc-mode? (:document/mode? config)]
  2652. (when (seq blocks)
  2653. (let [blocks->vec-tree #(if (custom-query-or-ref? config) % (tree/blocks->vec-tree % (:id config)))
  2654. flat-blocks (vec blocks)]
  2655. [:div.blocks-container.flex-1
  2656. {:class (when doc-mode? "document-mode")}
  2657. (lazy-blocks config flat-blocks blocks->vec-tree)]))))
  2658. ;; headers to hiccup
  2659. (defn ->hiccup
  2660. [blocks config option]
  2661. [:div.content
  2662. (cond-> option
  2663. (:document/mode? config) (assoc :class "doc-mode"))
  2664. (cond
  2665. (and (:custom-query? config)
  2666. (:group-by-page? config))
  2667. [:div.flex.flex-col
  2668. (let [blocks (sort-by (comp :block/journal-day first) > blocks)]
  2669. (for [[page blocks] blocks]
  2670. (let [alias? (:block/alias? page)
  2671. page (db/entity (:db/id page))
  2672. parent-blocks (group-by :block/parent blocks)]
  2673. [:div.my-2 (cond-> {:key (str "page-" (:db/id page))}
  2674. (:ref? config)
  2675. (assoc :class "color-level px-2 sm:px-7 py-2 rounded"))
  2676. (ui/foldable
  2677. [:div
  2678. (page-cp config page)
  2679. (when alias? [:span.text-sm.font-medium.opacity-50 " Alias"])]
  2680. (for [[_parent blocks] parent-blocks]
  2681. (let [block (first blocks)]
  2682. [:div
  2683. (when (:breadcrumb-show? config)
  2684. (block-parents config (state/get-current-repo) (:block/uuid block)
  2685. {:show-page? false}))
  2686. (blocks-container blocks (assoc config :breadcrumb-show? false))]))
  2687. {})])))]
  2688. (and (:group-by-page? config)
  2689. (vector? (first blocks)))
  2690. [:div.flex.flex-col
  2691. (let [blocks (sort-by (comp :block/journal-day first) > blocks)]
  2692. (for [[page blocks] blocks]
  2693. (let [alias? (:block/alias? page)
  2694. page (db/entity (:db/id page))]
  2695. [:div.my-2 (cond-> {:key (str "page-" (:db/id page))}
  2696. (:ref? config)
  2697. (assoc :class "color-level px-2 sm:px-7 py-2 rounded"))
  2698. (ui/foldable
  2699. [:div
  2700. (page-cp config page)
  2701. (when alias? [:span.text-sm.font-medium.opacity-50 " Alias"])]
  2702. (blocks-container blocks config)
  2703. {})])))]
  2704. :else
  2705. (blocks-container blocks config))])