editor.cljs 164 KB

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