1
0

editor.cljs 164 KB

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