editor.cljs 138 KB

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