editor.cljs 160 KB

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