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