editor.cljs 158 KB

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