events.cljs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. (ns frontend.handler.events
  2. "System-component-like ns that defines named events and listens on a
  3. core.async channel to handle them. Any part of the system can dispatch
  4. one of these events using state/pub-event!"
  5. (:refer-clojure :exclude [run!])
  6. (:require ["@capacitor/filesystem" :refer [Directory Filesystem]]
  7. ["@sentry/react" :as Sentry]
  8. [cljs-bean.core :as bean]
  9. [clojure.core.async :as async]
  10. [clojure.core.async.interop :refer [p->c]]
  11. [clojure.set :as set]
  12. [clojure.string :as string]
  13. [frontend.commands :as commands]
  14. [frontend.components.class :as class-component]
  15. [frontend.components.cmdk :as cmdk]
  16. [frontend.components.conversion :as conversion-component]
  17. [frontend.components.diff :as diff]
  18. [frontend.components.encryption :as encryption]
  19. [frontend.components.file-sync :as file-sync]
  20. [frontend.components.git :as git-component]
  21. [frontend.components.plugins :as plugin]
  22. [frontend.components.shell :as shell]
  23. [frontend.components.whiteboard :as whiteboard]
  24. [frontend.components.user.login :as login]
  25. [frontend.components.repo :as repo]
  26. [frontend.components.db-based.page :as db-page]
  27. [frontend.config :as config]
  28. [frontend.context.i18n :refer [t]]
  29. [frontend.db :as db]
  30. [frontend.db.conn :as conn]
  31. [frontend.db.model :as db-model]
  32. [frontend.db.persist :as db-persist]
  33. [frontend.extensions.srs :as srs]
  34. [frontend.fs :as fs]
  35. [frontend.fs.capacitor-fs :as capacitor-fs]
  36. [frontend.fs.nfs :as nfs]
  37. [frontend.fs.sync :as sync]
  38. [frontend.fs.watcher-handler :as fs-watcher]
  39. [frontend.handler.common :as common-handler]
  40. [frontend.handler.editor :as editor-handler]
  41. [frontend.handler.file :as file-handler]
  42. [frontend.handler.file-sync :as file-sync-handler]
  43. [frontend.handler.notification :as notification]
  44. [frontend.handler.page :as page-handler]
  45. [frontend.handler.plugin :as plugin-handler]
  46. [frontend.handler.repo :as repo-handler]
  47. [frontend.handler.repo-config :as repo-config-handler]
  48. [frontend.handler.route :as route-handler]
  49. [frontend.handler.search :as search-handler]
  50. [frontend.handler.shell :as shell-handler]
  51. [frontend.handler.ui :as ui-handler]
  52. [frontend.handler.user :as user-handler]
  53. [frontend.handler.property.util :as pu]
  54. [frontend.handler.db-based.property.util :as db-pu]
  55. [frontend.handler.file-based.property.util :as property-util]
  56. [frontend.handler.property :as property-handler]
  57. [frontend.handler.whiteboard :as whiteboard-handler]
  58. [frontend.handler.web.nfs :as nfs-handler]
  59. [frontend.mobile.core :as mobile]
  60. [frontend.mobile.graph-picker :as graph-picker]
  61. [frontend.mobile.util :as mobile-util]
  62. [frontend.modules.instrumentation.posthog :as posthog]
  63. [frontend.modules.instrumentation.sentry :as sentry-event]
  64. [frontend.modules.shortcut.core :as st]
  65. [frontend.quick-capture :as quick-capture]
  66. [frontend.search :as search]
  67. [frontend.state :as state]
  68. [frontend.ui :as ui]
  69. [frontend.util :as util]
  70. [frontend.util.persist-var :as persist-var]
  71. [goog.dom :as gdom]
  72. [logseq.db.frontend.schema :as db-schema]
  73. [logseq.graph-parser.config :as gp-config]
  74. [promesa.core :as p]
  75. [rum.core :as rum]
  76. [frontend.db.listener :as db-listener]))
  77. ;; TODO: should we move all events here?
  78. (defmulti handle first)
  79. (defn file-sync-restart! []
  80. (async/go (async/<! (p->c (persist-var/load-vars)))
  81. (async/<! (sync/<sync-stop))
  82. (some-> (sync/<sync-start) async/<!)))
  83. (defn- file-sync-stop! []
  84. (async/go (async/<! (p->c (persist-var/load-vars)))
  85. (async/<! (sync/<sync-stop))))
  86. (defn- enable-beta-features!
  87. []
  88. (when-not (false? (state/enable-sync?)) ; user turns it off
  89. (file-sync-handler/set-sync-enabled! true)))
  90. (defmethod handle :user/fetch-info-and-graphs [[_]]
  91. (state/set-state! [:ui/loading? :login] false)
  92. (async/go
  93. (let [result (async/<! (sync/<user-info sync/remoteapi))]
  94. (cond
  95. (instance? ExceptionInfo result)
  96. nil
  97. (map? result)
  98. (do
  99. (state/set-user-info! result)
  100. (when-let [uid (user-handler/user-uuid)]
  101. (sentry-event/set-user! uid))
  102. (let [status (if (user-handler/alpha-or-beta-user?) :welcome :unavailable)]
  103. (when (and (= status :welcome) (user-handler/logged-in?))
  104. (enable-beta-features!)
  105. (async/<! (file-sync-handler/load-session-graphs))
  106. (p/let [repos (repo-handler/refresh-repos!)]
  107. (when-let [repo (state/get-current-repo)]
  108. (when (some #(and (= (:url %) repo)
  109. (vector? (:sync-meta %))
  110. (util/uuid-string? (first (:sync-meta %)))
  111. (util/uuid-string? (second (:sync-meta %)))) repos)
  112. (sync/<sync-start)))))
  113. (ui-handler/re-render-root!)
  114. (file-sync/maybe-onboarding-show status)))))))
  115. (defmethod handle :user/logout [[_]]
  116. (file-sync-handler/reset-session-graphs)
  117. (sync/remove-all-pwd!)
  118. (file-sync-handler/reset-user-state!)
  119. (login/sign-out!))
  120. (defmethod handle :user/login [[_ host-ui?]]
  121. (if (or host-ui? (not util/electron?))
  122. (js/window.open config/LOGIN-URL)
  123. (login/open-login-modal!)))
  124. (defmethod handle :graph/added [[_ repo {:keys [empty-graph?]}]]
  125. (db/set-key-value repo :ast/version db-schema/ast-version)
  126. (search-handler/rebuild-indices!)
  127. (plugin-handler/hook-plugin-app :graph-after-indexed {:repo repo :empty-graph? empty-graph?})
  128. (when (state/setups-picker?)
  129. (if empty-graph?
  130. (route-handler/redirect! {:to :import :query-params {:from "picker"}})
  131. (route-handler/redirect-to-home!)))
  132. (when-let [dir-name (and (not (config/db-based-graph? repo)) (config/get-repo-dir repo))]
  133. (fs/watch-dir! dir-name))
  134. (file-sync-restart!))
  135. (defmethod handle :init/commands [_]
  136. (page-handler/init-commands!))
  137. (defmethod handle :graph/unlinked [repo current-repo]
  138. (when (= (:url repo) current-repo)
  139. (file-sync-restart!)))
  140. ;; FIXME(andelf): awful multi-arty function.
  141. ;; Should use a `-impl` function instead of the awful `skip-ios-check?` param with nested callback.
  142. (defn- graph-switch
  143. ([graph]
  144. (graph-switch graph false))
  145. ([graph skip-ios-check?]
  146. (let [db-based? (config/db-based-graph? graph)]
  147. (if (and (mobile-util/native-ios?) (not skip-ios-check?))
  148. (state/pub-event! [:validate-appId graph-switch graph])
  149. (do
  150. (state/set-current-repo! graph)
  151. (page-handler/init-commands!)
  152. ;; load config
  153. (repo-config-handler/restore-repo-config! graph)
  154. (when-not (= :draw (state/get-current-route))
  155. (route-handler/redirect-to-home!))
  156. (srs/update-cards-due-count!)
  157. (state/pub-event! [:graph/ready graph])
  158. (when-not db-based?
  159. (file-sync-restart!))
  160. (when-let [dir-name (and (not db-based?) (config/get-repo-dir graph))]
  161. (fs/watch-dir! dir-name)))))))
  162. ;; Parameters for the `persist-db` function, to show the notification messages
  163. (defn- graph-switch-on-persisted
  164. "graph: the target graph to switch to"
  165. [graph _opts]
  166. (p/do!
  167. (repo-handler/restore-and-setup-repo! graph)
  168. (graph-switch graph)
  169. state/set-state! :sync-graph/init? false))
  170. (defmethod handle :graph/switch [[_ graph opts]]
  171. ;; FIXME: wait for writes finished
  172. ;; (if (or (not (false? (get @outliner-file/*writes-finished? graph)))
  173. ;; (:sync-graph/init? @state/state))
  174. ;; (graph-switch-on-persisted graph opts)
  175. ;; (notification/show!
  176. ;; "Please wait seconds until all changes are saved for the current graph."
  177. ;; :warning))
  178. )
  179. (defmethod handle :graph/pull-down-remote-graph [[_ graph dir-name]]
  180. (if (mobile-util/native-ios?)
  181. (when-let [graph-name (or dir-name (:GraphName graph))]
  182. (let [graph-name (util/safe-sanitize-file-name graph-name)]
  183. (if (string/blank? graph-name)
  184. (notification/show! "Illegal graph folder name.")
  185. ;; Create graph directory under Logseq document folder (local)
  186. (when-let [root (state/get-local-container-root-url)]
  187. (let [graph-path (graph-picker/validate-graph-dirname root graph-name)]
  188. (->
  189. (p/let [exists? (fs/dir-exists? graph-path)]
  190. (let [overwrite? (if exists?
  191. (js/confirm (str "There's already a directory with the name \"" graph-name "\", do you want to overwrite it? Make sure to backup it first if you're not sure about it."))
  192. true)]
  193. (if overwrite?
  194. (p/let [_ (fs/mkdir-if-not-exists graph-path)]
  195. (nfs-handler/ls-dir-files-with-path!
  196. graph-path
  197. {:ok-handler (fn []
  198. (file-sync-handler/init-remote-graph graph-path graph)
  199. (js/setTimeout (fn [] (repo-handler/refresh-repos!)) 200))}))
  200. (let [graph-name (-> (js/prompt "Please specify a new directory name to download the graph:")
  201. str
  202. string/trim)]
  203. (when-not (string/blank? graph-name)
  204. (state/pub-event! [:graph/pull-down-remote-graph graph graph-name]))))))
  205. (p/catch (fn [^js e]
  206. (notification/show! (str e) :error)
  207. (js/console.error e)))))))))
  208. (state/set-modal!
  209. (file-sync/pick-dest-to-sync-panel graph)
  210. {:center? true})))
  211. (defmethod handle :graph/pick-page-histories [[_ graph-uuid page-name]]
  212. (state/set-modal!
  213. (file-sync/pick-page-histories-panel graph-uuid page-name)
  214. {:id :page-histories :label "modal-page-histories"}))
  215. (defmethod handle :graph/open-new-window [[_ev target-repo]]
  216. (p/let [current-repo (state/get-current-repo)]
  217. (ui-handler/open-new-window-or-tab! current-repo target-repo)))
  218. (defmethod handle :graph/migrated [[_ _repo]]
  219. (js/alert "Graph migrated."))
  220. (defn get-local-repo
  221. []
  222. (when-let [repo (state/get-current-repo)]
  223. (when (config/local-file-based-graph? repo)
  224. repo)))
  225. (defn ask-permission
  226. [repo]
  227. (when
  228. (and (not (util/electron?))
  229. (not (mobile-util/native-platform?)))
  230. (fn [close-fn]
  231. [:div
  232. ;; TODO: fn translation with args
  233. [:p
  234. "Grant native filesystem permission for directory: "
  235. [:b (config/get-local-dir repo)]]
  236. (ui/button
  237. (t :settings-permission/start-granting)
  238. :class "ui__modal-enter"
  239. :on-click (fn []
  240. (nfs/check-directory-permission! repo)
  241. (close-fn)))])))
  242. (defmethod handle :modal/nfs-ask-permission []
  243. (when-let [repo (get-local-repo)]
  244. (state/set-modal! (ask-permission repo))))
  245. (defonce *query-properties (atom {}))
  246. (rum/defc query-properties-settings-inner < rum/reactive
  247. {:will-unmount (fn [state]
  248. (reset! *query-properties {})
  249. state)}
  250. [block shown-properties all-properties]
  251. (let [query-properties (rum/react *query-properties)]
  252. [:div.p-4
  253. [:div.font-bold (t :query/config-property-settings)]
  254. [:div.flex
  255. {:title "Refresh list of columns"
  256. :on-click
  257. (fn []
  258. (reset! *query-properties {})
  259. (property-handler/remove-block-property! (state/get-current-repo) (:block/uuid block) :query-properties))}
  260. (ui/icon "refresh")]
  261. (for [property all-properties]
  262. (let [property-value (get query-properties property)
  263. shown? (if (nil? property-value)
  264. (contains? shown-properties property)
  265. property-value)]
  266. [:div.flex.flex-row.m-2.justify-between.align-items
  267. [:div (if (uuid? property) (db-pu/get-property-name property) (name property))]
  268. [:div.mt-1 (ui/toggle shown?
  269. (fn []
  270. (let [value (not shown?)]
  271. (swap! *query-properties assoc property value)
  272. (editor-handler/set-block-query-properties!
  273. (:block/uuid block)
  274. all-properties
  275. property
  276. value)))
  277. true)]]))]))
  278. (defn query-properties-settings
  279. [block shown-properties all-properties]
  280. (fn [_close-fn]
  281. (query-properties-settings-inner block shown-properties all-properties)))
  282. (defmethod handle :modal/set-query-properties [[_ block all-properties]]
  283. (let [properties (:block/properties block)
  284. query-properties (pu/lookup properties :query-properties)
  285. block-properties (if (config/db-based-graph? (state/get-current-repo))
  286. query-properties
  287. (some-> query-properties
  288. (common-handler/safe-read-string "Parsing query properties failed")))
  289. shown-properties (if (seq block-properties)
  290. (set block-properties)
  291. (set all-properties))
  292. shown-properties (set/intersection (set all-properties) shown-properties)]
  293. (state/set-modal! (query-properties-settings block shown-properties all-properties)
  294. {:center? true})))
  295. (defmethod handle :modal/show-cards [_]
  296. (state/set-modal! srs/global-cards {:id :srs
  297. :label "flashcards__cp"}))
  298. (defmethod handle :modal/show-instruction [_]
  299. (state/set-modal! capacitor-fs/instruction {:id :instruction
  300. :label "instruction__cp"}))
  301. (defmethod handle :modal/show-themes-modal [_]
  302. (plugin/open-select-theme!))
  303. (rum/defc modal-output
  304. [content]
  305. content)
  306. (defmethod handle :modal/show [[_ content]]
  307. (state/set-modal! #(modal-output content)))
  308. (defmethod handle :modal/set-git-username-and-email [[_ _content]]
  309. (state/set-modal! git-component/set-git-username-and-email))
  310. (defmethod handle :page/title-property-changed [[_ old-title new-title]]
  311. (page-handler/rename! old-title new-title))
  312. (defmethod handle :page/create [[_ page-name opts]]
  313. (page-handler/create! page-name opts))
  314. (defmethod handle :page/create-today-journal [[_ _repo]]
  315. (p/let [_ (page-handler/create-today-journal!)]
  316. (ui-handler/re-render-root!)))
  317. (defmethod handle :file/not-matched-from-disk [[_ path disk-content db-content]]
  318. (state/clear-edit!)
  319. (when-let [repo (state/get-current-repo)]
  320. (when (and disk-content db-content
  321. (not= (util/trim-safe disk-content) (util/trim-safe db-content)))
  322. (state/set-modal! #(diff/local-file repo path disk-content db-content)
  323. {:label "diff__cp"}))))
  324. (defmethod handle :modal/display-file-version [[_ path content hash]]
  325. (state/set-modal! #(git-component/file-specific-version path hash content)))
  326. ;; Hook on a graph is ready to be shown to the user.
  327. ;; It's different from :graph/restored, as :graph/restored is for window reloaded
  328. ;; FIXME: config may not be loaded when the graph is ready.
  329. (defmethod handle :graph/ready
  330. [[_ repo]]
  331. (when (config/local-file-based-graph? repo)
  332. (p/let [dir (config/get-repo-dir repo)
  333. dir-exists? (fs/dir-exists? dir)]
  334. (when (and (not dir-exists?)
  335. (not util/nfs?))
  336. (state/pub-event! [:graph/dir-gone dir]))))
  337. (p/let [loaded-homepage-files (when-not (config/db-based-graph? repo)
  338. (fs-watcher/preload-graph-homepage-files!))
  339. ;; re-render-root is async and delegated to rum, so we need to wait for main ui to refresh
  340. _ (js/setTimeout #(mobile/mobile-postinit) 1000)
  341. ;; FIXME: an ugly implementation for redirecting to page on new window is restored
  342. _ (repo-handler/graph-ready! repo)
  343. _ (when-not (config/db-based-graph? repo)
  344. (fs-watcher/load-graph-files! repo loaded-homepage-files))]))
  345. (defmethod handle :notification/show [[_ {:keys [content status clear?]}]]
  346. (notification/show! content status clear?))
  347. (defmethod handle :command/run [_]
  348. (when (util/electron?)
  349. (state/set-modal! shell/shell)))
  350. (defmethod handle :go/search [_]
  351. (state/set-modal! cmdk/cmdk-modal
  352. {:fullscreen? true
  353. :close-btn? false
  354. :panel? false
  355. :label "ls-modal-search"}))
  356. (defmethod handle :go/plugins [_]
  357. (plugin/open-plugins-modal!))
  358. (defmethod handle :go/plugins-waiting-lists [_]
  359. (plugin/open-waiting-updates-modal!))
  360. (defmethod handle :go/plugins-from-file [[_ plugins]]
  361. (plugin/open-plugins-from-file-modal! plugins))
  362. (defmethod handle :go/plugins-settings [[_ pid nav? title]]
  363. (if pid
  364. (do
  365. (state/set-state! :plugin/focused-settings pid)
  366. (state/set-state! :plugin/navs-settings? (not (false? nav?)))
  367. (plugin/open-focused-settings-modal! title))
  368. (state/close-sub-modal! "ls-focused-settings-modal")))
  369. (defmethod handle :go/proxy-settings [[_ agent-opts]]
  370. (state/set-sub-modal!
  371. (fn [_] (plugin/user-proxy-settings-panel agent-opts))
  372. {:id :https-proxy-panel :center? true}))
  373. (defmethod handle :redirect-to-home [_]
  374. (page-handler/create-today-journal!))
  375. (defmethod handle :instrument [[_ {:keys [type payload] :as opts}]]
  376. (when-not (empty? (dissoc opts :type :payload))
  377. (js/console.error "instrument data-map should only contains [:type :payload]"))
  378. (posthog/capture type payload))
  379. (defmethod handle :capture-error [[_ {:keys [error payload]}]]
  380. (let [[user-uuid graph-uuid tx-id] @sync/graphs-txid
  381. payload (assoc payload
  382. :user-id user-uuid
  383. :graph-id graph-uuid
  384. :tx-id tx-id)]
  385. (Sentry/captureException error
  386. (bean/->js {:tags payload}))))
  387. (defmethod handle :exec-plugin-cmd [[_ {:keys [pid cmd action]}]]
  388. (commands/exec-plugin-simple-command! pid cmd action))
  389. (defmethod handle :shortcut-handler-refreshed [[_]]
  390. (when-not @st/*pending-inited?
  391. (reset! st/*pending-inited? true)
  392. (st/consume-pending-shortcuts!)))
  393. (defmethod handle :mobile/keyboard-will-show [[_ keyboard-height]]
  394. (let [main-node (util/app-scroll-container-node)]
  395. (state/set-state! :mobile/show-tabbar? false)
  396. (state/set-state! :mobile/show-toolbar? true)
  397. (state/set-state! :mobile/show-action-bar? false)
  398. (when (= (state/sub :editor/record-status) "RECORDING")
  399. (state/set-state! :mobile/show-recording-bar? true))
  400. (when (mobile-util/native-ios?)
  401. (reset! util/keyboard-height keyboard-height)
  402. (set! (.. main-node -style -marginBottom) (str keyboard-height "px"))
  403. (when-let [^js html (js/document.querySelector ":root")]
  404. (.setProperty (.-style html) "--ls-native-kb-height" (str keyboard-height "px"))
  405. (.add (.-classList html) "has-mobile-keyboard"))
  406. (when-let [left-sidebar-node (gdom/getElement "left-sidebar")]
  407. (set! (.. left-sidebar-node -style -bottom) (str keyboard-height "px")))
  408. (when-let [right-sidebar-node (gdom/getElementByClass "sidebar-item-list")]
  409. (set! (.. right-sidebar-node -style -paddingBottom) (str (+ 150 keyboard-height) "px")))
  410. (when-let [card-preview-el (js/document.querySelector ".cards-review")]
  411. (set! (.. card-preview-el -style -marginBottom) (str keyboard-height "px")))
  412. (when-let [card-preview-el (js/document.querySelector ".encryption-password")]
  413. (set! (.. card-preview-el -style -marginBottom) (str keyboard-height "px")))
  414. (js/setTimeout (fn []
  415. (when-let [toolbar (.querySelector main-node "#mobile-editor-toolbar")]
  416. (set! (.. toolbar -style -bottom) (str keyboard-height "px"))))
  417. 100))))
  418. (defmethod handle :mobile/keyboard-will-hide [[_]]
  419. (let [main-node (util/app-scroll-container-node)]
  420. (state/set-state! :mobile/show-toolbar? false)
  421. (state/set-state! :mobile/show-tabbar? true)
  422. (when (= (state/sub :editor/record-status) "RECORDING")
  423. (state/set-state! :mobile/show-recording-bar? false))
  424. (when (mobile-util/native-ios?)
  425. (when-let [^js html (js/document.querySelector ":root")]
  426. (.removeProperty (.-style html) "--ls-native-kb-height")
  427. (.remove (.-classList html) "has-mobile-keyboard"))
  428. (when-let [card-preview-el (js/document.querySelector ".cards-review")]
  429. (set! (.. card-preview-el -style -marginBottom) "0px"))
  430. (when-let [card-preview-el (js/document.querySelector ".encryption-password")]
  431. (set! (.. card-preview-el -style -marginBottom) "0px"))
  432. (set! (.. main-node -style -marginBottom) "0px")
  433. (when-let [left-sidebar-node (gdom/getElement "left-sidebar")]
  434. (set! (.. left-sidebar-node -style -bottom) "0px"))
  435. (when-let [right-sidebar-node (gdom/getElementByClass "sidebar-item-list")]
  436. (set! (.. right-sidebar-node -style -paddingBottom) "150px"))
  437. (when-let [toolbar (.querySelector main-node "#mobile-editor-toolbar")]
  438. (set! (.. toolbar -style -bottom) 0)))))
  439. (defn- get-ios-app-id
  440. [repo-url]
  441. (when repo-url
  442. (let [app-id (-> (first (string/split repo-url "/Documents"))
  443. (string/split "/")
  444. last)]
  445. app-id)))
  446. (defmethod handle :validate-appId [[_ graph-switch-f graph]]
  447. (when-let [deprecated-repo (or graph (state/get-current-repo))]
  448. (if (mobile-util/in-iCloud-container-path? deprecated-repo)
  449. ;; Installation is not changed for iCloud
  450. (when graph-switch-f
  451. (graph-switch-f graph true)
  452. (state/pub-event! [:graph/ready (state/get-current-repo)]))
  453. ;; Installation is changed for App Documents directory
  454. (p/let [deprecated-app-id (get-ios-app-id deprecated-repo)
  455. current-document-url (.getUri Filesystem #js {:path ""
  456. :directory (.-Documents Directory)})
  457. current-app-id (-> (js->clj current-document-url :keywordize-keys true)
  458. get-ios-app-id)]
  459. (if (= deprecated-app-id current-app-id)
  460. (when graph-switch-f (graph-switch-f graph true))
  461. (do
  462. (notification/show! [:div "Migrating from previous App installation..."]
  463. :warning
  464. true)
  465. (prn ::migrate-app-id :from deprecated-app-id :to current-app-id)
  466. (file-sync-stop!)
  467. (.unwatch mobile-util/fs-watcher)
  468. (let [current-repo (string/replace deprecated-repo deprecated-app-id current-app-id)
  469. current-repo-dir (config/get-repo-dir current-repo)]
  470. (try
  471. ;; replace app-id part of repo url
  472. (reset! conn/conns
  473. (update-keys @conn/conns
  474. (fn [key]
  475. (if (string/includes? key deprecated-app-id)
  476. (string/replace key deprecated-app-id current-app-id)
  477. key))))
  478. (db-persist/rename-graph! deprecated-repo current-repo)
  479. (search/remove-db! deprecated-repo)
  480. (state/add-repo! {:url current-repo :nfs? true})
  481. (state/delete-repo! {:url deprecated-repo})
  482. (catch :default e
  483. (js/console.error e)))
  484. (state/set-current-repo! current-repo)
  485. (db-listener/listen-and-persist! current-repo)
  486. (repo-config-handler/restore-repo-config! current-repo)
  487. (when graph-switch-f (graph-switch-f current-repo true))
  488. (.watch mobile-util/fs-watcher #js {:path current-repo-dir})
  489. (file-sync-restart!))))
  490. (state/pub-event! [:graph/ready (state/get-current-repo)])))))
  491. (defmethod handle :plugin/consume-updates [[_ id prev-pending? updated?]]
  492. (let [downloading? (:plugin/updates-downloading? @state/state)
  493. auto-checking? (plugin-handler/get-auto-checking?)]
  494. (when-let [coming (and (not downloading?)
  495. (get-in @state/state [:plugin/updates-coming id]))]
  496. (let [error-code (:error-code coming)
  497. error-code (if (= error-code (str :no-new-version)) nil error-code)
  498. title (:title coming)]
  499. (when (and prev-pending? (not auto-checking?))
  500. (if-not error-code
  501. (plugin/set-updates-sub-content! (str title "...") 0)
  502. (notification/show!
  503. (str "[Checked]<" title "> " error-code) :error)))))
  504. (if (and updated? downloading?)
  505. ;; try to start consume downloading item
  506. (if-let [next-coming (state/get-next-selected-coming-update)]
  507. (plugin-handler/check-or-update-marketplace-plugin!
  508. (assoc next-coming :only-check false :error-code nil)
  509. (fn [^js e] (js/console.error "[Download Err]" next-coming e)))
  510. (plugin-handler/close-updates-downloading))
  511. ;; try to start consume pending item
  512. (if-let [next-pending (second (first (:plugin/updates-pending @state/state)))]
  513. (do
  514. (println "Updates: take next pending - " (:id next-pending))
  515. (js/setTimeout
  516. #(plugin-handler/check-or-update-marketplace-plugin!
  517. (assoc next-pending :only-check true :auto-check auto-checking? :error-code nil)
  518. (fn [^js e]
  519. (notification/show! (.toString e) :error)
  520. (js/console.error "[Check Err]" next-pending e))) 500))
  521. ;; try to open waiting updates list
  522. (do (when (and prev-pending? (not auto-checking?)
  523. (seq (state/all-available-coming-updates)))
  524. (plugin/open-waiting-updates-modal!))
  525. (plugin-handler/set-auto-checking! false))))))
  526. (defmethod handle :plugin/hook-db-tx [[_ {:keys [blocks tx-data] :as payload}]]
  527. (when-let [payload (and (seq blocks)
  528. (merge payload {:tx-data (map #(into [] %) tx-data)}))]
  529. (plugin-handler/hook-plugin-db :changed payload)
  530. (plugin-handler/hook-plugin-block-changes payload)))
  531. (defmethod handle :plugin/loader-perf-tip [[_ {:keys [^js o _s _e]}]]
  532. (when-let [opts (.-options o)]
  533. (notification/show!
  534. (plugin/perf-tip-content (.-id o) (.-name opts) (.-url opts))
  535. :warning false (.-id o))))
  536. (defmethod handle :mobile-file-watcher/changed [[_ ^js event]]
  537. (let [type (.-event event)
  538. payload (js->clj event :keywordize-keys true)]
  539. (fs-watcher/handle-changed! type payload)
  540. (when (file-sync-handler/enable-sync?)
  541. (sync/file-watch-handler type payload))))
  542. (defmethod handle :rebuild-slash-commands-list [[_]]
  543. (page-handler/rebuild-slash-commands-list!))
  544. (defmethod handle :shortcut/refresh [[_]]
  545. (st/refresh!))
  546. (defn- refresh-cb []
  547. (page-handler/create-today-journal!)
  548. (file-sync-restart!))
  549. (defmethod handle :graph/ask-for-re-fresh [_]
  550. (handle
  551. [:modal/show
  552. [:div {:style {:max-width 700}}
  553. [:p (t :sync-from-local-changes-detected)]
  554. (ui/button
  555. (t :yes)
  556. :autoFocus "on"
  557. :class "ui__modal-enter"
  558. :on-click (fn []
  559. (state/close-modal!)
  560. (nfs-handler/refresh! (state/get-current-repo) refresh-cb)))]]))
  561. (defmethod handle :sync/create-remote-graph [[_ current-repo]]
  562. (let [graph-name (js/decodeURI (util/node-path.basename current-repo))]
  563. (async/go
  564. (async/<! (sync/<sync-stop))
  565. (state/set-state! [:ui/loading? :graph/create-remote?] true)
  566. (when-let [GraphUUID (get (async/<! (file-sync-handler/create-graph graph-name)) 2)]
  567. (async/<! (sync/<sync-start))
  568. (state/set-state! [:ui/loading? :graph/create-remote?] false)
  569. ;; update existing repo
  570. (state/set-repos! (map (fn [r]
  571. (if (= (:url r) current-repo)
  572. (assoc r
  573. :GraphUUID GraphUUID
  574. :GraphName graph-name
  575. :remote? true)
  576. r))
  577. (state/get-repos)))))))
  578. (defmethod handle :modal/remote-encryption-input-pw-dialog [[_ repo-url remote-graph-info type opts]]
  579. (state/set-modal!
  580. (encryption/input-password
  581. repo-url nil (merge
  582. (assoc remote-graph-info
  583. :type (or type :create-pwd-remote)
  584. :repo repo-url)
  585. opts))
  586. {:center? true :close-btn? false :close-backdrop? false}))
  587. (defmethod handle :journal/insert-template [[_ page-name]]
  588. (let [page-name (util/page-name-sanity-lc page-name)]
  589. (when-let [page (db/pull [:block/name page-name])]
  590. (when (db/page-empty? (state/get-current-repo) page-name)
  591. (when-let [template (state/get-default-journal-template)]
  592. (editor-handler/insert-template!
  593. nil
  594. template
  595. {:target page}))))))
  596. (defmethod handle :editor/set-org-mode-heading [[_ block heading]]
  597. (when-let [id (:block/uuid block)]
  598. (editor-handler/set-heading! id heading)))
  599. (defmethod handle :file-sync-graph/restore-file [[_ graph page-entity content]]
  600. (when (db/get-db graph)
  601. (let [file (:block/file page-entity)]
  602. (when-let [path (:file/path file)]
  603. (when (and (not= content (:file/content file))
  604. (:file/content file))
  605. (sync/add-new-version-file graph path (:file/content file)))
  606. (p/let [_ (file-handler/alter-file graph
  607. path
  608. content
  609. {:re-render-root? true
  610. :skip-compare? true})]
  611. (state/close-modal!)
  612. (route-handler/redirect! {:to :page
  613. :path-params {:name (:block/name page-entity)}}))))))
  614. (defmethod handle :whiteboard/onboarding [[_ opts]]
  615. (state/set-modal!
  616. (fn [close-fn] (whiteboard/onboarding-welcome close-fn))
  617. (merge {:close-btn? false
  618. :center? true
  619. :close-backdrop? false} opts)))
  620. (defmethod handle :file-sync/onboarding-tip [[_ type opts]]
  621. (let [type (keyword type)]
  622. (state/set-modal!
  623. (file-sync/make-onboarding-panel type)
  624. (merge {:close-btn? false
  625. :center? true
  626. :close-backdrop? (not= type :welcome)} opts))))
  627. (defmethod handle :file-sync/maybe-onboarding-show [[_ type]]
  628. (file-sync/maybe-onboarding-show type))
  629. (defmethod handle :file-sync/storage-exceed-limit [[_]]
  630. (notification/show! "file sync storage exceed limit" :warning false)
  631. (file-sync-stop!))
  632. (defmethod handle :file-sync/graph-count-exceed-limit [[_]]
  633. (notification/show! "file sync graph count exceed limit" :warning false)
  634. (file-sync-stop!))
  635. (defmethod handle :graph/restored [[_ _graph]]
  636. (mobile/init!)
  637. (when-not (mobile-util/native-ios?)
  638. (state/pub-event! [:graph/ready (state/get-current-repo)])))
  639. (defmethod handle :whiteboard-link [[_ shapes]]
  640. (route-handler/go-to-search! :whiteboard/link)
  641. (state/set-state! :whiteboard/linked-shapes shapes))
  642. (defmethod handle :whiteboard-go-to-link [[_ link]]
  643. (route-handler/redirect! {:to :whiteboard
  644. :path-params {:name link}}))
  645. (defmethod handle :graph/dir-gone [[_ dir]]
  646. (state/pub-event! [:notification/show
  647. {:content (str "The directory " dir " has been renamed or deleted, the editor will be disabled for this graph, you can unlink the graph.")
  648. :status :error
  649. :clear? false}])
  650. (state/update-state! :file/unlinked-dirs (fn [dirs] (conj dirs dir))))
  651. (defmethod handle :graph/dir-back [[_ repo dir]]
  652. (when (contains? (:file/unlinked-dirs @state/state) dir)
  653. (notification/clear-all!)
  654. (state/pub-event! [:notification/show
  655. {:content (str "The directory " dir " has been back, you can edit your graph now.")
  656. :status :success
  657. :clear? true}])
  658. (state/update-state! :file/unlinked-dirs (fn [dirs] (disj dirs dir)))
  659. (when (= dir (config/get-repo-dir repo))
  660. (fs/watch-dir! dir))))
  661. (defmethod handle :ui/notify-outdated-filename-format [[_ paths]]
  662. ;; paths - the affected paths that contains reserved characters
  663. (notification/show!
  664. [:div
  665. [:div.mb-4
  666. [:div.font-semibold.mb-4.text-xl "It seems that some of your filenames are in the outdated format."]
  667. [:div
  668. [:p
  669. "We suggest you upgrade now to avoid potential bugs."]
  670. (when (seq paths)
  671. [:p
  672. "For example, the files below have reserved characters that can't be synced on some platforms."])]]
  673. (ui/button
  674. "Update filename format"
  675. :aria-label "Update filename format"
  676. :on-click (fn []
  677. (notification/clear-all!)
  678. (state/set-modal!
  679. (fn [_] (conversion-component/files-breaking-changed))
  680. {:id :filename-format-panel :center? true})))
  681. (when (seq paths)
  682. [:ol.my-2
  683. (for [path paths]
  684. [:li path])])]
  685. :warning
  686. false))
  687. (defmethod handle :ui/notify-skipped-downloading-files [[_ paths]]
  688. (notification/show!
  689. [:div
  690. [:div.mb-4
  691. [:div.font-semibold.mb-4.text-xl "It seems that some of your filenames are in the outdated format."]
  692. [:p
  693. "The files below that have reserved characters can't be saved on this device."]
  694. [:div.overflow-y-auto.max-h-96
  695. [:ol.my-2
  696. (for [path paths]
  697. [:li path])]]
  698. [:div
  699. [:p
  700. "Check " [:a {:href "https://docs.logseq.com/#/page/logseq%20file%20and%20folder%20naming%20rules"
  701. :target "_blank"}
  702. "Logseq file and folder naming rules"]
  703. " for more details."]
  704. [:p
  705. (util/format "To solve this problem, we suggest you quit Logseq and update the filename format (on Settings > Advanced > Filename format > click EDIT button)%s to avoid more potential bugs."
  706. (if (and util/mac? (not (mobile-util/native-ios?)))
  707. ""
  708. " in other devices"))]]]]
  709. :warning
  710. false))
  711. (defmethod handle :graph/setup-a-repo [[_ opts]]
  712. (let [opts' (merge {:picked-root-fn #(state/close-modal!)
  713. :native-icloud? (not (string/blank? (state/get-icloud-container-root-url)))
  714. :logged? (user-handler/logged-in?)} opts)]
  715. (if (mobile-util/native-ios?)
  716. (state/set-modal!
  717. #(graph-picker/graph-picker-cp opts')
  718. {:label "graph-setup"})
  719. (page-handler/ls-dir-files! st/refresh! opts'))))
  720. (defmethod handle :graph/new-db-graph [[_ _opts]]
  721. (state/set-modal!
  722. repo/new-db-graph
  723. {:id :new-db-graph
  724. :label "graph-setup"}))
  725. (defmethod handle :search/transact-data [[_ repo data]]
  726. (let [file-based? (config/local-file-based-graph? repo)
  727. data' (cond-> data
  728. file-based?
  729. ;; remove built-in properties from content
  730. (update :blocks-to-add
  731. (fn [blocks]
  732. (map #(update % :content
  733. (fn [content]
  734. (property-util/remove-built-in-properties (get % :format :markdown) content)))
  735. blocks))))]
  736. (search/transact-blocks! repo data')))
  737. (defmethod handle :class/configure [[_ page]]
  738. (state/set-modal!
  739. #(vector :<>
  740. (class-component/configure page)
  741. (db-page/page-properties page {:configure? true}))
  742. {:id :page-configure
  743. :label "page-configure"
  744. :container-overflow-visible? true}))
  745. (defmethod handle :file/alter [[_ repo path content]]
  746. (p/let [_ (file-handler/alter-file repo path content {:from-disk? true})]
  747. (ui-handler/re-render-root!)))
  748. (defmethod handle :ui/re-render-root [[_]]
  749. (ui-handler/re-render-root!))
  750. (rum/defcs file-id-conflict-item <
  751. (rum/local false ::resolved?)
  752. [state repo file data]
  753. (let [resolved? (::resolved? state)
  754. id (last (:assertion data))]
  755. [:li {:key file}
  756. [:div
  757. [:a {:on-click #(js/window.apis.openPath file)} file]
  758. (if @resolved?
  759. [:div.flex.flex-row.items-center
  760. (ui/icon "circle-check" {:style {:font-size 20}})
  761. [:div.ml-1 "Resolved"]]
  762. [:div
  763. [:p
  764. (str "It seems that another whiteboard file already has the ID \"" id
  765. "\". You can fix it by changing the ID in this file with another UUID.")]
  766. [:p
  767. "Or, let me"
  768. (ui/button "Fix"
  769. :on-click (fn []
  770. (let [dir (config/get-repo-dir repo)]
  771. (p/let [content (fs/read-file dir file)]
  772. (let [new-content (string/replace content (str id) (str (random-uuid)))]
  773. (p/let [_ (fs/write-file! repo
  774. dir
  775. file
  776. new-content
  777. {})]
  778. (reset! resolved? true))))))
  779. :class "inline mx-1")
  780. "it."]])]]))
  781. (defmethod handle :file/parse-and-load-error [[_ repo parse-errors]]
  782. (state/pub-event! [:notification/show
  783. {:content
  784. [:div
  785. [:h2.title "Oops. These files failed to import to your graph:"]
  786. [:ol.my-2
  787. (for [[file error] parse-errors]
  788. (let [data (ex-data error)]
  789. (cond
  790. (and (gp-config/whiteboard? file)
  791. (= :transact/upsert (:error data))
  792. (uuid? (last (:assertion data))))
  793. (rum/with-key (file-id-conflict-item repo file data) file)
  794. :else
  795. (do
  796. (state/pub-event! [:capture-error {:error error
  797. :payload {:type :file/parse-and-load-error}}])
  798. [:li.my-1 {:key file}
  799. [:a {:on-click #(js/window.apis.openPath file)} file]
  800. [:p (.-message error)]]))))]
  801. [:p "Don't forget to re-index your graph when all the conflicts are resolved."]]
  802. :status :error}]))
  803. (defmethod handle :run/cli-command [[_ command content]]
  804. (when (and command (not (string/blank? content)))
  805. (shell-handler/run-cli-command-wrapper! command content)))
  806. (defmethod handle :whiteboard/undo [[_ e]]
  807. (whiteboard-handler/undo! e))
  808. (defmethod handle :whiteboard/redo [[_ e]]
  809. (whiteboard-handler/redo! e))
  810. (defmethod handle :editor/quick-capture [[_ args]]
  811. (quick-capture/quick-capture args))
  812. (defmethod handle :modal/keymap [[_]]
  813. (state/open-settings! :keymap))
  814. (defmethod handle :editor/toggle-own-number-list [[_ blocks]]
  815. (let [batch? (sequential? blocks)
  816. blocks (cond->> blocks
  817. batch?
  818. (map #(cond-> % (or (uuid? %) (string? %)) (db-model/get-block-by-uuid))))]
  819. (if (and batch? (> (count blocks) 1))
  820. (editor-handler/toggle-blocks-as-own-order-list! blocks)
  821. (when-let [block (cond-> blocks batch? (first))]
  822. (if (editor-handler/own-order-number-list? block)
  823. (editor-handler/remove-block-own-order-list-type! block)
  824. (editor-handler/make-block-as-own-order-list! block))))))
  825. (defmethod handle :editor/remove-own-number-list [[_ block]]
  826. (when (some-> block (editor-handler/own-order-number-list?))
  827. (editor-handler/remove-block-own-order-list-type! block)))
  828. (defmethod handle :editor/toggle-children-number-list [[_ block]]
  829. (when-let [blocks (and block (db-model/get-block-immediate-children (state/get-current-repo) (:block/uuid block)))]
  830. (editor-handler/toggle-blocks-as-own-order-list! blocks)))
  831. (defmethod handle :editor/new-property [[_]]
  832. (when-let [edit-block (state/get-edit-block)]
  833. (when-let [block-id (:block/uuid edit-block)]
  834. (let [block (db/entity [:block/uuid block-id])
  835. collapsed? (or (get-in @state/state [:ui/collapsed-blocks (state/get-current-repo) block-id])
  836. (:block/collapsed? block))]
  837. (when collapsed?
  838. (editor-handler/set-blocks-collapsed! [block-id] false)))))
  839. (property-handler/editing-new-property!))
  840. (defmethod handle :editor/edit-block [[_ block pos id opts]]
  841. (editor-handler/edit-block! block pos id opts))
  842. (rum/defc multi-tabs-dialog
  843. []
  844. (let [word (if (util/electron?) "window" "tab")]
  845. [:div.flex.p-4.flex-col.gap-4.h-64
  846. [:span.warning.text-lg
  847. (util/format "Logseq doesn't support multiple %ss access to the same graph yet, please close this %s or switch to another graph."
  848. word word)]
  849. [:div.text-lg
  850. [:p "Switch to another repo: "]
  851. (repo/repos-dropdown {:on-click (fn [e]
  852. (util/stop e)
  853. (state/set-state! :error/multiple-tabs-access-opfs? false)
  854. (state/close-modal!))})]]))
  855. (defmethod handle :show/multiple-tabs-error-dialog [_]
  856. (state/set-state! :error/multiple-tabs-access-opfs? true)
  857. (state/set-modal! multi-tabs-dialog {:container-overflow-visible? true}))
  858. (defn run!
  859. []
  860. (let [chan (state/get-events-chan)]
  861. (async/go-loop []
  862. (let [[payload d] (async/<! chan)]
  863. (->
  864. (try
  865. (p/resolved (handle payload))
  866. (catch :default error
  867. (p/rejected error)))
  868. (p/then (fn [result]
  869. (p/resolve! d result)))
  870. (p/catch (fn [error]
  871. (let [type :handle-system-events/failed]
  872. (state/pub-event! [:capture-error {:error error
  873. :payload {:type type
  874. :payload payload}}])
  875. (p/reject! d error))))))
  876. (recur))
  877. chan))
  878. (comment
  879. (let [{:keys [deprecated-app-id current-app-id]} {:deprecated-app-id "AFDADF9A-7466-4ED8-B74F-AAAA0D4565B9", :current-app-id "7563518E-0EFD-4AD2-8577-10CFFD6E4596"}]
  880. (def deprecated-app-id deprecated-app-id)
  881. (def current-app-id current-app-id))
  882. (def deprecated-repo (state/get-current-repo))
  883. (def new-repo (string/replace deprecated-repo deprecated-app-id current-app-id))
  884. (update-file-path deprecated-repo new-repo deprecated-app-id current-app-id))