editor.cljs 165 KB

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