editor.cljs 151 KB

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