editor.cljs 164 KB

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