editor.cljs 160 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892
  1. (ns ^:no-doc frontend.handler.editor
  2. (:require [clojure.set :as set]
  3. [clojure.string :as string]
  4. [clojure.walk :as w]
  5. [dommy.core :as dom]
  6. [frontend.commands :as commands]
  7. [frontend.config :as config]
  8. [frontend.date :as date]
  9. [frontend.db :as db]
  10. [frontend.db.model :as db-model]
  11. [frontend.db.utils :as db-utils]
  12. [frontend.db.async :as db-async]
  13. [frontend.diff :as diff]
  14. [frontend.format.block :as block]
  15. [frontend.format.mldoc :as mldoc]
  16. [frontend.fs :as fs]
  17. [logseq.common.path :as path]
  18. [frontend.extensions.pdf.utils :as pdf-utils]
  19. [frontend.handler.assets :as assets-handler]
  20. [frontend.handler.block :as block-handler]
  21. [frontend.handler.common :as common-handler]
  22. [frontend.handler.property :as property-handler]
  23. [frontend.handler.property.util :as pu]
  24. [frontend.handler.db-based.property.util :as db-pu]
  25. [frontend.handler.export.html :as export-html]
  26. [frontend.handler.export.text :as export-text]
  27. [frontend.handler.notification :as notification]
  28. [frontend.handler.repeated :as repeated]
  29. [frontend.handler.route :as route-handler]
  30. [frontend.handler.db-based.editor :as db-editor-handler]
  31. [frontend.handler.file-based.editor :as file-editor-handler]
  32. [frontend.mobile.util :as mobile-util]
  33. [logseq.outliner.core :as outliner-core]
  34. [frontend.modules.outliner.op :as outliner-op]
  35. [frontend.modules.outliner.ui :as ui-outliner-tx]
  36. [frontend.modules.outliner.tree :as tree]
  37. [logseq.outliner.tree :as otree]
  38. [frontend.search :as search]
  39. [frontend.state :as state]
  40. [frontend.template :as template]
  41. [frontend.util :as util :refer [profile]]
  42. [frontend.util.clock :as clock]
  43. [frontend.util.cursor :as cursor]
  44. [frontend.util.drawer :as drawer]
  45. [frontend.util.keycode :as keycode]
  46. [frontend.util.list :as list]
  47. [frontend.handler.file-based.status :as status]
  48. [frontend.handler.property.file :as property-file]
  49. [frontend.util.text :as text-util]
  50. [frontend.util.thingatpt :as thingatpt]
  51. [goog.dom :as gdom]
  52. [goog.dom.classes :as gdom-classes]
  53. [goog.object :as gobj]
  54. [goog.crypt.base64 :as base64]
  55. [goog.string :as gstring]
  56. [lambdaisland.glogi :as log]
  57. [logseq.db.frontend.schema :as db-schema]
  58. [logseq.graph-parser.block :as gp-block]
  59. [logseq.graph-parser.mldoc :as gp-mldoc]
  60. [logseq.graph-parser.property :as gp-property]
  61. [logseq.graph-parser.text :as text]
  62. [logseq.graph-parser.utf8 :as utf8]
  63. [logseq.common.util :as common-util]
  64. [logseq.common.util.block-ref :as block-ref]
  65. [logseq.common.util.page-ref :as page-ref]
  66. [promesa.core :as p]
  67. [rum.core :as rum]
  68. [frontend.fs.capacitor-fs :as capacitor-fs]
  69. [logseq.db :as ldb]))
  70. ;; FIXME: should support multiple images concurrently uploading
  71. (defonce *asset-uploading? (atom false))
  72. (defonce *asset-uploading-process (atom 0))
  73. (def clear-selection! state/clear-selection!)
  74. (def edit-block! block-handler/edit-block!)
  75. (defn- outliner-save-block!
  76. [block]
  77. (outliner-op/save-block! block))
  78. (defn get-block-own-order-list-type
  79. [block]
  80. (let [properties (:block/properties block)]
  81. (pu/lookup properties :logseq.property/order-list-type)))
  82. (defn set-block-own-order-list-type!
  83. [block type]
  84. (when-let [uuid (:block/uuid block)]
  85. (property-handler/set-block-property! (state/get-current-repo) uuid (pu/get-pid :logseq.property/order-list-type) (name type))))
  86. (defn remove-block-own-order-list-type!
  87. [block]
  88. (when-let [uuid (:block/uuid block)]
  89. (property-handler/remove-block-property! (state/get-current-repo) uuid (pu/get-pid :logseq.property/order-list-type))))
  90. (defn own-order-number-list?
  91. [block]
  92. (when-let [block (db/entity (:db/id block))]
  93. (= (get-block-own-order-list-type block) "number")))
  94. (defn make-block-as-own-order-list!
  95. [block]
  96. (some-> block (set-block-own-order-list-type! "number")))
  97. (defn toggle-blocks-as-own-order-list!
  98. [blocks]
  99. (when (seq blocks)
  100. (let [has-ordered? (some own-order-number-list? blocks)
  101. blocks-uuids (some->> blocks (map :block/uuid) (remove nil?))
  102. order-list-prop (pu/get-pid :logseq.property/order-list-type)
  103. repo (state/get-current-repo)]
  104. (if has-ordered?
  105. (property-handler/batch-remove-block-property! repo blocks-uuids order-list-prop)
  106. (property-handler/batch-set-block-property! repo blocks-uuids order-list-prop "number")))))
  107. (defn get-selection-and-format
  108. []
  109. (when-let [block (state/get-edit-block)]
  110. (when (:block/uuid block)
  111. (when-let [edit-id (state/get-edit-input-id)]
  112. (when-let [input (gdom/getElement edit-id)]
  113. (let [selection-start (util/get-selection-start input)
  114. selection-end (util/get-selection-end input)
  115. value (gobj/get input "value")
  116. selection (when (not= selection-start selection-end)
  117. (subs value selection-start selection-end))
  118. selection-start (+ selection-start
  119. (count (take-while #(= " " %) selection)))
  120. selection-end (- selection-end
  121. (count (take-while #(= " " %) (reverse selection))))]
  122. {:selection-start selection-start
  123. :selection-end selection-end
  124. :selection (some-> selection
  125. string/trim)
  126. :format (:block/format block)
  127. :value value
  128. :block block
  129. :edit-id edit-id
  130. :input input}))))))
  131. (defn- format-text!
  132. [pattern-fn]
  133. (when-let [m (get-selection-and-format)]
  134. (let [{:keys [selection-start selection-end format selection value edit-id input]} m
  135. pattern (pattern-fn format)
  136. pattern-count (count pattern)
  137. pattern-prefix (subs value (max 0 (- selection-start pattern-count)) selection-start)
  138. pattern-suffix (subs value selection-end (min (count value) (+ selection-end pattern-count)))
  139. already-wrapped? (= pattern pattern-prefix pattern-suffix)
  140. prefix (if already-wrapped?
  141. (subs value 0 (- selection-start pattern-count))
  142. (subs value 0 selection-start))
  143. postfix (if already-wrapped?
  144. (subs value (+ selection-end pattern-count))
  145. (subs value selection-end))
  146. inner-value (cond-> selection
  147. (not already-wrapped?)
  148. (#(str pattern % pattern)))
  149. new-value (str prefix inner-value postfix)]
  150. (state/set-edit-content! edit-id new-value)
  151. (cond
  152. already-wrapped? (cursor/set-selection-to input (- selection-start pattern-count) (- selection-end pattern-count))
  153. selection (cursor/move-cursor-to input (+ selection-end pattern-count))
  154. :else (cursor/set-selection-to input (+ selection-start pattern-count) (+ selection-end pattern-count))))))
  155. (defn bold-format! []
  156. (format-text! config/get-bold))
  157. (defn italics-format! []
  158. (format-text! config/get-italic))
  159. (defn highlight-format! []
  160. (when-let [block (state/get-edit-block)]
  161. (let [format (:block/format block)]
  162. (format-text! #(config/get-highlight format)))))
  163. (defn strike-through-format! []
  164. (format-text! config/get-strike-through))
  165. (defn html-link-format!
  166. ([]
  167. (html-link-format! nil))
  168. ([text]
  169. (when-let [m (get-selection-and-format)]
  170. (let [{:keys [selection-start selection-end format selection value edit-id input]} m
  171. empty-selection? (= selection-start selection-end)
  172. selection-link? (and selection (gp-mldoc/mldoc-link? format selection))
  173. [content forward-pos] (cond
  174. empty-selection?
  175. (config/get-empty-link-and-forward-pos format)
  176. (and text selection-link?)
  177. (config/with-label-link format text selection)
  178. text
  179. (config/with-label-link format selection text)
  180. selection-link?
  181. (config/with-default-link format selection)
  182. :else
  183. (config/with-default-label format selection))
  184. new-value (str
  185. (subs value 0 selection-start)
  186. content
  187. (subs value selection-end))
  188. cur-pos (or selection-start (cursor/pos input))]
  189. (state/set-edit-content! edit-id new-value)
  190. (cursor/move-cursor-to input (+ cur-pos forward-pos))))))
  191. (defn open-block-in-sidebar!
  192. [block-id]
  193. ; (assert (uuid? block-id) "frontend.handler.editor/open-block-in-sidebar! expects block-id to be of type uuid")
  194. (when block-id
  195. (when-let [block (db/entity (if (number? block-id) block-id [:block/uuid block-id]))]
  196. (let [page? (nil? (:block/page block))]
  197. (state/sidebar-add-block!
  198. (state/get-current-repo)
  199. (:db/id block)
  200. (if page? :page :block))))))
  201. (defn reset-cursor-range!
  202. [node]
  203. (when node
  204. (state/set-cursor-range! (util/caret-range node))))
  205. (defn restore-cursor-pos!
  206. [id markup]
  207. (when-let [node (gdom/getElement (str id))]
  208. (let [cursor-range (state/get-cursor-range)
  209. pos (or (state/get-editor-last-pos)
  210. (and cursor-range
  211. (diff/find-position markup cursor-range)))]
  212. (cursor/move-cursor-to node pos)
  213. (state/clear-editor-last-pos!))))
  214. (defn highlight-block!
  215. [block-uuid]
  216. (let [blocks (array-seq (js/document.getElementsByClassName (str "id" block-uuid)))]
  217. (doseq [block blocks]
  218. (dom/add-class! block "block-highlight"))))
  219. (defn unhighlight-blocks!
  220. []
  221. (let [blocks (some->> (array-seq (js/document.getElementsByClassName "block-highlight"))
  222. (repeat 2)
  223. (apply concat))]
  224. (doseq [block blocks]
  225. (gdom-classes/remove block "block-highlight"))))
  226. (defn wrap-parse-block
  227. [block]
  228. (if (config/db-based-graph? (state/get-current-repo))
  229. (db-editor-handler/wrap-parse-block block)
  230. (file-editor-handler/wrap-parse-block block)))
  231. (defn- save-block-inner!
  232. [block value opts]
  233. (let [block {:db/id (:db/id block)
  234. :block/uuid (:block/uuid block)
  235. :block/content value}]
  236. (profile
  237. "Save block: "
  238. (let [block' (-> (wrap-parse-block block)
  239. ;; :block/uuid might be changed when backspace/delete
  240. ;; a block that has been refed
  241. (assoc :block/uuid (:block/uuid block)))
  242. opts' (assoc opts :outliner-op :save-block)
  243. original-block (db/entity (:db/id block))
  244. original-props (:block/properties original-block)]
  245. (ui-outliner-tx/transact!
  246. opts'
  247. (outliner-save-block! block')
  248. ;; page properties changed
  249. (when-let [page-name (and (:block/pre-block? block')
  250. (not= original-props (:block/properties block'))
  251. (some-> (:block/page block') :db/id (db-utils/pull) :block/name))]
  252. (state/set-page-properties-changed! page-name)))))))
  253. ;; id: block dom id, "ls-block-counter-uuid"
  254. (defn- another-block-with-same-id-exists?
  255. [current-id block-id]
  256. (when-let [id (and (string? block-id) (parse-uuid block-id))]
  257. (and (not= current-id id)
  258. (db/entity [:block/uuid id]))))
  259. (defn save-block-if-changed!
  260. ([block value]
  261. (save-block-if-changed! block value nil))
  262. ([block value
  263. {:keys [force?]
  264. :as opts}]
  265. (let [{:block/keys [uuid page format repo content properties]} block
  266. repo (or repo (state/get-current-repo))
  267. format (or format (state/get-preferred-format))
  268. page (db/entity repo (:db/id page))
  269. block-id (when (and (not (config/db-based-graph? repo)) (map? properties))
  270. (get properties :id))
  271. content (-> (property-file/remove-built-in-properties-when-file-based repo format content)
  272. (drawer/remove-logbook))]
  273. (cond
  274. (another-block-with-same-id-exists? uuid block-id)
  275. (notification/show!
  276. [:p.content
  277. (util/format "Block with the id %s already exists!" block-id)]
  278. :error)
  279. force?
  280. (save-block-inner! block value opts)
  281. :else
  282. (when content
  283. (let [content-changed? (not= (string/trim content) (string/trim value))]
  284. (when (and content-changed? page)
  285. (save-block-inner! block value opts))))))))
  286. (defn- compute-fst-snd-block-text
  287. [value selection-start selection-end]
  288. (when (string? value)
  289. (let [fst-block-text (subs value 0 selection-start)
  290. snd-block-text (string/triml (subs value selection-end))]
  291. [fst-block-text snd-block-text])))
  292. (declare save-current-block!)
  293. (defn outliner-insert-block!
  294. [config current-block new-block {:keys [sibling? keep-uuid? ordered-list?
  295. replace-empty-target?]}]
  296. (let [ref-query-top-block? (and (or (:ref? config)
  297. (:custom-query? config))
  298. (not (:ref-query-child? config)))
  299. has-children? (db/has-children? (:block/uuid current-block))
  300. sibling? (cond
  301. ref-query-top-block?
  302. false
  303. (boolean? sibling?)
  304. sibling?
  305. (util/collapsed? current-block)
  306. true
  307. :else
  308. (not has-children?))]
  309. (ui-outliner-tx/transact!
  310. {:outliner-op :insert-blocks}
  311. (save-current-block! {:current-block current-block})
  312. (outliner-op/insert-blocks! [new-block] current-block {:sibling? sibling?
  313. :keep-uuid? keep-uuid?
  314. :ordered-list? ordered-list?
  315. :replace-empty-target? replace-empty-target?}))))
  316. (defn- block-self-alone-when-insert?
  317. [config uuid]
  318. (let [current-page (state/get-current-page)
  319. block-id (or (some-> (:id config) parse-uuid)
  320. (some-> current-page parse-uuid))]
  321. (= uuid block-id)))
  322. (defn insert-new-block-before-block-aux!
  323. [config block value]
  324. (let [edit-input-id (state/get-edit-input-id)
  325. input (gdom/getElement edit-input-id)
  326. input-text-selected? (util/input-text-selected? input)
  327. new-m {:block/uuid (db/new-block-id)
  328. :block/content ""}
  329. prev-block (-> (merge (if (config/db-based-graph? (state/get-current-repo))
  330. (select-keys block [:block/parent :block/left :block/format :block/page])
  331. (select-keys block [:block/parent :block/left :block/format
  332. :block/page :block/journal?]))
  333. new-m)
  334. (wrap-parse-block))
  335. left-block (db/pull (:db/id (:block/left block)))]
  336. (when input-text-selected?
  337. (let [selection-start (util/get-selection-start input)
  338. selection-end (util/get-selection-end input)
  339. [_ new-content] (compute-fst-snd-block-text value selection-start selection-end)]
  340. (state/set-edit-content! edit-input-id new-content)))
  341. (p/let [_ (let [sibling? (not= (:db/id left-block) (:db/id (:block/parent block)))]
  342. (outliner-insert-block! config left-block prev-block {:sibling? sibling?
  343. :keep-uuid? true}))]
  344. prev-block)))
  345. (defn insert-new-block-aux!
  346. [config
  347. {:block/keys [uuid]
  348. :as block}
  349. value]
  350. (let [block-self? (block-self-alone-when-insert? config uuid)
  351. input (gdom/getElement (state/get-edit-input-id))
  352. selection-start (util/get-selection-start input)
  353. selection-end (util/get-selection-end input)
  354. [fst-block-text snd-block-text] (compute-fst-snd-block-text value selection-start selection-end)
  355. current-block (assoc block :block/content fst-block-text)
  356. current-block (apply dissoc current-block db-schema/retract-attributes)
  357. new-m {:block/uuid (db/new-block-id)
  358. :block/content snd-block-text}
  359. next-block (-> (merge (if (config/db-based-graph? (state/get-current-repo))
  360. (select-keys block [:block/parent :block/left :block/format :block/page])
  361. (select-keys block [:block/parent :block/left :block/format
  362. :block/page :block/journal?]))
  363. new-m)
  364. (wrap-parse-block))
  365. sibling? (when block-self? false)]
  366. (p/let [_ (outliner-insert-block! config current-block next-block {:sibling? sibling?
  367. :keep-uuid? true})]
  368. (util/set-change-value input fst-block-text)
  369. (assoc next-block :block/content snd-block-text))))
  370. (defn clear-when-saved!
  371. []
  372. (commands/restore-state))
  373. (defn get-state
  374. []
  375. (let [[{:keys [on-hide block block-id block-parent-id format sidebar?]} id config] (state/get-editor-args)
  376. node (gdom/getElement id)]
  377. (when node
  378. (let [value (gobj/get node "value")
  379. pos (util/get-selection-start node)]
  380. {:config config
  381. :on-hide on-hide
  382. :sidebar? sidebar?
  383. :format format
  384. :id id
  385. :block (or (db/pull [:block/uuid (:block/uuid block)]) block)
  386. :block-id block-id
  387. :block-parent-id block-parent-id
  388. :node node
  389. :value value
  390. :pos pos}))))
  391. (defn insert-new-block!
  392. "Won't save previous block content - remember to save!"
  393. ([state]
  394. (insert-new-block! state nil))
  395. ([_state block-value]
  396. (when (not config/publishing?)
  397. (when-let [state (get-state)]
  398. (let [{:keys [block value config]} state
  399. value (if (string? block-value) block-value value)
  400. block-id (:block/uuid block)
  401. block-self? (block-self-alone-when-insert? config block-id)
  402. input-id (state/get-edit-input-id)
  403. input (gdom/getElement input-id)
  404. block-node (state/get-edit-block-node)
  405. selection-start (util/get-selection-start input)
  406. selection-end (util/get-selection-end input)
  407. [fst-block-text snd-block-text] (compute-fst-snd-block-text value selection-start selection-end)
  408. insert-above? (and (string/blank? fst-block-text) (not (string/blank? snd-block-text)))
  409. block' (or (db/pull [:block/uuid block-id]) block)
  410. original-block (:original-block config)
  411. block'' (or
  412. (when original-block
  413. (let [e (db/entity (:db/id block'))]
  414. (if (and (some? (first (:block/_parent e)))
  415. (not (:block/collapsed? e)))
  416. ;; object has children and not collapsed
  417. block'
  418. original-block)))
  419. block')
  420. insert-fn (cond
  421. block-self?
  422. insert-new-block-aux!
  423. insert-above?
  424. insert-new-block-before-block-aux!
  425. :else
  426. insert-new-block-aux!)]
  427. (p/let [last-block (insert-fn config block'' value)]
  428. (clear-when-saved!)
  429. (edit-block! last-block 0 (when-not original-block block-node))))))))
  430. (defn api-insert-new-block!
  431. [content {:keys [page block-uuid sibling? before? properties
  432. custom-uuid replace-empty-target? edit-block? ordered-list? other-attrs]
  433. :or {sibling? false
  434. before? false
  435. edit-block? true}}]
  436. (when (or page block-uuid)
  437. (let [repo (state/get-current-repo)
  438. before? (if page false before?)
  439. sibling? (boolean sibling?)
  440. sibling? (if before? true (if page false sibling?))
  441. block (if page
  442. (db/get-page page)
  443. (db/entity [:block/uuid block-uuid]))
  444. db-based? (config/db-based-graph? repo)]
  445. (when block
  446. (let [last-block (when (not sibling?)
  447. (let [children (:block/_parent block)
  448. blocks (db/sort-by-left children block)
  449. last-block-id (:db/id (last blocks))]
  450. (when last-block-id
  451. (db/pull last-block-id))))
  452. format (or
  453. (:block/format block)
  454. (db/get-page-format (:db/id block))
  455. (state/get-preferred-format))
  456. content (if (seq properties)
  457. (property-file/insert-properties-when-file-based repo format content properties)
  458. content)
  459. new-block (-> (if db-based?
  460. (select-keys block [:block/page])
  461. ;; TODO: Figure out if journal attributes in this ns for file graphs is a bug
  462. (select-keys block [:block/page :block/journal? :block/journal-day]))
  463. (assoc :block/content content
  464. :block/format format))
  465. new-block (assoc new-block :block/page
  466. (if page
  467. (:db/id block)
  468. (:db/id (:block/page new-block))))
  469. new-block (-> new-block
  470. (wrap-parse-block)
  471. (assoc :block/uuid (or custom-uuid (db/new-block-id))))
  472. new-block (merge new-block other-attrs)
  473. [block-m sibling?] (cond
  474. before?
  475. (let [first-child? (->> [:block/parent :block/left]
  476. (map #(:db/id (get block %)))
  477. (apply =))
  478. block (db/pull (:db/id (:block/left block)))
  479. sibling? (if (or first-child? ;; insert as first child
  480. (:block/name block))
  481. false sibling?)]
  482. [block sibling?])
  483. sibling?
  484. [(db/pull (:db/id block)) sibling?]
  485. last-block
  486. [last-block true]
  487. block
  488. [(db/pull (:db/id block)) sibling?]
  489. ;; FIXME: assert
  490. :else
  491. nil)
  492. new-block' (if db-based?
  493. (merge new-block properties)
  494. new-block)]
  495. (when block-m
  496. (p/do!
  497. (outliner-insert-block! {} block-m new-block' {:sibling? sibling?
  498. :keep-uuid? true
  499. :ordered-list? ordered-list?
  500. :replace-empty-target? replace-empty-target?})
  501. (when edit-block?
  502. (if (and replace-empty-target?
  503. (string/blank? (:block/content last-block)))
  504. (edit-block! last-block :max nil)
  505. (edit-block! new-block :max nil)))
  506. new-block)))))))
  507. (defn insert-first-page-block-if-not-exists!
  508. ([page-title]
  509. (insert-first-page-block-if-not-exists! page-title {}))
  510. ([page-title opts]
  511. (when (and (string? page-title)
  512. (not (string/blank? page-title)))
  513. (state/pub-event! [:page/create page-title opts]))))
  514. (defn update-timestamps-content!
  515. [{:block/keys [repeated? marker format] :as block} content]
  516. (if repeated?
  517. (let [scheduled-ast (block-handler/get-scheduled-ast block)
  518. deadline-ast (block-handler/get-deadline-ast block)
  519. content (some->> (filter repeated/repeated? [scheduled-ast deadline-ast])
  520. (map (fn [ts]
  521. [(repeated/timestamp->text ts)
  522. (repeated/next-timestamp-text ts)]))
  523. (reduce (fn [content [old new]]
  524. (string/replace content old new))
  525. content))
  526. content (string/replace-first
  527. content marker
  528. (case marker
  529. "DOING"
  530. "TODO"
  531. "NOW"
  532. "LATER"
  533. marker))
  534. content (clock/clock-out format content)
  535. content (drawer/insert-drawer
  536. format content "logbook"
  537. (util/format (str (if (= :org format) "-" "*")
  538. " State \"DONE\" from \"%s\" [%s]")
  539. marker
  540. (date/get-date-time-string-3)))]
  541. content)
  542. content))
  543. (defn check
  544. [{:block/keys [marker content repeated? uuid] :as block}]
  545. (let [new-content (string/replace-first content marker "DONE")
  546. new-content (if repeated?
  547. (update-timestamps-content! block content)
  548. new-content)
  549. input-id (state/get-edit-input-id)]
  550. (if (and input-id
  551. (string/ends-with? input-id (str uuid)))
  552. (state/set-edit-content! input-id new-content)
  553. (save-block-if-changed! block new-content))))
  554. (defn uncheck
  555. [{:block/keys [content uuid] :as block}]
  556. (let [marker (if (= :now (state/get-preferred-workflow))
  557. "LATER"
  558. "TODO")
  559. new-content (string/replace-first content "DONE" marker)
  560. input-id (state/get-edit-input-id)]
  561. (if (and input-id
  562. (string/ends-with? input-id (str uuid)))
  563. (state/set-edit-content! input-id new-content)
  564. (save-block-if-changed! block new-content))))
  565. (defn get-selected-blocks
  566. []
  567. (distinct (seq (state/get-selection-blocks))))
  568. (defn set-marker
  569. "The set-marker will set a new marker on the selected block.
  570. if the `new-marker` is nil, it will generate it automatically."
  571. ([block]
  572. (set-marker block nil))
  573. ([{:block/keys [marker content format] :as block} new-marker]
  574. (let [[new-content _] (status/cycle-marker content marker new-marker format (state/get-preferred-workflow))]
  575. (save-block-if-changed! block new-content))))
  576. (defn file-based-cycle-todo!
  577. [block]
  578. (when (not-empty (:block/content block))
  579. (set-marker block)))
  580. (defn db-based-cycle-todo!
  581. [block]
  582. (let [task (db/entity :logseq.class/task)
  583. status-value-id (:logseq.task/status block)
  584. status-value (when status-value-id (db/entity [:block/uuid status-value-id]))
  585. next-status (case (:db/ident status-value)
  586. :logseq.task/status.todo
  587. :logseq.task/status.doing
  588. :logseq.task/status.doing
  589. :logseq.task/status.done
  590. :logseq.task/status.done
  591. nil
  592. :logseq.task/status.todo)]
  593. (if next-status
  594. (outliner-op/save-block! {:db/id (:db/id block)
  595. :logseq.task/status (:block/uuid (db/entity next-status))
  596. :block/tags #{{:db/id (:db/id task)}}})
  597. (db/transact! (state/get-current-repo)
  598. [[:db/retract (:db/id block) :logseq.task/status]]
  599. {:outliner-op :save-block}))))
  600. (defn cycle-todos!
  601. []
  602. (when-let [blocks (seq (get-selected-blocks))]
  603. (let [db-based? (config/db-based-graph? (state/get-current-repo))
  604. ids (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  605. (uuid id)) blocks))
  606. (remove nil?))]
  607. (ui-outliner-tx/transact!
  608. {:outliner-op :cycle-todos}
  609. (doseq [id ids]
  610. (when-let [block (db/entity [:block/uuid id])]
  611. (if db-based?
  612. (db-based-cycle-todo! block)
  613. (file-based-cycle-todo! block))))))))
  614. (defn cycle-todo!
  615. []
  616. #_:clj-kondo/ignore
  617. (when-not (state/get-editor-action)
  618. (if-let [blocks (seq (get-selected-blocks))]
  619. (cycle-todos!)
  620. (when-let [edit-block (state/get-edit-block)]
  621. (let [edit-input-id (state/get-edit-input-id)
  622. current-input (gdom/getElement edit-input-id)]
  623. (if (config/db-based-graph? (state/get-current-repo))
  624. (when-let [block (db/entity (:db/id edit-block))]
  625. (let [pos (state/get-edit-pos)]
  626. (p/do!
  627. (ui-outliner-tx/transact!
  628. {:outliner-op :cycle-todos}
  629. (db-based-cycle-todo! block))
  630. ;; FIXME: don't change current editor's position
  631. )))
  632. (let [content (state/get-edit-content)
  633. format (or (db/get-page-format (state/get-current-page))
  634. (state/get-preferred-format))
  635. [new-content marker] (status/cycle-marker content nil nil format (state/get-preferred-workflow))
  636. new-pos (commands/compute-pos-delta-when-change-marker
  637. content marker (cursor/pos current-input))]
  638. (state/set-edit-content! edit-input-id new-content)
  639. (cursor/move-cursor-to current-input new-pos))))))))
  640. (defn set-priority
  641. [{:block/keys [priority content] :as block} new-priority]
  642. (when-not (config/db-based-graph? (state/get-current-repo))
  643. (let [new-content (string/replace-first content
  644. (util/format "[#%s]" priority)
  645. (util/format "[#%s]" new-priority))]
  646. (save-block-if-changed! block new-content))))
  647. (defn delete-block-aux!
  648. [{:block/keys [uuid repo] :as _block} children? & {:keys [_children-checks?] :as delete-opts}]
  649. (let [repo (or repo (state/get-current-repo))
  650. block (db/pull repo '[*] [:block/uuid uuid])]
  651. (when block
  652. (let [blocks (block-handler/get-top-level-blocks [block])]
  653. (state/set-state! :ui/deleting-block uuid)
  654. (ui-outliner-tx/transact!
  655. {:outliner-op :delete-blocks}
  656. (outliner-op/delete-blocks! blocks
  657. (merge
  658. delete-opts
  659. {:children? children?})))))))
  660. (defn- move-to-prev-block
  661. [repo sibling-block format _id value]
  662. (when (and repo sibling-block)
  663. (when-let [sibling-block-id (dom/attr sibling-block "blockid")]
  664. (when-let [block (db/entity [:block/uuid (uuid sibling-block-id)])]
  665. (if (:block/name block)
  666. (do
  667. (edit-block! block :max (state/get-edit-block-node) {})
  668. {:prev-block block
  669. :new-value (:block/original-name block)})
  670. (let [edit-block (some-> (:db/id (state/get-edit-block)) db/entity)
  671. edit-block-has-refs? (some? (:block/_refs edit-block))
  672. db? (config/db-based-graph? repo)
  673. original-content (util/trim-safe (:block/content block))
  674. value' (if db?
  675. original-content
  676. (-> (property-file/remove-built-in-properties-when-file-based repo format original-content)
  677. (drawer/remove-logbook)))
  678. value (if db?
  679. value
  680. (->> value
  681. (property-file/remove-properties-when-file-based repo format)
  682. (drawer/remove-logbook)))
  683. new-value (str value' value)
  684. tail-len (count value)
  685. pos (max
  686. (if original-content
  687. (gobj/get (utf8/encode original-content) "length")
  688. 0)
  689. 0)
  690. edit-target (if edit-block-has-refs?
  691. (db/pull (:db/id edit-block))
  692. (db/pull (:db/id block)))]
  693. (edit-block! edit-target
  694. pos
  695. (state/get-edit-block-node)
  696. {:custom-content new-value
  697. :tail-len tail-len})
  698. {:prev-block block
  699. :new-content new-value
  700. :pos pos}))))))
  701. (declare save-block!)
  702. (defn- block-has-no-ref?
  703. [eid]
  704. (empty? (:block/_refs (db/entity eid))))
  705. (declare expand-block!)
  706. (defn delete-block!
  707. [repo delete-children?]
  708. (let [{:keys [id block-id block-parent-id value format config]} (get-state)]
  709. (when block-id
  710. (when-let [block-e (db/entity [:block/uuid block-id])]
  711. (let [prev-block (db-model/get-prev (db/get-db) (:db/id block-e))]
  712. (cond
  713. (nil? prev-block)
  714. nil
  715. :else
  716. (let [has-children? (seq (:block/_parent block-e))
  717. block (db/pull (:db/id block-e))
  718. left (otree/-get-left (outliner-core/block (db/get-db) block) (db/get-db false))
  719. left-has-children? (and left
  720. (when-let [block-id (:block/uuid (:data left))]
  721. (let [block (db/entity [:block/uuid block-id])]
  722. (seq (:block/_parent block)))))
  723. delete-block-fn (fn [block]
  724. (delete-block-aux! block delete-children? {:children-check? false}))]
  725. (when-not (and has-children? left-has-children?)
  726. (when block-parent-id
  727. (let [block-parent (gdom/getElement block-parent-id)
  728. sibling-block (if (:embed? config)
  729. (util/get-prev-block-non-collapsed
  730. block-parent
  731. {:container (util/rec-get-blocks-container block-parent)})
  732. (util/get-prev-block-non-collapsed-non-embed block-parent))
  733. {:keys [prev-block new-content]} (move-to-prev-block repo sibling-block format id value)
  734. concat-prev-block? (boolean (and prev-block new-content))
  735. transact-opts {:outliner-op :delete-blocks}
  736. db-based? (config/db-based-graph? repo)
  737. db (db/get-db repo)]
  738. (ui-outliner-tx/transact!
  739. transact-opts
  740. (cond
  741. (and prev-block (:block/name prev-block)
  742. (not= (:db/id prev-block) (:db/id (:block/parent block)))
  743. (db-model/hidden-page? (:block/page block))) ; embed page
  744. nil
  745. concat-prev-block?
  746. (let [prev-e (db/entity (:db/id prev-block))
  747. current-e (db/entity (:db/id block))
  748. new-properties (merge (:block/properties prev-e)
  749. (:block/properties current-e))
  750. new-tags (->> (concat (:block/tags prev-e) (:block/tags current-e)))]
  751. (if (seq (:block/_refs (db/entity (:db/id block))))
  752. (do
  753. (delete-block-fn prev-block)
  754. (save-block! repo block new-content {})
  755. (outliner-save-block! {:db/id (:db/id block)
  756. :block/parent (:db/id (:block/parent prev-block))
  757. :block/left (or (:db/id (:block/left prev-block))
  758. (:db/id (:block/parent prev-block)))})
  759. ;; block->right needs to point its `left` to block->left
  760. (let [block-right (outliner-core/get-right-sibling db (:db/id block))]
  761. (when (and block-right (not= (:db/id (:block/parent prev-block))
  762. (:db/id (:block/parent block))))
  763. (outliner-save-block! {:db/id (:db/id block-right)
  764. :block/left (:db/id (:block/left block))})))
  765. ;; update prev-block's children to point to the refed block
  766. (when (or (:block/collapsed? prev-block)
  767. (= (:db/id prev-block) (:db/id (:block/parent block))))
  768. (let [children (:block/_parent prev-block)]
  769. (doseq [child children]
  770. (when-not (= (:db/id child) (:db/id block))
  771. (outliner-save-block! {:db/id (:db/id child)
  772. :block/parent (:db/id block)
  773. :block/left (:db/id block)})))))
  774. ;; parent will be removed
  775. (when (= (:db/id prev-block) (:db/id (:block/parent block)))
  776. (when-let [parent-right (when prev-block (outliner-core/get-right-sibling db (:db/id prev-block)))]
  777. (outliner-save-block! {:db/id (:db/id parent-right)
  778. :block/left (:db/id block)})))
  779. (when db-based?
  780. (outliner-save-block! {:db/id (:db/id block)
  781. :block/properties new-properties
  782. :block/tags new-tags})))
  783. (do
  784. (delete-block-fn block)
  785. (save-block! repo prev-block new-content {})
  786. (when db-based?
  787. (outliner-save-block! {:db/id (:db/id prev-block)
  788. :block/properties new-properties
  789. :block/tags new-tags})))))
  790. :else
  791. (delete-block-fn block)))))))))))))
  792. (defn delete-blocks!
  793. [repo block-uuids blocks dom-blocks]
  794. (when (seq block-uuids)
  795. (let [uuid->dom-block (zipmap block-uuids dom-blocks)
  796. block (first blocks)
  797. block-parent (get uuid->dom-block (:block/uuid block))
  798. sibling-block (when block-parent (util/get-prev-block-non-collapsed-non-embed block-parent))
  799. blocks' (block-handler/get-top-level-blocks blocks)]
  800. (p/do!
  801. (ui-outliner-tx/transact!
  802. {:outliner-op :delete-blocks}
  803. (outliner-op/delete-blocks! blocks' nil))
  804. (when sibling-block
  805. (move-to-prev-block repo sibling-block
  806. (:block/format block)
  807. (dom/attr sibling-block "id")
  808. ""))))))
  809. (defn set-block-query-properties!
  810. [block-id all-properties key add?]
  811. (when-let [block (db/entity [:block/uuid block-id])]
  812. (let [query-properties (get block (pu/get-pid :logseq.property/query-properties))
  813. repo (state/get-current-repo)
  814. db-based? (config/db-based-graph? repo)
  815. query-properties (if db-based?
  816. query-properties
  817. (some-> query-properties
  818. (common-handler/safe-read-string "Parsing query properties failed")))
  819. query-properties (if (seq query-properties)
  820. query-properties
  821. all-properties)
  822. query-properties (if add?
  823. (distinct (conj query-properties key))
  824. (remove #{key} query-properties))
  825. query-properties (vec query-properties)]
  826. (if (seq query-properties)
  827. (property-handler/set-block-property! repo block-id
  828. (pu/get-pid :logseq.property/query-properties)
  829. (if db-based?
  830. query-properties
  831. (str query-properties)))
  832. (property-handler/remove-block-property! repo block-id (pu/get-pid :logseq.property/query-properties))))))
  833. (defn set-block-timestamp!
  834. [block-id key value]
  835. (let [key (string/lower-case (str key))
  836. block-id (if (string? block-id) (uuid block-id) block-id)
  837. value (str value)]
  838. (when-let [block (db/pull [:block/uuid block-id])]
  839. (let [{:block/keys [content]} block
  840. content (or content (state/get-edit-content))
  841. new-content (-> (text-util/remove-timestamp content key)
  842. (text-util/add-timestamp key value))]
  843. (when (not= content new-content)
  844. (let [input-id (state/get-edit-input-id)]
  845. (if (and input-id
  846. (string/ends-with? input-id (str block-id)))
  847. (state/set-edit-content! input-id new-content)
  848. (save-block-if-changed! block new-content))))))))
  849. (defn set-editing-block-timestamp!
  850. "Almost the same as set-block-timestamp! except for:
  851. - it doesn't save the block
  852. - it extracts current content from current input"
  853. [key value]
  854. (let [key (string/lower-case (str key))
  855. value (str value)
  856. content (state/get-edit-content)
  857. new-content (-> (text-util/remove-timestamp content key)
  858. (text-util/add-timestamp key value))]
  859. (when (not= content new-content)
  860. (let [input-id (state/get-edit-input-id)]
  861. (state/set-edit-content! input-id new-content)))))
  862. (defn set-blocks-id!
  863. "Persist block uuid to file if the uuid is valid, and it's not persisted in file.
  864. Accepts a list of uuids."
  865. [block-ids]
  866. (let [repo (state/get-current-repo)]
  867. (when-not (config/db-based-graph? repo)
  868. (file-editor-handler/set-blocks-id! block-ids))))
  869. (defn copy-block-ref!
  870. ([block-id]
  871. (copy-block-ref! block-id #(str %)))
  872. ([block-id tap-clipboard]
  873. (p/do!
  874. (save-current-block!)
  875. (set-blocks-id! [block-id])
  876. (util/copy-to-clipboard! (tap-clipboard block-id)))))
  877. (defn select-block!
  878. [block-uuid]
  879. (block-handler/select-block! block-uuid))
  880. (defn- compose-copied-blocks-contents
  881. [repo block-ids]
  882. (let [blocks (db-utils/pull-many repo '[*] (mapv (fn [id] [:block/uuid id]) block-ids))
  883. top-level-block-uuids (->> (block-handler/get-top-level-blocks blocks)
  884. (map :block/uuid))
  885. content (export-text/export-blocks-as-markdown
  886. repo top-level-block-uuids
  887. {:indent-style (state/get-export-block-text-indent-style)
  888. :remove-options (set (state/get-export-block-text-remove-options))})]
  889. [top-level-block-uuids content]))
  890. (defn- get-all-blocks-by-ids
  891. [repo ids]
  892. (loop [ids ids
  893. result []]
  894. (if (seq ids)
  895. (let [db-id (:db/id (db/entity [:block/uuid (first ids)]))
  896. blocks (tree/get-sorted-block-and-children repo db-id)
  897. result (vec (concat result blocks))]
  898. (recur (remove (set (map :block/uuid result)) (rest ids)) result))
  899. result)))
  900. (defn copy-selection-blocks
  901. [html?]
  902. (when-let [blocks (seq (state/get-selection-blocks))]
  903. (let [repo (state/get-current-repo)
  904. ids (distinct (keep #(when-let [id (dom/attr % "blockid")]
  905. (uuid id)) blocks))
  906. [top-level-block-uuids content] (compose-copied-blocks-contents repo ids)
  907. block (db/entity [:block/uuid (first ids)])]
  908. (when block
  909. (let [html (export-html/export-blocks-as-html repo top-level-block-uuids nil)
  910. copied-blocks (get-all-blocks-by-ids repo top-level-block-uuids)]
  911. (common-handler/copy-to-clipboard-without-id-property! repo (:block/format block) content (when html? html) copied-blocks))
  912. (state/set-block-op-type! :copy)
  913. (notification/show! "Copied!" :success)))))
  914. (defn copy-block-refs
  915. []
  916. (when-let [selected-blocks (seq (get-selected-blocks))]
  917. (let [blocks (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  918. (let [level (dom/attr % "level")]
  919. {:id (uuid id)
  920. :level (int level)}))
  921. selected-blocks))
  922. (remove nil?))
  923. first-block (first blocks)
  924. first-root-level-index (ffirst
  925. (filter (fn [[_ block]] (= (:level block) 1))
  926. (map-indexed vector blocks)))
  927. root-level (atom (:level first-block))
  928. adjusted-blocks (map-indexed
  929. (fn [index {:keys [id level]}]
  930. {:id id
  931. :level (if (< index first-root-level-index)
  932. (if (< level @root-level)
  933. (do
  934. (reset! root-level level)
  935. 1)
  936. (inc (- level @root-level)))
  937. level)})
  938. blocks)
  939. block (db/pull [:block/uuid (:id first-block)])
  940. copy-str (some->> adjusted-blocks
  941. (map (fn [{:keys [id level]}]
  942. (condp = (:block/format block)
  943. :org
  944. (str (string/join (repeat level "*")) " " (block-ref/->block-ref id))
  945. :markdown
  946. (str (string/join (repeat (dec level) "\t")) "- " (block-ref/->block-ref id)))))
  947. (string/join "\n\n"))]
  948. (set-blocks-id! (map :id blocks))
  949. (util/copy-to-clipboard! copy-str))))
  950. (defn copy-block-embeds
  951. []
  952. (when-let [blocks (seq (get-selected-blocks))]
  953. (let [ids (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  954. (uuid id)) blocks))
  955. (remove nil?))
  956. ids-str (some->> ids
  957. (map (fn [id] (util/format "{{embed ((%s))}}" id)))
  958. (string/join "\n\n"))]
  959. (set-blocks-id! ids)
  960. (util/copy-to-clipboard! ids-str))))
  961. (defn get-selected-toplevel-block-uuids
  962. []
  963. (when-let [blocks (seq (get-selected-blocks))]
  964. (let [repo (state/get-current-repo)
  965. block-ids (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  966. (uuid id)) blocks))
  967. (remove nil?))
  968. blocks (db-utils/pull-many repo '[*] (mapv (fn [id] [:block/uuid id]) block-ids))
  969. page-id (:db/id (:block/page (first blocks)))
  970. ;; filter out blocks not belong to page with 'page-id'
  971. blocks* (remove (fn [block] (some-> (:db/id (:block/page block)) (not= page-id))) blocks)]
  972. (->> (block-handler/get-top-level-blocks blocks*)
  973. (map :block/uuid)))))
  974. (defn cut-selection-blocks
  975. [copy?]
  976. (when copy? (copy-selection-blocks true))
  977. (state/set-block-op-type! :cut)
  978. (when-let [blocks (seq (get-selected-blocks))]
  979. ;; remove queries
  980. (let [dom-blocks (remove (fn [block]
  981. (= "true" (dom/attr block "data-query"))) blocks)]
  982. (when (seq dom-blocks)
  983. (let [repo (state/get-current-repo)
  984. block-uuids (distinct (map #(uuid (dom/attr % "blockid")) dom-blocks))
  985. lookup-refs (map (fn [id] [:block/uuid id]) block-uuids)
  986. blocks (db/pull-many repo '[*] lookup-refs)
  987. top-level-blocks (block-handler/get-top-level-blocks blocks)
  988. sorted-blocks (mapcat (fn [block]
  989. (tree/get-sorted-block-and-children repo (:db/id block)))
  990. top-level-blocks)]
  991. (delete-blocks! repo (map :block/uuid sorted-blocks) sorted-blocks dom-blocks))))))
  992. (def url-regex
  993. "Didn't use link/plain-link as it is incorrectly detects words as urls."
  994. #"[^\s\(\[]+://[^\s\)\]]+")
  995. (defn extract-nearest-link-from-text
  996. [text pos & additional-patterns]
  997. (let [;; didn't use page-ref regexs b/c it handles page-ref and org link cases
  998. page-pattern #"\[\[([^\]]+)]]"
  999. tag-pattern #"#\S+"
  1000. page-matches (util/re-pos page-pattern text)
  1001. block-matches (util/re-pos block-ref/block-ref-re text)
  1002. tag-matches (util/re-pos tag-pattern text)
  1003. additional-matches (mapcat #(util/re-pos % text) additional-patterns)
  1004. matches (->> (concat page-matches block-matches tag-matches additional-matches)
  1005. (remove nil?))
  1006. [_ match] (first (sort-by
  1007. (fn [[start-pos content]]
  1008. (let [end-pos (+ start-pos (count content))]
  1009. (cond
  1010. (< pos start-pos)
  1011. (- pos start-pos)
  1012. (> pos end-pos)
  1013. (- end-pos pos)
  1014. :else
  1015. 0)))
  1016. >
  1017. matches))]
  1018. (when match
  1019. (cond
  1020. (some #(re-find % match) additional-patterns)
  1021. match
  1022. (string/starts-with? match "#")
  1023. (subs match 1 (count match))
  1024. :else
  1025. (subs match 2 (- (count match) 2))))))
  1026. (defn- get-nearest-page-or-url
  1027. "Return the nearest page-name (not dereferenced, may be an alias), block, tag or url"
  1028. []
  1029. (when-let [block (state/get-edit-block)]
  1030. (when (:block/uuid block)
  1031. (when-let [edit-id (state/get-edit-input-id)]
  1032. (when-let [input (gdom/getElement edit-id)]
  1033. (when-let [pos (cursor/pos input)]
  1034. (let [value (gobj/get input "value")]
  1035. (extract-nearest-link-from-text value pos url-regex))))))))
  1036. (defn- get-nearest-page
  1037. "Return the nearest page-name (not dereferenced, may be an alias), block or tag"
  1038. []
  1039. (when-let [block (state/get-edit-block)]
  1040. (when (:block/uuid block)
  1041. (when-let [edit-id (state/get-edit-input-id)]
  1042. (when-let [input (gdom/getElement edit-id)]
  1043. (when-let [pos (cursor/pos input)]
  1044. (let [value (gobj/get input "value")]
  1045. (extract-nearest-link-from-text value pos))))))))
  1046. (defn follow-link-under-cursor!
  1047. []
  1048. (when-let [page (get-nearest-page-or-url)]
  1049. (when-not (string/blank? page)
  1050. (p/do!
  1051. (state/clear-editor-action!)
  1052. (save-current-block!)
  1053. (if (re-find url-regex page)
  1054. (js/window.open page)
  1055. (let [page-name (db-model/get-redirect-page-name page)]
  1056. (state/clear-edit!)
  1057. (insert-first-page-block-if-not-exists! page-name)))))))
  1058. (defn open-link-in-sidebar!
  1059. []
  1060. (when-let [page (get-nearest-page)]
  1061. (let [page-name (string/lower-case page)
  1062. block? (util/uuid-string? page-name)]
  1063. (when-let [page (db/get-page page-name)]
  1064. (if block?
  1065. (state/sidebar-add-block!
  1066. (state/get-current-repo)
  1067. (:db/id page)
  1068. :block)
  1069. (state/sidebar-add-block!
  1070. (state/get-current-repo)
  1071. (:db/id page)
  1072. :page))))))
  1073. (declare save-current-block!)
  1074. (defn zoom-in! []
  1075. (if (state/editing?)
  1076. (when-let [id (some-> (state/get-edit-block)
  1077. :block/uuid
  1078. ((fn [id] [:block/uuid id]))
  1079. db/entity
  1080. :block/uuid)]
  1081. (state/clear-editor-action!)
  1082. (p/do!
  1083. (save-current-block!)
  1084. (let [pos (state/get-edit-pos)]
  1085. (route-handler/redirect-to-page! id)
  1086. (util/schedule #(edit-block! {:block/uuid id} pos nil)))))
  1087. (js/window.history.forward)))
  1088. (defn zoom-out!
  1089. []
  1090. (if (state/editing?)
  1091. (let [page (state/get-current-page)
  1092. block-id (and (string? page) (parse-uuid page))]
  1093. (p/do!
  1094. (state/clear-editor-action!)
  1095. (save-current-block!)
  1096. (when block-id
  1097. (let [block-parent (db/get-block-parent block-id)]
  1098. (if-let [id (and
  1099. (nil? (:block/name block-parent))
  1100. (:block/uuid block-parent))]
  1101. (do
  1102. (route-handler/redirect-to-page! id)
  1103. (util/schedule #(edit-block! {:block/uuid block-id} :max nil)))
  1104. (let [page-id (some-> (db/entity [:block/uuid block-id])
  1105. :block/page
  1106. :db/id)]
  1107. (when-let [page (db/entity page-id)]
  1108. (route-handler/redirect-to-page! (:block/uuid page))
  1109. (util/schedule #(edit-block! {:block/uuid block-id} :max nil)))))))))
  1110. (js/window.history.back)))
  1111. (defn cut-block!
  1112. [block-id]
  1113. (when-let [block (db/pull [:block/uuid block-id])]
  1114. (let [repo (state/get-current-repo)
  1115. ;; TODO: support org mode
  1116. [_top-level-block-uuids md-content] (compose-copied-blocks-contents repo [block-id])
  1117. html (export-html/export-blocks-as-html repo [block-id] nil)
  1118. sorted-blocks (tree/get-sorted-block-and-children repo (:db/id block))]
  1119. (common-handler/copy-to-clipboard-without-id-property! repo (:block/format block) md-content html sorted-blocks)
  1120. (state/set-block-op-type! :cut)
  1121. (delete-block-aux! block true))))
  1122. (defn highlight-selection-area!
  1123. ([end-block]
  1124. (highlight-selection-area! end-block false))
  1125. ([end-block append?]
  1126. (when-let [start-block (state/get-selection-start-block-or-first)]
  1127. (let [blocks (util/get-nodes-between-two-nodes start-block end-block "ls-block")
  1128. direction (util/get-direction-between-two-nodes start-block end-block "ls-block")
  1129. blocks (if (= :up direction)
  1130. (reverse blocks)
  1131. blocks)]
  1132. (if append?
  1133. (do (state/clear-edit!)
  1134. (state/conj-selection-block! blocks direction))
  1135. (state/exit-editing-and-set-selected-blocks! blocks direction))))))
  1136. (defn- select-block-up-down
  1137. [direction]
  1138. (cond
  1139. ;; when editing, quit editing and select current block
  1140. (state/editing?)
  1141. (let [element (gdom/getElement (state/get-editing-block-dom-id))]
  1142. (when element
  1143. (util/scroll-to-block element)
  1144. (state/exit-editing-and-set-selected-blocks! [element])))
  1145. ;; when selection and one block selected, select next block
  1146. (and (state/selection?) (== 1 (count (state/get-selection-blocks))))
  1147. (let [f (if (= :up direction) util/get-prev-block-non-collapsed util/get-next-block-non-collapsed-skip)
  1148. element (f (first (state/get-selection-blocks)))]
  1149. (when element
  1150. (util/scroll-to-block element)
  1151. (state/conj-selection-block! element direction)))
  1152. ;; if same direction, keep conj on same direction
  1153. (and (state/selection?) (= direction (state/get-selection-direction)))
  1154. (let [f (if (= :up direction) util/get-prev-block-non-collapsed util/get-next-block-non-collapsed-skip)
  1155. first-last (if (= :up direction) first last)
  1156. element (f (first-last (state/get-selection-blocks)))]
  1157. (when element
  1158. (util/scroll-to-block element)
  1159. (state/conj-selection-block! element direction)))
  1160. ;; if different direction, keep clear until one left
  1161. (state/selection?)
  1162. (let [f (if (= :up direction) util/get-prev-block-non-collapsed util/get-next-block-non-collapsed)
  1163. last-first (if (= :up direction) last first)
  1164. element (f (last-first (state/get-selection-blocks)))]
  1165. (when element
  1166. (util/scroll-to-block element)
  1167. (state/drop-last-selection-block!))))
  1168. nil)
  1169. (defn on-select-block
  1170. [direction]
  1171. (fn [_event]
  1172. (select-block-up-down direction)))
  1173. (defn save-block-aux!
  1174. [block value opts]
  1175. (let [entity (db/entity [:block/uuid (:block/uuid block)])]
  1176. (when (and (:db/id entity)
  1177. (not (contains? (:block/type entity) "property")))
  1178. (let [value (string/trim value)]
  1179. ;; FIXME: somehow frontend.components.editor's will-unmount event will loop forever
  1180. ;; maybe we shouldn't save the block/file in "will-unmount" event?
  1181. (if (:block/original-name entity)
  1182. (let [existing-tags (:block/tags block)
  1183. tags (mldoc/extract-tags value)]
  1184. (when (seq tags)
  1185. (let [tag-pages (concat
  1186. (map #(block/page-name->map % true) tags)
  1187. (map :db/id existing-tags))
  1188. opts {:outliner-op :save-block}]
  1189. (ui-outliner-tx/transact!
  1190. opts
  1191. (outliner-save-block! {:db/id (:db/id block)
  1192. :block/tags tag-pages})))))
  1193. (save-block-if-changed! block value opts))))))
  1194. (defn save-block!
  1195. ([repo block-or-uuid content]
  1196. (save-block! repo block-or-uuid content {}))
  1197. ([repo block-or-uuid content {:keys [properties] :as opts}]
  1198. (let [block (if (or (uuid? block-or-uuid)
  1199. (string? block-or-uuid))
  1200. (db-model/query-block-by-uuid block-or-uuid) block-or-uuid)]
  1201. (save-block!
  1202. {:block block :repo repo :opts (dissoc opts :properties)}
  1203. (if (seq properties)
  1204. (property-file/insert-properties-when-file-based repo (:block/format block) content properties)
  1205. content))))
  1206. ([{:keys [block repo opts] :as _state} value]
  1207. (let [repo (or repo (state/get-current-repo))]
  1208. (when (db/entity repo [:block/uuid (:block/uuid block)])
  1209. (save-block-aux! block value opts)))))
  1210. (defn save-blocks!
  1211. [blocks]
  1212. (ui-outliner-tx/transact!
  1213. {:outliner-op :save-block}
  1214. (doseq [[block value] blocks]
  1215. (save-block-if-changed! block value))))
  1216. (defn save-current-block!
  1217. "skip-properties? if set true, when editing block is likely be properties, skip saving"
  1218. ([]
  1219. (save-current-block! {}))
  1220. ([{:keys [force? skip-properties? current-block] :as opts}]
  1221. ;; non English input method
  1222. (when-not (or (state/editor-in-composition?)
  1223. (state/get-editor-action))
  1224. (when (state/get-current-repo)
  1225. (try
  1226. (let [input-id (state/get-edit-input-id)
  1227. block (state/get-edit-block)
  1228. db-block (when-let [block-id (:block/uuid block)]
  1229. (db/pull [:block/uuid block-id]))
  1230. elem (and input-id (gdom/getElement input-id))
  1231. db-content (:block/content db-block)
  1232. db-content-without-heading (and db-content
  1233. (common-util/safe-subs db-content (:block/level db-block)))
  1234. value (if (= (:block/uuid current-block) (:block/uuid block))
  1235. (:block/content current-block)
  1236. (and elem (gobj/get elem "value")))]
  1237. (when value
  1238. (cond
  1239. force?
  1240. (save-block-aux! db-block value opts)
  1241. (and skip-properties?
  1242. (db-model/top-block? block)
  1243. (when elem (thingatpt/properties-at-point elem)))
  1244. nil
  1245. (and block value db-content-without-heading
  1246. (not= (string/trim db-content-without-heading)
  1247. (string/trim value)))
  1248. (save-block-aux! db-block value opts))))
  1249. (catch :default error
  1250. (log/error :save-block-failed error)))))))
  1251. (defn- clean-content!
  1252. [repo format content]
  1253. (if (config/db-based-graph? repo)
  1254. content
  1255. (some->> (text/remove-level-spaces content format (config/get-block-pattern format))
  1256. (drawer/remove-logbook)
  1257. (property-file/remove-properties-when-file-based repo format)
  1258. string/trim)))
  1259. (defn insert-command!
  1260. [id command-output format {:keys [restore?]
  1261. :or {restore? true}
  1262. :as option}]
  1263. (cond
  1264. ;; replace string
  1265. (string? command-output)
  1266. (commands/insert! id command-output option)
  1267. ;; steps
  1268. (vector? command-output)
  1269. (commands/handle-steps command-output format)
  1270. (fn? command-output)
  1271. (let [s (command-output)]
  1272. (commands/insert! id s option))
  1273. :else
  1274. nil)
  1275. (when restore?
  1276. (commands/restore-state)))
  1277. (defn- ensure-assets-dir!
  1278. [repo]
  1279. (p/let [repo-dir (config/get-repo-dir repo)
  1280. assets-dir "assets"
  1281. _ (fs/mkdir-if-not-exists (path/path-join repo-dir assets-dir))]
  1282. [repo-dir assets-dir]))
  1283. (defn get-asset-path
  1284. "Get asset path from filename, ensure assets dir exists"
  1285. [filename]
  1286. (p/let [[repo-dir assets-dir] (ensure-assets-dir! (state/get-current-repo))]
  1287. (path/path-join repo-dir assets-dir filename)))
  1288. (defn save-assets!
  1289. "Save incoming(pasted) assets to assets directory.
  1290. Returns: [file-rpath file-obj file-fpath matched-alias]"
  1291. ([repo files]
  1292. (p/let [[repo-dir assets-dir] (ensure-assets-dir! repo)]
  1293. (save-assets! repo repo-dir assets-dir files
  1294. (fn [index file-stem]
  1295. ;; TODO: maybe there're other chars we need to handle?
  1296. (let [file-base (-> file-stem
  1297. (string/replace " " "_")
  1298. (string/replace "%" "_")
  1299. (string/replace "/" "_"))
  1300. file-name (str file-base "_" (.now js/Date) "_" index)]
  1301. (string/replace file-name #"_+" "_"))))))
  1302. ([repo repo-dir asset-dir-rpath files gen-filename]
  1303. (p/all
  1304. (for [[index ^js file] (map-indexed vector files)]
  1305. ;; WARN file name maybe fully qualified path when paste file
  1306. (let [file-name (util/node-path.basename (.-name file))
  1307. [file-stem ext-full ext-base] (if file-name
  1308. (let [ext-base (util/node-path.extname file-name)
  1309. ext-full (if-not (config/extname-of-supported? ext-base)
  1310. (util/full-path-extname file-name) ext-base)]
  1311. [(subs file-name 0 (- (count file-name)
  1312. (count ext-full))) ext-full ext-base])
  1313. ["" "" ""])
  1314. filename (str (gen-filename index file-stem) ext-full)
  1315. file-rpath (str asset-dir-rpath "/" filename)
  1316. matched-alias (assets-handler/get-matched-alias-by-ext ext-base)
  1317. file-rpath (cond-> file-rpath
  1318. (not (nil? matched-alias))
  1319. (string/replace #"^[.\/\\]*assets[\/\\]+" ""))
  1320. dir (or (:dir matched-alias) repo-dir)]
  1321. (if (util/electron?)
  1322. (let [from (not-empty (.-path file))]
  1323. (js/console.debug "Debug: Copy Asset #" dir file-rpath from)
  1324. (-> (js/window.apis.copyFileToAssets dir file-rpath from)
  1325. (p/then
  1326. (fn [dest]
  1327. [file-rpath
  1328. (if (string? dest) (js/File. #js[] dest) file)
  1329. (path/path-join dir file-rpath)
  1330. matched-alias]))
  1331. (p/catch #(js/console.error "Debug: Copy Asset Error#" %))))
  1332. (p/do! (js/console.debug "Debug: Writing Asset #" dir file-rpath)
  1333. (cond
  1334. (mobile-util/native-platform?)
  1335. ;; capacitor fs accepts Blob, File implements Blob
  1336. (p/let [buffer (.arrayBuffer file)
  1337. content (base64/encodeByteArray (js/Uint8Array. buffer))
  1338. fpath (path/path-join dir file-rpath)]
  1339. (capacitor-fs/<write-file-with-base64 fpath content))
  1340. (config/db-based-graph? repo) ;; memory-fs
  1341. (p/let [buffer (.arrayBuffer file)
  1342. content (js/Uint8Array. buffer)]
  1343. (fs/write-file! repo dir file-rpath content nil))
  1344. :else ; nfs
  1345. (fs/write-file! repo dir file-rpath (.stream file) nil))
  1346. [file-rpath file (path/path-join dir file-rpath) matched-alias])))))))
  1347. (defn delete-asset-of-block!
  1348. [{:keys [repo href full-text block-id local? delete-local?] :as _opts}]
  1349. (let [block (db-model/query-block-by-uuid block-id)
  1350. _ (or block (throw (str block-id " not exists")))
  1351. text (:block/content block)
  1352. content (string/replace text full-text "")]
  1353. (save-block! repo block content)
  1354. (when (and local? delete-local?)
  1355. (when-let [href (if (util/electron?) href
  1356. (second (re-find #"\((.+)\)$" full-text)))]
  1357. (let [block-file-rpath (db-model/get-block-file-path block)
  1358. asset-fpath (if (string/starts-with? href "assets://")
  1359. (path/url-to-path href)
  1360. (config/get-repo-fpath
  1361. repo
  1362. (path/resolve-relative-path block-file-rpath href)))]
  1363. (prn ::deleting-asset href asset-fpath)
  1364. (fs/unlink! repo asset-fpath nil))))))
  1365. ;; assets/journals_2021_02_03_1612350230540_0.png
  1366. (defn resolve-relative-path
  1367. "Relative path to current file path.
  1368. Requires editing state"
  1369. [file-path]
  1370. (if-let [current-file-rpath (or (db-model/get-block-file-path (state/get-edit-block))
  1371. ;; fix dummy file path of page
  1372. (when (config/get-pages-directory)
  1373. (path/path-join (config/get-pages-directory) "_.md"))
  1374. "pages/contents.md")]
  1375. (let [repo-dir (config/get-repo-dir (state/get-current-repo))
  1376. current-file-fpath (path/path-join repo-dir current-file-rpath)]
  1377. (path/get-relative-path current-file-fpath file-path))
  1378. file-path))
  1379. (defn upload-asset
  1380. "Paste asset and insert link to current editing block"
  1381. [id ^js files format uploading? drop-or-paste?]
  1382. (let [repo (state/get-current-repo)]
  1383. (when (or (config/local-file-based-graph? repo)
  1384. (config/db-based-graph? repo))
  1385. (-> (save-assets! repo (js->clj files))
  1386. ;; FIXME: only the first asset is handled
  1387. (p/then
  1388. (fn [res]
  1389. (when-let [[asset-file-name file-obj asset-file-fpath matched-alias] (and (seq res) (first res))]
  1390. (let [image? (config/ext-of-image? asset-file-name)]
  1391. (insert-command!
  1392. id
  1393. (assets-handler/get-asset-file-link format
  1394. (if matched-alias
  1395. (str
  1396. (if image? "../assets/" "")
  1397. "@" (:name matched-alias) "/" asset-file-name)
  1398. (resolve-relative-path (or asset-file-fpath asset-file-name)))
  1399. (if file-obj (.-name file-obj) (if image? "image" "asset"))
  1400. image?)
  1401. format
  1402. {:last-pattern (if drop-or-paste? "" commands/command-trigger)
  1403. :restore? true
  1404. :command :insert-asset})))))
  1405. (p/catch (fn [e]
  1406. (js/console.error e)))
  1407. (p/finally
  1408. (fn []
  1409. (reset! uploading? false)
  1410. (reset! *asset-uploading? false)
  1411. (reset! *asset-uploading-process 0)))))))
  1412. ;; Editor should track some useful information, like editor modes.
  1413. ;; For example:
  1414. ;; 1. Which file format is it, markdown or org mode?
  1415. ;; 2. Is it in the properties area? Then we can enable the ":" autopair
  1416. (def autopair-map
  1417. {"[" "]"
  1418. "{" "}"
  1419. "(" ")"
  1420. "`" "`"
  1421. "~" "~"
  1422. "*" "*"
  1423. "_" "_"
  1424. "^" "^"
  1425. "=" "="
  1426. "/" "/"
  1427. "+" "+"})
  1428. ;; ":" ":" ; TODO: only properties editing and org mode tag
  1429. (def reversed-autopair-map
  1430. (zipmap (vals autopair-map)
  1431. (keys autopair-map)))
  1432. (def autopair-when-selected
  1433. #{"*" "^" "_" "=" "+" "/"})
  1434. (def delete-map
  1435. (assoc autopair-map
  1436. "$" "$"
  1437. ":" ":"))
  1438. (defn- autopair
  1439. [input-id prefix _format _option]
  1440. (let [value (get autopair-map prefix)
  1441. selected (util/get-selected-text)
  1442. postfix (str selected value)
  1443. value (str prefix postfix)
  1444. input (gdom/getElement input-id)]
  1445. (when value
  1446. (let [[prefix _pos] (commands/simple-replace! input-id value selected
  1447. {:backward-pos (count postfix)
  1448. :check-fn (fn [new-value prefix-pos]
  1449. (when (>= prefix-pos 0)
  1450. [(subs new-value prefix-pos (+ prefix-pos 2))
  1451. (+ prefix-pos 2)]))})]
  1452. (cond
  1453. (= prefix page-ref/left-brackets)
  1454. (do
  1455. (commands/handle-step [:editor/search-page])
  1456. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)
  1457. :selected selected}))
  1458. (= prefix block-ref/left-parens)
  1459. (do
  1460. (commands/handle-step [:editor/search-block :reference])
  1461. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)
  1462. :selected selected})))))))
  1463. (defn surround-by?
  1464. [input before end]
  1465. (when input
  1466. (let [value (gobj/get input "value")
  1467. pos (cursor/pos input)]
  1468. (text-util/surround-by? value pos before end))))
  1469. (defn- autopair-left-paren?
  1470. [input key]
  1471. (and (= key "(")
  1472. (or (surround-by? input :start "")
  1473. (surround-by? input "\n" "")
  1474. (surround-by? input " " "")
  1475. (surround-by? input "]" "")
  1476. (surround-by? input "(" ""))))
  1477. (defn wrapped-by?
  1478. [input before end]
  1479. (when input
  1480. (let [value (gobj/get input "value")
  1481. pos (cursor/pos input)]
  1482. (when (>= pos 0)
  1483. (text-util/wrapped-by? value pos before end)))))
  1484. (defn <get-matched-pages
  1485. "Return matched page names"
  1486. [q]
  1487. (p/let [block (state/get-edit-block)
  1488. editing-page (and block
  1489. (when-let [page-id (:db/id (:block/page block))]
  1490. (:block/name (db/entity page-id))))
  1491. pages (search/page-search q)]
  1492. (if editing-page
  1493. ;; To prevent self references
  1494. (remove (fn [p] (= (util/page-name-sanity-lc p) editing-page)) pages)
  1495. pages)))
  1496. (comment
  1497. (defn get-matched-classes
  1498. "Return matched class names"
  1499. [q]
  1500. (let [classes (->> (db-model/get-all-classes (state/get-current-repo))
  1501. (map first))]
  1502. (search/fuzzy-search classes q {:limit 100}))))
  1503. (defn get-matched-blocks
  1504. [q block-id]
  1505. ;; remove current block
  1506. (let [current-block (state/get-edit-block)
  1507. block-parents (set (->> (db/get-block-parents (state/get-current-repo)
  1508. block-id
  1509. {:depth 99})
  1510. (map (comp str :block/uuid))))
  1511. current-and-parents (set/union #{(str (:block/uuid current-block))} block-parents)]
  1512. (p/let [result (search/block-search (state/get-current-repo) q {:limit 20})]
  1513. (remove
  1514. (fn [h]
  1515. (contains? current-and-parents (:block/uuid h)))
  1516. result))))
  1517. (defn <get-matched-templates
  1518. [q]
  1519. (search/template-search q))
  1520. (defn <get-matched-properties
  1521. [q]
  1522. (search/property-search q))
  1523. (defn get-matched-property-values
  1524. [property q]
  1525. (search/property-value-search property q))
  1526. (defn get-matched-commands
  1527. [input]
  1528. (try
  1529. (let [edit-content (or (gobj/get input "value") "")
  1530. pos (cursor/pos input)
  1531. last-slash-caret-pos (:pos (:pos (state/get-editor-action-data)))
  1532. last-command (and last-slash-caret-pos (subs edit-content last-slash-caret-pos pos))]
  1533. (when (> pos 0)
  1534. (or
  1535. (and (= commands/command-trigger (util/nth-safe edit-content (dec pos)))
  1536. @commands/*initial-commands)
  1537. (and last-command
  1538. (commands/get-matched-commands last-command)))))
  1539. (catch :default e
  1540. (js/console.error e)
  1541. nil)))
  1542. (defn get-matched-block-commands
  1543. [input]
  1544. (try
  1545. (let [edit-content (gobj/get input "value")
  1546. pos (cursor/pos input)
  1547. last-command (subs edit-content
  1548. (:pos (:pos (state/get-editor-action-data)))
  1549. pos)]
  1550. (when (> pos 0)
  1551. (or
  1552. (and (= \< (util/nth-safe edit-content (dec pos)))
  1553. (commands/block-commands-map))
  1554. (and last-command
  1555. (commands/get-matched-commands
  1556. last-command
  1557. (commands/block-commands-map))))))
  1558. (catch :default _error
  1559. nil)))
  1560. (defn auto-complete?
  1561. []
  1562. (or @*asset-uploading?
  1563. (state/get-editor-action)))
  1564. (defn in-shui-popup?
  1565. []
  1566. (some-> js/document.activeElement
  1567. (.closest "[data-radix-menu-content]")
  1568. (nil?)
  1569. (not)))
  1570. (defn get-current-input-char
  1571. [input]
  1572. (when-let [pos (cursor/pos input)]
  1573. (let [value (gobj/get input "value")]
  1574. (when (and (>= (count value) (inc pos))
  1575. (>= pos 1))
  1576. (util/nth-safe value pos)))))
  1577. (defn move-up-down
  1578. [up?]
  1579. (fn [event]
  1580. (util/stop event)
  1581. (let [edit-block-id (:block/uuid (state/get-edit-block))
  1582. move-nodes (fn [blocks]
  1583. (let [blocks' (block-handler/get-top-level-blocks blocks)
  1584. result (ui-outliner-tx/transact!
  1585. {:outliner-op :move-blocks}
  1586. (outliner-op/move-blocks-up-down! blocks' up?))]
  1587. (when-let [block-node (util/get-first-block-by-id (:block/uuid (first blocks)))]
  1588. (.scrollIntoView block-node #js {:behavior "smooth" :block "nearest"}))
  1589. result))]
  1590. (if edit-block-id
  1591. (when-let [block (db/pull [:block/uuid edit-block-id])]
  1592. (let [blocks [(assoc block :block/content (state/get-edit-content))]
  1593. pos (state/get-edit-pos)]
  1594. (p/do!
  1595. (save-current-block!)
  1596. (move-nodes blocks)
  1597. (when-let [input-id (state/get-edit-input-id)]
  1598. (when-let [input (gdom/getElement input-id)]
  1599. (.focus input)
  1600. (util/scroll-editor-cursor input))
  1601. (util/schedule (fn []
  1602. (when-not (gdom/getElement input-id)
  1603. ;; could be crossing containers
  1604. (edit-block! block pos nil))))))))
  1605. (let [ids (state/get-selection-block-ids)]
  1606. (when (seq ids)
  1607. (let [lookup-refs (map (fn [id] [:block/uuid id]) ids)
  1608. blocks (db/pull-many (state/get-current-repo) '[*] lookup-refs)]
  1609. (move-nodes blocks))))))))
  1610. (defn get-selected-ordered-blocks
  1611. []
  1612. (let [repo (state/get-current-repo)
  1613. ids (state/get-selection-block-ids)
  1614. lookup-refs (->> (map (fn [id] [:block/uuid id]) ids)
  1615. (remove nil?))]
  1616. (db/pull-many repo '[*] lookup-refs)))
  1617. (defn on-tab
  1618. "`direction` = :left | :right."
  1619. [direction]
  1620. (let [blocks (get-selected-ordered-blocks)]
  1621. (block-handler/indent-outdent-blocks! blocks (= direction :right) nil)))
  1622. (defn- get-link [format link label]
  1623. (let [link (or link "")
  1624. label (or label "")]
  1625. (case (keyword format)
  1626. :markdown (util/format "[%s](%s)" label link)
  1627. :org (util/format "[[%s][%s]]" link label)
  1628. nil)))
  1629. (defn- get-image-link
  1630. [format link label]
  1631. (let [link (or link "")
  1632. label (or label "")]
  1633. (case (keyword format)
  1634. :markdown (util/format "![%s](%s)" label link)
  1635. :org (util/format "[[%s]]"))))
  1636. (defn handle-command-input-close [id]
  1637. (state/set-editor-show-input! nil)
  1638. (when-let [saved-cursor (state/get-editor-last-pos)]
  1639. (when-let [input (gdom/getElement id)]
  1640. (.focus input)
  1641. (cursor/move-cursor-to input saved-cursor))))
  1642. (defn handle-command-input [command id format m]
  1643. ;; TODO: Add error handling for when user doesn't provide a required field.
  1644. ;; (The current behavior is to just revert back to the editor.)
  1645. (case command
  1646. :link (let [{:keys [link label]} m]
  1647. (when-not (or (string/blank? link) (string/blank? label))
  1648. (insert-command!
  1649. id
  1650. (get-link format link label)
  1651. format
  1652. {:last-pattern (str commands/command-trigger "link")
  1653. :command :link})))
  1654. :image-link (let [{:keys [link label]} m]
  1655. (when (not (string/blank? link))
  1656. (insert-command!
  1657. id
  1658. (get-image-link format link label)
  1659. format
  1660. {:last-pattern (str commands/command-trigger "link")
  1661. :command :image-link})))
  1662. nil)
  1663. (handle-command-input-close id))
  1664. (defn- close-autocomplete-if-outside
  1665. [input]
  1666. (when (and input
  1667. (contains? #{:page-search :page-search-hashtag :block-search} (state/get-editor-action))
  1668. (not (wrapped-by? input page-ref/left-brackets page-ref/right-brackets))
  1669. (not (wrapped-by? input block-ref/left-parens block-ref/right-parens))
  1670. ;; wrapped-by? doesn't detect multiple beginnings when ending with "" so
  1671. ;; use subs to correctly detect current hashtag
  1672. (not (text-util/wrapped-by? (subs (.-value input) 0 (cursor/pos input)) (cursor/pos input) commands/hashtag "")))
  1673. (state/clear-editor-action!)))
  1674. (defn resize-image!
  1675. [block-id metadata full_text size]
  1676. (let [new-meta (merge metadata size)
  1677. image-part (first (string/split full_text #"\{"))
  1678. new-full-text (str image-part (pr-str new-meta))
  1679. block (db/pull [:block/uuid block-id])
  1680. value (:block/content block)
  1681. new-value (string/replace value full_text new-full-text)]
  1682. (save-block-aux! block new-value {})))
  1683. (defonce *auto-save-timeout (atom nil))
  1684. (defn edit-box-on-change!
  1685. [e _block id]
  1686. (let [value (util/evalue e)
  1687. repo (state/get-current-repo)]
  1688. (state/set-edit-content! id value false)
  1689. (when @*auto-save-timeout
  1690. (js/clearTimeout @*auto-save-timeout))
  1691. (block-handler/mark-last-input-time! repo)
  1692. (reset! *auto-save-timeout
  1693. (js/setTimeout
  1694. (fn []
  1695. (when (and (state/input-idle? repo :diff 450)
  1696. ;; don't auto-save block if it has tags
  1697. (not (and
  1698. (config/db-based-graph? repo)
  1699. (re-find #"#\S+" value))))
  1700. ; don't auto-save for page's properties block
  1701. (save-current-block! {:skip-properties? true})))
  1702. 450))))
  1703. (defn- start-of-new-word?
  1704. [input pos]
  1705. (contains? #{" " "\t"} (get (.-value input) (- pos 2))))
  1706. (defn handle-last-input []
  1707. (let [input (state/get-input)
  1708. input-id (state/get-edit-input-id)
  1709. edit-block (state/get-edit-block)
  1710. pos (cursor/pos input)
  1711. content (.-value input)
  1712. last-input-char (util/nth-safe content (dec pos))
  1713. last-prev-input-char (util/nth-safe content (dec (dec pos)))
  1714. prev-prev-input-char (util/nth-safe content (- pos 3))
  1715. repo (state/get-current-repo)
  1716. db-based? (config/db-based-graph? repo)]
  1717. ;; TODO: is it cross-browser compatible?
  1718. ;; (not= (gobj/get native-e "inputType") "insertFromPaste")
  1719. (cond
  1720. (and (= content "1. ") (= last-input-char " ") input-id edit-block
  1721. (not (own-order-number-list? edit-block)))
  1722. (p/let [_ (state/pub-event! [:editor/toggle-own-number-list edit-block])]
  1723. (state/set-edit-content! input-id ""))
  1724. (and (= last-input-char commands/command-trigger)
  1725. (or (re-find #"(?m)^/" (str (.-value input))) (start-of-new-word? input pos)))
  1726. (do
  1727. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)})
  1728. (commands/reinit-matched-commands!)
  1729. (state/set-editor-show-commands!))
  1730. (= last-input-char commands/angle-bracket)
  1731. (do
  1732. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)})
  1733. (commands/reinit-matched-block-commands!)
  1734. (state/set-editor-show-block-commands!))
  1735. (and (= last-input-char last-prev-input-char commands/colon)
  1736. (or (nil? prev-prev-input-char)
  1737. (= prev-prev-input-char "\n"))
  1738. (not db-based?))
  1739. (do
  1740. (cursor/move-cursor-backward input 2)
  1741. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)})
  1742. (state/set-editor-action! :property-search))
  1743. (and
  1744. (not= :property-search (state/get-editor-action))
  1745. (let [{:keys [line start-pos]} (text-util/get-current-line-by-pos (.-value input) (dec pos))]
  1746. (text-util/wrapped-by? line (- pos start-pos) "" gp-property/colons))
  1747. (not db-based?))
  1748. (do
  1749. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)})
  1750. (state/set-editor-action! :property-search))
  1751. (and (= last-input-char commands/colon)
  1752. (= :property-search (state/get-editor-action))
  1753. (not db-based?))
  1754. (state/clear-editor-action!)
  1755. (or (= last-input-char last-prev-input-char commands/hashtag)
  1756. (and (= last-prev-input-char commands/hashtag)
  1757. (= last-input-char " ")))
  1758. (state/clear-editor-action!)
  1759. ;; Open "Search page or New page" auto-complete
  1760. (and (= last-input-char commands/hashtag)
  1761. ;; Only trigger at beginning of a line or before whitespace
  1762. (or (re-find #"(?m)^#" (str (.-value input))) (start-of-new-word? input pos)))
  1763. (do
  1764. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)})
  1765. (state/set-editor-last-pos! pos)
  1766. (state/set-editor-action! :page-search-hashtag))
  1767. :else
  1768. nil)))
  1769. (defn get-selected-text
  1770. []
  1771. (let [text (:selected (state/get-editor-action-data))]
  1772. (when-not (string/blank? text)
  1773. text)))
  1774. (defn block-on-chosen-handler
  1775. [id q format selected-text]
  1776. (fn [chosen _click?]
  1777. (state/clear-editor-action!)
  1778. (let [uuid-string (str (:block/uuid chosen))]
  1779. ;; block reference
  1780. (insert-command! id
  1781. (block-ref/->block-ref uuid-string)
  1782. format
  1783. {:last-pattern (str block-ref/left-parens (if selected-text "" q))
  1784. :end-pattern block-ref/right-parens
  1785. :postfix-fn (fn [s] (util/replace-first block-ref/right-parens s ""))
  1786. :forward-pos 3
  1787. :command :block-ref})
  1788. ;; Save it so it'll be parsed correctly in the future
  1789. (property-handler/file-persist-block-id! (state/get-current-repo) (:block/uuid chosen))
  1790. (when-let [input (gdom/getElement id)]
  1791. (.focus input)))))
  1792. (defn block-non-exist-handler
  1793. [input]
  1794. (fn []
  1795. (state/clear-editor-action!)
  1796. (cursor/move-cursor-forward input 2)))
  1797. (defn- paste-block-cleanup
  1798. [repo block page exclude-properties format content-update-fn keep-uuid?]
  1799. (let [db-based? (config/db-based-graph? (state/get-current-repo))
  1800. new-content
  1801. (if content-update-fn
  1802. (content-update-fn (:block/content block))
  1803. (:block/content block))
  1804. new-content
  1805. (cond->> new-content
  1806. (not keep-uuid?) (property-file/remove-property-when-file-based repo format "id")
  1807. true (property-file/remove-property-when-file-based repo format "custom_id"))]
  1808. (merge (apply dissoc block (conj (when-not keep-uuid? [:block/_refs]) :block/pre-block? :block/meta))
  1809. (cond->
  1810. {:block/page {:db/id (:db/id page)}
  1811. :block/format format
  1812. ;; only file graphs exclude properties because db graphs don't put ids in properties
  1813. :block/properties (if db-based?
  1814. (:block/properties block)
  1815. (apply dissoc (:block/properties block)
  1816. (concat
  1817. (when-not keep-uuid? [:id])
  1818. [:custom_id :custom-id]
  1819. exclude-properties)))
  1820. :block/content new-content}
  1821. (not db-based?)
  1822. (assoc :block/properties-text-values (apply dissoc (:block/properties-text-values block)
  1823. (concat
  1824. (when-not keep-uuid? [:id])
  1825. exclude-properties)))))))
  1826. (defn- edit-last-block-after-inserted!
  1827. [result]
  1828. (util/schedule
  1829. (fn []
  1830. (when-let [last-block (last (:blocks result))]
  1831. (clear-when-saved!)
  1832. (let [last-block' (db/pull [:block/uuid (:block/uuid last-block)])]
  1833. (edit-block! last-block' :max nil))))))
  1834. (defn- nested-blocks
  1835. [blocks]
  1836. (let [ids (set (map :db/id blocks))]
  1837. (some? (some #(ids (:db/id (:block/parent %))) blocks))))
  1838. (defn paste-blocks
  1839. "Given a vec of blocks, insert them into the target page.
  1840. keep-uuid?: if true, keep the uuid provided in the block structure."
  1841. [blocks {:keys [content-update-fn
  1842. exclude-properties
  1843. target-block
  1844. sibling?
  1845. keep-uuid?
  1846. revert-cut-txs
  1847. skip-empty-target?]
  1848. :or {exclude-properties []}}]
  1849. (let [editing-block (when-let [editing-block (state/get-edit-block)]
  1850. (some-> (db/pull [:block/uuid (:block/uuid editing-block)])
  1851. (assoc :block/content (state/get-edit-content))))
  1852. has-unsaved-edits (and editing-block
  1853. (not= (:block/content (db/pull (:db/id editing-block)))
  1854. (state/get-edit-content)))
  1855. target-block (or target-block editing-block)
  1856. block (db/entity (:db/id target-block))
  1857. page (if (:block/name block) block
  1858. (when target-block (:block/page (db/entity (:db/id target-block)))))
  1859. empty-target? (if (true? skip-empty-target?) false
  1860. (string/blank? (:block/content target-block)))
  1861. paste-nested-blocks? (nested-blocks blocks)
  1862. target-block-has-children? (db/has-children? (:block/uuid target-block))
  1863. replace-empty-target? (and empty-target?
  1864. (or (not target-block-has-children?)
  1865. (and target-block-has-children? (= (count blocks) 1)))
  1866. (block-has-no-ref? (:db/id target-block)))
  1867. target-block' (if (and empty-target? target-block-has-children? paste-nested-blocks?)
  1868. (db/pull (:db/id (:block/left target-block)))
  1869. target-block)
  1870. sibling? (cond
  1871. (and paste-nested-blocks? empty-target?)
  1872. (= (:block/parent target-block') (:block/parent target-block))
  1873. (some? sibling?)
  1874. sibling?
  1875. target-block-has-children?
  1876. false
  1877. :else
  1878. true)]
  1879. (p/let [_ (when has-unsaved-edits
  1880. (ui-outliner-tx/transact!
  1881. {:outliner-op :save-block}
  1882. (outliner-save-block! editing-block)))
  1883. result (ui-outliner-tx/transact!
  1884. {:outliner-op :insert-blocks
  1885. :additional-tx revert-cut-txs}
  1886. (when target-block'
  1887. (let [format (or (:block/format target-block') (state/get-preferred-format))
  1888. repo (state/get-current-repo)
  1889. blocks' (map (fn [block]
  1890. (paste-block-cleanup repo block page exclude-properties format content-update-fn keep-uuid?))
  1891. blocks)]
  1892. (outliner-op/insert-blocks! blocks' target-block' {:sibling? sibling?
  1893. :outliner-op :paste
  1894. :replace-empty-target? replace-empty-target?
  1895. :keep-uuid? keep-uuid?}))))]
  1896. (state/set-block-op-type! nil)
  1897. (when result (edit-last-block-after-inserted! (ldb/read-transit-str result))))))
  1898. (defn- block-tree->blocks
  1899. "keep-uuid? - maintain the existing :uuid in tree vec"
  1900. [repo tree-vec format keep-uuid? page-name]
  1901. (->> (outliner-core/tree-vec-flatten tree-vec)
  1902. (map (fn [block]
  1903. (let [content (:content block)
  1904. props (into [] (:properties block))
  1905. content* (str (if (= :markdown format) "- " "* ")
  1906. (property-file/insert-properties-when-file-based repo format content props))
  1907. ast (mldoc/->edn content* format)
  1908. blocks (->> (block/extract-blocks ast content* format {:page-name page-name})
  1909. (map wrap-parse-block))
  1910. fst-block (first blocks)
  1911. fst-block (if (and keep-uuid? (uuid? (:uuid block)))
  1912. (assoc fst-block :block/uuid (:uuid block))
  1913. fst-block)]
  1914. (assert fst-block "fst-block shouldn't be nil")
  1915. (assoc fst-block :block/level (:block/level block)))))))
  1916. (defn insert-block-tree
  1917. "`tree-vec`: a vector of blocks.
  1918. A block element: {:content :properties :children [block-1, block-2, ...]}"
  1919. [tree-vec format {:keys [target-block keep-uuid?] :as opts}]
  1920. (let [repo (state/get-current-repo)
  1921. page-id (:db/id (:block/page target-block))
  1922. page-name (some-> page-id (db/entity) :block/name)
  1923. blocks (block-tree->blocks repo tree-vec format keep-uuid? page-name)
  1924. blocks (gp-block/with-parent-and-left page-id blocks)
  1925. block-refs (->> (mapcat :block/refs blocks)
  1926. (set)
  1927. (filter (fn [ref] (and (vector? ref) (= :block/uuid (first ref))))))]
  1928. (when (seq block-refs)
  1929. (db/transact! (map (fn [[_ id]] {:block/uuid id}) block-refs)))
  1930. (paste-blocks blocks opts)))
  1931. (defn insert-block-tree-after-target
  1932. "`tree-vec`: a vector of blocks.
  1933. A block element: {:content :properties :children [block-1, block-2, ...]}"
  1934. [target-block-id sibling? tree-vec format keep-uuid?]
  1935. (insert-block-tree tree-vec format
  1936. {:target-block (db/pull target-block-id)
  1937. :keep-uuid? keep-uuid?
  1938. :skip-empty-target? true
  1939. :sibling? sibling?}))
  1940. (defn insert-template!
  1941. ([element-id db-id]
  1942. (insert-template! element-id db-id {}))
  1943. ([element-id db-id {:keys [target] :as opts}]
  1944. (let [repo (state/get-current-repo)
  1945. db? (config/db-based-graph? repo)]
  1946. (when-not db?
  1947. (p/let [block (if (integer? db-id)
  1948. (db-async/<pull repo db-id)
  1949. (db-async/<get-template-by-name (name db-id)))]
  1950. (when-let [db-id (:db/id block)]
  1951. (let [journal? (:block/journal? target)
  1952. target (or target (state/get-edit-block))
  1953. format (:block/format block)
  1954. block-uuid (:block/uuid block)
  1955. template-including-parent? (not (false? (:template-including-parent (:block/properties block))))
  1956. blocks (db/get-block-and-children repo block-uuid)
  1957. root-block (db/pull db-id)
  1958. blocks-exclude-root (remove (fn [b] (= (:db/id b) db-id)) blocks)
  1959. sorted-blocks (tree/sort-blocks blocks-exclude-root root-block)
  1960. sorted-blocks (cons
  1961. (-> (first sorted-blocks)
  1962. (update :block/properties-text-values dissoc :template)
  1963. (update :block/properties-order (fn [keys]
  1964. (vec (remove #{:template} keys)))))
  1965. (rest sorted-blocks))
  1966. blocks (if template-including-parent?
  1967. sorted-blocks
  1968. (drop 1 sorted-blocks))]
  1969. (when element-id
  1970. (insert-command! element-id "" format {:end-pattern commands/command-trigger}))
  1971. (let [exclude-properties [:id :template :template-including-parent]
  1972. content-update-fn (fn [content]
  1973. (->> content
  1974. (property-file/remove-property-when-file-based repo format "template")
  1975. (property-file/remove-property-when-file-based repo format "template-including-parent")
  1976. template/resolve-dynamic-template!))
  1977. page (if (:block/name block) block
  1978. (when target (:block/page (db/entity (:db/id target)))))
  1979. blocks' (map (fn [block]
  1980. (paste-block-cleanup repo block page exclude-properties format content-update-fn false))
  1981. blocks)
  1982. sibling? (:sibling? opts)
  1983. sibling?' (cond
  1984. (some? sibling?)
  1985. sibling?
  1986. (db/has-children? (:block/uuid target))
  1987. false
  1988. :else
  1989. true)]
  1990. (try
  1991. (p/let [result (ui-outliner-tx/transact!
  1992. {:outliner-op :insert-blocks
  1993. :created-from-journal-template? journal?}
  1994. (when-not (string/blank? (state/get-edit-content))
  1995. (save-current-block!))
  1996. (outliner-op/insert-blocks! blocks' target
  1997. (assoc opts :sibling? sibling?')))]
  1998. (when result (edit-last-block-after-inserted! (ldb/read-transit-str result))))
  1999. (catch :default ^js/Error e
  2000. (notification/show!
  2001. [:p.content
  2002. (util/format "Template insert error: %s" (.-message e))]
  2003. :error)))))))))))
  2004. (defn template-on-chosen-handler
  2005. [element-id]
  2006. (fn [[_template template-block] _click?]
  2007. (when-let [db-id (:db/id template-block)]
  2008. (insert-template! element-id db-id
  2009. {:replace-empty-target? true}))))
  2010. (defn get-searching-property
  2011. [input]
  2012. (let [value (.-value input)
  2013. pos (util/get-selection-start input)
  2014. postfix (subs value pos)
  2015. end-index (when-let [idx (string/index-of postfix gp-property/colons)]
  2016. (+ (max 0 (count (subs value 0 pos))) idx))
  2017. start-index (or (when-let [p (string/last-index-of (subs value 0 pos) "\n")]
  2018. (inc p))
  2019. 0)]
  2020. {:end-index end-index
  2021. :searching-property (when (and start-index end-index (>= end-index start-index))
  2022. (subs value start-index end-index))}))
  2023. (defn property-on-chosen-handler
  2024. [element-id q]
  2025. (fn [property]
  2026. (when-let [input (gdom/getElement element-id)]
  2027. (let [{:keys [end-index searching-property]} (get-searching-property input)]
  2028. (cursor/move-cursor-to input (+ end-index 2))
  2029. (commands/insert! element-id (str (or property q) gp-property/colons " ")
  2030. {:last-pattern (str searching-property gp-property/colons)})
  2031. (state/clear-editor-action!)
  2032. (js/setTimeout (fn []
  2033. (let [pos (let [input (gdom/getElement element-id)]
  2034. (cursor/get-caret-pos input))]
  2035. (state/set-editor-action-data! {:property (or property q)
  2036. :pos pos})
  2037. (state/set-editor-action! :property-value-search)))
  2038. 50)))))
  2039. (defn property-value-on-chosen-handler
  2040. [element-id q]
  2041. (fn [property-value]
  2042. (commands/insert! element-id (str gp-property/colons " " (or property-value q))
  2043. {:last-pattern (str gp-property/colons " " q)})
  2044. (state/clear-editor-action!)))
  2045. (defn outdent-on-enter
  2046. [node]
  2047. (let [original-block (block-handler/get-current-editing-original-block)
  2048. parent-node (otree/-get-parent node (db/get-db false))
  2049. target (or original-block (:data parent-node))
  2050. pos (state/get-edit-pos)
  2051. block (:data node)]
  2052. (p/do!
  2053. (ui-outliner-tx/transact!
  2054. {:outliner-op :move-blocks
  2055. :real-outliner-op :indent-outdent}
  2056. (save-current-block!)
  2057. (when target
  2058. (outliner-op/move-blocks! (block-handler/get-top-level-blocks [block])
  2059. target true)))
  2060. (when original-block
  2061. (util/schedule #(edit-block! block pos nil))))))
  2062. (defn- last-top-level-child?
  2063. [{:keys [id]} current-node]
  2064. (when id
  2065. (when-let [entity (if-let [id' (parse-uuid (str id))]
  2066. (db/entity [:block/uuid id'])
  2067. (db/get-page id))]
  2068. (= (:block/uuid entity) (otree/-get-parent-id current-node (db/get-db false))))))
  2069. (defn insert
  2070. ([insertion]
  2071. (insert insertion false))
  2072. ([insertion auto-complete-enabled?]
  2073. (when (or auto-complete-enabled?
  2074. (not (auto-complete?)))
  2075. (let [^js input (state/get-input)
  2076. selected-start (util/get-selection-start input)
  2077. selected-end (util/get-selection-end input)
  2078. value (.-value input)
  2079. s1 (subs value 0 selected-start)
  2080. s2 (subs value selected-end)]
  2081. (state/set-edit-content! (state/get-edit-input-id)
  2082. (str s1 insertion))
  2083. ;; HACK: save scroll-pos of current pos, then add trailing content
  2084. ;; This logic is also in commands/simple-insert!
  2085. (let [scroll-container (util/nearest-scrollable-container input)
  2086. scroll-pos (.-scrollTop scroll-container)]
  2087. (state/set-edit-content! (state/get-edit-input-id)
  2088. (str s1 insertion s2))
  2089. (cursor/move-cursor-to input (+ selected-start (count insertion)))
  2090. (set! (.-scrollTop scroll-container) scroll-pos))))))
  2091. (defn- keydown-new-line
  2092. "Insert newline to current cursor position"
  2093. []
  2094. (insert "\n"))
  2095. (declare delete-and-update)
  2096. (defn- dwim-in-properties
  2097. [state]
  2098. (when-not (auto-complete?)
  2099. (let [{:keys [block]} (get-state)]
  2100. (when block
  2101. (let [input (state/get-input)
  2102. content (gobj/get input "value")
  2103. format (:block/format (:block (get-state)))
  2104. property-key (:raw-content (thingatpt/property-key-at-point input))
  2105. org? (= format :org)
  2106. move-to-pos (if org? 2 3)]
  2107. (if org?
  2108. (cond
  2109. (and property-key (not= property-key ""))
  2110. (case property-key
  2111. ;; When cursor in "PROPERTIES", add :|: in a new line and move cursor to |
  2112. "PROPERTIES"
  2113. (do (cursor/move-cursor-to-line-end input)
  2114. (insert "\n:: ")
  2115. (cursor/move-cursor-backward input move-to-pos))
  2116. ;; When cursor in "END", new block (respect the previous enter behavior)
  2117. "END"
  2118. (do
  2119. (cursor/move-cursor-to-end input)
  2120. (save-current-block!)
  2121. (insert-new-block! state))
  2122. ;; cursor in other positions of :ke|y: or ke|y::, move to line end for inserting value.
  2123. (if (property-file/property-key-exist?-when-file-based format content property-key)
  2124. (notification/show!
  2125. [:p.content
  2126. (util/format "Property key \"%s\" already exists!" property-key)]
  2127. :error)
  2128. (cursor/move-cursor-to-line-end input)))
  2129. ;; when cursor in empty property key
  2130. (and property-key (= property-key ""))
  2131. (do (delete-and-update
  2132. input
  2133. (cursor/line-beginning-pos input)
  2134. (inc (cursor/line-end-pos input)))
  2135. (property-file/goto-properties-end-when-file-based format input)
  2136. (cursor/move-cursor-to-line-end input))
  2137. :else
  2138. ;;When cursor in other place of PROPERTIES drawer, add :|: in a new line and move cursor to |
  2139. (do
  2140. (insert "\n:: ")
  2141. (cursor/move-cursor-backward input move-to-pos)))
  2142. (insert "\n")))))))
  2143. (defn toggle-list-checkbox
  2144. [{:block/keys [content] :as block} item-content]
  2145. (let [toggle-fn (fn [m x-mark]
  2146. (case (string/lower-case x-mark)
  2147. "[ ]" (str "[x] " item-content)
  2148. "[x]" (str "[ ] " item-content)
  2149. m))
  2150. pattern (re-pattern (str "(\\[[xX ]\\])\\s+?" (gstring/regExpEscape item-content)))
  2151. new-content (string/replace-first content pattern toggle-fn)]
  2152. (save-block-if-changed! block new-content)))
  2153. (defn- dwim-in-list
  2154. []
  2155. (when-not (auto-complete?)
  2156. (let [{:keys [block]} (get-state)]
  2157. (when block
  2158. (let [input (state/get-input)]
  2159. (when-let [item (thingatpt/list-item-at-point input)]
  2160. (let [{:keys [full-content indent bullet checkbox ordered _]} item
  2161. next-bullet (if ordered (str (inc bullet) ".") bullet)
  2162. checkbox (when checkbox "[ ] ")]
  2163. (if (and
  2164. (= (count full-content)
  2165. (+ (if ordered (+ (count (str bullet)) 2) 2) (when checkbox (count checkbox))))
  2166. (string/includes? (.-value input) "\n"))
  2167. (delete-and-update input (cursor/line-beginning-pos input) (cursor/line-end-pos input))
  2168. (let [start-pos (util/get-selection-start input)
  2169. value (.-value input)
  2170. before (subs value 0 start-pos)
  2171. after (subs value start-pos)
  2172. cursor-in-item-content? (and (re-find #"^(\d+){1}\." (last (string/split-lines before)))
  2173. (not (string/blank? (first (string/split-lines after)))))]
  2174. (when-not cursor-in-item-content?
  2175. (cursor/move-cursor-to-line-end input)
  2176. (insert (str "\n" indent next-bullet " " checkbox)))
  2177. (when ordered
  2178. (let [value (.-value input)
  2179. start-pos (util/get-selection-start input)
  2180. after-lists-str (string/trim (subs value start-pos))
  2181. after-lists-str (if cursor-in-item-content?
  2182. (str indent next-bullet " " after-lists-str)
  2183. after-lists-str)
  2184. lines (string/split-lines after-lists-str)
  2185. after-lists-str' (list/re-order-items lines (if cursor-in-item-content? bullet (inc bullet)))
  2186. value' (str (subs value 0 start-pos) "\n" after-lists-str')
  2187. cursor' (if cursor-in-item-content?
  2188. (inc (count (str (subs value 0 start-pos) indent next-bullet " ")))
  2189. (+ (:end item) (count next-bullet) 2))]
  2190. (state/set-edit-content! (state/get-edit-input-id) value')
  2191. (cursor/move-cursor-to input cursor'))))))))))))
  2192. (defn toggle-page-reference-embed
  2193. [parent-id]
  2194. (let [{:keys [block]} (get-state)]
  2195. (when block
  2196. (let [input (state/get-input)
  2197. new-pos (cursor/get-caret-pos input)
  2198. page-ref-fn (fn [bounds backward-pos]
  2199. (commands/simple-insert!
  2200. parent-id bounds
  2201. {:backward-pos backward-pos
  2202. :check-fn (fn [_ _ _]
  2203. (state/set-editor-action-data! {:pos new-pos})
  2204. (commands/handle-step [:editor/search-page]))}))]
  2205. (state/clear-editor-action!)
  2206. (let [selection (get-selection-and-format)
  2207. {:keys [selection-start selection-end selection]} selection]
  2208. (if selection
  2209. (do (delete-and-update input selection-start selection-end)
  2210. (insert (page-ref/->page-ref selection)))
  2211. (if-let [embed-ref (thingatpt/embed-macro-at-point input)]
  2212. (let [{:keys [raw-content start end]} embed-ref]
  2213. (delete-and-update input start end)
  2214. (if (= 5 (count raw-content))
  2215. (page-ref-fn page-ref/left-and-right-brackets 2)
  2216. (insert raw-content)))
  2217. (if-let [page-ref (thingatpt/page-ref-at-point input)]
  2218. (let [{:keys [start end full-content raw-content]} page-ref]
  2219. (delete-and-update input start end)
  2220. (if (= raw-content "")
  2221. (page-ref-fn "{{embed [[]]}}" 4)
  2222. (insert (util/format "{{embed %s}}" full-content))))
  2223. (page-ref-fn page-ref/left-and-right-brackets 2)))))))))
  2224. (defn toggle-block-reference-embed
  2225. [parent-id]
  2226. (let [{:keys [block]} (get-state)]
  2227. (when block
  2228. (let [input (state/get-input)
  2229. new-pos (cursor/get-caret-pos input)
  2230. block-ref-fn (fn [bounds backward-pos]
  2231. (commands/simple-insert!
  2232. parent-id bounds
  2233. {:backward-pos backward-pos
  2234. :check-fn (fn [_ _ _]
  2235. (state/set-editor-action-data! {:pos new-pos})
  2236. (commands/handle-step [:editor/search-block]))}))]
  2237. (state/clear-editor-action!)
  2238. (if-let [embed-ref (thingatpt/embed-macro-at-point input)]
  2239. (let [{:keys [raw-content start end]} embed-ref]
  2240. (delete-and-update input start end)
  2241. (if (= 5 (count raw-content))
  2242. (block-ref-fn block-ref/left-and-right-parens 2)
  2243. (insert raw-content)))
  2244. (if-let [page-ref (thingatpt/block-ref-at-point input)]
  2245. (let [{:keys [start end full-content raw-content]} page-ref]
  2246. (delete-and-update input start end)
  2247. (if (= raw-content "")
  2248. (block-ref-fn "{{embed (())}}" 4)
  2249. (insert (util/format "{{embed %s}}" full-content))))
  2250. (block-ref-fn block-ref/left-and-right-parens 2)))))))
  2251. (defn- keydown-new-block
  2252. [state]
  2253. (when-not (auto-complete?)
  2254. (let [{:keys [block config]} (get-state)]
  2255. (when block
  2256. (let [input (state/get-input)
  2257. config (assoc config :keydown-new-block true)
  2258. content (gobj/get input "value")
  2259. pos (cursor/pos input)
  2260. current-node (outliner-core/block (db/get-db) block)
  2261. has-right? (-> (otree/-get-right current-node (db/get-db false))
  2262. (tree/satisfied-inode?))
  2263. db-based? (config/db-based-graph? (state/get-current-repo))
  2264. thing-at-point ;intern is not supported in cljs, need a more elegant solution
  2265. (or (when (thingatpt/get-setting :admonition&src?)
  2266. (thingatpt/admonition&src-at-point input))
  2267. (when (thingatpt/get-setting :markup?)
  2268. (thingatpt/markup-at-point input))
  2269. (when (thingatpt/get-setting :block-ref?)
  2270. (thingatpt/block-ref-at-point input))
  2271. (when (thingatpt/get-setting :page-ref?)
  2272. (thingatpt/page-ref-at-point input))
  2273. (when (and (not db-based?) (thingatpt/get-setting :properties?))
  2274. (thingatpt/properties-at-point input))
  2275. (when (thingatpt/get-setting :list?)
  2276. (and (not (cursor/beginning-of-line? input))
  2277. (thingatpt/list-item-at-point input))))]
  2278. (cond
  2279. thing-at-point
  2280. (case (:type thing-at-point)
  2281. "markup" (let [right-bound (:bounds thing-at-point)]
  2282. (cursor/move-cursor-to
  2283. input
  2284. (+ (string/index-of content right-bound pos)
  2285. (count right-bound))))
  2286. "admonition-block" (keydown-new-line)
  2287. "source-block" (do
  2288. (keydown-new-line)
  2289. (case (:action thing-at-point)
  2290. :into-code-editor
  2291. (state/into-code-editor-mode!)
  2292. nil))
  2293. "block-ref" (open-block-in-sidebar! (:link thing-at-point))
  2294. "page-ref" (when-not (string/blank? (:link thing-at-point))
  2295. (let [page (:link thing-at-point)
  2296. page-name (db-model/get-redirect-page-name page)]
  2297. (insert-first-page-block-if-not-exists! page-name)))
  2298. "list-item" (dwim-in-list)
  2299. "properties-drawer" (dwim-in-properties state))
  2300. (and (string/blank? content)
  2301. (own-order-number-list? block)
  2302. (not (some-> (db-model/get-block-parent (:block/uuid block))
  2303. (own-order-number-list?))))
  2304. (remove-block-own-order-list-type! block)
  2305. (and
  2306. (string/blank? content)
  2307. (not has-right?)
  2308. (not (last-top-level-child? config current-node)))
  2309. (outdent-on-enter current-node)
  2310. :else
  2311. (let [main-container (gdom/getElement "main-content-container")
  2312. ;; Lazy blocks will not be rendered by default if it's below the screen
  2313. input-top (some-> (state/get-input)
  2314. (.getBoundingClientRect)
  2315. (gobj/get "top"))
  2316. bottom-reached? (when input-top
  2317. (< (- js/window.innerHeight input-top) 100))]
  2318. (when (and bottom-reached? main-container)
  2319. (util/scroll-to main-container (+ (.-scrollTop main-container)
  2320. 200)
  2321. false))
  2322. (profile
  2323. "Insert block"
  2324. (ui-outliner-tx/transact!
  2325. {:outliner-op :insert-blocks}
  2326. (insert-new-block! state))))))))))
  2327. (defn- inside-of-single-block
  2328. "When we are in a single block wrapper, we should always insert a new line instead of new block"
  2329. [el]
  2330. (some? (dom/closest el ".single-block")))
  2331. (defn keydown-new-block-handler [e]
  2332. (let [state (get-state)]
  2333. (if (or (state/doc-mode-enter-for-new-line?) (inside-of-single-block (rum/dom-node state)))
  2334. (keydown-new-line)
  2335. (do
  2336. (.preventDefault e)
  2337. (keydown-new-block state)))))
  2338. (defn keydown-new-line-handler [e]
  2339. (let [state (get-state)]
  2340. (if (and (state/doc-mode-enter-for-new-line?) (not (inside-of-single-block (rum/dom-node state))))
  2341. (keydown-new-block state)
  2342. (do
  2343. (.preventDefault e)
  2344. (keydown-new-line)))))
  2345. (defn- select-first-last
  2346. "Select first or last block in viewpoint"
  2347. [direction]
  2348. (let [f (case direction :up last :down first)
  2349. block (->> (util/get-blocks-noncollapse)
  2350. (f))]
  2351. (when block
  2352. (util/scroll-to-block block)
  2353. (state/exit-editing-and-set-selected-blocks! [block]))))
  2354. (defn- select-up-down [direction]
  2355. (let [selected-blocks (state/get-selection-blocks)
  2356. selected (case direction
  2357. :up (first selected-blocks)
  2358. :down (last selected-blocks))
  2359. f (case direction
  2360. :up util/get-prev-block-non-collapsed
  2361. :down util/get-next-block-non-collapsed)
  2362. sibling-block (f selected)]
  2363. (when (and sibling-block (dom/attr sibling-block "blockid"))
  2364. (util/scroll-to-block sibling-block)
  2365. (state/exit-editing-and-set-selected-blocks! [sibling-block]))))
  2366. (defn- move-cross-boundary-up-down
  2367. [direction move-opts]
  2368. (let [input (state/get-input)
  2369. line-pos (util/get-line-pos (.-value input) (util/get-selection-start input))
  2370. repo (state/get-current-repo)
  2371. f (case direction
  2372. :up util/get-prev-block-non-collapsed
  2373. :down util/get-next-block-non-collapsed)
  2374. sibling-block (f (gdom/getElement (state/get-editing-block-dom-id)))
  2375. {:block/keys [uuid content format]} (state/get-edit-block)]
  2376. (if sibling-block
  2377. (when-let [sibling-block-id (dom/attr sibling-block "blockid")]
  2378. (let [value (state/get-edit-content)]
  2379. (when (not= (clean-content! repo format content)
  2380. (string/trim value))
  2381. (save-block! repo uuid value)))
  2382. (let [new-uuid (cljs.core/uuid sibling-block-id)
  2383. block (db/pull repo '[*] [:block/uuid new-uuid])]
  2384. (edit-block! block
  2385. (or (:pos move-opts)
  2386. [direction line-pos])
  2387. (state/get-edit-block-node)
  2388. {:direction direction})))
  2389. (case direction
  2390. :up (cursor/move-cursor-to input 0)
  2391. :down (cursor/move-cursor-to-end input)))))
  2392. (defn keydown-up-down-handler
  2393. [direction {:keys [_pos] :as move-opts}]
  2394. (let [input (state/get-input)
  2395. selected-start (util/get-selection-start input)
  2396. selected-end (util/get-selection-end input)
  2397. up? (= direction :up)
  2398. down? (= direction :down)]
  2399. (cond
  2400. (not= selected-start selected-end)
  2401. (if up?
  2402. (cursor/move-cursor-to input selected-start)
  2403. (cursor/move-cursor-to input selected-end))
  2404. (or (and up? (cursor/textarea-cursor-first-row? input))
  2405. (and down? (cursor/textarea-cursor-last-row? input)))
  2406. (move-cross-boundary-up-down direction move-opts)
  2407. :else
  2408. (if up?
  2409. (cursor/move-cursor-up input)
  2410. (cursor/move-cursor-down input)))))
  2411. (defn- move-to-block-when-cross-boundary
  2412. [direction]
  2413. (let [up? (= :left direction)
  2414. pos (if up? :max 0)
  2415. {:block/keys [format uuid] :as block} (state/get-edit-block)
  2416. repo (state/get-current-repo)
  2417. editing-block (gdom/getElement (state/get-editing-block-dom-id))
  2418. f (if up? util/get-prev-block-non-collapsed util/get-next-block-non-collapsed)
  2419. sibling-block (f editing-block)
  2420. same-container? (when (and editing-block sibling-block)
  2421. (->> [editing-block sibling-block]
  2422. (map (fn [^js b] (.closest b ".blocks-container")))
  2423. (apply =)))]
  2424. (when (and sibling-block same-container?)
  2425. (when-let [sibling-block-id (dom/attr sibling-block "blockid")]
  2426. (let [content (:block/content block)
  2427. value (state/get-edit-content)]
  2428. (when (and value (not= (clean-content! repo format content) (string/trim value)))
  2429. (save-block! repo uuid value)))
  2430. (let [block (db/pull repo '[*] [:block/uuid (cljs.core/uuid sibling-block-id)])]
  2431. (edit-block! block pos (state/get-edit-block-node)))))))
  2432. (defn keydown-arrow-handler
  2433. [direction]
  2434. (let [input (state/get-input)
  2435. element js/document.activeElement
  2436. selected-start (util/get-selection-start input)
  2437. selected-end (util/get-selection-end input)
  2438. left? (= direction :left)
  2439. right? (= direction :right)]
  2440. (when (= input element)
  2441. (cond
  2442. (not= selected-start selected-end)
  2443. (if left?
  2444. (cursor/move-cursor-to input selected-start)
  2445. (cursor/move-cursor-to input selected-end))
  2446. (or (and left? (cursor/start? input))
  2447. (and right? (cursor/end? input)))
  2448. (move-to-block-when-cross-boundary direction)
  2449. :else
  2450. (if left?
  2451. (cursor/move-cursor-backward input)
  2452. (cursor/move-cursor-forward input))))))
  2453. (defn- delete-and-update [^js input start end]
  2454. (util/safe-set-range-text! input "" start end)
  2455. (state/set-edit-content! (state/get-edit-input-id) (.-value input)))
  2456. (defn- delete-concat [current-block]
  2457. (p/let [repo (state/get-current-repo)
  2458. ^js input (state/get-input)
  2459. current-pos (cursor/pos input)
  2460. value (gobj/get input "value")
  2461. collapsed? (util/collapsed? current-block)
  2462. next-block (when-let [e (db-model/get-next (db/get-db repo) (:db/id current-block))]
  2463. (db/pull (:db/id e)))
  2464. next-block-right (when next-block (db-async/<get-right-sibling repo (:db/id next-block)))
  2465. db-based? (config/db-based-graph? repo)]
  2466. (cond
  2467. (nil? next-block)
  2468. nil
  2469. ;; TODO: merge children from both the current block and the next block
  2470. (and collapsed? next-block (db/has-children? (:block/uuid next-block)))
  2471. nil
  2472. :else
  2473. (let [edit-block (state/get-edit-block)
  2474. next-block-has-refs? (some? (:block/_refs (db/entity (:db/id next-block))))
  2475. new-content (if next-block-has-refs?
  2476. (str value ""
  2477. (->> (:block/content next-block)
  2478. (property-file/remove-properties-when-file-based repo (:block/format next-block))
  2479. (drawer/remove-logbook)))
  2480. (str value "" (:block/content next-block)))
  2481. repo (state/get-current-repo)
  2482. delete-block (if next-block-has-refs? edit-block next-block)
  2483. keep-block (if next-block-has-refs? next-block edit-block)]
  2484. (p/do!
  2485. (ui-outliner-tx/transact!
  2486. {:outliner-op :delete-blocks}
  2487. (delete-block-aux! delete-block false)
  2488. (save-block! repo keep-block new-content {})
  2489. (when next-block-has-refs?
  2490. (outliner-save-block! {:db/id (:db/id keep-block)
  2491. :block/left (:db/id (:block/left delete-block))
  2492. :block/parent (:db/id (:block/parent delete-block))})
  2493. (when (and next-block-right (not= (:db/id (:block/parent next-block))
  2494. (:db/id (:block/parent edit-block))))
  2495. (outliner-save-block! {:db/id (:db/id next-block-right)
  2496. :block/left (:db/id (:block/left next-block))})))
  2497. (when db-based?
  2498. (let [next-e (db/entity (:db/id next-block))
  2499. current-e (db/entity (:db/id edit-block))
  2500. new-properties (merge
  2501. (:block/properties current-e)
  2502. (:block/properties next-e))
  2503. new-tags (->> (concat (:block/tags next-e) (:block/tags current-e)))]
  2504. (when (or (not= new-properties (:block/properties keep-block))
  2505. (not= (map :db/id new-tags) (map :db/id (:block/tags keep-block))))
  2506. (outliner-save-block! {:db/id (:db/id keep-block)
  2507. :block/properties new-properties
  2508. :block/tags new-tags})))))
  2509. (let [block (if next-block-has-refs? next-block edit-block)]
  2510. (edit-block! block current-pos nil)))))))
  2511. (defn keydown-delete-handler
  2512. [_e]
  2513. (let [^js input (state/get-input)
  2514. current-pos (cursor/pos input)
  2515. value (gobj/get input "value")
  2516. end? (= current-pos (count value))
  2517. current-block (state/get-edit-block)
  2518. selected-start (util/get-selection-start input)
  2519. selected-end (util/get-selection-end input)]
  2520. (when current-block
  2521. (cond
  2522. (not= selected-start selected-end)
  2523. (delete-and-update input selected-start selected-end)
  2524. (and end? current-block)
  2525. (let [editor-state (get-state)
  2526. custom-query? (get-in editor-state [:config :custom-query?])]
  2527. (when-not custom-query?
  2528. (delete-concat current-block)))
  2529. :else
  2530. (delete-and-update
  2531. input current-pos (util/safe-inc-current-pos-from-start (.-value input) current-pos))))))
  2532. (defn keydown-backspace-handler
  2533. [cut? e]
  2534. (let [^js input (state/get-input)
  2535. id (state/get-edit-input-id)
  2536. current-pos (cursor/pos input)
  2537. value (gobj/get input "value")
  2538. deleted (and (> current-pos 0)
  2539. (util/nth-safe value (dec current-pos)))
  2540. selected-start (util/get-selection-start input)
  2541. selected-end (util/get-selection-end input)
  2542. block (state/get-edit-block)
  2543. repo (state/get-current-repo)
  2544. top-block? (= (:block/left block) (:block/page block))
  2545. single-block? (inside-of-single-block (.-target e))
  2546. root-block? (= (:block.temp/container block) (str (:block/uuid block)))]
  2547. (block-handler/mark-last-input-time! repo)
  2548. (cond
  2549. (not= selected-start selected-end)
  2550. (do
  2551. (util/stop e)
  2552. (when cut?
  2553. (js/document.execCommand "copy"))
  2554. (delete-and-update input selected-start selected-end))
  2555. (zero? current-pos)
  2556. (let [editor-state (get-state)
  2557. custom-query? (get-in editor-state [:config :custom-query?])]
  2558. (util/stop e)
  2559. (when (and (not (and top-block? (not (string/blank? value))))
  2560. (not root-block?)
  2561. (not single-block?)
  2562. (not custom-query?))
  2563. (if (own-order-number-list? block)
  2564. (p/do!
  2565. (save-current-block!)
  2566. (remove-block-own-order-list-type! block))
  2567. (delete-block! repo false))))
  2568. (and (> current-pos 1)
  2569. (= (util/nth-safe value (dec current-pos)) commands/command-trigger))
  2570. (do
  2571. (util/stop e)
  2572. (commands/restore-state)
  2573. (delete-and-update input (dec current-pos) current-pos))
  2574. (and (> current-pos 1)
  2575. (= (util/nth-safe value (dec current-pos)) commands/angle-bracket))
  2576. (do
  2577. (util/stop e)
  2578. (commands/restore-state)
  2579. (delete-and-update input (dec current-pos) current-pos))
  2580. ;; pair
  2581. (and
  2582. deleted
  2583. (contains?
  2584. (set (keys delete-map))
  2585. deleted)
  2586. (>= (count value) (inc current-pos))
  2587. (= (util/nth-safe value current-pos)
  2588. (get delete-map deleted)))
  2589. (do
  2590. (util/stop e)
  2591. (commands/delete-pair! id)
  2592. (cond
  2593. (and (= deleted "[") (state/get-editor-show-page-search?))
  2594. (state/clear-editor-action!)
  2595. (and (= deleted "(") (state/get-editor-show-block-search?))
  2596. (state/clear-editor-action!)
  2597. :else
  2598. nil))
  2599. ;; deleting hashtag
  2600. (and (= deleted "#") (state/get-editor-show-page-search-hashtag?))
  2601. (do
  2602. (state/clear-editor-action!)
  2603. (delete-and-update input (dec current-pos) current-pos))
  2604. ;; just delete
  2605. :else
  2606. (when-not (mobile-util/native-ios?)
  2607. (util/stop e)
  2608. (delete-and-update
  2609. input (util/safe-dec-current-pos-from-end (.-value input) current-pos) current-pos)))))
  2610. (defn indent-outdent
  2611. [indent?]
  2612. (let [editor (state/get-input)
  2613. pos (some-> editor cursor/pos)
  2614. {:keys [block]} (get-state)]
  2615. (when block
  2616. (state/set-editor-last-pos! pos)
  2617. (block-handler/indent-outdent-blocks! [block] indent? save-current-block!))))
  2618. (defn keydown-tab-handler
  2619. [direction]
  2620. (fn [e]
  2621. (cond
  2622. (state/editing?)
  2623. (when-not (state/get-editor-action)
  2624. (util/stop e)
  2625. (indent-outdent (not (= :left direction))))
  2626. (state/selection?)
  2627. (do
  2628. (util/stop e)
  2629. (on-tab direction)))
  2630. nil))
  2631. (defn ^:large-vars/cleanup-todo keydown-not-matched-handler
  2632. "NOTE: Keydown cannot be used on Android platform"
  2633. [format]
  2634. (fn [e _key-code]
  2635. (let [input-id (state/get-edit-input-id)
  2636. input (state/get-input)
  2637. key (gobj/get e "key")
  2638. value (gobj/get input "value")
  2639. ctrlKey (gobj/get e "ctrlKey")
  2640. metaKey (gobj/get e "metaKey")
  2641. pos (cursor/pos input)
  2642. hashtag? (or (surround-by? input "#" " ")
  2643. (surround-by? input "#" :end)
  2644. (= key "#"))]
  2645. (when (and (not @(:editor/start-pos @state/state))
  2646. (not (and key (string/starts-with? key "Arrow"))))
  2647. (state/set-state! :editor/start-pos pos))
  2648. (cond
  2649. (and (contains? #{"ArrowLeft" "ArrowRight"} key)
  2650. (contains? #{:property-search :property-value-search} (state/get-editor-action)))
  2651. (state/clear-editor-action!)
  2652. (and (util/goog-event-is-composing? e true) ;; #3218
  2653. (not hashtag?) ;; #3283 @Rime
  2654. (not (state/get-editor-show-page-search-hashtag?))) ;; #3283 @MacOS pinyin
  2655. nil
  2656. (or ctrlKey metaKey)
  2657. nil
  2658. ;; FIXME: On mobile, a backspace click to call keydown-backspace-handler
  2659. ;; does not work if cursor is at the beginning of a block, hence the block
  2660. ;; can't be deleted. Need to figure out why and find a better solution.
  2661. (and (mobile-util/native-platform?)
  2662. (= key "Backspace")
  2663. (zero? pos)
  2664. (string/blank? (.toString (js/window.getSelection))))
  2665. (keydown-backspace-handler false e)
  2666. (and (= key "#")
  2667. (and (> pos 0)
  2668. (= "#" (util/nth-safe value (dec pos)))))
  2669. (state/clear-editor-action!)
  2670. (and (contains? (set/difference (set (keys reversed-autopair-map))
  2671. #{"`"})
  2672. key)
  2673. (= (get-current-input-char input) key))
  2674. (do
  2675. (util/stop e)
  2676. (cursor/move-cursor-forward input))
  2677. (and (autopair-when-selected key) (string/blank? (util/get-selected-text)))
  2678. nil
  2679. (some? @(:editor/action @state/state))
  2680. nil
  2681. (and (not (string/blank? (util/get-selected-text)))
  2682. (contains? keycode/left-square-brackets-keys key))
  2683. (do
  2684. (autopair input-id "[" format nil)
  2685. (util/stop e))
  2686. (and (not (string/blank? (util/get-selected-text)))
  2687. (contains? keycode/left-paren-keys key))
  2688. (do (util/stop e)
  2689. (autopair input-id "(" format nil))
  2690. ;; If you type `xyz`, the last backtick should close the first and not add another autopair
  2691. ;; If you type several backticks in a row, each one should autopair to accommodate multiline code (```)
  2692. (-> (keys autopair-map)
  2693. set
  2694. (disj "(")
  2695. (contains? key)
  2696. (or (autopair-left-paren? input key)))
  2697. (let [curr (get-current-input-char input)
  2698. prev (util/nth-safe value (dec pos))]
  2699. (util/stop e)
  2700. (if (and (= key "`") (= "`" curr) (not= "`" prev))
  2701. (cursor/move-cursor-forward input)
  2702. (autopair input-id key format nil)))
  2703. (let [sym "$"]
  2704. (and (= key sym)
  2705. (>= (count value) 1)
  2706. (> pos 0)
  2707. (= (nth value (dec pos)) sym)
  2708. (if (> (count value) pos)
  2709. (not= (nth value pos) sym)
  2710. true)))
  2711. (commands/simple-insert! input-id "$$" {:backward-pos 2})
  2712. (let [sym "^"]
  2713. (and (= key sym)
  2714. (>= (count value) 1)
  2715. (> pos 0)
  2716. (= (nth value (dec pos)) sym)
  2717. (if (> (count value) pos)
  2718. (not= (nth value pos) sym)
  2719. true)))
  2720. (commands/simple-insert! input-id "^^" {:backward-pos 2})
  2721. :else
  2722. nil))))
  2723. (defn- input-page-ref?
  2724. [k current-pos blank-selected? last-key-code]
  2725. (and blank-selected?
  2726. (contains? keycode/left-square-brackets-keys k)
  2727. (= (:key last-key-code) k)
  2728. (> current-pos 0)))
  2729. (defn- default-case-for-keyup-handler
  2730. [input current-pos k code is-processed? c]
  2731. (let [last-key-code (state/get-last-key-code)
  2732. blank-selected? (string/blank? (util/get-selected-text))
  2733. non-enter-processed? (and is-processed? ;; #3251
  2734. (not= code keycode/enter-code)) ;; #3459
  2735. editor-action (state/get-editor-action)]
  2736. (if (and (= editor-action :page-search-hashtag)
  2737. (input-page-ref? k current-pos blank-selected? last-key-code))
  2738. (do
  2739. (commands/handle-step [:editor/input page-ref/right-brackets {:last-pattern :skip-check
  2740. :backward-pos 2}])
  2741. (commands/handle-step [:editor/search-page])
  2742. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)}))
  2743. (when (and (not editor-action) (not non-enter-processed?))
  2744. (cond
  2745. ;; When you type text inside square brackets
  2746. (and (not (contains? #{"ArrowDown" "ArrowLeft" "ArrowRight" "ArrowUp" "Escape"} k))
  2747. (wrapped-by? input page-ref/left-brackets page-ref/right-brackets))
  2748. (let [orig-pos (cursor/get-caret-pos input)
  2749. value (gobj/get input "value")
  2750. square-pos (string/last-index-of (subs value 0 (:pos orig-pos)) page-ref/left-brackets)
  2751. pos (+ square-pos 2)
  2752. _ (state/set-editor-last-pos! pos)
  2753. pos (assoc orig-pos :pos pos)
  2754. command-step (if (= \# (util/nth-safe value (dec square-pos)))
  2755. :editor/search-page-hashtag
  2756. :editor/search-page)]
  2757. (commands/handle-step [command-step])
  2758. (state/set-editor-action-data! {:pos pos}))
  2759. ;; Handle non-ascii square brackets
  2760. (and (input-page-ref? k current-pos blank-selected? last-key-code)
  2761. (not (wrapped-by? input page-ref/left-brackets page-ref/right-brackets)))
  2762. (do
  2763. (commands/handle-step [:editor/input page-ref/left-and-right-brackets {:backward-truncate-number 2
  2764. :backward-pos 2}])
  2765. (commands/handle-step [:editor/search-page])
  2766. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)}))
  2767. ;; Handle non-ascii parentheses
  2768. (and blank-selected?
  2769. (contains? keycode/left-paren-keys k)
  2770. (= (:key last-key-code) k)
  2771. (> current-pos 0)
  2772. (not (wrapped-by? input block-ref/left-parens block-ref/right-parens)))
  2773. (do
  2774. (commands/handle-step [:editor/input block-ref/left-and-right-parens {:backward-truncate-number 2
  2775. :backward-pos 2}])
  2776. (commands/handle-step [:editor/search-block :reference])
  2777. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)}))
  2778. ;; Handle non-ascii angle brackets
  2779. (and (= "〈" c)
  2780. (= "《" (util/nth-safe (gobj/get input "value") (dec (dec current-pos))))
  2781. (> current-pos 0))
  2782. (do
  2783. (commands/handle-step [:editor/input commands/angle-bracket {:last-pattern "《〈"
  2784. :backward-pos 0}])
  2785. (state/set-editor-action-data! {:pos (cursor/get-caret-pos input)})
  2786. (state/set-editor-show-block-commands!))
  2787. :else
  2788. nil)))))
  2789. (defn keyup-handler
  2790. [_state input input-id]
  2791. (fn [e key-code]
  2792. (when-not (util/goog-event-is-composing? e)
  2793. (let [current-pos (cursor/pos input)
  2794. value (gobj/get input "value")
  2795. c (util/nth-safe value (dec current-pos))
  2796. [key-code k code is-processed?]
  2797. (if (and c
  2798. (mobile-util/native-android?)
  2799. (or (= key-code 229)
  2800. (= key-code 0)))
  2801. [(.charCodeAt value (dec current-pos))
  2802. c
  2803. (cond
  2804. (= c " ")
  2805. "Space"
  2806. (parse-long c)
  2807. (str "Digit" c)
  2808. :else
  2809. (str "Key" (string/upper-case c)))
  2810. false]
  2811. [key-code
  2812. (gobj/get e "key")
  2813. (if (mobile-util/native-android?)
  2814. (gobj/get e "key")
  2815. (gobj/getValueByKeys e "event_" "code"))
  2816. ;; #3440
  2817. (util/goog-event-is-composing? e true)])]
  2818. (cond
  2819. ;; When you type something after /
  2820. (and (= :commands (state/get-editor-action)) (not= k commands/command-trigger))
  2821. (if (= commands/command-trigger (second (re-find #"(\S+)\s+$" value)))
  2822. (state/clear-editor-action!)
  2823. (let [matched-commands (get-matched-commands input)]
  2824. (if (seq matched-commands)
  2825. (reset! commands/*matched-commands matched-commands)
  2826. (state/clear-editor-action!))))
  2827. ;; When you type search text after < (and when you release shift after typing <)
  2828. (and (= :block-commands (state/get-editor-action)) (not= key-code 188)) ; not <
  2829. (let [matched-block-commands (get-matched-block-commands input)
  2830. format (:format (get-state))]
  2831. (if (seq matched-block-commands)
  2832. (cond
  2833. (= key-code 9) ;tab
  2834. (do
  2835. (util/stop e)
  2836. (insert-command! input-id
  2837. (last (first matched-block-commands))
  2838. format
  2839. {:last-pattern commands/angle-bracket
  2840. :command :block-commands}))
  2841. :else
  2842. (reset! commands/*matched-block-commands matched-block-commands))
  2843. (state/clear-editor-action!)))
  2844. ;; When you type two spaces after a command character (may always just be handled by the above instead?)
  2845. (and (contains? #{:block-commands} (state/get-editor-action))
  2846. (= c (util/nth-safe value (dec (dec current-pos))) " "))
  2847. (state/clear-editor-action!)
  2848. :else
  2849. (default-case-for-keyup-handler input current-pos k code is-processed? c))
  2850. (close-autocomplete-if-outside input)
  2851. (when-not (or (= k "Shift") is-processed?)
  2852. (state/set-last-key-code! {:key-code key-code
  2853. :code code
  2854. :key k
  2855. :shift? (.-shiftKey e)}))))))
  2856. (defn editor-on-click!
  2857. [id]
  2858. (fn [_e]
  2859. (let [input (gdom/getElement id)]
  2860. (util/scroll-editor-cursor input)
  2861. (close-autocomplete-if-outside input))))
  2862. (defn editor-on-change!
  2863. [block id search-timeout]
  2864. (fn [e]
  2865. (if (= :block-search (state/sub :editor/action))
  2866. (let [timeout 300]
  2867. (when @search-timeout
  2868. (js/clearTimeout @search-timeout))
  2869. (reset! search-timeout
  2870. (js/setTimeout
  2871. #(edit-box-on-change! e block id)
  2872. timeout)))
  2873. (let [input (gdom/getElement id)]
  2874. (edit-box-on-change! e block id)
  2875. (util/scroll-editor-cursor input)))))
  2876. (defn- cut-blocks-and-clear-selections!
  2877. [copy?]
  2878. (when-not (get-in @state/state [:ui/find-in-page :active?])
  2879. (cut-selection-blocks copy?)
  2880. (clear-selection!)))
  2881. (defn shortcut-copy-selection
  2882. [_e]
  2883. (copy-selection-blocks true))
  2884. (defn shortcut-cut-selection
  2885. [e]
  2886. (util/stop e)
  2887. (cut-blocks-and-clear-selections! true))
  2888. (defn shortcut-delete-selection
  2889. [e]
  2890. (util/stop e)
  2891. (cut-blocks-and-clear-selections! false))
  2892. (defn- copy-current-block-ref
  2893. [format]
  2894. (when-let [current-block (state/get-edit-block)]
  2895. (when-let [block-id (:block/uuid current-block)]
  2896. (if (= format "embed")
  2897. (copy-block-ref! block-id #(str "{{embed ((" % "))}}"))
  2898. (copy-block-ref! block-id block-ref/->block-ref)))))
  2899. (defn copy-current-block-embed []
  2900. (copy-current-block-ref "embed"))
  2901. (defn shortcut-copy
  2902. "shortcut copy action:
  2903. * when in selection mode, copy selected blocks
  2904. * when in edit mode but no text selected, copy current block ref
  2905. * when in edit mode with text selected, copy selected text as normal
  2906. * when text is selected on a PDF, copy the highlighted text"
  2907. [e]
  2908. (when-not (auto-complete?)
  2909. (cond
  2910. (state/selection?)
  2911. (shortcut-copy-selection e)
  2912. (state/editing?)
  2913. (let [input (state/get-input)
  2914. selected-start (util/get-selection-start input)
  2915. selected-end (util/get-selection-end input)]
  2916. (save-current-block!)
  2917. (when (= selected-start selected-end)
  2918. (copy-current-block-ref "ref")))
  2919. (and (state/get-current-pdf)
  2920. (.closest (.. js/window getSelection -baseNode -parentElement) ".pdfViewer"))
  2921. (util/copy-to-clipboard!
  2922. (pdf-utils/fix-selection-text-breakline (.. js/window getSelection toString))
  2923. nil))))
  2924. (defn shortcut-copy-text
  2925. "shortcut copy action:
  2926. * when in selection mode, copy selected blocks
  2927. * when in edit mode with text selected, copy selected text as normal"
  2928. [_e]
  2929. (when-not (auto-complete?)
  2930. (cond
  2931. (state/selection?)
  2932. (copy-selection-blocks false)
  2933. :else
  2934. (js/document.execCommand "copy"))))
  2935. (defn whiteboard?
  2936. []
  2937. (and (db-model/whiteboard-page? (state/get-current-page))
  2938. (.closest (.-activeElement js/document) ".logseq-tldraw")))
  2939. (defn shortcut-cut
  2940. "shortcut cut action:
  2941. * when in selection mode, cut selected blocks
  2942. * when in edit mode with text selected, cut selected text
  2943. * otherwise nothing need to be handled."
  2944. [e]
  2945. (cond
  2946. (state/selection?)
  2947. (shortcut-cut-selection e)
  2948. (and (state/editing?) (util/input-text-selected?
  2949. (gdom/getElement (state/get-edit-input-id))))
  2950. (keydown-backspace-handler true e)
  2951. (whiteboard?)
  2952. (.cut (state/active-tldraw-app))
  2953. :else
  2954. nil))
  2955. (defn delete-selection
  2956. [e]
  2957. (cond
  2958. (state/selection?)
  2959. (shortcut-delete-selection e)
  2960. (and (whiteboard?) (not (state/editing?)))
  2961. (.deleteShapes (.-api ^js (state/active-tldraw-app)))
  2962. :else
  2963. nil))
  2964. (defn editor-delete
  2965. [e]
  2966. (when (state/editing?)
  2967. (util/stop e)
  2968. (keydown-delete-handler e)))
  2969. (defn editor-backspace
  2970. [e]
  2971. (when (state/editing?)
  2972. (keydown-backspace-handler false e)))
  2973. (defn- slide-focused?
  2974. []
  2975. (some-> (first (dom/by-class "reveal"))
  2976. (dom/has-class? "focused")))
  2977. (defn shortcut-up-down [direction]
  2978. (fn [e]
  2979. (when (and (not (auto-complete?))
  2980. (not (in-shui-popup?))
  2981. (not (slide-focused?))
  2982. (not (state/get-timestamp-block)))
  2983. (util/stop e)
  2984. (cond
  2985. (state/editing?)
  2986. (keydown-up-down-handler direction {})
  2987. (state/selection?)
  2988. (select-up-down direction)
  2989. ;; if there is an edit-input-id set, we are probably still on editing mode, that is not fully initialized
  2990. (not (state/get-edit-input-id))
  2991. (select-first-last direction)))
  2992. nil))
  2993. (defn shortcut-select-up-down [direction]
  2994. (fn [e]
  2995. (util/stop e)
  2996. (if (state/editing?)
  2997. (let [input (state/get-input)
  2998. selected-start (util/get-selection-start input)
  2999. selected-end (util/get-selection-end input)
  3000. [anchor cursor] (case (util/get-selection-direction input)
  3001. "backward" [selected-end selected-start]
  3002. [selected-start selected-end])
  3003. cursor-rect (cursor/get-caret-pos input cursor)]
  3004. (if
  3005. ;; if the move is to cross block boundary, select the whole block
  3006. (or (and (= direction :up) (cursor/textarea-cursor-rect-first-row? cursor-rect))
  3007. (and (= direction :down) (cursor/textarea-cursor-rect-last-row? cursor-rect)))
  3008. (select-block-up-down direction)
  3009. ;; simulate text selection
  3010. (cursor/select-up-down input direction anchor cursor-rect)))
  3011. (select-block-up-down direction))))
  3012. (defn open-selected-block!
  3013. [direction e]
  3014. (let [selected-blocks (state/get-selection-blocks)
  3015. f (case direction
  3016. :left first
  3017. :right last)]
  3018. (when-let [block-id (some-> selected-blocks
  3019. f
  3020. (dom/attr "blockid")
  3021. uuid)]
  3022. (util/stop e)
  3023. (let [block {:block/uuid block-id}
  3024. block-id (-> selected-blocks
  3025. f
  3026. (gobj/get "id"))
  3027. left? (= direction :left)]
  3028. (edit-block! block
  3029. (if left? 0 :max)
  3030. (when block-id (gdom/getElement block-id)))))))
  3031. (defn shortcut-left-right [direction]
  3032. (fn [e]
  3033. (when (and (not (auto-complete?))
  3034. (not (state/get-timestamp-block)))
  3035. (cond
  3036. (state/editing?)
  3037. (do
  3038. (util/stop e)
  3039. (keydown-arrow-handler direction))
  3040. (state/selection?)
  3041. (do
  3042. (util/stop e)
  3043. (open-selected-block! direction e))
  3044. :else
  3045. nil))))
  3046. (defn clear-block-content! []
  3047. (save-current-block! {:force? true})
  3048. (state/set-edit-content! (state/get-edit-input-id) ""))
  3049. (defn kill-line-before! []
  3050. (save-current-block! {:force? true})
  3051. (util/kill-line-before! (state/get-input)))
  3052. (defn kill-line-after! []
  3053. (save-current-block! {:force? true})
  3054. (util/kill-line-after! (state/get-input)))
  3055. (defn beginning-of-block []
  3056. (cursor/move-cursor-to (state/get-input) 0))
  3057. (defn end-of-block []
  3058. (cursor/move-cursor-to-end (state/get-input)))
  3059. (defn cursor-forward-word []
  3060. (cursor/move-cursor-forward-by-word (state/get-input)))
  3061. (defn cursor-backward-word []
  3062. (cursor/move-cursor-backward-by-word (state/get-input)))
  3063. (defn backward-kill-word []
  3064. (let [input (state/get-input)]
  3065. (save-current-block! {:force? true})
  3066. (util/backward-kill-word input)
  3067. (state/set-edit-content! (state/get-edit-input-id) (.-value input))))
  3068. (defn forward-kill-word []
  3069. (let [input (state/get-input)]
  3070. (save-current-block! {:force? true})
  3071. (util/forward-kill-word input)
  3072. (state/set-edit-content! (state/get-edit-input-id) (.-value input))))
  3073. (defn block-with-title?
  3074. [format content semantic?]
  3075. (and (string/includes? content "\n")
  3076. (if semantic?
  3077. (let [ast (mldoc/->edn content format)
  3078. first-elem-type (first (ffirst ast))]
  3079. (mldoc/block-with-title? first-elem-type))
  3080. true)))
  3081. (defn- valid-dsl-query-block?
  3082. "Whether block has a valid dsl query."
  3083. [block]
  3084. (some-> (:block/content block)
  3085. (string/includes? "{{query ")))
  3086. (defn- valid-custom-query-block?
  3087. "Whether block has a valid custom query."
  3088. [block]
  3089. (let [entity (db/entity (:db/id block))
  3090. content (:block/content entity)]
  3091. (when content
  3092. (when (and (string/includes? content "#+BEGIN_QUERY")
  3093. (string/includes? content "#+END_QUERY"))
  3094. (let [ast (mldoc/->edn (string/trim content) (or (:block/format entity) :markdown))
  3095. q (mldoc/extract-first-query-from-ast ast)]
  3096. (some? (:query (common-util/safe-read-string q))))))))
  3097. (defn collapsable?
  3098. ([block-id]
  3099. (collapsable? block-id {}))
  3100. ([block-id {:keys [semantic?]
  3101. :or {semantic? false}}]
  3102. (when block-id
  3103. (let [repo (state/get-current-repo)]
  3104. (if-let [block (db/entity [:block/uuid block-id])]
  3105. (let [db-based? (config/db-based-graph? repo)
  3106. tags (:block/tags (db/entity (:db/id block)))]
  3107. (or (db-model/has-children? block-id)
  3108. (valid-dsl-query-block? block)
  3109. (valid-custom-query-block? block)
  3110. (and db-based?
  3111. (seq (:block/properties block))
  3112. (not (db-pu/all-hidden-properties? (keys (:block/properties block)))))
  3113. (and db-based? (seq tags)
  3114. (some (fn [t]
  3115. (let [properties (map :db/ident (:class/schema.properties (:block/schema t)))]
  3116. (and (seq properties)
  3117. (not (db-pu/all-hidden-properties? properties))))) tags))
  3118. (and
  3119. (:outliner/block-title-collapse-enabled? (state/get-config))
  3120. (block-with-title? (:block/format block)
  3121. (:block/content block)
  3122. semantic?))))
  3123. false)))))
  3124. (defn all-blocks-with-level
  3125. "Return all blocks associated with correct level
  3126. if :root-block is not nil, only return root block with its children
  3127. if :expanded? true, return expanded children
  3128. if :collapse? true, return without any collapsed children
  3129. if :incremental? true, collapse/expand will be step by step
  3130. for example:
  3131. - a
  3132. - b (collapsed)
  3133. - c
  3134. - d
  3135. - e
  3136. return:
  3137. blocks
  3138. [{:block a :level 1}
  3139. {:block b :level 2}
  3140. {:block e :level 2}]"
  3141. [{:keys [collapse? expanded? incremental? root-block page]
  3142. :or {collapse? false expanded? false incremental? true root-block nil}}]
  3143. (when-let [page (or page
  3144. (state/get-current-page)
  3145. (date/today))]
  3146. (let [block-id (or root-block (parse-uuid page))
  3147. page-id (when-not block-id
  3148. (:db/id (db/get-page page)))
  3149. blocks (if block-id
  3150. (db/get-block-and-children (state/get-current-repo) block-id)
  3151. (db/get-page-blocks-no-cache page-id))
  3152. root-block (or block-id root-block)]
  3153. (if incremental?
  3154. (let [blocks (tree/blocks->vec-tree blocks (or block-id page-id))]
  3155. (->>
  3156. (cond->> blocks
  3157. root-block
  3158. (map (fn find [root]
  3159. (if (= root-block (:block/uuid root))
  3160. root
  3161. (first (filter find (:block/children root []))))))
  3162. collapse?
  3163. (w/postwalk
  3164. (fn [b]
  3165. (if (and (map? b)
  3166. (util/collapsed? b)
  3167. (not= root-block (:block/uuid b)))
  3168. (assoc b :block/children []) b)))
  3169. true
  3170. (mapcat (fn [x] (tree-seq map? :block/children x)))
  3171. expanded?
  3172. (filter (fn [b] (collapsable? (:block/uuid b))))
  3173. true
  3174. (map (fn [x] (dissoc x :block/children))))
  3175. (remove nil?)))
  3176. (cond->> blocks
  3177. collapse?
  3178. (filter util/collapsed?)
  3179. expanded?
  3180. (filter (fn [b] (collapsable? (:block/uuid b))))
  3181. true
  3182. (remove nil?))))))
  3183. (defn- skip-collapsing-in-db?
  3184. []
  3185. (let [config (last (state/get-editor-args))]
  3186. (:ref? config)))
  3187. (defn set-blocks-collapsed!
  3188. [block-ids value]
  3189. (let [block-ids (map (fn [block-id] (if (string? block-id) (uuid block-id) block-id)) block-ids)
  3190. repo (state/get-current-repo)
  3191. value (boolean value)]
  3192. (when repo
  3193. (save-current-block!) ;; Save the input contents before collapsing
  3194. (ui-outliner-tx/transact! ;; Save the new collapsed state as an undo transaction (if it changed)
  3195. {:outliner-op :collapse-expand-blocks}
  3196. (doseq [block-id block-ids]
  3197. (when-let [block (db/entity [:block/uuid block-id])]
  3198. (let [current-value (boolean (:block/collapsed? block))]
  3199. (when-not (= current-value value)
  3200. (let [block {:block/uuid block-id
  3201. :block/collapsed? value}]
  3202. (outliner-save-block! block)))))))
  3203. (doseq [block-id block-ids]
  3204. (state/set-collapsed-block! block-id value)))))
  3205. (defn collapse-block! [block-id]
  3206. (when (collapsable? block-id)
  3207. (when-not (skip-collapsing-in-db?)
  3208. (set-blocks-collapsed! [block-id] true))))
  3209. (defn expand-block! [block-id]
  3210. (when-not (skip-collapsing-in-db?)
  3211. (set-blocks-collapsed! [block-id] false)))
  3212. (defn expand!
  3213. ([e] (expand! e false))
  3214. ([e clear-selection?]
  3215. (util/stop e)
  3216. (cond
  3217. (state/editing?)
  3218. (when-let [block-id (:block/uuid (state/get-edit-block))]
  3219. (expand-block! block-id))
  3220. (state/selection?)
  3221. (do
  3222. (->> (get-selected-blocks)
  3223. (map (fn [dom]
  3224. (-> (dom/attr dom "blockid")
  3225. uuid
  3226. expand-block!)))
  3227. doall)
  3228. (and clear-selection? (clear-selection!)))
  3229. (whiteboard?)
  3230. (.setCollapsed (.-api ^js (state/active-tldraw-app)) false)
  3231. :else
  3232. ;; expand one level
  3233. (let [blocks-with-level (all-blocks-with-level {})
  3234. max-level (or (apply max (map :block/level blocks-with-level)) 99)]
  3235. (loop [level 1]
  3236. (if (> level max-level)
  3237. nil
  3238. (let [blocks-to-expand (->> blocks-with-level
  3239. (filter (fn [b] (= (:block/level b) level)))
  3240. (filter util/collapsed?))]
  3241. (if (empty? blocks-to-expand)
  3242. (recur (inc level))
  3243. (doseq [{:block/keys [uuid]} blocks-to-expand]
  3244. (expand-block! uuid))))))))))
  3245. (defn collapse!
  3246. ([e] (collapse! e false))
  3247. ([e clear-selection?]
  3248. (when e (util/stop e))
  3249. (cond
  3250. (state/editing?)
  3251. (when-let [block-id (:block/uuid (state/get-edit-block))]
  3252. (collapse-block! block-id))
  3253. (state/selection?)
  3254. (do
  3255. (->> (get-selected-blocks)
  3256. (map (fn [dom]
  3257. (-> (dom/attr dom "blockid")
  3258. uuid
  3259. collapse-block!)))
  3260. doall)
  3261. (and clear-selection? (clear-selection!)))
  3262. (whiteboard?)
  3263. (.setCollapsed (.-api ^js (state/active-tldraw-app)) true)
  3264. :else
  3265. ;; collapse by one level from outside
  3266. (let [blocks-with-level
  3267. (all-blocks-with-level {:collapse? true})
  3268. max-level (or (apply max (map :block/level blocks-with-level)) 99)]
  3269. (loop [level max-level]
  3270. (if (zero? level)
  3271. nil
  3272. (let [blocks-to-collapse
  3273. (->> blocks-with-level
  3274. (filter (fn [b] (= (:block/level b) level)))
  3275. (filter (fn [b] (collapsable? (:block/uuid b)))))]
  3276. (if (empty? blocks-to-collapse)
  3277. (recur (dec level))
  3278. (doseq [{:block/keys [uuid]} blocks-to-collapse]
  3279. (collapse-block! uuid))))))))))
  3280. (defn toggle-collapse!
  3281. ([e] (toggle-collapse! e false))
  3282. ([e clear-selection?]
  3283. (when e (util/stop e))
  3284. (cond
  3285. (state/editing?)
  3286. (when-let [block (state/get-edit-block)]
  3287. ;; get-edit-block doesn't track the latest collapsed state, so we need to reload from db.
  3288. (let [block-id (:block/uuid block)
  3289. block (db/pull [:block/uuid block-id])]
  3290. (if (:block/collapsed? block)
  3291. (expand! e clear-selection?)
  3292. (collapse! e clear-selection?))))
  3293. (state/selection?)
  3294. (do
  3295. (let [block-ids (map #(-> % (dom/attr "blockid") uuid) (get-selected-blocks))
  3296. first-block-id (first block-ids)]
  3297. (when first-block-id
  3298. ;; If multiple blocks are selected, they may not have all the same collapsed state.
  3299. ;; For simplicity, use the first block's state to decide whether to collapse/expand all.
  3300. (let [first-block (db/pull [:block/uuid first-block-id])]
  3301. (if (:block/collapsed? first-block)
  3302. (doseq [block-id block-ids] (expand-block! block-id))
  3303. (doseq [block-id block-ids] (collapse-block! block-id))))))
  3304. (and clear-selection? (clear-selection!)))
  3305. (whiteboard?)
  3306. ;; TODO: Looks like detecting the whiteboard selection's collapse state will take more work.
  3307. ;; Leaving unimplemented for now.
  3308. nil
  3309. :else
  3310. ;; If no block is being edited or selected, the "toggle" action doesn't make sense,
  3311. ;; so we no-op here, unlike in the expand! & collapse! functions.
  3312. nil)))
  3313. (defn collapse-all!
  3314. ([]
  3315. (collapse-all! nil {}))
  3316. ([block-id {:keys [collapse-self?]
  3317. :or {collapse-self? true}}]
  3318. (let [blocks (all-blocks-with-level {:incremental? false
  3319. :expanded? true
  3320. :root-block block-id})
  3321. block-ids (cond->> (mapv :block/uuid blocks)
  3322. (not collapse-self?)
  3323. (remove #{block-id}))]
  3324. (set-blocks-collapsed! block-ids true))))
  3325. (defn expand-all!
  3326. ([]
  3327. (expand-all! nil))
  3328. ([block-id]
  3329. (let [blocks (all-blocks-with-level {:incremental? false
  3330. :collapse? true
  3331. :root-block block-id})
  3332. block-ids (map :block/uuid blocks)]
  3333. (set-blocks-collapsed! block-ids false))))
  3334. (defn collapse-all-selection!
  3335. []
  3336. (let [block-ids (->> (get-selected-toplevel-block-uuids)
  3337. (map #(all-blocks-with-level {:incremental? false
  3338. :expanded? true
  3339. :root-block %}))
  3340. flatten
  3341. (map :block/uuid)
  3342. distinct)]
  3343. (set-blocks-collapsed! block-ids true)))
  3344. (defn expand-all-selection!
  3345. []
  3346. (let [block-ids (->> (get-selected-toplevel-block-uuids)
  3347. (map #(all-blocks-with-level {:incremental? false
  3348. :collapse? true
  3349. :root-block %}))
  3350. flatten
  3351. (map :block/uuid)
  3352. distinct)]
  3353. (set-blocks-collapsed! block-ids false)))
  3354. (defn toggle-open! []
  3355. (let [all-expanded? (empty? (all-blocks-with-level {:incremental? false
  3356. :collapse? true}))]
  3357. (if all-expanded?
  3358. (collapse-all!)
  3359. (expand-all!))))
  3360. (defn toggle-open-block-children! [block-id]
  3361. (let [all-expanded? (empty? (all-blocks-with-level {:incremental? false
  3362. :collapse? true
  3363. :root-block block-id}))]
  3364. (if all-expanded?
  3365. (collapse-all! block-id {:collapse-self? false})
  3366. (expand-all! block-id))))
  3367. (defn select-all-blocks!
  3368. [{:keys [page]}]
  3369. (if-let [current-input-id (state/get-edit-input-id)]
  3370. (let [input (gdom/getElement current-input-id)
  3371. blocks-container (util/rec-get-blocks-container input)
  3372. blocks (dom/by-class blocks-container "ls-block")]
  3373. (state/exit-editing-and-set-selected-blocks! blocks))
  3374. (->> (all-blocks-with-level {:page page
  3375. :collapse? true})
  3376. (map (fn [b] (or (some-> (:db/id (:block/link b)) db/entity) b)))
  3377. (map (comp gdom/getElementByClass (fn [b] (str "id" (:block/uuid b)))))
  3378. state/exit-editing-and-set-selected-blocks!))
  3379. (state/set-state! :selection/selected-all? true))
  3380. (defn select-parent [e]
  3381. (let [edit-input (some-> (state/get-edit-input-id) gdom/getElement)
  3382. edit-block (state/get-edit-block)
  3383. target-element (.-nodeName (.-target e))]
  3384. (cond
  3385. ;; editing block fully selected
  3386. (and edit-block edit-input
  3387. (= (util/get-selected-text) (.-value edit-input)))
  3388. (do
  3389. (util/stop e)
  3390. (state/exit-editing-and-set-selected-blocks!
  3391. [(gdom/getElementByClass (str "id" (:block/uuid edit-block)))]))
  3392. edit-block
  3393. nil
  3394. ;; Focusing other input element, e.g. when editing page title.
  3395. (contains? #{"INPUT" "TEXTAREA"} target-element)
  3396. nil
  3397. (whiteboard?)
  3398. (do
  3399. (util/stop e)
  3400. (.selectAll (.-api ^js (state/active-tldraw-app))))
  3401. :else
  3402. (do
  3403. (util/stop e)
  3404. (when-not @(:selection/selected-all? @state/state)
  3405. (if-let [block-id (some-> (first (state/get-selection-blocks))
  3406. (dom/attr "blockid")
  3407. uuid)]
  3408. (when-let [block (db/entity [:block/uuid block-id])]
  3409. (let [parent (:block/parent block)]
  3410. (cond
  3411. (= (state/get-current-page) (str (:block/uuid block)))
  3412. nil
  3413. (and parent (:block/parent parent))
  3414. (state/exit-editing-and-set-selected-blocks! [(gdom/getElementByClass (str "id" (:block/uuid parent)))])
  3415. (:block/name parent)
  3416. ;; page block
  3417. (select-all-blocks! {:page (:block/name parent)}))))
  3418. (select-all-blocks! {})))))))
  3419. (defn escape-editing
  3420. ([]
  3421. (escape-editing true))
  3422. ([select?]
  3423. (if select?
  3424. (when-let [node (some-> (state/get-input) (util/rec-get-node "ls-block"))]
  3425. (state/exit-editing-and-set-selected-blocks! [node]))
  3426. (state/clear-edit!))))
  3427. (defn replace-block-reference-with-content-at-point
  3428. []
  3429. (let [repo (state/get-current-repo)]
  3430. (when-let [{:keys [start end link]} (thingatpt/block-ref-at-point)]
  3431. (when-let [block (db/pull [:block/uuid link])]
  3432. (let [block-content (:block/content block)
  3433. format (or (:block/format block) :markdown)
  3434. block-content-without-prop (-> (property-file/remove-properties-when-file-based repo format block-content)
  3435. (drawer/remove-logbook))]
  3436. (when-let [input (state/get-input)]
  3437. (when-let [current-block-content (gobj/get input "value")]
  3438. (let [block-content* (str (subs current-block-content 0 start)
  3439. block-content-without-prop
  3440. (subs current-block-content end))]
  3441. (state/set-block-content-and-last-pos! input block-content* 1)))))))))
  3442. (defn copy-current-ref
  3443. [block-id]
  3444. (when block-id
  3445. (util/copy-to-clipboard! (block-ref/->block-ref block-id))))
  3446. (defn delete-current-ref!
  3447. [block ref-id]
  3448. (when (and block ref-id)
  3449. (let [match (re-pattern (str "\\s?"
  3450. (string/replace (block-ref/->block-ref ref-id) #"([\(\)])" "\\$1")))
  3451. content (string/replace-first (:block/content block) match "")]
  3452. (save-block! (state/get-current-repo)
  3453. (:block/uuid block)
  3454. content))))
  3455. (defn replace-ref-with-text!
  3456. [block ref-id]
  3457. (when (and block ref-id)
  3458. (let [repo (state/get-current-repo)
  3459. match (block-ref/->block-ref ref-id)
  3460. ref-block (db/entity [:block/uuid ref-id])
  3461. block-ref-content (->> (or (:block/content ref-block) "")
  3462. (property-file/remove-built-in-properties-when-file-based repo (:block/format ref-block))
  3463. (drawer/remove-logbook))
  3464. content (string/replace-first (:block/content block) match
  3465. block-ref-content)]
  3466. (save-block! (state/get-current-repo)
  3467. (:block/uuid block)
  3468. content))))
  3469. (defn replace-ref-with-embed!
  3470. [block ref-id]
  3471. (when (and block ref-id)
  3472. (let [match (block-ref/->block-ref ref-id)
  3473. content (string/replace-first (:block/content block) match
  3474. (util/format "{{embed ((%s))}}"
  3475. (str ref-id)))]
  3476. (save-block! (state/get-current-repo)
  3477. (:block/uuid block)
  3478. content))))
  3479. (defn block-default-collapsed?
  3480. "Whether a block should be collapsed by default.
  3481. Currently, this handles several cases:
  3482. 1. References.
  3483. 2. Custom queries."
  3484. [block config]
  3485. (or
  3486. (and
  3487. (or (:ref? config) (:custom-query? config))
  3488. (>= (:block/level block) (state/get-ref-open-blocks-level))
  3489. ;; has children
  3490. (first (:block/_parent (db/entity (:db/id block)))))
  3491. (util/collapsed? block)))
  3492. (defn batch-set-heading!
  3493. [block-ids heading]
  3494. (let [repo (state/get-current-repo)]
  3495. (if (config/db-based-graph? repo)
  3496. (db-editor-handler/batch-set-heading! repo block-ids heading)
  3497. (file-editor-handler/batch-set-heading! block-ids heading))))
  3498. (defn set-heading!
  3499. [block-id heading]
  3500. (batch-set-heading! [block-id] heading))
  3501. (defn remove-heading!
  3502. [block-id]
  3503. (set-heading! block-id nil))
  3504. (defn batch-remove-heading!
  3505. [block-ids]
  3506. (batch-set-heading! block-ids nil))
  3507. (defn block->data-transfer!
  3508. "Set block or page name to the given event's dataTransfer. Used in dnd."
  3509. [block-or-page-name event page?]
  3510. (.setData (gobj/get event "dataTransfer")
  3511. (if page? "page-name" "block-uuid")
  3512. (str block-or-page-name)))